<?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 jj on Medium]]></title>
        <description><![CDATA[Stories by jj on Medium]]></description>
        <link>https://medium.com/@all2one?source=rss-cc8601a8e73c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cgZFq6FUJjME6l-b.jpg</url>
            <title>Stories by jj on Medium</title>
            <link>https://medium.com/@all2one?source=rss-cc8601a8e73c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:47:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@all2one/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[Intersecting two splines]]></title>
            <link>https://medium.com/@all2one/intersecting-two-splines-70a1d901c446?source=rss-cc8601a8e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/70a1d901c446</guid>
            <category><![CDATA[spline-intersection]]></category>
            <category><![CDATA[implicitization]]></category>
            <category><![CDATA[bezier-subdivision]]></category>
            <category><![CDATA[bezier-intersection]]></category>
            <category><![CDATA[interval-subdivision]]></category>
            <dc:creator><![CDATA[jj]]></dc:creator>
            <pubDate>Tue, 29 Aug 2017 23:41:19 GMT</pubDate>
            <atom:updated>2017-08-29T23:41:19.067Z</atom:updated>
            <content:encoded><![CDATA[<p>Spline is an inexhaustible cruse. A simple polynomial with a straightforward geometric interpretation, but there are a myriad of things you can do with it, each of which can involve a unique technical challenge. A long list of topics in <a href="https://pomax.github.io/bezierinfo/">this primer</a> demonstrates the point. This time I had to intersect two cubic splines (or two cubic Bézier curves since <a href="http://www.joshbarczak.com/blog/?p=730">they are the same thing</a>).</p><p>I surveyed (i.e. googled) relevant articles and papers and I’d like to share what I found.</p><p>There are mainly two approaches for spline-spline intersections: <em>implicitization</em> and <em>subdivision</em>. The former transforms the problem into a root finding of a polynomial in one variable. The latter finds (an) intersection(s) by recursively subdividing each curve involved into two sub-curves and removing pairs whose bounds don’t intersect at all until they can be properly approximated by lines. This basic subdivision approach is called <em>Bézier subdivision</em>. <em>Interval subdivision</em> is a variation of it, where the subdivision only happens where the tangent is either horizontal or vertical and known to be faster than the basic one. The literature seems to suggest the implicitization should be usually faster than subdivision-based approaches as long as the order of the curves are not too high (≤ 4). It becomes numerically unstable in higher degrees, also.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*OSBGxCHV85umE0vZDbELrQ.png" /><figcaption>Bézier subdivision from <a href="https://pomax.github.io/bezierinfo/#intersections">the primer</a> (You can interactively see how the algorithm works there. Recommend paying a visit)</figcaption></figure><p>A third option (although it’s conceptually closer to the subdivision) is <em>Bézier clipping</em>. It iteratively clips one curve to the other’s <em>fat line</em>. A fat line is defined by two parallel lines that tightly encloses the curve’s control hull. This technique is known to be faster than the subdivision approaches. There is even <a href="https://pdfs.semanticscholar.org/dfbb/c5b9d7e2bbfe1a624ec9f11718517aebac1f.pdf">a combo approach called <em>a cocktail algorithm</em></a>, where a subdivision approach is used to seed an implicitization one, which then computes the final intersections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*ZbFiL_UoUXL6ETDtxvervA.png" /><figcaption>Bézier clipping from <a href="http://www.tsplines.com/technology/edu/CurveIntersection.pdf">this course note</a></figcaption></figure><p>I ended up using Bézier subdivision for its simplicity. Another main reason was the availability of a credible implementation I can refer to. “Intersecting Parametric Cubic Curves by Midpoint Subdivision” in <a href="https://www.amazon.com/Graphics-Gems-IV-IBM-Version/dp/0123361559">Graphics Gems IV</a> explains the algorithm with <a href="https://github.com/erich666/GraphicsGems/tree/master/gemsiv/curve_isect">a C++ implementation</a>. It seems to run fast enough for my use cases, but when a push comes to a shove, I know which direction I should look further into to implement a faster one.</p><h3>References</h3><ol><li>A Primer on Bézier Curves — 25. Intersections: <a href="https://pomax.github.io/bezierinfo/#intersections">https://pomax.github.io/bezierinfo/#intersections</a></li><li>7.4 Computing the Intersection of Two Bézier Curves in T. W. Sederberg, BYU, Computer Aided Geometric Design Course Notes: <a href="http://www.tsplines.com/technology/edu/CurveIntersection.pdf">http://www.tsplines.com/technology/edu/CurveIntersection.pdf</a></li><li>A Comparison of Three Curve Intersection Algorithms: <a href="https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19850020280.pdf">https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19850020280.pdf</a></li><li>A cocktail algorithm for planar Bézier curve intersections: <a href="https://pdfs.semanticscholar.org/dfbb/c5b9d7e2bbfe1a624ec9f11718517aebac1f.pdf">https://pdfs.semanticscholar.org/dfbb/c5b9d7e2bbfe1a624ec9f11718517aebac1f.pdf</a></li><li>C++ code for the article “Intersecting Parametric Cubic Curves by Midpoint Subdivision” in Graphics Gems IV: <a href="https://github.com/erich666/GraphicsGems/tree/master/gemsiv/curve_isect">https://github.com/erich666/GraphicsGems/tree/master/gemsiv/curve_isect</a></li><li>Algorithms for Intersecting Parametric and Algebraic Curves: <a href="http://graphicsinterface.org/wp-content/uploads/gi1992-27.pdf">http://graphicsinterface.org/wp-content/uploads/gi1992-27.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70a1d901c446" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delaunay triangulation with Hilbert curve]]></title>
            <link>https://medium.com/@all2one/delaunay-triangulation-with-hilbert-curve-e3ee77959773?source=rss-cc8601a8e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3ee77959773</guid>
            <category><![CDATA[half-edge]]></category>
            <category><![CDATA[mesh-generation]]></category>
            <category><![CDATA[delaunay-triangulation]]></category>
            <category><![CDATA[hilbert-curve]]></category>
            <category><![CDATA[boundary-representation]]></category>
            <dc:creator><![CDATA[jj]]></dc:creator>
            <pubDate>Thu, 13 Jul 2017 16:28:30 GMT</pubDate>
            <atom:updated>2017-08-05T01:50:46.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*eBtTrSIq6WYxQKA0X6896g.gif" /><figcaption>Delaunay triagulation (black lines with red dots) with its dual, Voronoi diagram (yellow lines)</figcaption></figure><p>I recently had a chance to look into <em>mesh generation</em>. I could easily generate a point cloud from source geometry data I have, so I looked into <em>Delaunay triangulation</em>, which I had heard about, but hadn’t had a chance to implement before.</p><p><a href="https://en.wikipedia.org/wiki/Delaunay_triangulation">Delaunay triangulation</a> triangulates a given point cloud in a way that no point is inside the <a href="https://en.wikipedia.org/wiki/Circumscribed_circle">circumcircle</a> of any generated triangle. It maximizes the minimum angle of all the angles of the triangles in the triangulation. In other words, it tends to avoid sliver triangles, which are bad for interpolation or rasterization processes.</p><p>There are <a href="http://www.personal.psu.edu/faculty/c/x/cxc11/AERSP560/DELAUNEY/13_Two_algorithms_Delauney.pdf">two main approaches</a> to Delaunay triangulation. One is <em>divide-and-conquer</em>, where you recursively divide your input point cloud into two halves, triangulate each, and merge the results while maintaining the Delaunay property mentioned above. The other is <em>incremental insertion</em>, where you add one point at a time to the result and update the affected part so that the property is intact.</p><p>Especially, <a href="https://en.wikipedia.org/wiki/Bowyer%E2%80%93Watson_algorithm">Bowyer-Watson algorithm</a>, which belongs to the latter approach, looked conceptually simple and appealed to me. Another well-known incremental algorithm is using <a href="https://en.wikipedia.org/wiki/Delaunay_triangulation#Flip_algorithms">flipping</a> to fix triangles that each insertion invalidated. A naive implementation of it has quadratic time complexity because you need to scan through potentially all generated triangles to find invalidated ones for each insertion. So, it becomes a key for its optimization to come up with a way to quickly find those triangles. <a href="https://en.wikipedia.org/wiki/Bowyer%E2%80%93Watson_algorithm">Its Wikipedia page</a> mentions <em>Hilbert curve</em> as a way to achieve it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*R0tMs8nkUV8inL_79Ky2Rg.gif" /><figcaption>First 7 iterations of Hilbert curve: <a href="https://wolfr.am/mZfUayRO">https://wolfr.am/mZfUayRO</a></figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Hilbert_curve">Hilbert curve</a> is a continuous fractal space-filling curve. It’s perfect to incrementally fill 2-dimensional unit square (or any n-dimensional hypercube, for that matter) while maximizing spatial locality. The idea is using Hilbert curve to presort points. Once sorted, you can quickly find a triangle invalidated, by searching from the end of the generated triangle list, because a culprit is very likely to be among recently generated triangles due to the spatial locality. You can quickly extend the search to find all invalid triangles using adjacency info once you find one.</p><p>There are multiple ways to store adjacency info (or <a href="https://en.wikipedia.org/wiki/Boundary_representation">b-rep</a>, short for <em>boundary representation</em>) of a triangular mesh. <a href="http://www.flipcode.com/archives/The_Half-Edge_Data_Structure.shtml">Half-edge data structure</a> is a well-known one. I used tricks introduced in <a href="http://dtecta.com/files/GDC17_VanDenBergen_Gino_Brep_Triangle_Meshes.pdf">a GDC talk</a>, whose main idea is to ingeniously overlap its triangle array with its edge array in memory to minimize memory usage / allocation and maximize cache coherence. You end up having some extra space in the triangle struct (Face struct in the lined slides) with that scheme. I saved the triangle’s circumcenter info there because it was of right size and it’s a good optimization to memoize it. The algorithm requires a lot of point-in-circumcircle checks. It would have been ideal if it were possible to save circumradius there, too. Unfortunately there was not enough space for it. I ended up memoizing them in a separate table because doing it still gave a meaningful performance boost.</p><p>I originally didn’t put any optimization effort other than combining the main ideas of Bowyer-Watson + Hilbert curve sort + an optimized B-Rep. When I benchmarked it against a commercial library called <a href="http://www.geom.at/fade2d/html/">Fade2D</a>, which provides precompiled binaries for evaluation, I found my implementation is about ten times slower. I don’t know what approach it’s using. It’s likely to be a divide-and-conquer one given that <a href="https://en.wikipedia.org/wiki/Delaunay_triangulation">the Wikipedia page</a> notes it “has been shown to be the fastest DT generation technique”. I applied some obvious optimizations (while fixing some bugs) and managed to optimize it 2~3x. I ran the algorithms over a given number of random points (from 100,000 to 1000,000) in a square. Followings are some results from my not-very-scientific profiling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*gm_LwwKagMKqqCZV0VOb1g.png" /><figcaption>X axis is a number of points and Y axis is times taken in seconds.</figcaption></figure><p>You can see that both show linear time complexity, which is much nicer than the expected quadratic complexity. My implementation is 3x slower overall, though. Presorting by Hilbert curve is definitely being of help for my implementation because, for instance, it took 17s for 10,000 and 71s for 20,000 without it. A part of me wanted to further optimize it, but I had other things to tackle and it was already fast enough for my use cases, so I gave up.</p><p>Each technique I applied is conceptually simple, but, the devil is in the detail. You need to be careful to get every bit right. What follows is a pseudo code of my implementation for Hilbert curve sort:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fdcf43d13119a25297114580c70b28c/href">https://medium.com/media/7fdcf43d13119a25297114580c70b28c/href</a></iframe><p>And one for Bowyer-Watson DT algorithm:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/346c5a5e4722b6affba87593d18c3c16/href">https://medium.com/media/346c5a5e4722b6affba87593d18c3c16/href</a></iframe><p>For the super-triangle mentioned above, I used a triangle encompassing the region as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*tCW4ctQ_gAiLZQP3RKKc4Q.png" /><figcaption>super-triangle over bounding rectangle</figcaption></figure><p>One more thing to note: You need to check boundary cases of edges that don’t have opposing edges (i.e. boundary edges) when you traverse through a triangulated mesh’s b-rep. A nice trick to avoid such a special case handling is using <em>ghost triangles</em>, which are triangles consisting of a boundary edge and the point at infinity as mentioned in <a href="http://www.cs.cmu.edu/~quake/tripaper/triangle2.html">this</a> and <a href="http://www.redblobgames.com/x/1722-b-rep-triangle-meshes/">this</a>. Also, keep in mind that duplicate points are problematic because they can cause a catastrophic failure of the algorithm. You can either prefilter them or skip as your DT algorithm progresses.</p><p><em>Update</em> (Aug 4, 2017): Added a wonderful (as usual) explanation of Hilbert curve by <a href="https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw">3Blue1Brown</a> as reference #15 below</p><h3>References</h3><ol><li>Delaunay triangulation — Wikipedia: <a href="https://en.wikipedia.org/wiki/Delaunay_triangulation">https://en.wikipedia.org/wiki/Delaunay_triangulation</a></li><li>Circumscribed circle — Wikipedia: <a href="https://en.wikipedia.org/wiki/Circumscribed_circle">https://en.wikipedia.org/wiki/Circumscribed_circle</a></li><li>Two Algorithms for Constructing a Delaunay Triangulation: <a href="http://www.personal.psu.edu/faculty/c/x/cxc11/AERSP560/DELAUNEY/13_Two_algorithms_Delauney.pdf">http://www.personal.psu.edu/faculty/c/x/cxc11/AERSP560/DELAUNEY/13_Two_algorithms_Delauney.pdf</a></li><li>Bowyer-Watson algorithm — Wikipedia: <a href="https://en.wikipedia.org/wiki/Bowyer%E2%80%93Watson_algorithm">https://en.wikipedia.org/wiki/Bowyer%E2%80%93Watson_algorithm</a></li><li>Hilbert curve — Wikipedia: <a href="https://en.wikipedia.org/wiki/Hilbert_curve">https://en.wikipedia.org/wiki/Hilbert_curve</a></li><li>Space-filling curve — Wikipedia: <a href="https://en.wikipedia.org/wiki/Space-filling_curve">https://en.wikipedia.org/wiki/Space-filling_curve</a></li><li>Boundary representation — Wikipedia: <a href="https://en.wikipedia.org/wiki/Boundary_representation">https://en.wikipedia.org/wiki/Boundary_representation</a></li><li>The Half-Edge Data Structure — flipcode: <a href="http://www.flipcode.com/archives/The_Half-Edge_Data_Structure.shtml">http://www.flipcode.com/archives/The_Half-Edge_Data_Structure.shtml</a></li><li>B-rep for Triangle Meshes — Gino van den Bergen’s GDC 2017 talk: <a href="http://dtecta.com/files/GDC17_VanDenBergen_Gino_Brep_Triangle_Meshes.pdf">http://dtecta.com/files/GDC17_VanDenBergen_Gino_Brep_Triangle_Meshes.pdf</a></li><li>Fade2D: <a href="http://www.geom.at/fade2d/html/">http://www.geom.at/fade2d/html/</a></li><li>Triangulation Algorithms and Data Structures: <a href="http://www.cs.cmu.edu/%7Equake/tripaper/triangle2.html">http://www.cs.cmu.edu/~quake/tripaper/triangle2.html</a></li><li>Data structure for triangle meshes — Red Blob Games: <a href="http://www.redblobgames.com/x/1722-b-rep-triangle-meshes/">http://www.redblobgames.com/x/1722-b-rep-triangle-meshes/</a></li><li>Counting sort — Wikipedia: <a href="https://en.wikipedia.org/wiki/Counting_sort">https://en.wikipedia.org/wiki/Counting_sort</a></li><li>alpha-shapes aka concave hulls in d3: <a href="http://bl.ocks.org/gka/1552725">http://bl.ocks.org/gka/1552725</a></li><li>Hilbert’s Curve: Is infinite math useful?: <a href="https://www.youtube.com/watch?v=3s7h2MHQtxc">https://www.youtube.com/watch?v=3s7h2MHQtxc</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3ee77959773" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to compute the length of a spline]]></title>
            <link>https://medium.com/@all2one/how-to-compute-the-length-of-a-spline-e44f5f04c40?source=rss-cc8601a8e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e44f5f04c40</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spline]]></category>
            <category><![CDATA[gaussian-quadrature]]></category>
            <category><![CDATA[spline-length]]></category>
            <dc:creator><![CDATA[jj]]></dc:creator>
            <pubDate>Sat, 06 May 2017 01:34:40 GMT</pubDate>
            <atom:updated>2017-05-06T01:34:40.677Z</atom:updated>
            <content:encoded><![CDATA[<p>I needed to calculate the length of a <a href="https://en.wikipedia.org/wiki/Cubic_Hermite_spline">cubic Hermite spline</a>. A quick googling showed me that there is no “closed form” solution. Again, with <a href="https://medium.com/@all2one/computing-offset-curves-for-cubic-splines-d3f968e5a2e0">anything related to spline or Bézier curves</a>, <a href="https://pomax.github.io/bezierinfo/#arclength">this primer</a> is the go-to resource. You can resort to calculus and try to get the length by integrating the velocity across the curve, but even for quadratic curves, the integral becomes hairy enough so that <a href="http://www.wolframalpha.com/input/?i=antiderivative+for+sqrt((2*(1-t)*t*B+%2B+t%5E2*C)%27%5E2+%2B+(2*(1-t)*t*E)%27%5E2)&amp;incParTime=true">WolframAlpha nags you to retry with ‘Pro’ computation time</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYWCUnptDOaHdVng7gWlJg.png" /></figure><p>There is a rough calculation you can use called <em>chorded approximation</em>, where you emulate the original curve with piece-wise linear segments. Given a parametric curve <em>f(t) </em>with its parameter <em>t</em> ranging from 0 to 1, it’s basically calculating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*hFMhA6izfN9o_GCgDGPOXg@2x.png" /></figure><p>The bigger the <em>n</em>, the more accurate the result will become and the slower the execution. At first, I implemented this approach and it worked well enough for my use case. Splines’ length data was needed at an export time and the performance wasn’t really a concern. Still, I wanted to learn more about what alternatives mathematics can provide and that’s how I learned <a href="https://en.wikipedia.org/wiki/Gaussian_quadrature"><em>Gaussian quadature</em> (or <em>Legendre-Gauss quadrature</em>)</a>.</p><p>The idea originates from the same idea of the aforementioned velocity integration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/108/1*qeKXPJoIvjRCZhEq-8vvpA@2x.png" /></figure><p>You can utilize one of numerical integration methods, for instance, like doing the sum of discrete intervals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*pSfm2-RUu8gewST3brlXHg@2x.png" /></figure><p>It’s basically approximating the area under the curve with the sum of the rectangles like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qULv-LPOdvDfH3i2SLa7xA.png" /></figure><p>You can be a little more clever and use the mid-point of the interval instead:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*YkXtzTNQiS2gb-n_S7J2sA@2x.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LssRhftYXpkYegMbsFouCw.png" /></figure><p>Or trapezoids instead of rectangles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*y3-_R9gyCyq2N3wpiRreww@2x.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hJJmS5ctScyEt01Tvhjvg.png" /></figure><p>These concepts and how Gaussian quadrature improves upon them is well explained in this short youtube video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fk-yUdqRXijo%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dk-yUdqRXijo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fk-yUdqRXijo%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e664a3aa5f269679c5d3f8b4034a4a78/href">https://medium.com/media/e664a3aa5f269679c5d3f8b4034a4a78/href</a></iframe><p>If you see the formulas above, you notice they are all of the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*WTdCLI9eBN7W18LM3Z3NRQ@2x.png" /></figure><p>Given <em>n</em> uniformly divided intervals, you basically have <em>n</em> degrees of freedom in choosing <em>wi’</em>s, where <em>0 ≤ i ≤ n-1</em>. The gist of Gaussian quadrature is varying <em>xi</em>’s, too, instead of just using uniform intervals, on top of varying <em>wi</em>’s, to maximize the degree of freedom. With <em>n</em> points, you now have <em>2n</em> degrees of freedom instead of <em>n</em>. Let’s say <em>f(x)</em> is a polynomial of degree <em>m</em>. From its <em>(m+1)</em> polynomial bases, ranging from the constant term to the <em>m</em>-th order term, we get <em>(m+1)</em> equations to satisfy, if you think of the situation as a system of linear equations. The set-up is basically <em>2n</em> unknowns with <em>(m+1)</em> equations. Let <em>2n = m+1</em> and you get to the fact that, with <em>n</em>-point Gaussian quadrature, you can cleverly choose <em>xi</em>’s and <em>wi</em>’s so that it can yield an exact result for polynomials of degree <em>m(=2n-1)</em> or less.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*yUBK4nFlPUPfVT4COsvXBg.png" /><figcaption>This image I copied from the Wikipedia article demonstrates 2-point Gaussian quadrature. With carefully chosen x0 and x1 and associated weights, it gives a much better result than the trapezoid integration, which is indicated by ‘Trap’ above, (or rather the exact result due to the fact that the sum of two red areas is equal to the green area) for this 3rd order curve.</figcaption></figure><p>All these ideas and how you can derive those concrete values for <em>xi</em>, <em>wi</em> yourself to satisfy the aforementioned conditions (rather than resorting to numerous precalculated tables available on the internet), you can check another very helpful youtube video I found:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuxQCjeo955o%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuxQCjeo955o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuxQCjeo955o%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e4b3ef5b2720b01c06d6dab160f9b79/href">https://medium.com/media/0e4b3ef5b2720b01c06d6dab160f9b79/href</a></iframe><p>Does this mean Gaussian quadrature can produce an exact result for cubic splines? No, because the velocity you need to integrate in 2D or 3D space are no longer polynomials. It’s either:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*d4A9n1DSM0f_137ebYwcHA@2x.png" /><figcaption>2D</figcaption></figure><p>or:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*uNMefW0FI2F2B7DeFgCDYQ@2x.png" /><figcaption>3D</figcaption></figure><p>Also note that Gaussian quadrature is explained and derived with the interval of [-1, 1], but you can easily change the interval to something like [0, 1] to get the length of an entire spline segment or any interval like [a, b] for that matter to get the length of a sub-segment. Refer to the wikipedia article (or the last part of Wen Shen’s video) for the details.</p><p>By the way, <a href="https://www.unrealengine.com/what-is-unreal-engine-4">UnrealEngine 4</a> seems to be using 5-point Gaussian quadrature for its spline length calculation. Here is a C++ code snippet implementing it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f58b655d69347e200397eacb7a7e5dc/href">https://medium.com/media/4f58b655d69347e200397eacb7a7e5dc/href</a></iframe><h3>References</h3><ol><li>A Primer on Bézier Curves — 22. Arc length: <a href="https://pomax.github.io/bezierinfo/#arclength">https://pomax.github.io/bezierinfo/#arclength</a></li><li>Finding the Length of a Bezier Cubic Spline and its Subdivisions (pdf): <a href="http://www.tinaja.com/glib/nubzlen1.pdf">http://www.tinaja.com/glib/nubzlen1.pdf</a></li><li>Gaussian quadrature — Wikipedia: <a href="https://en.wikipedia.org/wiki/Gaussian_quadrature">https://en.wikipedia.org/wiki/Gaussian_quadrature</a></li><li>Linear Algebra 1b: Magic of Gaussian Quadrature — A Billion Times Better than the Next Best Thing: <a href="https://youtu.be/k-yUdqRXijo">https://youtu.be/k-yUdqRXijo</a></li><li>CMPSC/Math 451. Feb 25, 2015. Gaussian Quadrature. Wen Shen: <a href="https://youtu.be/uxQCjeo955o">https://youtu.be/uxQCjeo955o</a></li><li>How to write mathematics on Medium: <a href="https://medium.com/@tylerneylon/how-to-write-mathematics-on-medium-f89aa45c42a0">https://medium.com/@tylerneylon/how-to-write-mathematics-on-medium-f89aa45c42a0</a></li><li>A web tool used to generate LaTex math images in this post: <a href="https://www.codecogs.com/latex/eqneditor.php">https://www.codecogs.com/latex/eqneditor.php</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e44f5f04c40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computing Offset Curves for Cubic Splines]]></title>
            <link>https://medium.com/@all2one/computing-offset-curves-for-cubic-splines-d3f968e5a2e0?source=rss-cc8601a8e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3f968e5a2e0</guid>
            <category><![CDATA[parallel-curves]]></category>
            <category><![CDATA[offset-curves]]></category>
            <category><![CDATA[stroking]]></category>
            <category><![CDATA[bezier]]></category>
            <category><![CDATA[spline]]></category>
            <dc:creator><![CDATA[jj]]></dc:creator>
            <pubDate>Sun, 09 Apr 2017 00:56:31 GMT</pubDate>
            <atom:updated>2017-04-10T18:17:04.163Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently had to come up with a way to create parallel curves from <a href="https://en.wikipedia.org/wiki/Cubic_Hermite_spline">cubic Hermite splines</a>, like railroad lanes. At first, I just displaced their start/end control points along their normal directions, while keeping the same start/end tangents. It worked fine for most cases because most splines in my use cases are not very curved.</p><p>But I soon discovered curves replicated in such a naive way often result in narrowing even with some mildly curved splines. So, I decided to bite the bullet and looked into what other intelligent people have already figured out on it by googling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*VI-l69_9_6237abJNpN3Ng.png" /><figcaption>Narrowing from the naive approach</figcaption></figure><p>I quickly learned that an official term for such a curve is <em>offset curve</em> or <em>parallel curve</em>. The first approach I bumped into was to convert a curve into a poly-line, offset the poly-line, and then reconstruct it into a curve or curves: <a href="http://stackoverflow.com/a/3220819/900762">http://stackoverflow.com/a/3220819/900762</a>. It sounded complicated and I wanted to find a more direct approach where I don’t need to go through the poly-line phase.</p><p>The next approach I found was offsetting its control polygon (<a href="http://math.stackexchange.com/a/467038">http://math.stackexchange.com/a/467038</a> and <a href="http://brunoimbrizi.com/unbox/2015/03/offset-curve/).">http://brunoimbrizi.com/unbox/2015/03/offset-curve</a>). You can easily convert cubic Hermite splines to Bézier curves as <a href="http://www.joshbarczak.com/blog/?p=730">http://www.joshbarczak.com/blog/?p=730</a> explains. In a Bézier form, you get a control polygon from four control points. You can offset it as below and get an offset spline from it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*FvxC_jQ5gLQI8710jFPVvQ.jpeg" /><figcaption>An image from <a href="http://math.stackexchange.com/a/467038">http://math.stackexchange.com/a/467038</a></figcaption></figure><p>As both of the links above mention, the approach won’t work for curves with high curvatures and you need to split the original curve to multiple segments to get a better result in such cases. I didn’t think splitting / subdividing would be necessary for my use cases and decided to give the approach a try.</p><p>I had 3D splines, so I used the distance equation between skewed lines like <a href="http://2000clicks.com/mathhelp/GeometryPointsAndLines3D.aspx">http://2000clicks.com/mathhelp/GeometryPointsAndLines3D.aspx</a> to get intersections between offsetted edges of the control polygon. My splines also have just one tangent for each control point. In other words, no separate incoming / outgoing tangents. So, once I calculate offset splines for neighboring segments, I set the tangent of the shared control point to an average of the end tangent of the first segment and the start tangent of the second segment.</p><p>The approach provided parallel curves looking good enough for the most splines I have. But offset curves for some went bananas when their tangents are long and their control polygons self-intersect. Also, for some other cases, they kind of overcompensated and got wider than they should be. So, I introduced some tweaks like falling back to the naive way when internal angles of the control polygon are too acute and <em>lerp</em>ing between the results of the naive and this approach based on the cosines of the internal angles to avoid becoming too wide in some cases. There were still some rare cases this tweaked approach fails. For them, I could have applied splitting before this approach, but, for now, I decided to manually modify the original splines so that they can behave better with the approach without an automatic splitting. I think having a single tangent per control point (no separate incoming / outgoing tangents) also made some of these cases worse than it could be.</p><p>As you can see, it wasn’t totally satisfactory. It required some not-so-clean tweaks and still could not handle all cases. I dug some more in my spare time and found out some useful info and more approaches worth trying in the future. This archived PDF document <a href="http://web.archive.org/web/20061202151511/http://www.fho-emden.de/~hoffmann/bezier18122002.pdf">http://web.archive.org/web/20061202151511/http://www.fho-emden.de/~hoffmann/bezier18122002.pdf</a> explains getting Bézier offset curves by solving a system of three linear equations, starting from the page 34. It starts with the naive approach and compute how the resulting curve should be modified to satisfy the properties of an ideal offset curve by solving a system of linear equations with three unknowns. The approach also has some failure cases and the document explains a way to handle them by fixing one of the unknowns and just using two linear equations. It has sample code in Postscript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*oIjj1-A3X8pS370Ylk81Iw.png" /><figcaption>Captured from <a href="http://web.archive.org/web/20061202151511/http://www.fho-emden.de/~hoffmann/bezier18122002.pdf">http://web.archive.org/web/20061202151511/http://www.fho-emden.de/~hoffmann/bezier18122002.pdf</a></figcaption></figure><p>Many references tell you that, in general, one cannot express offset curves of a Bézier curve using another Bézier curve (or any polynomial parametric curve, for that matter, regardless of however higher-order you are willing to go). Page 28 of <a href="https://www.slideshare.net/Mark_Kilgard/22pathrender">https://www.slideshare.net/Mark_Kilgard/22pathrender</a> also says that an offset curve of an arbitrary cubic curve requires a 10th-order <a href="https://en.wikipedia.org/wiki/Algebraic_curve"><em>algebraic</em> curve</a>. A very nice and detailed primer on Bézier curves at <a href="https://pomax.github.io/bezierinfo/">https://pomax.github.io/bezierinfo/</a> has all sorts of useful info about them, with interactive and visual guides. <a href="https://pomax.github.io/bezierinfo/#offsetting">Its section for offset curves</a> explains another approach that involves splitting. With it, you “chop up a curve into ‘safe’ sub-curves (where safe means that all the control points are always on a single side of the baseline, and the midpoint of the curve at t=0.5 is roughly in the centre of the polygon defined by the curve coordinates) and then point-scale each sub-curve with respect to its scaling origin (which is the intersection of the point normals at the start and end points).” It has all the relevant codes in <a href="https://pomax.github.io/bezierjs/">https://pomax.github.io/bezierjs/</a>, so you can easily check its implementation details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*1SOZmtHtJ4iRyTN0iZpgNA.png" /><figcaption>Captured from <a href="https://pomax.github.io/bezierinfo/#offsetting">https://pomax.github.io/bezierinfo/#offsetting</a></figcaption></figure><p>The two alternatives mentioned above sound sensible and look not too hard to implement. I’m going to try them when the current approach of offsetting the control polygon becomes too fragile and cumbersome for my use cases.</p><p>This short research of mine was quite a fun and educational ride for me and demonstrated nuances and intricacies involved in a seemingly simple question of how you can get <em>parallel</em> versions of a spline curve. I hope it has be a fun and of help to you, too!</p><h3>References</h3><ol><li>Cubic Hermite spline: <a href="https://en.wikipedia.org/wiki/Cubic_Hermite_spline">https://en.wikipedia.org/wiki/Cubic_Hermite_spline</a></li><li>bezier path widening: <a href="http://stackoverflow.com/a/3220819/900762">http://stackoverflow.com/a/3220819/900762</a></li><li>Control points of offset bezier curve: <a href="http://math.stackexchange.com/a/467038">http://math.stackexchange.com/a/467038</a></li><li>How to Draw an Offset Curve: <a href="http://brunoimbrizi.com/unbox/2015/03/offset-curve/">http://brunoimbrizi.com/unbox/2015/03/offset-curve/</a></li><li>Splines Are Just Obfuscated Beziers: <a href="http://www.joshbarczak.com/blog/?p=730">http://www.joshbarczak.com/blog/?p=730</a></li><li>Equation of Lines in 3D — distance between two skew lines, and closest points: <a href="http://2000clicks.com/mathhelp/GeometryPointsAndLines3D.aspx">http://2000clicks.com/mathhelp/GeometryPointsAndLines3D.aspx</a></li><li>Bézier Curves by Gernot Hoffmann: <a href="http://web.archive.org/web/20061202151511/http://www.fho-emden.de/~hoffmann/bezier18122002.pdf">http://web.archive.org/web/20061202151511/http://www.fho-emden.de/~hoffmann/bezier18122002.pdf</a></li><li>CS 354 Vector Graphics &amp; Path Rendering: <a href="https://www.slideshare.net/Mark_Kilgard/22pathrender">https://www.slideshare.net/Mark_Kilgard/22pathrender</a></li><li>Algebraic curve: <a href="https://en.wikipedia.org/wiki/Algebraic_curve">https://en.wikipedia.org/wiki/Algebraic_curve</a></li><li>A Primer on Bézier Curves: <a href="https://pomax.github.io/bezierinfo/">https://pomax.github.io/bezierinfo/</a></li><li>A Primer on Bézier Curves | Curve offsetting: <a href="https://pomax.github.io/bezierinfo/#offsetting">https://pomax.github.io/bezierinfo/#offsetting</a></li><li>Bezier.js: <a href="https://pomax.github.io/bezierjs/">https://pomax.github.io/bezierjs/</a></li><li>A StackOverflow entry at <a href="http://stackoverflow.com/questions/4148831/how-to-offset-a-cubic-bezier-curve">http://stackoverflow.com/questions/4148831/how-to-offset-a-cubic-bezier-curve</a> has some more useful links.</li><li>Parallel curve: <a href="https://en.wikipedia.org/wiki/Parallel_curve">https://en.wikipedia.org/wiki/Parallel_curve</a></li><li>Offsets (a.k.a stroking) of Bézier curves: <a href="https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Offsets_.28a.k.a._stroking.29_of_B.C3.A9zier_curves">https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Offsets_.28a.k.a._stroking.29_of_B.C3.A9zier_curves</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3f968e5a2e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From C++ to Erlang]]></title>
            <link>https://medium.com/@all2one/from-c-to-erlang-eea8f10117db?source=rss-cc8601a8e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea8f10117db</guid>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[jj]]></dc:creator>
            <pubDate>Wed, 27 Apr 2016 20:28:38 GMT</pubDate>
            <atom:updated>2016-04-27T20:36:42.907Z</atom:updated>
            <content:encoded><![CDATA[<p>As a game developer, I used to work on the client-side of games, especially low-level engine programming, graphics/rendering and animation, mostly with C++. More than a decade of coding in C++. Through some unexpected turns of events and due to my interest in functional programming languages in general, I recently moved into a team working on game’s chat system in Erlang. My favorite is Haskell when it comes to functional languages, but there was no team using it at my current employer.</p><p>It was a big change, not just in the language, but also in development environment (from Windows to Mac) and tech stack (from developing applications to run on players’ machine to creating back-end software for distributed nodes). Now it’s been about four months since the switch and I have now become more or less familiar with the language itself and associated tech stack for distributed computing like <a href="https://aws.amazon.com/">AWS</a>, <a href="https://www.terraform.io/">Terraform</a> and others we’ve been using (to a lesser degree). I also been to <a href="http://www.erlang-factory.com/sfbay2016">Erlang Factory SF 2016</a> last March, which was a good opportunity to feel the vibe of Erlang community. Here I’d like to share my personal and subjective impressions on the language so far.</p><h4>Basic facts</h4><p><a href="https://en.wikipedia.org/wiki/Erlang_%28programming_language%29">Erlang</a> is a dynamically typed functional languages with its own virtual machine, well-suited for concurrent and fault-tolerant systems. It started as a language (and associated middleware/libraries called OTP, which represents for <em>Open Telecom Platform</em>) for telephony systems. You can see why Erlang can be adept at distribution and fault-tolerance from its origin.</p><h4>Quirky syntax</h4><p>The language was originally implemented in <a href="http://erlang.org/faq/academic.html">Prolog</a> and its influence still remains in its rather strange syntax (especially to programmers from C-style languages). ‘<strong>,</strong>’ is used to separate a sequence of statements (‘<strong>.</strong>’ designates the end of the sequence) and ‘<strong>;</strong>’ represents each case of <em>pattern matching</em> (further discussed below). <a href="http://stackoverflow.com/questions/6025132/when-to-prefer-and-over-andalso-in-guard-tests">The comma also can mean logical AND, and the semicolon can act as logical OR.</a> One of the weirdest things is its less-than comparison operator, which is ‘<strong>=&lt;</strong>’ rather than ‘<strong>&lt;=</strong>’. Admittedly, all these don’t really matter once you get used to the language.</p><p>Another thing I found peculiar at first was <a href="https://erlangcentral.org/wiki/index.php/Atom">its <em>atom</em> type</a>. You can think of it as run-time managed hashed string literals. It’s versatile and you can use it as any of enum, error code, variant tag, or whatnot.</p><h4>Loads of processes</h4><p>Erlang’s advantage for concurrency and distribution comes mainly from its lightweight processes and message passing, based on <a href="https://en.wikipedia.org/wiki/Actor_model">Actor model</a> or <a href="https://en.wikipedia.org/wiki/Communicating_sequential_processes">CSP</a>. It took some time for me to acquaint myself with thinking in terms of multiple processes communicating with each other through message queues, when designing a program. Another interesting approach coming from this is its <a href="http://c2.com/cgi/wiki?LetItCrash"><em>Let It Crash</em></a> philosophy. Instead of trying to prevent all potential crashes (even ones very rarely happening in production) from ever happening, it says just let the offending process crash and restart it from scratch (as long as it doesn’t adversely affect other running processes.) Erlang/OTP supports such a crash-then-restart strategy through <a href="http://learnyousomeerlang.com/supervisors">supervision trees and process monitoring/linking</a>. As a programmer mainly worked in native/low-level languages, where any crash is a big no-no, this approach is still quite alien to me, to be honest. I can see its point, though. No software (or hardware for that matter) will be entirely perfect (bug-free) and sometimes it can make more sense (and cost-effective) to make the system more tolerant to such rare crashes rather than trying to make it 100% crash(or bug)-free.</p><h4>Immutability and pattern matching</h4><p>Variables in Erlang are not your usual variables. You cannot reassign them because they are immutable. The initial assignment to a variable is thus called <em>binding</em>. Once bound, its value cannot be changed. It’s beneficial to check a flow of data and where modification happens. But I notes that I often need to come up with a sequence of variable names like State, State2, State3 to circumvent the limitation, even when I’m certain the ‘State’ won’t change from the specific chain of calls, where each call gets the ‘State’ as an input and returns a potentially modified ‘State’ (Apparently someone made a solution for this by using <a href="http://www.erlang-factory.com/upload/presentations/521/yrashk_parse_transformations_sf12.pdf"><em>parse transform</em>, Erlang’s metaprogramming facility</a>. Not sure if the situation warrants such a heavy-duty solution, though.)</p><p>Pattern matching is another feature you’d better get used to. It would be an unfamiliar thing to C++ programmers (C++ templates have a sort of pattern matching behavior and there has been <a href="http://www.stroustrup.com/OpenPatternMatching.pdf">an attempt</a> to add the feature to the language, though.) Let’s look at some examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fa972f5c78413e7a1a926539783e51e/href">https://medium.com/media/4fa972f5c78413e7a1a926539783e51e/href</a></iframe><p>My old habit as a C++ programmer makes me to write a code like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8385a5b2cf1ad5c6ba1a1abd34d15d5a/href">https://medium.com/media/8385a5b2cf1ad5c6ba1a1abd34d15d5a/href</a></iframe><p>But, it’s more erlang-ly to use the pattern matching like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e52dd20ad6f2fee4764fd251d0cc018d/href">https://medium.com/media/e52dd20ad6f2fee4764fd251d0cc018d/href</a></iframe><p>First of all, getting the length of a list is <em>O(n)</em>, which is not really necessary in this code. Pattern matching provides more efficient and arguably more readable implementation.</p><h4>Success typing</h4><p>As someone who prefers static typing, especially a powerful one like one provided by Haskell, Erlang’s dynamic typing is a pet peeve of mine, to say the least. To prevent some silly (but deadly) mistakes coming from the lack of type checking, Erlang supports a type checking based on annotations and something called <a href="https://www.it.uu.se/research/group/hipe/papers/succ_types.pdf"><em>success typing</em></a>. It’s not perfect and sometimes gives you inscrutable error messages, like the ones you can encounter while doing C++ template metaprogramming. Nevertheless it helps in many cases and my team has been actively using it.</p><h4>A new kid on the block, Elixir</h4><p>As I noted, Erlang is a vm-based language, which means there can be other languages running on the same virtual machine. <a href="http://lfe.io/">LFE</a> (List-Flavored Erlang) and <a href="http://elixir-lang.org/">Elixir</a> are good examples. The latter is gaining traction recently among Ruby developers. It’s boasting Ruby-like syntax and a powerful macro system and positioning itself as a Ruby(and Ruby-On-Rails) alternative.</p><h4>Users and community</h4><p>So, who the hell are actually using this obscure language in production, you might ask. There are a few, some of which you may even be quite familiar with. <a href="https://www.whatsapp.com/"><em>WhatsApp</em></a>, a popularmobile messenger app (now owned by Facebook), is using it. <em>Facebook messenger</em> was also based on Erlang originally, <a href="https://www.quora.com/When-did-Facebook-switch-away-from-using-Erlang-for-Facebook-Chat">although it has been switched to C++ a few years ago</a>. Given its origin, Erlang is a natural fit to such messenger systems. <a href="https://en.wikipedia.org/wiki/Riak"><em>Riak</em></a>, a NoSQL database, is based on Erlang, too. An open-source message broker software, <a href="https://www.rabbitmq.com/"><em>RabbitMQ</em></a>, is another. Some game companies are using Erlang for its back-end servers. Even some purely client-side applications (e.g. <a href="http://www.wings3d.com/">http://www.wings3d.com/</a>, a 3D modeler software) has been written in Erlang.</p><p>The conference I attended, held for two days in San Francisco, was small (if I compare it to something like, you know, <a href="https://medium.com/@all2one/gdc-2015-report-897f9f2f7c09#.lijlrlfdq"><em>Game Developers Conference</em></a> or <a href="https://medium.com/@all2one/siggraph-2015-report-66a9840ee726#.s8h2qii1b"><em>SIGGRAPH</em></a>), around 250 attendance this time, I think. The community seems friendly and inviting, though. It was easy to have a chitchat with a guy who created the language, for instance. Multiple sessions there were quite inspiring, too.</p><p>I hope this write pique your interest in the language, especially if you’re working on a distributed system. As a language geek, I think it’s worth studying Erlang even though you’re not going to use it in production. It has some interesting concepts and approaches, which you can still apply in other languages.</p><h4>Resources for learning Erlang</h4><ul><li>Learn X in Y minutes (where X = Erlang): <a href="https://learnxinyminutes.com/docs/erlang/">https://learnxinyminutes.com/docs/erlang/</a></li><li>How I Start (with Erlang): <a href="https://howistart.org/posts/erlang/1">https://howistart.org/posts/erlang/1</a></li><li>A nice introductory presentation on Erlang: <a href="http://ferd.ca/the-zen-of-erlang.html">http://ferd.ca/the-zen-of-erlang.html</a></li><li>A book, “Learn You Some Erlang” (its online version freely available): <a href="http://learnyousomeerlang.com/content">http://learnyousomeerlang.com/content</a></li><li>An ebook by the same author on not-so-beginner stuff like devops and profiling: <a href="http://www.erlang-in-anger.com/">http://www.erlang-in-anger.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea8f10117db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SIGGRAPH 2015 Report]]></title>
            <link>https://medium.com/@all2one/siggraph-2015-report-66a9840ee726?source=rss-cc8601a8e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/66a9840ee726</guid>
            <category><![CDATA[siggraph-2015]]></category>
            <category><![CDATA[siggraph]]></category>
            <dc:creator><![CDATA[jj]]></dc:creator>
            <pubDate>Wed, 16 Sep 2015 16:50:47 GMT</pubDate>
            <atom:updated>2015-09-16T16:50:47.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*xHUyGSi7Tp1plnYA." /><figcaption>SIGGRAPH 2015 at LA convention center</figcaption></figure><p><a href="http://s2015.siggraph.org/">SIGGRAPH</a>, an international conference and exhibition on computer graphics, was held at LA convention center last month. There were multiple inspiring talks that showed a glimpse of the future of computer graphics. Also, several sessions by game developers illustrated techniques and tricks they had invented to achieve stunning graphics within a time frame of a few milliseconds. I’d like to share here a few of the sessions that struck a chord with my inner geek as a graphic coder.</p><p>(This post contains a lot of real-time graphics jargon and abbreviations. So, its content won’t make much sense if you have not been into the real-time graphics. I hope web articles and papers I linked through the article can be of help to anyone who wants to dig deeper. You can still enjoy images and videos without such knowledge, though. :))</p><h3>Learning from Failure: a Survey of Promising, Unconventional and Mostly Abandoned Renderers for ‘Dreams PS4’, a Geometrically Dense, Painterly UGC Game (<a href="http://media.lolrus.mediamolecule.com/AlexEvans_SIGGRAPH-2015.pdf">pdf</a>)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dhIxqzayJurX7yzw." /><figcaption>One of surreal screenshots that you can savor from the ‘Learning from Failure’ slides</figcaption></figure><p>Alex Evans, a co-founder and Technical Director at<a href="http://www.mediamolecule.com/"> MediaMolecule</a>, creators of <em>LittleBigPlanet</em>, <em>Tearaway</em>, shared his journey to come up with an unconventional renderer for the company’s upcoming title, <em>Dreams</em>. It was four years’ effort with three abandoned attempts, which must have been a valuable experience for the project. He wanted to support<a href="https://en.wikipedia.org/wiki/Constructive_solid_geometry"> CSG (Constructive Solid Geometry)</a> sculpting with<a href="http://bytewrangler.blogspot.com/2011/10/signed-distance-fields.html"> signed distance fields</a> representation. At first, he implemented ‘<strong>the polygon edition</strong>’. He tried to convert the scene to polygons for traditional rendering by using<a href="https://en.wikipedia.org/wiki/Marching_cubes"> marching cubes</a> and some other<a href="https://en.wikipedia.org/wiki/Isosurface"> isosurfaces</a>. But, he had to ditch this because of issues like self-intersection and manifold. Then, inspired by<a href="http://phildec.users.sourceforge.net/Research/VolumetricBillboards.php"> volumetric billboards</a>, which he describes as a spiritual precursor to<a href="http://maverick.inria.fr/Publications/2011/Cra11/"> gigavoxels</a> and<a href="https://research.nvidia.com/publication/efficient-sparse-voxel-octrees"> sparse voxel octrees</a>, he tried a hybrid of it with rasterized gigavoxel cubes. The main advantage of this second try, which he called ‘<strong>the brick engine</strong>’, was its simplicity. Unfortunately, it lacked a prefiltered look, which was his main intention to invent an unconventional renderer with some form of filterable representation for the new game, to begin with.</p><p>‘<strong>The refinement renderer</strong>’ was the third attempt that used froxels, which mean frustum-shaped voxels. You can check such froxels being used in<a href="https://www.shadertoy.com/view/XslGRr"> this small, but neat shadertoy effect</a>, for instance. It initially looked promising and he added some lighting effects by applying<a href="http://www.crytek.com/download/Light_Propagation_Volumes.pdf"> Light Propagation Volumes</a>, a global illumination technique originated from<a href="http://crytek.com/"> Crytek</a>, with froxels. But, it was too slow. A bigger problem was the fact that the rendering result didn’t even look that different from conventional polygon rendering. He named the fourth try, which is going to be used for the final game, ‘<strong>the splats</strong>’. He explained it as <em>a cloud of clouds of point clouds</em>. As you can see from<a href="https://www.youtube.com/watch?v=4j8Wp-sx5K0"> this <em>Dreams</em> video</a>, it seems to enable much more painterly style rendering. He also dabbled with<a href="http://resources.mpi-inf.mpg.de/ImperfectShadowMaps/ISM.pdf"> Imperfect Shadow Maps</a> to get nice and soft shadow for this renderer.</p><p>This journey made many real-time graphics coders (including me) drool and green with envy for his creative freedom at the same time. It was possible due to the lucky combination of his being a co-founder and a coder at once and good track records of his earlier titles, I guess. Undoubtedly, it was a very inspiring talk and I can glimpse into the future when graphics coders all around the world are free from the tyranny of polygons in this talk.</p><h3>The Real-Time Volumetric Cloudscapes of Horizon: Zero Dawn (<a href="http://killzone.dl.playstation.net/killzone/horizonzerodawn/presentations/Siggraph15_Schneider_Real-Time_Volumetric_Cloudscapes_of_Horizon_Zero_Dawn.pptx">pptx</a>)</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbAQpGu29GX4%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbAQpGu29GX4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbAQpGu29GX4%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca5f1cb261b4c8064ad2de37e1d60366/href">https://medium.com/media/ca5f1cb261b4c8064ad2de37e1d60366/href</a></iframe><p>Andrew Schneider at<a href="http://www.guerrilla-games.com/"> Guerrilla Games</a> presented an amazing cloud rendering technique they developed for the studio’s upcoming title,<a href="https://www.youtube.com/watch?v=Fkg5UVTsKCE"> <em>Horizon: Zero Dawn</em></a>. The game features a vast open world with day/night cycle, dynamic weather, and epic scenery. They wanted art-directable, realistic, and evolving clouds for it, much more than what a skybox with nice textures can provide. At first, they experimented with a custom fluid solver to model clouds, but it turned out to be nonintuitive to use. Instead, they chose to use some simple shapes to model them. For a realistic modeling and rendering of clouds, they even researched a book from the 60’s, written by two meteorologists. Once bounded by the simple shapes, cloud’s internal is filled by using<a href="https://en.wikipedia.org/wiki/Worley_noise"> Worley noise</a> layered with<a href="https://en.wikipedia.org/wiki/Perlin_noise"> Perlin</a>, named <strong>Perlin-Worley</strong> noise. They used ray marching for rendering. When it comes to lighting, they wanted to be able to describe three things: directional scattering, silver-lining, and dark edges visible on clouds when you look away from the sun. For these goals, they applied<a href="https://en.wikipedia.org/wiki/Beer%E2%80%93Lambert_law"> Beer’s law</a> and<a href="http://www.cs.dartmouth.edu/%7Ewjarosz/publications/dissertation/chapter4.pdf"> Henyey-Greenstein phase function</a>. They also had to augment Beer’s law with ‘powder effect’ to emulate the dark edges. According to the presenter, emulating the dark edges doesn’t seem to be ever dealt in cloud simulation literature.</p><p>Their early implementation took around 20ms(!) to render. They managed to cut down on this number to 2ms by applying a variety of optimization techniques. Kudos to them for looking deeply into this rather narrow topic of rendering clouds and managing to come up with awesome, but still practical results.</p><h3>Anti-Aliasing: Are We There Yet? (<a href="http://openproblems.realtimerendering.com/Salvi_AA_AreWeThereYet.pptx">pptx</a>)</h3><p>This talk by Marco Salvi at NVIDIA was a part of a SIGGRAPH course named<a href="http://openproblems.realtimerendering.com/"> <em>Open Problems in Real-Time Rendering</em></a>. It summarized the current state of affairs with<a href="https://en.wikipedia.org/wiki/Anti-aliasing"> anti-aliasing</a> in computer graphics. According to him, even though as an industry we have made some tremendous progress in the last few years, “solving”<a href="https://en.wikipedia.org/wiki/Aliasing"> aliasing</a> in real-time applications still remains a distant and elusive goal. He defined <strong>aliasing</strong> as “identity theft” for signals because it’s basically <em>high frequency info disguised as low frequency info</em>. You can usually fix aliasing by throwing more samples (i.e. supersampling) or prefiltering. A poor reconstruction of signals can cause aliasing (post-aliasing), too. How does nature solve this? He argues that evolution gave us optics to filter out high-frequency details that could lead to aliasing. Film industry can afford (and use) per-shot tuning to get rid of any aliasing, but it’s not possible for interactive games. A very well-known prefiltering technique for game developers is<a href="https://en.wikipedia.org/wiki/Mipmap"> mipmapping</a>, but it only works for colors. Prefiltering visibility is really hard and prefiltering code (procedural logic) is even harder. On the other hand, a brute-force supersampling is often impractical. He describes anti-aliasing techniques like<a href="http://www.iryoku.com/mlaa/"> MLAA (Morphological Anti-Aliasing)</a> and<a href="https://en.wikipedia.org/wiki/Fast_approximate_anti-aliasing"> FXAA (Fast Approximate Anti-Aliasing)</a> as <em>hallucinating</em> new samples. It’s because they are trying to cleverly cover up aliasing artifacts rather than solving its root cause. He says that they can be fun when they work, though.<a href="https://de45xmedrsdbp.cloudfront.net/Resources/files/TemporalAA_small-59732822.pdf"> TAA(Temporal Anti-Aliasing)</a> has become everyone’s favorite when it comes to anti-aliasing for 3D games these days. He tells that it helps in generating more stable images.<a href="https://mynameismjp.wordpress.com/2012/10/24/msaa-overview/"> MSAA (Multisample Anti-Aliasing)</a> decouples visibility from shading, but, only works for geometry edges and doesn’t get along well with<a href="https://en.wikipedia.org/wiki/Deferred_shading"> deferred shading</a>. He mentioned one of the latest techniques for deferred renderers,<a href="http://graphics.cs.williams.edu/papers/AggregateI3D15/"> AGAA(Aggregate G-Buffer Anti-Aliasing)</a>.</p><p>Another useful remark of his is “level of detail done right is anti-aliasing.” He concluded with “anti-aliasing is not an algorithm, is a process” because it begins in the content creation pipeline and it ends on your retina. I highly recommend this talk to whoever wants to have a solid foundation for tackling aliasing problems.</p><h3>Other interesting sessions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*qNsr6vmnT9gOYyse." /><figcaption>Vulkan t-shirt I got from one of sessions on the new API</figcaption></figure><p>The first two sessions above are from<a href="http://advances.realtimerendering.com/s2015/index.html"> <em>Advances in Real-Time Rendering in Games</em></a> course. I enjoyed other talks of the course. For instance,<a href="http://advances.realtimerendering.com/s2015/siggraph15_volsampling.pptx"> A Novel Sampling Algorithm for Fast and Stable Real-Time Volume Rendering</a> by Huw Bowles and Daniel Zimmermann at Studio Gobo was a cute talk focused on stable sampling.<a href="http://advances.realtimerendering.com/s2015/DynamicOcclusionWithSignedDistanceFields.ppt"> Dynamic Occlusion with Signed Distance Fields</a> by Daniel Wright at Epic Games was interesting, too. It seems that SDF (Signed Distance Fields) has recently gained lots of traction as main or auxiliary scene representation in games. The result from<a href="http://advances.realtimerendering.com/s2015/Stochastic%20Screen-Space%20Reflections.pptx"> Stochastic Screen-Space Reflections</a> by Tomasz Stachowiak at Frostbite was impressive. Talks in<a href="http://nextgenapis.realtimerendering.com/"> <em>An Overview of Next-Generation Graphics API</em></a> are must-reads if you are interested in those new kids on the graphics API block, like Vulkan, DirectX 12, and Metal.<a href="http://www.readyatdawn.com/"> Ready At Dawn Studios</a>, which recently surprised gaming world with amazing graphics of their recent title,<a href="https://www.youtube.com/watch?v=8CnWazZpMeQ&amp;feature=youtu.be"> The Order: 1886</a>, shared<a href="http://www.readyatdawn.com/ready-at-dawn-siggraph/"> some good tips and tricks of theirs</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*UCpnVVTok7h-Yjh_." /><figcaption>My first SIGGRAPH was 2000… Yes, I’m old.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XHO8SjwZRZqHhB0U." /><figcaption>And I also attended SIGGRAPH 2005, which was held at the exact same venue as this year one.</figcaption></figure><h3>Links</h3><ul><li><a href="http://www.mediamolecule.com/blog/article/siggraph_2015">Learning from Failure: a Survey of Promising, Unconventional and Mostly Abandoned Renderers for ‘Dreams PS4’, a Geometrically Dense, Painterly UGC Game</a></li><li><a href="http://www.guerrilla-games.com/publications.html">The Real-Time Volumetric Cloudscapes of Horizon Zero Dawn</a></li><li><a href="http://advances.realtimerendering.com/s2015/index.html">SIGGRAPH 2015 Course: Advances in Real-Time Rendering in Games</a></li><li><a href="http://nextgenapis.realtimerendering.com/">SIGGRAPH 2015 Course: An Overview of Next-Generation Graphics APIs</a></li><li><a href="http://blog.selfshadow.com/publications/s2015-shading-course/">SIGGRAPH 2015 Course: Physically Based Shading in Theory and Practice</a></li><li><a href="http://openproblems.realtimerendering.com/">SIGGRAPH 2015 Course: Open Problems in Real-Time Rendering</a></li><li><a href="http://readyatdawn.com/ready-at-dawn-siggraph/">Ready At Dawn @ Siggraph</a></li><li><a href="https://community.arm.com/events/1155">SIGGRAPH 2015 Course: Moving Mobile Graphics</a></li><li><a href="http://www.multithreadingandvfx.org/course_notes/">SIGGRAPH 2015 Course: Multithreading and VFX</a></li><li><a href="http://www.nvidia.com/object/siggraph2015-theater.html?mkt_tok=3RkMMJWWfF9wsRolsq3JZKXonjHpfsX56uQqXKGwlMI%2F0ER3fOvrPUfGjI4ET8BgI%2BSLDwEYGJlv6SgFS7XDMa9m1LgKXxM%3D">NVIDIAs Best of GTC Theater at SIGGRAPH</a></li><li><a href="http://www.cse.chalmers.se/%7Eolaolss/main_frame.php?contents=publication&amp;id=efficient_shading_s2015">SIGGRAPH 2015 Course: Real-time Many-light Management and Shadows with Clustered Shading</a></li><li><a href="https://mynameismjp.wordpress.com/2015/08/16/siggraph-2015/">SIGGRAPH FOLLOW-UP: 2015 EDITION</a> (A blog post on SIGGRAPH 2015 by Matt Pettineo at Ready At Dawn Studios)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66a9840ee726" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GDC 2015 Report]]></title>
            <link>https://medium.com/@all2one/gdc-2015-report-897f9f2f7c09?source=rss-cc8601a8e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/897f9f2f7c09</guid>
            <dc:creator><![CDATA[jj]]></dc:creator>
            <pubDate>Tue, 11 Aug 2015 03:06:32 GMT</pubDate>
            <atom:updated>2015-08-11T03:06:32.431Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s that time again. Here I’d like to share my impression for GDC 2015 before my memory further fades away.</p><h3>Virtual Reality</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*8vqe_2GR3bO6PXxe.png" /></figure><p>VR is still trending as more companies venture into this uncharted territory. Valve unveiled its own VR headset, <em>Vive</em>, manufactured by a well-known smart phone maker, HTC. Oculus showed its latest headset model codenamed <em>Crescent Bay</em>. Sony was there to demonstrate its <em>Morpheus</em>, which was revealed at GDC last year. All of them had some nice hardware/software improvements, which brings consumer VR one step closer to the reality. I didn’t bother to line up for long demo queues, but you can still get the glimpse of them in <a href="http://www.reddit.com/r/oculus/comments/2yad4l/the_big_3_a_comparison_of_htc_valve_vive_oculus/">some</a> <a href="http://www.jonolick.com/home/vive-gdc-2015-review">posts</a> by others who did. John Carmack did <a href="http://www.gamesindustry.biz/articles/2015-03-06-watch-john-carmacks-gdc-session-in-full">a keynote about mobile VR</a>, which recently became more important in Oculus’ overall strategy according to him. He said he had mainly worked on <a href="http://www.samsung.com/global/microsite/gearvr/"><em>Gear VR</em></a> stuff since he joined Oculus and he sees a great potential in VR with a smart phone in spite of its relatively weak horsepower compared to its non-portable cousin. AMD and Nvidia apparently had been busy to become a better GPU provider for the brave new VR world. AMD called it <a href="http://www.anandtech.com/show/9043/amds-liquidvr-announced-amd-gets-expanded-vr-headset-functionality">LiquidVR</a>, Nvidia <a href="http://www.reedbeta.com/talks/">VR Direct</a>.</p><h3>Vulkan (a.k.a. glNext)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IRjz3si9O2jLarke.jpg" /></figure><p><a href="https://www.opengl.org/">OpenGL</a>, a de facto standard for cross-platform 3D graphics, finally brought out an entirely new (no baggage of legacy APIs) low-level API, <a href="https://www.khronos.org/vulkan"><em>Vulkan</em></a>, which had previously been codenamed as <em>glNext</em>. Now, the OpenGL camp has its answer for many doubts about the future of OpenGL and can compete with all those new kids on low-level graphics API block, such as Microsoft’s DirectX 12, <a href="https://developer.apple.com/metal/">Apple’s</a> <em>Metal</em>, and <a href="http://www.amd.com/en-us/innovations/software-technologies/technologies-gaming/mantle">AMD’s <em>Mantle</em></a>. Yes, it’s not replacing OpenGL. In other words, OpenGL will exist and continue to be updated as it is now. (OpenGL can &amp; will exist on top of <em>Vulkan</em>, I guess?) As they explicitly admitted (and thanked AMD for that), <a href="https://www.khronos.org/">Khronos Group</a>, a developer/maintainer of several standard media APIs including OpenGL, got inspirations for <em>Vulkan</em> from AMD’s <em>Mantle</em>. Its origin is very clear in (not-yet-finalized) API function names:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/0*vj1tTtJ4AZl4eaxR.png" /></figure><p>It’s built with multi-threading in mind and will require small drivers, which will result in a better driver quality. This means no run-time validation (by default, more on this later), more developer responsibility, including dealing with CPU/GPU synchronization and GPU memory hazards. It’s also architecture-neutral, which means it provides natural APIs even for mobile GPUs’ <a href="http://en.wikipedia.org/wiki/Tiled_rendering">tile-based rendering</a>. It has several great niceties up its sleeve, which can make usually grumpy graphics coders drool:</p><ul><li>An intermediate representation for shading language, <a href="https://www.khronos.org/spir"><em>SPIR-V</em></a></li><li>Layered API: you can enable optional layers between driver and application, such as loader, debug, validation, performance linting, ref counting, thread safety, and trace capture &amp; replay layer. See, you can have your cake (a lean &amp; mean low-level API) and eat it too (still with all the clutches you can use in development)!</li><li>An official SDK will be provided.This is definitely a very exciting news and they say they will deliver a finalized spec around the end of this year.</li></ul><h3>Game engines gone free</h3><blockquote><em>If you take Unreal and Unity, add them together and cancel out the “Un”s, you get REALITY. WOOOOOOOOOAAAAAAAAHHHHHH!</em></blockquote><blockquote><em>— Keith Judge (@KeefJudge) </em><a href="https://twitter.com/KeefJudge/status/575582595670491136"><em>March 11, 2015</em></a></blockquote><p>Following <a href="http://scriptogr.am/jj/post/gdc-2014-report">last year’s tradition</a>, game engine developers announced some exciting news for game developers. It started with Epic Games, announcing <a href="https://www.unrealengine.com/blog/ue4-is-free"><em>Unreal Engine 4</em> is free</a>. Yeah, it’s not entirely free since you should pay a 5% royalty on gross revenue after the first $3,000 per product, per quarter, but still it’s a bold &amp; wise move, I think. Unity hit back with <a href="http://www.rockpapershotgun.com/2015/03/03/unity-5-gdc-2015/">Unity Personal Edition, which is free, with no royalties, and for use for companies with earnings below $100k</a>. Epic Games also revealed its new tech demo, <em>Kite</em>, which you can see above, and <em>Unity 5</em> is also officially out with <a href="http://aras-p.info/texts/files/201503-GDC_Unity5_Graphics_notes.pdf">many cool tricks</a>.</p><h3>Other stuff</h3><p>A bunch of other interesting sessions I was able to attend: <em>Mike Acton</em>, the engine director of Insomniac Games, delivered <a href="http://www.slideshare.net/cellperformance/gdc15-code-clinic">another lecture on data-oriented design</a> in his unique style. <a href="http://www.slideshare.net/cellperformance/gdc15-great-management-of-technical-leads">Another session by him</a> was on the role of tech leads. He mentioned the struggle of green tech leads in balancing the time between coding and non-coding tasks and remarked the issue is moot since your task was problem-solving, not generating code, even when you were just a coder. <a href="http://developers.kongregate.com/blog/dont-call-them-whales-f2p-spenders-and-virtual-value"><em>Don’t Call Them Whales: F2P Spenders and Virtual Value</em></a> gives you a fresh perspective on so called freemium business model and big spenders there, who derogatively called <em>whales</em>. <a href="https://deplinenoise.wordpress.com/2015/03/06/slides-simd-at-insomniac-games-gdc-2015/"><em>SIMD at Insomniac Games</em></a> is another good talk from Insomniac Games on <a href="http://en.wikipedia.org/wiki/SIMD">SIMD</a> programming tips &amp; tricks. <em>Eric Lengyel</em> talked about some small, but interesting math <a href="http://www.terathon.com/gdc15_lengyel.pdf">tips on a better handling of occlusion boxes, oblique near plane trick and others</a> in one of math tutorials. You can find materials for other math tutorial sessions <a href="http://www.essentialmath.com/tutorial.htm">here</a>. A session about <a href="http://en.wikipedia.org/wiki/RGBA_color_space">RGBA color</a> math and another on 1D nonlinear transformations were especially useful to me. A session about an efficient path finding, <a href="http://www.gameaipro.com/Rabin_AISummitGDC2015_JPSPlusGoalBounding.zip">JPS+ now with Goal Bounding: Over 1000x Faster than A*</a>, was quite impressive. JPS represents <a href="http://gamedevelopment.tutsplus.com/tutorials/how-to-speed-up-a-pathfinding-with-the-jump-point-search-algorithm--gamedev-5818"><em>Jump Point Search</em></a> and JPS+ with <em>Goal Bounding</em> could deliver multiple orders of magnitude speed-up over the traditional <a href="http://en.wikipedia.org/wiki/A*_search_algorithm">A*</a>, though there were some requirements to be met like a static map, grids, uniform cost, etc. in order to get the full benefit. DirectX 12 is also taking concrete shape as you can see from a Microsoft talk, <a href="http://channel9.msdn.com/Events/GDC/GDC-2015/Advanced-DirectX12-Graphics-and-Performance"><em>Advanced DirectX12 Graphics and Performance</em></a>.</p><h3>Links</h3><ul><li><a href="http://channel9.msdn.com/Events/GDC/GDC-2015">Microsoft GDC session recordings in Channel 9</a></li><li><a href="http://blogs.wefrag.com/skaven/2015/03/03/gdc-2015-papers/">A collection of GDC slides/videos</a></li><li><a href="http://gsteph.blogspot.co.uk/2015/03/gdc-2015-links.html">Another collection of GDC slides/videos</a></li><li><a href="http://renderingpipeline.com/2015/03/vulkan-links/">Vulkan links</a></li></ul><p><em>Originally published at </em><a href="http://scriptogr.am/jj/post/gdc-2015-report"><em>scriptogr.am</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=897f9f2f7c09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Working Edit and Continue, DynamicPatcher]]></title>
            <link>https://medium.com/@all2one/a-working-edit-and-continue-dynamicpatcher-75c61091f6d?source=rss-cc8601a8e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/75c61091f6d</guid>
            <dc:creator><![CDATA[jj]]></dc:creator>
            <pubDate>Tue, 11 Aug 2015 03:03:41 GMT</pubDate>
            <atom:updated>2015-08-11T03:03:41.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/413/0*h3ypCfBGW3FCFbMO.png" /></figure><p>Iteration time is crucial for coders’ productivity. Unfortunately C++ is notorious for <a href="http://stackoverflow.com/questions/318398/why-does-c-compilation-take-so-long">its long compile/link time</a>. C++ coders had to come up with a bunch of <a href="https://www.incredibuild.com/">tricks</a> and <a href="http://www.reddit.com/comments/1kllhq">workarounds</a> to speed up build time. A language like Go boasts of <a href="http://stackoverflow.com/questions/2976630/why-does-go-compile-so-quickly">its fast compilation as one of its main features</a>. Even the C++ standards committee realized the crisis and started to come up with <a href="http://isocpp.org/files/papers/n4214.pdf">a possible solution</a>. But, even with all the tricks and workarounds, the result is usually a far cry from <a href="http://gamesfromwithin.com/whats-your-pain-threshold">being able to be in a flow with 2-second iteration</a>.</p><p><a href="http://msdn.microsoft.com/en-us/library/esaeyddf.aspx"><em>Edit and Continue</em> (E &amp; C) of Microsoft Visual C++</a> could have been an answer for this, on Windows, at least. No recompile, no need to rerun the program. Alas, only if it worked. It has <a href="http://msdn.microsoft.com/en-us/library/0dbey757.aspx">some limitations from the get-go</a> like no x64 support and incompatibility with an optimized build, still I would have happily used it if it reliably worked in the other cases. With it out of the question, are we at the end of our rope?</p><p>Fortunately not. There are some solutions available, which can be of help to you depending on your exact situation:</p><ul><li><a href="http://root.cern.ch/drupal/content/cling">Cling</a></li><li>LLVM &amp; Clang based C++ interpreter Developed to enable a fast iteration for physicists and other researchers at <a href="http://home.web.cern.ch/">CERN</a> Not usable on Windows, AFAIK</li><li><a href="http://runtimecompiledcplusplus.blogspot.com/">Runtime-Complied C++</a></li><li>A solution created by fellow game developers Separate a part that should be editable to a DLL Rely on serialization to restore the state when the DLL reloaded Simple, robust, and cross-platform This is quite intrusive and separating to a DLL can be cumbersome. <a href="https://www.unrealengine.com/products/unreal-engine-4">Unreal Engine 4</a>&#39;s Hot Reload seems to use a similar technique. Sample code is available <a href="https://github.com/RuntimeCompiledCPlusPlus/RuntimeCompiledCPlusPlus">here</a>. Caveat emptor: I have no hands-on experience of this, so some of the info might not be accurate. [Update 11/3/2014: Doug Binks, an author of RCC++ gave me some clarifications about its working in the comment below.]</li><li><a href="http://www.indefiant.com/">Recode</a></li><li>A commercial solution for Microsoft Visual Studio (MSVC) Support x64 and optimized builds Sparse info, no idea about how it works</li><li><a href="https://github.com/i-saint/DynamicPatcher">DynamicPatcher</a></li><li>An open-source solution with a permissive license At run-time, detect a .cpp file edited, compile it, and load/link a generated .obj file Modify the existing function (in runnable code on memory) that has been edited to <em>jmp</em> to the corresponding function in the recompiled module Only for Windows (and MSVC) Require /Zi (generate debug information) and /MAP (generate map files)</li><li>The latter is not required, but improves speed.</li><li><a href="http://alcantarea-cpp.com/">Alcantarea</a></li><li>A commercial solution for MSVC by the coder who authored DynamicPatcher Basically the same technology as DynamicPatcher, but more accessible &amp; convenient by being a Visual Studio add-in</li></ul><p>The subject of this post is <em>DynamicPatcher</em> as the its title indicates. You can check yourself the nitty-gritty of its implementation in the source code available in its github page, but let me tell you what I think of as its pros &amp; cons:</p><ul><li>Pros</li><li>Support x64 Support optimized code Minimally intrusive (require minimal change/set-up to use, more on this later)</li><li>Cons</li><li>Source code debugging won’t work after patching. Linking step after editing can take some time. Patching functions with function-static objects can be dangerous. Modifying data structure is risky and should be avoided. Not compatible with /LTCG Not compatible with /GR (using RTTI) Support Windows only</li></ul><p>So, what steps should be followed to actually use it on top of an obvious step of linking with the library? You should tell the library which directory it should watch over to detect any editing of source files in it, where .obj files will reside, and what specific build command should be used to compile code. Besides, you should tag a function/method to be modified with a macro called dpPatch, which is just __declspec(dllexport) in disguise. Why is this tagging needed? Because it’s too inefficient &amp; slow to try to relink &amp; patch every function in the new binary every time editing &amp; saving happens.</p><p>I applied this library to a project at work some time ago, but its usage didn’t seem to gain any traction among my coworkers. A seemingly simple step of tagging, which also should be removed before finally submitting the code, made its use rather cumbersome. You usually want to modify something when you’re already in a debug mode and feel some needs to tweak &amp; iterate. Having to tag, recompile, and rerun after the facto to rip the benefit of it was a higher enough barrier to hinder its use. A chance of using it gets lower if you consider that there are other more simpler and less esoteric approaches like introducing a global (or static) variable to toggle some behavior at run-time while debugging, which can be a poor man’s E &amp; C. I myself didn’t use the feature that much except a few cases where I really needed rapid iterations to tune a behavior of some code.</p><p>Recently I had some time to work on it so that I can get rid of as many sources for an excuse not to use it as possible. For instance, I made it already know all the default settings for the project so that other developers don’t need to set them up again in most usages. I also got away with the dpPatch stuff and made it accept a function name from its user instead. In other words, when you edit code, it’s automatically recompiled and the library asks the user about what function to patch when it gets to its linking phase. With these small changes, I myself began to use <em>DynamicPatcher</em> more. It’s still not the ideal sub-2-second iteration, but more like a sub-10-second turnaround, which is a great improvement.</p><p>I think <em>Alcantarea</em> is also using a similar trick to figure out a function to patch. It does this slightly better by detecting a function where the editing cursor is since it’s a VS add-in.</p><p><em>DynamicPatcher</em> isn’t perfect and has its warts as you can see from the cons above. There will be a bunch of corner cases where this kind of run-time patching doesn’t properly work, too. Nonetheless, I think it’s a much more usable alternative to the broken E &amp; C feature of MSVC. <em>Being an open-source is also a great boon</em> and it can be a great resource for anyone who wants to learn how run-time code patching works. In the long run, I hope C++ build time becomes less of an issue with a new module standard or similar. But, even with it, it’s unlikely to reach the 2-second turnaround for a sizable project, to be realistic. Also, the time to rerun the program still remains as a bottleneck, regardless of how fast it builds. So, <strong>E &amp; C solutions like <em>DynamicPatcher</em> will still remain valuable in the future and I hope more solutions come out in this area</strong>.</p><p><em>Originally published at </em><a href="http://scriptogr.am/jj/post/a-working-edit-and-continue-dynamicpatcher"><em>scriptogr.am</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75c61091f6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CppCon 2014 Report (2/2)]]></title>
            <link>https://medium.com/@all2one/cppcon-2014-report-2-2-27f1401aaddb?source=rss-cc8601a8e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/27f1401aaddb</guid>
            <dc:creator><![CDATA[jj]]></dc:creator>
            <pubDate>Tue, 11 Aug 2015 03:01:36 GMT</pubDate>
            <atom:updated>2015-08-11T03:01:36.772Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="http://scriptogr.am/jj/post/cppcon-2014-report-12">Here</a> is the part one. I’ll continue with remaining sessions I’d like to mention in this second part.</p><h3>Parallelism &amp; Concurrency</h3><p><a href="https://github.com/CppCon/CppCon2014/blob/master/Presentations/Overview%20of%20Parallel%20Programming%20in%20C%2B%2B/Overview%20of%20Parallel%20Programming%20in%20C%2B%2B%20-%20Pablo%20Halpern%20-%20CppCon%202014.pptx">Overview of Parallel Programming in C++</a></p><p>This was an introductory talk about C++ parallel programing. The speaker succinctly described the difference between concurrency and parallelism: <em>concurrency</em> is like basketball, focuses on interaction, and makes sense even for a single core, while <em>parallelism</em> is like track sports and focuses on independence. He gave a taster for each parallelism/concurrency solution like <a href="https://www.threadingbuildingblocks.org/">TBB</a>, <a href="http://msdn.microsoft.com/en-us/library/dd492418.aspx">PPL</a>, <a href="http://openmp.org/wp/">OpenMP</a>, <a href="http://www.cilkplus.org/">Cilk Plus</a>, and what the future version of STL has in store. He mentioned std::async is mainly for concurrency, not for parallelism. He explained <a href="https://en.wikipedia.org/wiki/False_sharing"><em>false sharing</em></a>, which is a crucial concept if you want to develop a program that is scalable and performant on multicore or many-core systems.</p><p><a href="https://github.com/CppCon/CppCon2014/raw/master/Presentations/Lock-Free%20Programming%20(or%2C%20Juggling%20Razor%20Blades)/Lock-Free%20Programming%20(or%2C%20Juggling%20Razor%20Blades)%20-%20Herb%20Sutter%20-%20CppCon%202014.pdf">Lock-Free Programming (or, Juggling Razor Blades)</a></p><p><a href="http://herbsutter.com/">Herb Sutter</a> gave a talk about lock-free programming <a href="http://herbsutter.com/2013/02/11/atomic-weapons-the-c-memory-model-and-modern-hardware/">this time</a>. He explained the subtle differences between <a href="http://en.wikipedia.org/wiki/Non-blocking_algorithm"><em>wait-free</em> (none waits), <em>lock-free</em> (at least one makes progress at any moment), and <em>obstruction-free</em> (one makes progress if all others are idle)</a>. Then, he showed an example of <a href="https://en.wikipedia.org/wiki/Double-checked_locking">double-checked locking</a>, why it’s important to use a local variable to reduce the number of atomic loads, and how <a href="http://en.cppreference.com/w/cpp/thread/call_once">std::call_once</a> comes handy for this. The next topic was a lock-free single-linked list: how it’s much harder to implement one than it first seems and how tricky issues like <a href="https://en.wikipedia.org/wiki/ABA_problem">ABA</a> and delete-while-traversing can be solved by ref counting + reference (instead of raw pointer).</p><h3>From game industry</h3><p><a href="https://github.com/CppCon/CppCon2014/raw/master/Presentations/Data-Oriented%20Design%20and%20C%2B%2B/Data-Oriented%20Design%20and%20C%2B%2B%20-%20Mike%20Acton%20-%20CppCon%202014.pptx">Data-Oriented Design and C++</a></p><p>This was the keynote by <a href="http://www.linkedin.com/in/mikeacton">Mike Acton</a>, which I mentioned in <a href="http://scriptogr.am/jj/post/cppcon-2014-report-12">the first post</a>. It felt like a summary of his talks about <a href="http://www.dataorienteddesign.com/dodmain/"><em>data-oriented design</em></a> given in <a href="http://www.gdconf.com/">Game Developer Conference</a>. He listed hard deadlines, soft real-time performance requirements, usability, performance, maintenance, and debuggablity as what matters to game developers. In one of his unique hand-written-post-it-shot-by-camera slide, he said <em>“Where there is one, there are many.”</em> He said there were three big lies that are responsible for sluggish programs we have these days on faster-than-ever hardwares:</p><ul><li>software is platform</li><li>code designed around model of the world</li><li>code is more important than data</li></ul><p>He also argued that you couldn’t “future proof”. He demonstrated many interesting code samples, so I highly recommend to check them unless you have already seen his talk in GDC. His talk was <a href="https://www.youtube.com/watch?v=rX0ItVEVjHc">quite controversial among the audience</a>, especially with his argumentative approach. Nonetheless, I think it can be a good balance if you have soaked in object-orientedness too much and a chance to see how experienced game developers tend to approach programming.</p><p><a href="https://github.com/CppCon/CppCon2014/raw/master/Presentations/How%20Ubisoft%20Montreal%20Develops%20Games%20for%20Multicore/How%20Ubisoft%20Montreal%20Develops%20Games%20for%20Multicore%20-%20Before%20and%20After%20C%2B%2B11%20-%20Jeff%20Preshing%20-%20CppCon%202014.pdf">How Ubisoft Montreal Develops Games for Multicore</a></p><p>Another awesome game coder, <a href="http://preshing.com/">Jeff Preshing</a> gave this talk about how video games usually utilize parallelism. He explained three common threading patterns in games: pipelining (e.g. overlapping of update/render phases in a typical game loop by double-buffering), dedicated threads, and task scheduler approach. He also elucidated atomic operations and showed how you can implement a wait-free single-producer-single-consumer queue.</p><h3>Etc.</h3><p><a href="https://github.com/CppCon/CppCon2014/raw/master/Presentations/The%20Philosophy%20of%20Google%27s%20C%2B%2B%20Style%20Guide/The%20Philosophy%20of%20Google%27s%20C%2B%2B%20Style%20Guide%20-%20Titus%20Winters%20-%20CppCon%202014.pdf">The Philosophy of Google’s C++ Style Guide</a></p><p>Google has 4k-ish C++ coders according to the speaker. They are using a source code indexer called <em>Kythe</em>, regularly run by <a href="http://en.wikipedia.org/wiki/Continuous_integration">CI</a>. He said it would be open-sourced soon. He talked about meta-rules governing the google style guide like:</p><ul><li>Optimize for the reader, not the writer</li><li>Rules should pull their weight</li><li>Be consistent</li><li>If something unusual is happening, leave explicit evidence for the reader</li><li>Concede to optimization and practicalities when necessary</li></ul><p>Google is not using exceptions, like many others who also acknowledged no love/use for it in this CppCon. One contentious rule was ‘no non-const refs as function arguments’. Their rationales were consistency, leaving a trace/explicitness (about the argument likely to be modified in the function), and lifetime issues with reference parameters. But, he also admitted it had its own downsides like slightly worse readability and a need for null checks.</p><p><a href="https://github.com/CppCon/CppCon2014/raw/master/Presentations/Hourglass%20Interfaces%20for%20C%2B%2B%20APIs/Hourglass%20Interfaces%20for%20C%2B%2B%20APIs%20-%20Stefanus%20Du%20Toit%20-%20CppCon%202014.pdf">Hourglass Interfaces for C++ APIs</a></p><p>It’s well known that portably using C++ shared libraries can be a nuisance because of ABI issues. The speaker suggested what he called <em>hourglass interfaces</em> as a solution for that. It can be summarized as below:</p><pre>Broad C++ Interface &gt; Thin C89 API &lt; Broad C++ implementation</pre><p>The name of hourglass apparently comes from the shape. The left side of ‘Broad C++ Interface’ is usually headers-only. It also enforces no use of non-trivial C++ types and keeps the internal layout of data a secret with forward-declared structs. One more advantage of this approach is that it’s really easy to make it available in other languages through <a href="http://en.wikipedia.org/wiki/Foreign_function_interface">FFI</a>.</p><p>CppCon 2014 was definitely an interesting &amp; inspiring experience for me. C++ as a language never has been so agile and its community never has been this much active. I encourage anyone who love-hate C++ to join CppCon next year.</p><h3>Links</h3><ul><li><a href="https://github.com/CppCon/CppCon2014/tree/master/Presentations">Slides</a></li><li><a href="https://www.youtube.com/channel/UCMlGfpWw-RUdWX_JbLCukXg">Videos</a></li></ul><p><em>Originally published at </em><a href="http://scriptogr.am/jj/post/cppcon-2014-report-22"><em>scriptogr.am</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27f1401aaddb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CppCon 2014 Report (1/2)]]></title>
            <link>https://medium.com/@all2one/cppcon-2014-report-1-2-95200485487a?source=rss-cc8601a8e73c------2</link>
            <guid isPermaLink="false">https://medium.com/p/95200485487a</guid>
            <dc:creator><![CDATA[jj]]></dc:creator>
            <pubDate>Tue, 11 Aug 2015 03:00:35 GMT</pubDate>
            <atom:updated>2015-08-11T03:00:35.736Z</atom:updated>
            <content:encoded><![CDATA[<p>I was able to attend <a href="http://cppcon.org/">CppCon</a> 2014, held in Bellevue, WA. It was the first conference in the name of <em>CppCon</em>. It was useful for me to see the trend/vibe of C++ as a programming language and brush up on my knowledge on the latest C++, especially stuff from its new standards. There were multiple sessions by game developers (one of them was a keynote) too, so it was especially interesting to me as a game developer. It seems that game industry is now starting to be regarded as an important part of C++ community, which is somewhat late, but still a great news in my opinion. A game coder’s relationship with C++ has been usually a thing of love-hate (more biased toward hate these days) as you can see in <a href="http://www.linkedin.com/in/mikeacton">Mike Acton</a>’s keynote later. This will be the first of a two-part post.</p><h3>Advanced Basics</h3><p><a href="https://github.com/CppCon/CppCon2014/raw/master/Presentations/Back%20to%20the%20Basics!%20Essentials%20of%20Modern%20C%2B%2B%20Style/Back%20to%20the%20Basics!%20Essentials%20of%20Modern%20C%2B%2B%20Style%20-%20Herb%20Sutter%20-%20CppCon%202014.pdf">Back to the Basics! Essentials of Modern C++ Style</a></p><p><a href="http://herbsutter.com/">Herb Sutter</a> started with saying that we should be aware of an addiction to complexity. He also recommended <a href="http://www.amazon.com/Tour-In-Depth-Series-Bjarne-Stroustrup/dp/0321958314"><em>A Tour of C++</em></a> by Bjarne as a book explaining modern C++ in a small volume.</p><p>An effective use of smart pointers is important. You should use raw pointers only for the stuff you don’t have an ownership at the moment. He explained how to use smart pointers properly as function parameters, too.</p><p>In another topic, he preached why auto should be a preferred way of declaration in most cases. There are two possible styles: one is <em>track/deduce</em> way of auto var{init}; and the other is <em>stick/commit</em> way of auto var = Type{init}; or Type var{init};. When it comes to the opinion that it makes code less readable, he argued that it reflected a bias to code against implementations, not against interfaces. Type deduction gives us correctness, maintainability, performance (owing to no implicit conversion), usability (some types like lambda cannot be uttered), and convenience. Another benefit is that uninitialized variables are impossible with the auto. He also argued that C++ was moving to <em>left-to-right style</em> as in category name = type / initializer; in general with the auto as its main enabler. He admitted that there were still some (rare) cases where you cannot use the auto.</p><p>He advised that we should use <em>return-by-value</em> more often, but against overusing <em>pass-by-value</em>. He went in detail about how parameter passing should be done in various situations. He suggested that we should begin to use a term of <em>forwarding references</em> in lieu of <a href="http://scottmeyers.blogspot.com/2012/10/new-article-universal-references-in-c11.html"><em>universal references</em></a>, a term coined by <a href="http://www.aristeia.com/">Scott Meyers</a>. He also advocated using <a href="http://en.cppreference.com/w/cpp/utility/tuple/tie">std::tie</a> and <a href="http://en.cppreference.com/w/cpp/utility/tuple">tuple</a> for multiple return values in C++.</p><p><a href="https://github.com/CppCon/CppCon2014/raw/master/Presentations/Make%20Simple%20Tasks%20Simple/Make%20Simple%20Tasks%20Simple%20-%20Bjarne%20Stroustrup%20-%20CppCon%202014.pptx">Make Simple Tasks Simple</a></p><p><a href="https://en.wikipedia.org/wiki/Alexander_Stepanov">Alexander Stepanov</a> introduced the speaker, <a href="https://en.wikipedia.org/wiki/Bjarne_Stroustrup">Bjarne Stroustrup</a> through <a href="https://www.youtube.com/watch?v=-n8FP7Ncq8A&amp;feature=youtu.be">a recorded video</a>. According to him, three main reasons why C++ has been able to thrive still are enabling us to look into bits, a native support of addressable memory, and providing abstractions based on this reality.</p><p>We should strive to avoid accidental complexity, Bjarne spoke. For instance, <a href="https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization"><em>RAII</em></a> can be a simplifier. He showed an example of converting a raw loop to a form using a ranged version of find_if step by step and how the final form was much simpler than the original. He explained how <a href="https://en.wikipedia.org/wiki/Concepts_(C%2B%2B)"><em>Concepts</em></a> would make generic programming ‘ordinary programming’ and why you could think of auto as the least constrained concept. He also said every powerful new feature could and would be misused. So, don’t fuss about the danger of accepting new features/practices. (Also, see what pain we have inflicted on ourselves by making the template syntax so verbose under the assumption that the new &amp; dangerous feature (at that time) should be more conspicuous when used.) He concluded the keynote with saying <em>“Simplification is hard.”</em></p><p><a href="https://github.com/CppCon/CppCon2014/raw/master/Presentations/Type%20Deduction%20and%20Why%20You%20Care/C%2B%2B%20Type%20Deduction%20and%20Why%20You%20Care%20-%20Scott%20Meyers%20-%20CppCon%202014%20-%20CppCon%202014.pdf">C++ Type Deduction and Why You Care</a></p><p>Scott Meyers started his session with <a href="http://www.aristeia.com/hairpoll/">a poll about his hair</a>. According to him, there are six types of deduction rules now in C++. A deduction rule for auto is exactly the same as the rule for template except for braced initializers. (But, this might change in C++17.) In int x;, decltype(x) = int, but decltype((x)) = int&amp;. I recommend to check his slide for the nitty-gritty of the deduction rules. On a related note, his new book, <em>Effective Modern C++</em> is <a href="http://scottmeyers.blogspot.com/2014/09/the-four-stages-of-doneness.html">almost done at the time of this writing</a>.</p><p><a href="https://github.com/CppCon/CppCon2014/raw/master/Presentations/STL%20Features%20And%20Implementation%20Techniques/STL%20Features%20And%20Implementation%20Techniques%20-%20Stephan%20T.%20Lavavej%20-%20CppCon%202014.pptx">STL Features And Implementation Techniques</a></p><p>As a guy working on MSVC’s STL (an abbreviation for his name is also STL, BTW), Stephan T. Lavavej showed a variety of useful tidbits about STL implementations, especially stuff from the new standards. He explained why newly added <em>dual-range</em> algorithms provided a better opportunity for optimization than existing <em>1.5-range</em> algorithms. Other topics included improvements on heterogeneous associative lookup, when const rvalue reference matters, and what form of auto (auto vs. auto&amp; vs. auto&amp;&amp;) should be used for range-based for loops.</p><p>Making Allocators Work (no slide online yet)</p><p>The speaker said that two main problems with C++03 allocators had been their being part of type signatures and not being able to have any state. He explained the changes/improvements the new standards had brought for allocators mainly with <a href="http://en.cppreference.com/w/cpp/memory/allocator_traits">allocator_traits</a>. You don’t need to know how to implement allocator_traits unless you work for standard library vendors. And it’s enough for container authors to know how to use allocator_traits. Usual coders should be ok with the knowledge of how to implement new allocators and use them.</p><h3>Performance, Performance, and Performance</h3><p>Efficiency with Algorithms, Performance with Data Structures (no slide online yet)</p><p>The speaker started with a quotation: <em>“Software is getting slower more rapidly than hardware becomes faster”</em> — <a href="https://en.wikipedia.org/wiki/Niklaus_Wirth">Nicklaus Wirth</a>. It was an interesting idea that distinguishes the concept of <em>efficiency</em> and <em>performance</em>, each associated with algorithms and data structures. Efficiency is about <em>how much work is required by a task</em>. Performance is about <em>how quickly a program does its work</em>.</p><p>Power has become crucial with mobile computing. To save power, programs should run faster. Compute/watt dominates. C++ doesn’t give us performance, rather a control over performance.</p><p>As a sample of algorithmic efficiency, he talked about substring search and how an algorithm like <a href="https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm">Knuth-Morris-Pratt</a> (and <a href="http://scriptogr.am/jj/post/Boyer-Moore">Boyer-Moore</a> even better) can be used to reduce the amount of work to be done compared to a naive approach.</p><p><em>Discontinuous data structures are roots of all (perf) evil!</em> A performant hash table design would be open addressing + local probing on collision (assuming key and value are relatively small in size). Data structures and algorithms are tightly coupled. Sometimes worse can be better: <a href="https://en.wikipedia.org/wiki/Bubble_sort">bubble sort</a> can be the fastest when the item count is small and a sophisticated algorithm like <a href="https://en.wikipedia.org/wiki/Cuckoo_hashing">cuckoo hashing</a> often doesn’t perform well in real-world scenarios.</p><p><a href="https://github.com/CppCon/CppCon2014/raw/master/Presentations/Optimization%20Tips/Optimization%20Tips%20-%20Andrei%20Alexandrescu%20-%20CppCon%202014.pdf">Optimization Tips</a></p><p><a href="http://erdani.com/">Andrei Alexandrescu</a> introduced some optimization tips and tricks, which Facebook has applied to good effect. It’s interesting to see that another performance-obsessed sector of C++ software industry (other than game industry) is huge-scale online services like Facebook and Google.</p><p>The first topic was inlining. Inlining interacts with I-Cache. He said it was hard to predict its impact, especially when it comes “Dark Matter” code like constructors and destructors: often implicitly generated and trivial, but can be deadly at scale. So, beware inline destructors. He showed a single destructor inlined in Facebook’s code base had decreased CPU instruction count, but increased CPU time.</p><p>The next topic was about their custom shared_ptr implementation. They applied some clever tips and a bunch of micro-optimizations to squeeze out as much performance as possible. It included assuming a single-thread usage by default, utilizing the fact that <a href="http://users.cecs.anu.edu.au/~steveb/downloads/pdf/rc-ismm-2012.pdf">ref counts usually remain low throughout their lifetimes</a>, lazy allocation of ref count, skipping last decrement, etc.</p><h3>For Template Junkies</h3><p>Modern Template Metaprogramming (no slide online yet)</p><p>Template metaprogramming helps in source code flexibility and run-time performance. The speaker said that C++11/14 constexpr function could be an alternative for compile-time metaprogramming, but templates still had an edge over it since they offer us more tools by being structs rather than just functions. He explained what std::enable_if was about, how <a href="https://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error">SFINAE</a> enabled it, and how <a href="https://en.wikipedia.org/wiki/Concepts_(C%2B%2B)">Concepts</a> would reduce the need for this clunky tool. He also showed the power of using the combo of inheritance and template specialization. The concept of unevaluated operands, which applies to operators such as sizeof, typeid, decltype, and noexcept and why sizeof used to be a poor man’s decltype prior to C++11 have been discussed.</p><p>Lastly, he Introduced a very(too?) clever trick called void_t, which can replace the up-coming Concepts altogether in a pinch. It requires <a href="https://stackoverflow.com/questions/12654067/what-is-expression-sfinae">expression SFINAE</a> and is currently <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3911.pdf">proposed</a> by the speaker to be included as a standard utility in the next standard.</p><p>That’s it for the first part. I’ll continue with sessions about parallelism &amp; concurrency and sessions from game developer (including Mike Acton’s one mentioned at the beginning) in the part two.</p><p><em>Originally published at </em><a href="http://scriptogr.am/jj/post/cppcon-2014-report-12"><em>scriptogr.am</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95200485487a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>