<?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 Shoichiro Yamanishi on Medium]]></title>
        <description><![CDATA[Stories by Shoichiro Yamanishi on Medium]]></description>
        <link>https://medium.com/@e92rodbearings?source=rss-dffcfc53a82------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vDNhHcoX1A0ls1n6ZnhktA.png</url>
            <title>Stories by Shoichiro Yamanishi on Medium</title>
            <link>https://medium.com/@e92rodbearings?source=rss-dffcfc53a82------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:24:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@e92rodbearings/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[Rotation Averaging for Software Developers: Practical Analysis and Implementations in C++]]></title>
            <link>https://medium.com/@e92rodbearings/rotation-averaging-for-software-developers-practical-analysis-and-implementations-in-c-330287cda21b?source=rss-dffcfc53a82------2</link>
            <guid isPermaLink="false">https://medium.com/p/330287cda21b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[quaternion]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[cpp-programming]]></category>
            <dc:creator><![CDATA[Shoichiro Yamanishi]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 06:42:28 GMT</pubDate>
            <atom:updated>2026-08-10T06:42:28.606Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJBcE6izYEZjCnFNXzwwKA.png" /><figcaption>Image of Averaging Rotations</figcaption></figure><h3>1 Introduction</h3><p>Rotation Averaging has applications in many fields, such as the attitude control of spacecrafts in the aerospace engineering, orientation estimation in computer vision, and the joint control in computer games. In aerospace engineering, an algorithm called QUEST [9] has been used for almost half a century to control the orientation of the satellites. In computer games, where every CPU clock cycle and every data byte count, the quaternion averaging has been used with some heuristics to find the correct polarity of the quaternions [8]. In computer vision, the research has been very active. One particular seminal article [3] works as a good survey on theory. It also provides new findings.</p><p>The purpose of this article is to gather and sort out what has been independently discovered and used in practice in individual engineering areas, and to present them in a single compact article for software developers. The focus is on the implementations of the working algorithms and practical analysis, rather than on theories with mathematical rigor. It comes with 4 individual header-only implementations in C++, any of which you can drop-in to your applications.</p><p>In general, this article recommends the QUEST algorithm, as it runs fast, the output precision is pretty good, and it scales very well. If a reference quaternion is available, from which all the input rotations are known to have relative angles less than π/2, then the simple element-wise quaternion averaging may run faster, depending on the hardware and the number of rotations.</p><p>This article is organized as follows. First, it defines representations of the rotations on computer, and then distance metrics, and then formulates <em>averaging rotations</em> as a minimization problem on the sum of L2 distances. Second, it discusses the distribution of the rotations, especially conditions under which the set of rotations admit a global minimum. Third, it presents 4 algorithms with C++ implementations. And finally, it analyzes the performance of the algorithms in terms of the processing time and the output precision.</p><h3>2 Accompanying Website</h3><p>This article comes with a repo on Github: <a href="https://github.com/ShoYamanishi/RotationAveraging">https://github.com/ShoYamanishi/RotationAveraging</a></p><p>This repo contains code in C++ in 4 independent single header files that can be dropped-in to your codebase. It also contains some utilities to conduct the same experiments performed for this article.</p><h3>3 Representations of Rotation</h3><h4>3.1 SO(3) Rotation Matrix</h4><p>The most common way to represent a rotation is by a 3×3 matrix R. It is an orthonormal matrix of determinant 1. There is a one-to-one mapping from each rotation to a matrix without ambiguity. The set of such matrices are closed under the matrix multiplication and the matrix inverse operations, and it forms a group SO(3). This set forms a smooth manifold, i.e., it is continuously diﬀerentiable at every point, which is required later to find an average numerically by an iterative solver. It is a Lie group.</p><h4>3.2 Quaternion</h4><p>The set of unit quaternions is another common representation for rotations, which is isomorphic to SU(2,C) through the Pauli matrices. SU(2,C) is a spinor in physics. The unit quaternions are popular, as they are more compact and less cumbersome than SO(3) to use. A major drawback of using quaternions is their ambiguity called double-cover in representing the same rotation, which stems from the underlying characteristics of the spinor. Mathematically, SO(3) is isomorphic to the quotient group SU(2,C)/<em>kerφ</em>, where <em>kerφ</em>= {I,−I}, and this kernel is the cause of the ambiguity in the quaternions.</p><h4>3.3 Angle-Axis Representation and Lie Algebra</h4><p>Another way to represent a rotation is to use an axis of rotation and the amount of rotation θ in radian. This is not used explicitly in practice, but it is needed to derive a gradient-based solver for the geodesic L2-mean, which will be explained later. The axis of rotation is represented by a 3-dimensional unit vector <strong>v</strong>, and the amount of rotation can be limited in the range of [0,π] without losing generality. The rotation of more than π can be represented by the unit vector of the opposite direction with the amount 2π−θ. By multiplying the unit vector <strong>v</strong> with θ, we can make an angle-axis representation θ<strong>v</strong> in <em>R</em>³. We could use a single vector <strong>v̂</strong> notation such that <strong>v̂</strong> = θ<strong>v</strong>, but in this article, the angle-axis representation is written as θ<strong>v</strong> to make the scalar angle amount θ and the direction of vector of the unit length <strong>v</strong> explicit. The set of such vectors form a ball B of radius π by attaching the tail of <strong>v</strong> to the origin. There is a one-to-one mapping from a rotation θ<strong>v</strong> to a point p in the ball, except on the surface <em>S</em>² of the ball, i.e., the points with distance θ= π from the origin. A pair of bipolar opposite points on <em>S</em>² represent the same rotation with the amount π. Mathematically, if we identify the pair by projecting them at infinity, we obtain the projective space <em>R</em>P³ [3], which is isomorphic to SO(3), but basically the only thing we need to know here is that there is virtually one-to-one mapping between the rotation matrices and the angle-axis vectors.</p><h4>3.4 Connection between SO(3) and Angle-Axis Representation</h4><p>The connection between SO(3) and angle-axis representation θ<strong>v</strong> is made through the two mappings exp(Ω) : <strong>so</strong>(3) →SO(3) and log(R) : SO(3) →<strong>so</strong>(3) between Lie group SO(3) and Lie algebra <strong>so</strong>(3), whose elements are 3 ×3 skew-symmetric matrices A [6]. We can connect the angle-axis representation θ<strong>v</strong> to <strong>so</strong>(3) by the following formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRAp3G_CaPOF59dTp8j_8Q.png" /></figure><p>where <strong>v</strong> = [v₁,v₂,v₃]ᵀ. The conversion from a skew-symmetry matrix A to a 3-dimensional vector is denoted by [<strong>so</strong>(3)]∨. In this article, we treat the definition of <strong>so</strong>(3) and [<strong>so</strong>(3)]∨ interchangeably, as we don’t use the algebra part of <strong>so</strong>(3), such as Lie bracket operations, beyond the standard element-wise additions and subtractions.</p><p>The mapping <strong>so</strong>(3) →SO(3) is exp(θ<strong>v</strong>) defined by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjIRq4WVR1B_o9ja73mOnA.png" /></figure><p>and the mapping log(R) : SO(3) →<strong>so</strong>(3) is log(R) is defined by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ThejoQi8ZRmBmu3fvuSHTQ.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cD8R9cNYowBOsNKQ_Ht7w.png" /></figure><p>With those two mappings we can convert the representation of a rotation between R ∈SO(3) and angle-axis representation θ<strong>v</strong> ∈[<strong>so</strong>(3)]∨.</p><h3>4 Distance Metrics</h3><p>In this section, we formally define how far apart two rotations Rᵢ and Rⱼ are. There are three major metrics used for averaging rotations. One is called the geodesic distance denoted by d_{geodesic}(Rᵢ,Rⱼ), another is the chordal distance by d_{chordal}(Rᵢ,Rⱼ), and the last is the quaternion distance by d_{quat}(qᵢ,qⱼ), where Rᵢ,Rⱼ ∈SO(3) and qᵢ,qⱼ ∈Q. For all the three types, bi-invariance holds [3], i.e., for any rotation S or qₛ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxO45UXe4nu11qVBqw0MsA.png" /></figure><h4>4.1 Geodesic Distance</h4><p>This is simply the relative angular amount θᵢⱼ between the two rotations Rᵢ and Rⱼ. The relative angular amount can be the amount of the composite rotation by RⱼRᵀᵢor Rᵀᵢ Rⱼ. Please note that R⁻¹ = Rᵀ for R∈SO(3). Hence,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2NPFyqv8ZNjzO26fXBeSA.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWxQB7AJIXcW0tReqSA1kg.png" /></figure><h4>4.2 Chordal Distance</h4><p>This is derived from the Frobenius norm of matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzufOu2xbKyidRxBB_CgVA.png" /></figure><p>The chordal distance is defined as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ThddPSWISNFbcyD3G9i2ng.png" /></figure><p>By some algebraic manipulation with the definition of the exp(θ<strong>v</strong>), we can prove the following in terms of the angular amount θᵢⱼ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vxcANBrOS0fYIMXFpBb0A.png" /></figure><h4>4.3 Quaternion Distance</h4><p>The quaternion distance is defined as the simple Euclidean distance with the quaternions viewed as the 4-dimensional vectors in <em>R</em>⁴. Due to the ambiguities in the polarities, you have to express the distance as the minimum of 4 terms as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U02R3fiYEZ7TTLGxhof6Gw.png" /></figure><h3>5 Definitions of Average of Rotations</h3><p>First, consider the average of points pᵢ in the ordinary D-dimensional Euclidean space Rᴰ. The formula is given in a closed form as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVQpCp6mK8-3E3dLy3jsQQ.png" /></figure><p>In fact the above equation is the solution for the following minimization problem of the L2-norm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uj5JBJxmhCCokfAIgXzV3Q.png" /></figure><p>The solution is given at the point where the gradient ∇p of the right hand side vanishes. In the same way, we can define the average as a minimization of the sum of the L2-norm as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NbmPey_lIhO9DeDcIKPXpw.png" /></figure><p>or</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6P6E_NtJ7bsr1VRagX2WSQ.png" /></figure><p>Depending on the distance metrics used, we can define 3 types of averages of rotations.</p><h4>5.1 Geodesic L2-mean</h4><p>Using the geodesic distance, we define the geodesic L2-mean as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6RhlGU2ml7tMO2CjNUo4g.png" /></figure><p>This definition is called <em>Karcher mean</em> in the literature [3] and it is considered the most natural way of averaging rotations. In this article, we treat the geodesic L2-mean as the baseline.</p><h4>5.2 Chordal L2-mean</h4><p>Using the chordal distance, we define the geodesic L2-mean as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQ9kzOXZvo557ds-31Yhow.png" /></figure><h4>5.3 Quaternion L2-mean</h4><p>Using the quaternion distance, we define the geodesic L2-mean as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tyV3RbDkksF7V4yIg2-7A.png" /></figure><h3>6 Distribution of the Rotations and Global Minimum</h3><p>The rotations in SO(3) form a manifold that corresponds to a sphere<em> S</em>³ in the 4-dimensional euclidean space <em>R</em>⁴. One such sphere can be formed by the set of unit quaternions q = (s,x,y,z) such that r² = (s² + x² + y² + z²) = 1. Since q and −q represent the same rotation, each pair of the polar opposite points on S³ represent a single rotation.</p><p>Due to this spherical nature, there is not always a single global minimum of the average. As it is hard to visualize the sphere <em>S</em>³ ∈<em>R</em>⁴, consider <em>S</em>² in the 3-dimensional space <em>R</em>³, and assume each point on the surface represents a rotation.</p><p>Imagine the points are evenly distributed at the 5 vertices of the 20 hexagons of the surface of a soccer ball. Then it is easy to see there will be no single point on the surface of the soccer ball that minimizes the sum of the geodesic or chordal squared distance from all the points. However, if all the points are contained within a single hexagon, then the average point will lie within that hexagon.</p><p>The question is then how can we specify the distribution of the points for which a single global minimum of average is guaranteed? According to the convextity analysis research, if the points are contained within a half sphere, then there will be a single global minimum, regardless of the distance metrics used. Please see [3] and [6] for details. The rest of this section presents some more metric-specific results.</p><h4>6.1 Geodesic L2-mean</h4><p>For the rotations in SO(3) with the geodesic L2-mean, the following result has been proven [4], [3]. For a given set of rotations <em>S</em>ᵣ = {<em>R</em>₁,<em>R</em>₂,…,<em>R</em>ₙ}, ∃R*∈ SO(3) such that ∀<em>R</em>ᵢ ∈<em>S</em>ᵣ,||[log(<em>R</em>*ᵀ<em>R</em>ᵢ)]∨||₂ &lt; π/2 , then the sum of such geodesic L2-norm is convex. In other words, if there is a rotation <em>R</em>* such that the relative angular amounts between <em>R</em>* and all the rotations <em>R</em>ᵢ are less than π/2 , then the average rotation Ṝ in terms of the geodesic L2-mean can be found by some algorithm.</p><h4>6.2 Chordal L2-mean</h4><p>For the chordal L2-mean, the following lesser result has been proven [3]. For a given set of rotations <em>S</em>ᵣ = {<em>R</em>₁,<em>R</em>₂,…,<em>R</em>ₙ}, ∃R*∈SO(3) such that ∀<em>R</em>ᵢ ∈<em>S</em>ᵣ,||[log(<em>R</em>*ᵀ<em>R</em>ᵢ)]∨||₂ &lt; π/4 , then the sum of such chordal L2-norm is convex. In other words, if there is a rotation <em>R</em>* such that the relative angular amounts between <em>R</em>* and all the rotations <em>R</em>ᵢ are less than π/4 , then the average rotation Ṝ in terms of the chordal L2-mean can be found by some algorithm. Please note that the angle is narrower than the case for the geodesic L2-mean.</p><h4>6.3 Quaternion L2-mean</h4><p>For the quaternion L2-mean, the following result has been proven [3]. For a given set of rotations <em>Sq </em>= {<em>q</em>₁,<em>q</em>₂,…,<em>q</em>ₙ}, if there is a reference quaternion <em>q_{ref}</em>, from which all thequaternions in<em> Sq </em>are known to have relative angles θ_{i,ref} of <em>qᵢq*_{ref}</em> less than π/2, then we can find the global minimum as follows.</p><p>Let <em>S⁺q</em> = {<em>q⁺</em>₁ ,<em>q⁺</em>₂ ,…<em>q⁺</em>ₙ}, where <em>q⁺ᵢ</em> is the polarity-correct version of <em>qᵢ</em> with respect to q_{ref}, then the simple element-wise summation of <em>S⁺q</em> , and projection(normalization) gives the global minimum [3].</p><h3>7 Algorithms</h3><p>In this section we finally present 4 algorithms for 3 types of distance metrics. Each section provides the algorithm first, and then an implementation in C++ follows. The implementations depend on<a href="http://glm.g-truc.net/"> glm.g-truc.net</a>, and the following is assumed.</p><pre>#define GLM_FORCE_RADIANS <br>#include &lt;glm/glm.hpp&gt;<br>#include &lt;glm/gtc/quaternion.hpp&gt;</pre><h4>7.1 Geodesic L2-mean: Fixed-step Gradient Descent</h4><p>In general, a gradient descent algorithm for a minimization problem works iteratively as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDGU0ZWKnFdOqRbtovq3Rg.png" /></figure><p>In other words, you try to find a better <strong>x</strong>ₜ₊₁, in the sense f(<strong>x</strong>ₜ₊₁) &lt; f(<strong>x</strong>ₜ), and you try to find <strong>x</strong>ₜ₊₁ from <strong>x</strong>ₜ in the direction of −∇<strong>x</strong>f(<strong>x</strong>ₜ), as it is locally the steepest direction to reduce f(<strong>x</strong>) around <strong>x</strong>ₜ.</p><p>In the same way, we can define a gradient descent algorithm for the rotations. However, the definition of the gradient in SO(3) is diﬀerent from the gradient in the Euclidean space. In SO(3), the gradient is defined at each rotation <em>R</em>∈SO(3) in its tangent space <em>TRSO</em>(3) to the Riemannian manifold touching at <em>R</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SADypbQCQP81swONqLZCPQ.png" /></figure><p>This can be viewed as the Lie algebra <strong>so</strong>(3)rotated by <em>R</em>, as <strong>so</strong>(3) is the tangent space at <em>I</em> ∈SO(3) by definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOBtyslCaGy9qQ_78leCvA.png" /></figure><p>Let the objective function g(<em>R</em>) to minimize be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmDiwDw3nLgxIxDIa_4p3w.png" /></figure><p>According to [4], the tangential gradient of g(<em>R</em>) is given by the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ddHqhN9yy1fhjcTcebAXQ.png" /></figure><p>∇_{TR}g(<em>R</em>) lies in the tangential space <em>TRSO</em>(3) local to <em>R</em>. Then we can find <em>R</em>ₜ₊₁ based on Rt and the direction ∇T<em>R</em>ₜ g(<em>R</em>)|_{R=Rₜ} such that g(<em>R</em>ₜ₊₁) &lt;g(<em>R</em>ₜ).</p><p>Using the relationship exp_{<em>R</em>ₜ} (<em>R</em>ₜA) = <em>R</em>ₜexp(A), we can find <em>R</em>ₜ₊₁ as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYuDcv--Nav106FsT0LnnA.png" /></figure><p>This is a type of gradient descent algorithm in the space of SO(3) we wanted to find. The convergence to the global minimum has been proven in [2], provided the distribution of the rotations meet the condition in subsection 6.1 above. [2] and [3] suggest we set <em>R_</em>{<em>t</em>=0} to any <em>R</em>ᵢ, and η = 0.5. The following shows an implementation in C++. We use the output from this implementation as the baseline result.</p><pre>inline glm::mat3 geodesic_L2_mean_SO3(<br>    const std::vector&lt; glm::mat3 &gt;&amp; Rs,<br>    const int32_t                   max_iter,<br>    const float                     eps<br>) {<br>    assert( !Rs.empty() );<br><br>    const float n_inv = 1.0f / static_cast&lt; float &gt;( Rs.size() );<br>    const float eps2 = eps * eps;<br><br>    glm::mat3 R = Rs[0];<br>   <br>    for ( int32_t i = 0 ; i &lt; max_iter; i++ ) {<br><br>        const auto Rt = glm::transpose( R );<br><br>        glm::vec3 r{ 0.0f, 0.0f, 0.0f };<br><br>        for ( const auto&amp; Ri : Rs ) {<br><br>            r += SO3_log( Rt * Ri, eps );<br>        }<br><br>        r = r * n_inv;<br><br>        if ( length2( r ) &lt; eps2 ) {<br><br>            break;<br>        }<br><br>        R = R * so3_exp( r, eps );<br>    }<br><br>    return R;<br>}</pre><p>And the implementations of the two functions exp(<em>A</em>) and log(<em>R</em>) are given as follows.</p><pre>inline glm::mat3 so3_exp( const glm::vec3&amp; v, const float eps )<br>{<br>    const auto theta = glm::length( v );<br>    if ( theta &lt; eps ) {<br><br>        return glm::mat3{ 1.0f };<br>    }<br><br>    const auto nv = v / theta;<br>    const glm::mat3 Mv{<br>        glm::vec3{         0.0f,         nv.z, -1.0f * nv.y }, // col 1<br>        glm::vec3{ -1.0f * nv.z,         0.0f,         nv.x }, // col 2<br>        glm::vec3{         nv.y, -1.0f * nv.x,         0.0f }  // col 3<br>    };<br><br>    const auto Mv2 = Mv * Mv;<br><br>    return   glm::mat3{ 1.0f }<br>           + Mv * std::sin( theta ) <br>           + Mv * Mv * (1.0f - std::cos( theta ) );<br>}<br><br>inline glm::vec3 SO3_log( const glm::mat3&amp; R, const float eps )<br>{<br>    const float y1 = 0.5f * ( R[1][2] - R[2][1] );<br>    const float y2 = 0.5f * ( R[2][0] - R[0][2] );<br>    const float y3 = 0.5f * ( R[0][1] - R[1][0] );<br><br>    const glm::vec3 y{ y1, y2, y3 };<br><br>    const auto norm_2_y = glm::length( y );<br><br>    if ( norm_2_y &lt;= eps ) {<br><br>        return glm::vec3{ 0.0f, 0.0f, 0.0f };<br>    }<br><br>    const float theta = std::acos( <br>        std::clamp(<br>            0.5f * ( R[0][0] + R[1][1] + R[2][2] - 1.0f ),<br>            -1.0f,<br>            1.0f<br>        )<br>    );<br><br>    return y * ( theta / norm_2_y );<br>}</pre><h4>7.2 Chordal L2-mean: SVD</h4><p>For the chordal-L2-mean, we should find R that minimizes the following objective function g(<em>R</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56WX1ZzSk3XXXpPTvO5vGA.png" /></figure><p>Using the Frobenius inner product ⟨<em>R</em>,<em>R</em>⟩_F [3] , we can rewrite the objective function as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8c9c9XmBeBX7_RQMNxfr5g.png" /></figure><p>And the original minimization problem can be solved by the following auxiliary maximization problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oed71847lizVhiqSvFZMJA.png" /></figure><p>This problem is a type of so-called Wahba’s problem [10], and it is known to be solved by the singular value decomposition of <em>B</em>=Σ^<em>N</em>_{i=1}<em>R</em>ᵢ. Decompose <em>B </em>into <em>U</em>, <em>D</em>, and <em>V</em> by the singular value decomposition algorithm [5].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwHOCMuMvA083Ddvl6436w.png" /></figure><p>Then <em>R= UJV</em>ᵀ, where <em>J</em>= <em>diag</em>[1,1,det(<em>U</em>)det(<em>V</em>)]. The following shows an implementation in C++. It uses <strong>Eigen3</strong>’s <strong>decomposer Eigen::JacobiSVD</strong>.</p><pre>#include &lt;Eigen/Dense&gt;<br><br>inline glm::mat3 chordal_L2_mean_SO3_SVD( const std::vector&lt; glm::mat3 &gt; Rs )<br>{<br>    glm::mat3 Rglm{ 0.0f };<br><br>    for ( const auto&amp; R : Rs ) {<br><br>        Rglm += R;<br>    }<br><br>    Eigen::Matrix&lt; float, 3, 3 &gt; Reigen;<br><br>    Reigen &lt;&lt; Rglm[0][0], Rglm[1][0], Rglm[2][0],<br>              Rglm[0][1], Rglm[1][1], Rglm[2][1],<br>              Rglm[0][2], Rglm[1][2], Rglm[2][2];<br><br>    Eigen::JacobiSVD&lt; Eigen::Matrix&lt; float, 3, 3 &gt; &gt;<br>        svd( Reigen, Eigen::ComputeFullV | Eigen::ComputeFullU );<br><br>    const auto Ueigen = svd.matrixU();<br>    const auto Veigen = svd.matrixV();<br><br>    glm::mat3 Uglm{<br>        glm::vec3{ Ueigen( 0 ,0 ), Ueigen( 1, 0 ), Ueigen( 2 ,0 ) },<br>        glm::vec3{ Ueigen( 0 ,1 ), Ueigen( 1, 1 ), Ueigen( 2 ,1 ) },<br>        glm::vec3{ Ueigen( 0 ,2 ), Ueigen( 1, 2 ), Ueigen( 2 ,2 ) }<br>    };<br><br>    glm::mat3 Vglm{<br>        glm::vec3{ Veigen( 0 ,0 ), Veigen( 1, 0 ), Veigen( 2 ,0 ) },<br>        glm::vec3{ Veigen( 0 ,1 ), Veigen( 1, 1 ), Veigen( 2 ,1 ) },<br>        glm::vec3{ Veigen( 0 ,2 ), Veigen( 1, 2 ), Veigen( 2 ,2 ) }<br>    };<br><br>    glm::mat3 UVt = Uglm * glm::transpose( Vglm );<br><br>    if ( glm::determinant( UVt ) &lt; 0.0f ) {<br>    <br>        glm::mat3 D{ 1.0f };<br>        D[2][2] = -1.0f;<br><br>        UVt = Uglm * D * glm::transpose( Vglm );<br>    }<br><br>    return UVt;<br>}</pre><h4>7.3 Chordal L2-mean: QUEST</h4><p>Continuing from the previous section, the chordal-L2-mean can be transformed to the following maximization problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tETUdro56v0UwH1O100Fg.png" /></figure><p>In the literature g(<em>R</em>) = tr(<em>B</em>ᵀ<em>R</em>) is called the gain function[1]. According to the literature, the gain function can be equivalently expressed in the quaternion as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVkIMCNq6HavLB7tPb22GQ.png" /></figure><p>where <em>K</em> ∈<em>R</em>⁴ˣ⁴ is called <em>Davenport matrix</em> defined as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klQR6T37f2cTQe8VwFLptQ.png" /></figure><p>Then the chordal-L2-mean is found in the following maximization problem on the quaternion <em>q</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcplMdMS1niNTiUEaUEyWw.png" /></figure><p>This is an eigen value problem of a symmetric 4 ×4 matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txK5LTkJFIMMn8vnqzNUAA.png" /></figure><p>The characteristics function for this problem is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXQEV_dhU0o7JEMFSnZH0Q.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4XGrKMx-1HpDPea7ARPpw.png" /></figure><p>And QUEST algorithm solves f(λ) = 0 by a Newton-Raphson iterative solver with the termination criteria:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4szSrjssh0DijqPQefm_Xw.png" /></figure><p>With λ_{max} found atove, we can find the <em>q̄</em>= (ω,<strong>v</strong>) as the eigenvector. From the lower 3 rows of <em>Kq̄</em>= λ_{max}<em>q̄</em>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8oAC80mwSjVQsl22Bmh9CA.png" /></figure><p>By some algebraic manipulation and Cayley-Hamilton theorem,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODXJ7Vfy0Zz7D_M30td1DQ.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52OPHK1SOOlDzUKXSd5qkw.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FK2dckoHhywmv_0byObstA.png" /></figure><p>Care must be taken if the angle of the resultant rotation is near 0 or π. [9] states the condition in which this occurs is ||<strong>z</strong>||₂ &lt; ϵ_z. In this case, the <em>K</em> matrix will look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lojiRTc-zhVtRCHpoouWNQ.png" /></figure><p>Recall s = tr(<em>B</em>) ≈(1 + 2 cos(θ)). We can use the sign of s to determine if the resultant angle is near 0 or π.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CprirgBrFKBIrUIVKNSaZg.png" /></figure><p>The appropriate values for ϵ_{term} and ϵ_z will be discussed in the section 8.4. Apart from QUEST, there are some other algorithms proposed to solve λ_{max} and <em>q</em>, such as ESOQ- 2 [7], but they are not considered in this article, as they don’t seem to have significant advantages over QUEST, and QUEST has been used for real use cases for a long time. The following shows an implementation in C++.</p><pre>inline glm::mat3 chordal_L2_mean_SO3_QUEST(<br>    const std::vector&lt; glm::mat3 &gt;&amp; Rs,<br>    const int32_t                   max_iter,<br>    const float                     eps_termination      = 1.0e-6f,<br>    const float                     eps_z_zero_tolerance = 1.0e-3f<br>) {<br>    glm::mat3 B{ 0.0f };<br><br>    for ( const auto&amp; R : Rs ) {<br><br>        B += R;<br>    }<br><br>    B = B / ( static_cast&lt; float &gt;( Rs.size() ) );<br><br>    const auto s = B[0][0] + B[1][1] + B[2][2];// Tr(B)<br><br>    const auto BBt = B + glm::transpose( B );<br><br>    const glm::vec3 z{<br>        B[2][1] - B[1][2],<br>        B[0][2] - B[2][0],<br>        B[1][0] - B[0][1]<br>    };<br><br>    const auto z_len_2 = length2( z );<br><br>    const auto s2 = s * s;<br><br>    const auto BBt2 = BBt * BBt;<br><br>    const auto detBBt = glm::determinant( BBt );<br><br>    const auto tradjBBt = ( BBt[1][1] * BBt[2][2] +<br>                            BBt[0][0] * BBt[2][2] +<br>                            BBt[0][0] * BBt[1][1]  ) -<br>                          ( BBt[2][1] * BBt[1][2] +<br>                            BBt[2][0] * BBt[0][2] +<br>                            BBt[1][0] * BBt[0][1]  ); // tr[adj(S)]<br><br>    const auto a = s2 - tradjBBt;<br><br>    const auto b = s2 + z_len_2;<br><br>    const auto c = detBBt + glm::dot( z, BBt * z );<br><br>    const auto d = glm::dot( z, BBt2 * z );<br><br>    // Find lambda with Newton-Raphson.<br><br>    float lambda{ 3.0f }; // The initial value set to 3.0, as the lambda seems to be in the range of [ 2.9-3.0 ].<br><br>    for ( size_t iter = 0; iter &lt; max_iter; iter++ ) {<br><br>        const auto lambda_2 = lambda * lambda;<br><br>        const auto f = ( lambda_2 - a ) * ( lambda_2 - b )<br>                     - c * lambda <br>                     + ( c * s - d );<br><br>        const auto f_dash = 2.0f * lambda * ( 2.0f * lambda_2 - ( a + b ) )<br>                          - c;<br><br>        if ( std::fabs( f_dash ) &lt; eps_termination ) {<br><br>            break;<br>        }<br><br>        const auto nr_delta = f / f_dash;<br><br>        if ( std::fabs( nr_delta ) &lt; eps_termination ) {<br><br>            break;<br>        }<br>       <br>        lambda -= nr_delta;<br>    }<br><br>    // Get the quaternion<br>    const auto alpha = lambda * lambda - s2 + tradjBBt;<br><br>    const auto beta = lambda - s;<br><br>    const auto x = (   ( glm::mat3{ 1.0f } * alpha )<br>                     + ( BBt * beta ) <br>                     + BBt2 <br>                   ) * z;<br><br>    const auto gamma = -1.0f * ( ( lambda + s ) * alpha - detBBt );<br><br>    if ( z_len_2 &gt; eps_z_zero_tolerance * eps_z_zero_tolerance ) {<br><br>        const auto q = glm::normalize( glm::quat{ gamma, x } );<br><br>        return glm::mat3_cast( q );<br>    }<br><br>    if ( s &lt; 0.0 ) {<br><br>        const auto q = glm::normalize( glm::quat{ 0.0f, x } );<br><br>        return glm::mat3_cast( q );<br>    }<br>    else {<br>        return glm::mat3{ 1.0f };<br>    }<br>}</pre><h4>7.4 Quaternion L2-mean</h4><p>The outline of the algorithm is given in Section 6.3. First, we determine the correct polarities of the quaternions as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dn6hM1KSDdiLudfL1e4-gw.png" /></figure><p>Then the set of the polarity-corrected quaternions is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AyGBY064gT_MPa40rVgKWw.png" /></figure><p>And the problem is formulated as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LT53-cu4EDZLNuRExNVYyg.png" /></figure><p>This problem could be solved iteratively with a local gradient-descent solver on the Riemannian manifold <em>S</em>³. However, [3] proves that a closed exact formulas of the simple summation and then the projection back onto <em>S</em>³ gives the optimum solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dx39GB75RFJ0PwktesSVfA.png" /></figure><p>The following shows an implementation in C++.</p><pre>inline glm::quat quaternion_L2_mean_R4(<br>    const std::vector&lt; glm::quat &gt;&amp; Qs,<br>    const glm::quat&amp;                q_ref<br>) {<br>    const glm::vec4 v_ref{ q_ref.x, q_ref.y, q_ref.z, q_ref.w };<br><br>    glm::vec4 V{ 0.0f, 0.0f, 0.0f, 0.0f };<br><br>    for ( const auto&amp; q : Qs ) {<br><br>        const glm::vec4 v{ q.x, q.y, q.z, q.w };        <br><br>        const auto len_1 = length2( v_ref - v ); <br>        const auto len_2 = length2( v_ref + v ); <br><br>        if ( len_1 &lt; len_2 ) {<br><br>            V.x += q.x;<br>            V.y += q.y;<br>            V.z += q.z;<br>            V.w += q.w;<br>        }<br>        else {<br>            V.x -= q.x;<br>            V.y -= q.y;<br>            V.z -= q.z;<br>            V.w -= q.w;<br>        }<br>    }<br><br>    V = glm::normalize( V );<br><br>    return glm::quat{ V.w, V.x, V.y, V.z };<br>}</pre><h3>8 Practical Analysis on The Implementations</h3><p>In this section, we analyze the performance of the 4 C++ implementations given above with some artificially generated test patterns on an actual computer. We analyze the processing time, and the output precision with respect to the output from the geodesic implementation as a rererence. We also study the behavior of the QUEST algorithm, and finds appropriate value ranges for the two parameters ε_{term} and ε_z. You can run the same experiments on your computer with the tools provided in the accompanying <a href="https://github.com/ShoYamanishi/RotationAveraging">Guthub repo</a>.</p><h4>8.1 Test Patterns</h4><p>A test pattern consists of rotations in either SO(3) or unit quaternion. A test pattern takes two parameters: the number of rotations N, and the cone half angle ω. A test pattern is generated in two steps.</p><p>First, a base rotation is sampled as an angle-axis representation. The axis <strong>v_{</strong>base} is sampled from the uniform distribution of the 3 dimensional cube of the range x : [−1,1], y : [−1,1], z : [−1,1], and it is normalized to the unit length. The angle α_{base} is sampled from the uniform distribution in the range of [0,π]. From <strong>v_{</strong>base} and α_{base}, a quaternion <em>q_{</em>base} is generated. All the samples in the pattern are generated around this base orientation.</p><p>Second, a set of N quaternions Q_{rel} = {<em>q</em>₁,<em>q</em>₂,…<em>q</em>ₙ}are generated in the same way, from randomly drawn axis vector <strong>v</strong>ᵢ, and an angle αᵢ from the uniform distribution in the range of [0,ω]. The final test pattern is generated by composing each quaternion in Q_{rel} with q_{base} into Q_{pattern}= {<em>q</em>₁ ∗<em>q_{</em>base}, <em>q</em>₂ ∗<em>q_{</em>base}, <em>q</em>₃ ∗<em>q_{</em>base}…<em>q</em>ₙ ∗<em>q_{</em>base} }, and this set is further converted into SO(3) if necessary by the standard formula to transform a quaternion to a rotation matrix.</p><h4>8.2 Processing Time</h4><p>This section analyzes the relationship between the number of rotations N in the input and the processing time of each implementation.</p><p><strong>8.2.1 Condition</strong></p><p>For each test case, a number of rotations N is assigned. In total, 37 test cases are made in the ascending order of the number of rotations from 2 up to 1,000. For each test case, 10,000 independent test patterns are generated with the parameters ω = 0.499π and N. Each implementation is executed for 10,000 times using those 10,000 diﬀerent test patterns. Processing time is sampled per execution with <strong>std::chrono::high resolution clock::now() </strong>in C++. The tests are performed on a M1 Mac Mini 2020.</p><p><strong>8.2.2 Results</strong></p><p>Figure 1 shows the results. As those plots in the figure show, all 4 implementations exhibit the running time of order O(N), but the geodesic iterative algorithm runs significantly slower than the chordal and quaternion algorithms. The QUEST and the quaternion algorithms perform better than the rest, and on this particular hardware, the quaternion algorithm performs best for N &lt;200, and the QUEST for N &gt;200.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDUhb_OQRjrVkZC8QddyUA.png" /><figcaption>Figure 1: Processing Time of Each Implementation</figcaption></figure><h4>8.3 Precision</h4><p>This section analyzes the relationship between the cone half angle in the input, and the output precision of each implementation. As the baseline reference, the results from the geodesic L2-norm implementation is used. This section measures the deviation of the outputs of the other implementations from the baseline.</p><p><strong>8.3.1 Condition</strong></p><p>For each test case, a specific cone half angle is assigned. In total, 50 test cases are made in the ascending order of the cone half angle from 0 up to 0.49π at the interval of 0.01π. For each test case, 10,000 independent test patterns are generated with N= {2,3,5,10,100,1000}. Each implementation is executed for 10,000 times using those 10,000 diﬀerent test patterns for each N.</p><p><strong>8.3.2 Results</strong></p><p>Figures 2 shows the results. It contains 6 plots for diﬀerent Ns for the number of input rotations. The X-axis is for the cone half angle with which the test patterns are generated. The Y-axis is for the deviation in radians from the baseline (geodesic L2-norm) results. As those plots show, the outputs from the quaternion algorithm are of better precision than the ones from the chordal-L2-norm algorithms. The deviasions of the chordal-based algorithms become progressively higher after passing the half cone angle of 0.5[rad]/28.6◦. However they can be considered within the acceptable range, depending on the use cases. The reason why the deviations are lower if N = 2 or N is large can be explained by the shape of <em>B</em>=Σ^<em>N</em>_{i=1}<em>R</em>ᵢ. Since the test patterns are drawn from the uniform distributions, the larger N is , the closer B becomes to the manifold of SO(3). And for N = 2, the problem becomes simply finding the midpoint along the geodesic between R₁ and R₂ on the manifold of SO(3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAoFJeNu4NTxrNPMRHceZg.png" /><figcaption>Figure 2: Angular Deviation from the Geodesic L2-Mean</figcaption></figure><h4>8.4 Parameters of QUEST</h4><p>This section studies the behavior of the QUEST algorithm, and finds appropriate value ranges for the parameters ϵ_{term} andϵ_z. The ϵ_{term} is for the loop termination criteria , and ϵ_z is to consider <strong>z</strong> = 0 or not.</p><p>The ϵ_{term} is used to terminate the Newton-Raphson loop. The typical shape of f(λ) is shown in the upper left plot of Fig 3. Setting it too high will cause early termination of the iteration loop, and will harm the precision, while setting it too low will cause too many unnecessary iterations in the loop. The lower two plots of Fig 3 show the sweet spot is around 10⁻⁶.</p><p>The eﬀect of ϵ_z on the precision is shown in Fig 3. As this plot shows, the sweet spot is around 10⁻³.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HeqYRnMWhREcRF5yXURLgg.png" /><figcaption>Figure 3: Quest Parameters</figcaption></figure><h3>9 Conclusion</h3><p>In this article we have covered the basics about handling the rotation averaging on computer. we have briefly walked through some theories, and defined 3 types of averages: geodesic, chordal, and quaternion. Then we have walked through 4 algorithms with the implementations in C++, and analyzed their performance in terms of the processing speed and the output precision. We have concluded that QUEST and the quaternion based algorithms will work well in general for the real applications. I hope you have enjoyed this article. Happy programming!</p><h3>References</h3><p>[1] Yang Cheng and Malcolm David Shuster. Improvement to the implementation of the quest algorithm. Journal of Guidance Control and Dynamics, 37:301–305, 2014.</p><p>[2] Richard I. Hartley, Jochen Trumpf, and Yuchao Dai. Rotation averaging and weak convexity. 2010.</p><p>[3] Richard I. Hartley, Jochen Trumpf, Yuchao Dai, and Hongdong Li. Rotation averaging. International Journal of Computer Vision, 103:267–305, 2013.</p><p>[4] Jonathan H. Manton. A globally convergent numerical algorithm for computing the centre of mass on compact lie groups. ICARCV 2004 8th Control, Automation, Robotics and Vision Conference, 2004., 3:2211–2216 Vol. 3, 2004.</p><p>[5] Francis Landis Markley. Attitude determination using vector observations and the singular value decomposition. Journal of The Astronautical Sciences, 36:245–258, 1988.</p><p>[6] Maher Moakher. Means and averaging in the group of rotations. SIAM Journal on Matrix Analysis and Applications, 24:1–16, 07 2006.</p><p>[7] D. Mortari. Esoq-2 single-point algorithm for fast optimal spacecraft attitude determination. 95, 01 1997.</p><p>[8] Casey Muratori. Quaternions, double-cover and the rest pose neighborhood (2006), 2016.</p><p>[9] Malcolm David Shuster. Approximate algorithms for fast optimal attitude computation. 1978.</p><p>[10] Grace Wahba. A least squares estimate of satellite attitude. Siam Review, 7:409–409, 1965.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=330287cda21b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supplemental Study Material to PRML on Expectation Propagation and the Clutter Problem]]></title>
            <link>https://medium.com/@e92rodbearings/supplemental-study-material-to-prml-on-expectation-propagation-and-the-clutter-problem-a42ef21bd675?source=rss-dffcfc53a82------2</link>
            <guid isPermaLink="false">https://medium.com/p/a42ef21bd675</guid>
            <category><![CDATA[pattern-recognition]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <category><![CDATA[bayesian-inference]]></category>
            <dc:creator><![CDATA[Shoichiro Yamanishi]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 03:47:41 GMT</pubDate>
            <atom:updated>2024-03-28T03:47:41.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3hq49WHuJfQVTFOrTN-rA.png" /><figcaption>Snippet from the book PRML by Bishop</figcaption></figure><h3>Introduction</h3><p>This is intended to be supplemental material for the section <em>10.7 “Expectation Propagation” of </em><a href="https://www.microsoft.com/en-us/research/uploads/prod/2006/01/Bishop-Pattern-Recognition-and-Machine-Learning-2006.pdf"><em>the book “Pattern Recognition and Machine Learning” </em>by Bishop.</a></p><p>If you have read the section 10.7, and got the overall concept of the expectation propagation, but got stuck in 10.7.1 <em>“Example: The clutter problem”</em>, especially after the equation (10.216), and then perhaps you have read <a href="https://tminka.github.io/papers/ep/minka-ep-uai.pdf">the original paper</a> and <a href="https://tminka.github.io/papers/ep/roadmap.html">some materials by Minka</a> and others, but if you are still confused, then this blog post may hopefully help you understand it better.</p><p>This blog post attempts to fill the gaps and the missing details with the following approach. It prioritizes clarity over elegance at the cost of lengthy-ness to minimize the conceptual gap between the lines.</p><ol><li>Make the following 4 steps for one iteration of the algorithm explicit: Making a cavity, making a hybrid, matching the moments, and finding the newly updated approximating factor.</li><li>At each step, maintain the partition function (normalization coefficient) explicitly. Especially a hybrid will be expressed as a function of <strong>θ</strong>, to be precise as a mixture of two Gaussians with a partition function.</li><li>At the moment-matching step, we explicitly evaluate the moments on both sides: the hybrid side and the new approximation q(<strong>θ</strong>) side. The original paper and the textbook implicitly use the advance formulas (10.244) &amp; (10.245) to find the moments (the derivation can be found at <a href="https://github.com/zhengqigao/PRML-Solution-Manual/blob/master/PRML_Solution_Manual.pdf">this nice solution site</a> for the exersises by Gao, and others), and directly derive the new parameters in (10.217) and (10.218), but it hides the tedious but important details to understand the concept of the alrogithm. This blog post takes a different approach to keep the conceptual gap between the lines small, using elementary algebraic manipulations.</li></ol><h4>Forecast</h4><p>First, we review the spherical Gaussian in the mean-variance form as well as in the natural parameter form, as both are important to understand the algorithm, then we cover the composition and the initialization of the approximation q(<strong>θ</strong>), and then we walk through the 4 steps of one iteration of the algorithm to see how q(<strong>θ</strong>) develops through the execution of the algorithm. We follow the notational convention in PRML.</p><h3>Spherical Gaussian in the Mean-Variance Form and in the Natural Parameter Form</h3><p>The calculation of the cavity, the hybrid, and the partition functions are better understood in the natural parameter form, while the moment matching is in the mean-variance form.</p><h4>Definitions</h4><p>Let <strong>m</strong> be the mean and <em>v</em> be the variance of the spherical Gaussian.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLGSXnVK2b0pJqdCPhEArA.png" /></figure><p>By simple algebraic manipulation, it can be rearranged in terms of <strong>θ</strong> and<strong> θ</strong>ᵀ<strong>θ.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZmXcYE08_P0vzwhyKzvAg.png" /></figure><p>Let</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFUKxURNW_AAcN9ILIQkKQ.png" /></figure><p>Then the spherical Gaussian in the natural parameter form Ε(<strong>θ|η</strong>) is expressed as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X927ppzrE5VDAfGQlIG1kQ.png" /></figure><p>To convert <strong>η</strong> to the mean <strong>m</strong> and variance <em>v</em>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7U1f4dJ7dAfVGiKJBpVIA.png" /></figure><h4>Characteristics in the Natural Parameter Form</h4><p>In the natural parameter form, it is easy to multiply and divide Gaussians by another Gaussian.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eD64qD_vD8iBaCOfyfnFDA.png" /></figure><p>If we don’t have to keep track of the normalization coefficients, then we can just add or subtract <strong>η’</strong>s in the exponents, and then complete the square.</p><h4>Characteristics in the Mean-Variance Form</h4><p>In the 3rd step of the algorithm, we use the moment-matching. It involves the calculation of the expectations of <strong>θ</strong> and<strong> θ</strong>ᵀ<strong>θ</strong>.</p><p>The expectation of <strong>θ</strong> is simply the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMkQGl_RRvylM7NqTosYYQ.png" /></figure><p>The expectation of <strong>θ</strong>ᵀ<strong>θ</strong> can be derived as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIuTePcMdxzk2fpBhYtE7g.png" /></figure><p>We also need to deal with the expectations over a mixture of Gaussians. They can be expressed as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9ccUY_k1LoQ84Z3eKByGA.png" /></figure><p>The expectation over the mixture of Gaussians is the weighted sum of the expectations over each of the Gaussians.</p><p>We have covered the spherical Gaussians in this section. Let’s move on to the actual algorithm.</p><h3>Composition and Initialization of the Approximation q(<strong>θ</strong>)</h3><p>The approximation q(<strong>θ</strong>) for the joint distribution p( <strong>θ</strong>, <em>D</em>) is factorized into N+1 factors f◌̂ᵢ(<strong>θ</strong>) according to the factorization of p( <strong>θ</strong>, <em>D</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Np2AhI_O8kGLbtADVUJSYQ.png" /></figure><p>For f◌̂₀(<strong>θ</strong>), we can use the prior in the natural parameter form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gixt6UROpJrUrOooMQ374w.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtAoQpKAld9ZLxQj7G1neA.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IscPGJ02CxYjOdvQ-jiVcw.png" /></figure><p>Through the execution of the algorithm, the parameter c₀ stays 1, and it does not have to be learned.</p><p>For the rest, the approximating factors are initialized as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USbT-wrVXhODgzHn1XCVuQ.png" /></figure><p>We initialize cₙ and <strong>η</strong>ₙ to some sensible values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8lQuUIPF1PPmHqwIeWQRg.png" /></figure><p>I think ε should be set to a small number such as 1.0⁻²⁰. Please note that during the execution of the algorithm, <strong>η</strong>ₙ can take some values that are outside the natural parameter space. Care should be taken to keep the value of the last element ηᵥ within (-1/ε, -ε) ∪ (ε, 1/ε) for numerical stability.</p><p>The composition of all the initial approximating factors for the joint distribution p(<strong>θ, </strong><em>D</em>) with <em>D</em> observed can be expressed as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HR4-mT4nODpBLpLGdlWLOA.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8hDm7sEkECsc1x9fVeuHw.png" /></figure><p>We can obtain the approximation of p(<em>D</em>), if we marginalize q(<strong>θ</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cD_exL_vuLKce-f3mpPjCg.png" /></figure><p>This corresponds to (10.223) and (10.224) of PRML, if we convert <strong>η’</strong>s in C to the means and variances, and compare it to the RHS of (10.223) factor-by-factor.</p><p>The approximation of the posterior, which is a proper density function, is expressed as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wmwQKtFSkOQAGl0ES-rPQ.png" /></figure><p>We have covered the initialization and the composition of the approximation q(<strong>θ</strong>). In the following, at each iteration of the algorithm, we try to improve C and <strong>η</strong>, by comparing q(<strong>θ</strong>)/C against the normalized hybrid with KL-divergence.</p><h3>1. Making a Cavity</h3><p>We remove f◌̂ⱼ(<strong>θ</strong>) from q(<strong>θ</strong>) to make a cavity q\ʲ(<strong>θ</strong>). This is done in the natural parameter form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZfHCR900AYLo5D-GeekOg.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UwQBRUTaAcSpakNIVTbmA.png" /></figure><p>This corresponds to (10.214) and (10.215) in PRML, if we convert <strong>η</strong>’s to the mean and the variance form.</p><h3>2. Making a Hybrid</h3><p>We insert to the cavity the posterior p(<strong>x</strong>ⱼ|<strong>θ</strong>), which is the following mixture of two Gaussians over <strong>x</strong>ⱼ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acn5WSF7iCMOndvAlFwByw.png" /></figure><p>Then we multiply q\ʲ(<strong>θ</strong>) by p(<strong>x</strong>ⱼ|<strong>θ</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BG5UAMQ_n54hab20ULiowA.png" /></figure><p>We can swap the roles of <strong>x</strong>ⱼ and <strong>θ </strong>of the 1st Gaussian by some algebraic manipulation as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m11lHajgwWm72YzC9FgElQ.png" /></figure><p>Then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwvYzg4Wi9NABr9BfsVotg.png" /></figure><p>and we have obtained a mixture of two Gaussians over <strong>θ</strong>. If we let</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g3fcuyv05I9hrDwT0lAucA.png" /></figure><p>Then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ug2DKgKlRYZK6tMg_LVwtg.png" /></figure><p>and we have found the hybrid as qₕ(<strong>θ</strong>).</p><p>Alternatively, α + β can be found using the fact that N(<strong>θ</strong>) is a conjugate prior of N(<strong>x</strong>ⱼ) as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43S8_GuE4DMKrTSnOrqtwg.png" /></figure><p>This corresponds to (10.216) in PRML, and it implies the following equality,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3zLT_J8DPtkgm9xP95mAQ.png" /></figure><p>and the parameter α can also be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXKA9RY4AQoHd_HfNoMQ6A.png" /></figure><p>If we interpret qₕ(<strong>θ</strong>) as an approximation of the joint distribution p( <strong>θ</strong>, <em>D</em>), then the following relationships will hold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nf2RFiNhIERHk_AvGEvxgA.png" /></figure><p>This will be used in the moment matching in the KL-divergence.</p><h3>3. Matching the Moments</h3><p>After making the hybrid qₕ(<strong>θ</strong>), we try to make the approximation q(<strong>θ</strong>) as close to it as possible. The closeness is measured by the KL-divergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8yxGUCVIR6nPuAHeRbDcA.png" /></figure><p>To simplify the equations, we momentarily introduce the following notations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oj5ABjyvlGYeRBVic32WNQ.png" /></figure><p>Then, we convert the Gaussians to the mean-variance form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-gS7DyAdPe-FGChyZ2uXg.png" /></figure><p>Then, we apply the moment matching, i.e., equate the expectations of <strong>u</strong>(<strong>θ</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wEPIYybW0sRVRGxm29MCg.png" /></figure><p>And the new parameters are found as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GGqOzdlbD3Ef4u2R2dOzw.png" /></figure><p>Those two equations above correspond to (10.217) and (10.218). The equivalence can be proven by some tedious algebraic rearrangements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gcdqp9UcXtML8PzoD8KBw.png" /></figure><p>The variance can also be proven in the same way.</p><p>After finding the new mean and the variance, we can convert them to the natural parameter form, and we can form the new q(<strong>θ</strong>) as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWlBRkwtQHdlecjnxVnUyQ.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMFz-jpZFdM9H3D_zbWYnw.png" /></figure><p>This concludes the step for the moment matching.</p><h3>4. Updating f◌̂ⱼ(<strong>θ</strong>) from the cavity and the new q(<strong>θ</strong>)</h3><p>After finding the new q(<strong>θ</strong>), we can find the approximating factor f◌̂ⱼ(<strong>θ</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjtnpV3ewtCanFfjK9vyew.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eva8cqk88YTISJdXiGUz7w.png" /></figure><p>If we convert it to the mean-variance form, we will get (10.220), (10.221), and (10.222) in PRML.</p><p>This is the final step and it concludes one iteration. At the next iteration we pick a different approximating factor, make a cavity and a hybrid, perform the moment matching, and then update that factor. The algorithm repeats that process until it converges (if it converges).</p><h3>References</h3><ul><li><a href="https://www.microsoft.com/en-us/research/uploads/prod/2006/01/Bishop-Pattern-Recognition-and-Machine-Learning-2006.pdf">PRML</a> : One of the most popular machine learning books for CS people like me.</li><li><a href="https://tminka.github.io/papers/ep/">The portal page organized by the original author of EP, Dr. Minka.</a></li><li><a href="https://youtu.be/0tomU1q3AdY">Youtube: The Expectation-Propagation algorithm: a tutorial — Part1</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a42ef21bd675" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Analysis on the Z-fighting and the Logarithmic Depth Tests for Computer Graphics]]></title>
            <link>https://medium.com/@e92rodbearings/practical-analysis-on-the-z-fighting-and-the-logarithmic-depth-tests-for-computer-graphics-43509504e065?source=rss-dffcfc53a82------2</link>
            <guid isPermaLink="false">https://medium.com/p/43509504e065</guid>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[3d-design]]></category>
            <category><![CDATA[3d-modeling]]></category>
            <dc:creator><![CDATA[Shoichiro Yamanishi]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 06:18:18 GMT</pubDate>
            <atom:updated>2024-03-12T06:18:18.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="rendering of a model duck in 3d space with perspective projection" src="https://cdn-images-1.medium.com/max/1024/1*moZk9JNcWttwnuegE72Frw.png" /><figcaption>Screenshot of an OpenGL Rendering with Logarithmic Depth Test (All images by the author)</figcaption></figure><h3><strong>Introduction</strong></h3><p>Z-Fighting is a problem that occurs in the depth tests in the rendering pipeline. It is caused by the finite numerical precision for the depth value. The failure will manifest as the incorrect rendering where an object that should be occluded behind another is incorrectly shown on the screen. The failure occurs mainly with the perspective projection transform, but it can also occur with the orthographic projection transform. A good known solution so far is to use the logarithmic depth tests, but care must be taken when implementing and using it. Either way, to deal with the Z-Fighting, it is important to correctly recognize the limitations quantitatively for the given conditions.</p><p>This blog post is intended to be a practical source of information when dealing with the Z-Fighting. It shows why and how it occurs with brief theoretical analyses, and then shows some numerical results from actual implementations with OpenGL. Then it discusses some implementation issues regarding the logarithmic depth tests. It also comes with <a href="https://github.com/ShoYamanishi/ZFightingTools">three accompanying tools with OpenGL</a>. With those tools you can visualize the effects of the Z-Fighting, and conduct experiments by setting the parameters for your environment.</p><h3>Key Takeaways</h3><p>This blog post has three key points that are useful for the modelers and developers to design 3D models and sceneries, and to develop rendering systems. You can skip this section if you are not yet familiar with the coordinate transforms and the depth tests.</p><h4>1. General Rules</h4><p>I recommend the following general rules, after I did some research into this topic, and conducted some analysis and experiments.</p><ol><li>Use the logarithmic Depth of the NF type with gl_FragDepth in the fragment shader wherever applicable.</li><li>If the GPU workload by the fragment shader becomes an issue and if you want to enable the early fragment test, you have two choices: One is setting the log-depth to gl_Position.z at the sacrifice of distorted geometry. The other is to go back to the ordinary perspective projection depth with increased Z-fighting for distant objects. You may have to render the scene in multiple draw calls in order from back to front, each with the cleared depth buffer.</li></ol><h4>2. Minimum Gap to Avoid Z-Fighting</h4><p>The common theme throughout this blog post is the following question:</p><blockquote>Assume there are two points that are close to each other, and distant from the camera approximately by z in VCS. How much gap Δz is required between those two points along the line of sight, so that the depths of them are correctly compared in SCS?</blockquote><p>VCS and SCS denote View Coordinate System and Screen Coordinate System respectively. They will be explained later below.</p><p>And to put the conclusion first, the following are the two most important charts in this blog post.</p><figure><img alt="Plot that shows the theoretical depth values by various depth types." src="https://cdn-images-1.medium.com/max/1024/1*grE-9gIXnmK4EseFJ7CdJA.png" /></figure><figure><img alt="Chart of the observed depth values sampled from a test program." src="https://cdn-images-1.medium.com/max/1024/1*ADRwFS6ub1lhBNNncm6LPQ.png" /></figure><p>The 1st chart above shows the theoretical values assuming the depth format is GL_DEPTH24_STENCIL8 in case of OpenGL. The 2nd chart shows the sampled values taken from a test program, which will be described later. The area below each line or plot is where the false comparison, or Z-Fighting occurs. For example, if two objects are placed 10² = 100 [m] far from the camera, those two must be at least 0.1–0.6 [m] apart along the line of sight, if the logarithmic depth of type CF with C=1/10⁶ is used. The minimum distance will be around 0.01 [m] with the perspective (ordinary) depth type, and around 100 [μm] with the other depth types.</p><h4>3. Effect of Assigning the Log-Depth to gl_Position in the Vertex Shaders</h4><p>Some implementations assign the log-depth to gl_Position to reduce the invocations of the fragment shader by enabling the early fragment test. However, it comes with a negative effect caused by the frustum culling and the linear interpolation in the rasterization. This negative effect distorts the geometry. As it is difficult to show the effect by charts, this blog post comes with an interactive tool to see the effect visually in real time. The following is a screenshot from the tool implemented with OpenGL.</p><figure><img alt="Rendering of two cylindrical polytopes with three types of depth tests." src="https://cdn-images-1.medium.com/max/1024/1*BSgSDzd499oi3R08y8mm4w.png" /></figure><p>The left pane is rendered by the ordinary perspective projection without a logarithmic depth test. The right pane is rendered with the logarithmic depth set in the fragment shader to gl_FragDepth. The center pane is rendered with the logarithmic depth to gl_Position.z, which distorts the geometry as shown with the incorrect occlusion and the distorted shape of the polygons.</p><p>Those were the three key points that I wanted to share in the beginning. The rest of this blog post is organized as follows.</p><h3>Forecast</h3><ul><li>Quick recap on the coordinate transforms used in the graphics rendering.</li><li>Analysis on the ordinary perspective projection transform, and why and how Z-Fighting occurs.</li><li>Analysis on the logarithmic depth test of the NF type, and how it can mitigate the effect of Z-Fighting.</li><li>Analysis on the logarithmic depth test of the CF type, and how it could be advantageous compared with the NF type on certain conditions.</li><li>Discussion on the implementations of logarithmic depth tests.</li><li>Brief explanation of the three accompanying tools. Tools are found in <a href="https://github.com/ShoYamanishi/ZFightingTools">[</a><a href="https://github.com/ShoYamanishi/ZFightingTools">github.com/ShoYamanishi/ZFightingTools</a><a href="https://github.com/ShoYamanishi/ZFightingTools">]</a></li></ul><h3>Recap on the Coordinate Transforms</h3><p>This section briefly goes through the transforms in the graphics pipeline from the 3D world coordinate system to the 2D screen coordinate system. It assumes OpenGL and GLFW in the final stage of the render pipeline, but it is also applicable to other technologies such as Vulkan and Metal.</p><h4>Camera Orientation</h4><figure><img alt="XYZ local coordinate systems for the camera." src="https://cdn-images-1.medium.com/max/862/1*eFK-KYEP6i8h8r-qn4hMPg.png" /><figcaption>Orientation of the Camera in its LCS</figcaption></figure><p>By convention, the camera is oriented in its Local Coordinated System, or LCS such that it is facing the negative Z-direction, and the vertical upward direction is aligned with the positive Y-direction. As explained later, it is identical to the View Coordinate System.</p><h4>Placing and Orienting the Camera in the WCS</h4><figure><img alt="Graphical representation of the position and the orientation of the camera in the world coordinate system." src="https://cdn-images-1.medium.com/max/862/1*kDCDrDI1ANyrfZPmtnbsHQ.png" /><figcaption>Translation and Orientation of the Camera in WCS</figcaption></figure><p>The camera is placed in the World Coordinate System, or WCS by the rotation matrix <strong>R</strong> and the translation vector <strong>v_</strong>c. Those are combined to the 4x4 model matrix as shown below.</p><figure><img alt="The definition of model matrix for the camera that consists of the rotation matrix R and the translation vector vc." src="https://cdn-images-1.medium.com/max/862/1*HbmQvnWWN8uDVHfadAyEbQ.png" /></figure><h4>Bringing the World into the Camera’s LCS</h4><p>To view the objects that are placed and oriented in WCS through the camera, which is also placed and oriented in WCS, you need to bring those objects in the camera’s local coordinate system. This is the view transform defined by the view matrix, and it is the inverse of the camera’s model matrix. The resultant coordinate system is the View Coordinate System, or VCS. This is same as the camera’s LCS.</p><figure><img alt="The view matrix as the inverse of the camera’s model matrix." src="https://cdn-images-1.medium.com/max/862/1*SSBQzO9YRfEByJTix9L_rw.png" /></figure><h4>From VCS to NDCS, and then to SCS</h4><figure><img alt="Graphical representation of the coordinate transform from the view coordinate system to the normalized device coordinate system, and then to the screen coordinate system." src="https://cdn-images-1.medium.com/max/1024/1*Tz_OlwXbJiEKvs7v62x70g.png" /><figcaption>Transformation from VCS to SCS via NDCS</figcaption></figure><p>The coordinates in the VCS are transformed into the Normalized Device Coordinate System, or NDCS. The view frustum defined in the negative Z region of the VCS is transformed into a cube centered at the origin in the NDCS. The positive Z region of the VCS (behind the eye-point) is transformed into the region behind the plane z=f/(f-n) in NDCS. The transform for the plane z=0 in VCS is undefined in NDCS. The coordinates in the NDCS are finally translated into the Screen Coordinate System, or SCS, in which the depth tests are performed with the Z-buffer. The range of the values along the Z-axis changes from [-far, -near) in VCS to [-1.0, 1.0) in NDCS and then to [0, (2²⁴-1)/2²⁴] in SCS for OpenGL (assuming GL_DEPTH24_STENCIL8). Please note that SCS is the rasterized integer coordinate space for the x- and y-directions, and the fixed point number space with the step size of 1/2²⁴ for the z-direction.</p><figure><img alt="The definition of the perspective projection matrix." src="https://cdn-images-1.medium.com/max/862/1*OxsjXle8K8phhigkXDl2VQ.png" /></figure><p>The definition of the perspective matrix is also shown above. Please note that the direction of the Z-axis is flipped through the perspective transform. The VCS is a left-hand coordinate system while the NDCS is a right-hand one. If we focus on the Z-axis, then the transform from VCS to NDCS is given as follows:</p><figure><img alt="Equation from Z in VCS to Z in NDCS." src="https://cdn-images-1.medium.com/max/1024/1*b3xIVLb34-IaP8KWdVxIPA.png" /></figure><p>The Z-coordinate in SCS is obtained from the one in NDCS with the following simple conversion in case of OpenGL.</p><figure><img alt="The equation to map Z in NDCS to Z in SCS." src="https://cdn-images-1.medium.com/max/1024/1*7BmVXH6ok6FOvUFntait4A.png" /></figure><p>Z*_ndcs is the sampled and interpolated value of Z_ndcs. The depth tests are performed in SCS with the Z-buffer. Due to the quantization, two different Z-coordinates z_1 and z_2 in NDCS can get the same value in SCS, if |z_1 - z_2| ≤ 1/2²³, and it causes the Z-fighting.</p><h3>Analysis on the Depths with the Perspective Projection</h3><p>The mapping of the Z-coordinates from VCS to SCS is given by the following function, if we ignore the effect of the interpolation and the quantization.</p><figure><img alt="Function definition of F(z)." src="https://cdn-images-1.medium.com/max/1024/1*fVRArSFMh-0-4mChJNOd4w.png" /></figure><p>And the derivative is:</p><figure><img alt="The definition of the derivative of F(z), dF(z)/dz." src="https://cdn-images-1.medium.com/max/1024/1*IosZyLhusA4AYYpYHaCelw.png" /></figure><p>Assuming the derivative does not change in the vicinity of z, and considering the granularity of the Z-buffer is 1/2²⁴, the minimum gap Δz_vcs required for the Z-coordinates in VCS is given as follows.</p><figure><img alt="Equation to calculate the minimum gap in VCS." src="https://cdn-images-1.medium.com/max/1024/1*31t2uQik2HfrBoLF1vuSQw.png" /></figure><p>And the following charts shows the plots of these functions with <em>n</em> = 0.1 and <em>f</em> at various locations. The near plane at 0.1 can be interpreted as the view finder placed 0.1 [m] from the eye.</p><figure><img alt="Chart that shows the F(z) with various far values." src="https://cdn-images-1.medium.com/max/1024/1*vaZj8BaAlB9TO83Jj2DQ5A.png" /></figure><figure><img alt="Chart that shows the derivative of F(z) for various far values." src="https://cdn-images-1.medium.com/max/1024/1*i_Yorci2KHuqfGZZ0NC3Zg.png" /></figure><figure><img alt="Chart for the minimum gaps for various far values and the plots of the observed values from a test program." src="https://cdn-images-1.medium.com/max/1024/1*gESDI51oKtD67s1NEKZi6A.png" /></figure><p>The last chart also shows the plots of the observed minimum gaps by a batch test program implemented with OpenGL. It is one of three accompanying tools, and it will be described later below.</p><h4>Analysis</h4><p>As the last chart suggests, the minimum gap required increases progressively, and the depth test will become virtually useless approximately -z_vcs &gt; <em>near * 1.0E6</em>. If two objects are placed 1 [km] from the camera, the minimum gap will be approximately 1 [m].</p><p>Also, some articles suggest to place the near and the far planes as close as possible to fully utilize the range of [0,1.0] in SCS, but as the 2nd and the 3rd charts suggest, it will have little effect on the minimum gaps, unless the view frustum becomes very shallow like a pancake, but in this case, there will be little point in using the perspective projection.</p><h3>Analysis on the Logarithmic Depths: NF Type</h3><p>The problem with the depth values in the perspective projection is that it quickly approaches to 1.0 and stays relatively flat, i.e., dF(z)/dz approaches 0 quickly. It is desirable to find a mapping function F(z) from VCS to SCS whose derivative dF(z)/dz stays relatively high. Also, it must have the following characteristics.</p><ol><li>F(-near) ≥ 0 and F(-far) ≤ 1.</li><li>F(z) is one-to-one mapping.</li><li>F(z) is monotone decreasing, i.e., -z1_vcs &gt; -z2_vcs =&gt; z1_scs &gt; z2_scs.</li></ol><p>The following logarithmic depth is one such function.</p><figure><img alt="Definition of F(z) for the logarithmic depth of type NF." src="https://cdn-images-1.medium.com/max/1024/1*vYcQlI-4ntosL_mhvFYnNA.png" /></figure><figure><img alt="The definition of the derivative of F(z) for the logarithmic depth of type NF." src="https://cdn-images-1.medium.com/max/1024/1*UgD6-Zr29ECostxu3tPb7g.png" /></figure><p>And the following 3 charts show the function plots, and the theoretical minimum gaps and the observed values in the test program.</p><figure><img alt="Chart that shows the F(z) with various far values." src="https://cdn-images-1.medium.com/max/1024/1*hQUH5d3Vsr0VX_33gHREPw.png" /></figure><figure><img alt="Chart that shows the derivative of F(z) for various far values." src="https://cdn-images-1.medium.com/max/1024/1*ne2ZM92V2c-kGtv6NwWJkA.png" /></figure><figure><img alt="Chart for the minimum gaps for various far values and the plots of the observed values from a test program." src="https://cdn-images-1.medium.com/max/1024/1*A2FaeZWvugloU5iSkunung.png" /></figure><h4>Analysis</h4><p>As the 3rd chart shows, the minimum gap is much more favorable with the logarithmic depth, compared with the mapping with the ordinary perspective projection.</p><p>For two objects that are approximately 1 [km] from the camera, the minimum gap will be 1 [mm] (ham slice). For two objects 1 [m] distant from the camera, the minimum gap will be 1 [μm] (size of bacteria). This ratio of distance to the gap stays the same at 1/10⁶ at any distance in (-near, -far).</p><h3>Analysis on the Logarithmic Depths: CF Type</h3><p>This is a parametric form of a logarithmic depth mapping with a parameter ‘c’ <a href="https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html">[Outerra2009]</a>. This seems to be an attempt to further improve the NF Type by bringing the pseudo near plane closer to the far plane without narrowing the domain of F(z). The parameter ‘c’ can be considered the reciprocal of ‘near’, i.e., c=1/n. The definition and its derivative are given as follows.</p><figure><img alt="Definition of F(z) for the logarithmic depth of type CF." src="https://cdn-images-1.medium.com/max/1024/1*i7Tu8v4odRW5PTJkZM_dag.png" /></figure><figure><img alt="The definition of the derivative of F(z) for the logarithmic depth of type CF." src="https://cdn-images-1.medium.com/max/1024/1*eZfRFxRVG_5zigmHBL2pEA.png" /></figure><p>And the following charts show the plots for f = 10¹⁰, and c = 1.0, 1/10³ and 1/10⁶.</p><figure><img alt="Chart that shows the F(z) with various far values." src="https://cdn-images-1.medium.com/max/1024/1*KH1JbvTRVwZCDf16Lwtk5g.png" /></figure><figure><img alt="Chart that shows the derivative of F(z) for various far values." src="https://cdn-images-1.medium.com/max/1024/1*v5sp3lb4M2py5x72_t5WxQ.png" /></figure><figure><img alt="Chart for the minimum gaps for various far values and the plots of the observed values from a test program." src="https://cdn-images-1.medium.com/max/1024/1*yah7kRjvVPoutJVNsgq6sQ.png" /></figure><h4>Analysis</h4><p>Compared with the NF type, there is little gain in using the CF type.</p><p>The difference between NF and CF types can be analyzed with the following approximated derivatives.</p><p>For the NF-type:</p><figure><img alt="Approximated derivative of F(z) for the NF type." src="https://cdn-images-1.medium.com/max/1024/1*NdM6PWB5gPR_LmRSABCfxw.png" /></figure><p>For the CF-type:</p><figure><img alt="Approximated derivative of F(z) for the CF type, for small -Z in VCS." src="https://cdn-images-1.medium.com/max/1024/1*Y09uLGhh5GcaArimd1D8Hg.png" /></figure><figure><img alt="Approximated derivative of F(z) for the CF type, for large -Z in VCS." src="https://cdn-images-1.medium.com/max/1024/1*1AWFq76LD6jh8Hxmeb4JZQ.png" /></figure><p>If -z_vcs is sufficiently large, the major difference is in the denominator. Those two types are approximately the same, if we set c=1/n. If we set n=1/10¹ and c=1/10⁶, then:</p><figure><img alt="The gain of using CF type with C=1.0E-6 to the NF type is 2.75." src="https://cdn-images-1.medium.com/max/1024/1*WGZUSumJV-L-yEd8vBBTKw.png" /></figure><p>and roughly speaking the minimum gap required with the CF type will be 2.75 times smaller than the gap with the NF type. If c=1/10³, then it will be 11/7 =1.57 If c=1.0, then the gain will be 11/10=1.1.</p><p>If -z_vcs is small, then dF(z)/dz and the minimum gaps for the CF type will become a constant. If c=1/10⁶, then |dF(z)/dz| ≅1.09/10⁷, and the minimum gap ≅ 0.55 [m]. If c=1/10³, then |dF(z)/dz| ≅ 6.0/10⁵, and the minimum gap ≅ 9.6/10⁴ ≅ 1 [mm]</p><p>As shown above, you will have to set a significantly lower value to c, say, c = 1/10⁶ for some meaningful gain for -z_vcs * c &gt;&gt; 1.0 compared with the NF type, but the drawback is the large minimum gap for -z_vcs * c &lt;&lt; 1.0.</p><p>For most of the practical use cases, c = 1/10⁶ will be impractical due to the large constant minimum gap for small Z-coordinates. If c = 1/10³, it will be acceptable for many use cases, but the gain you will get for the large Z-coordinates will not be significant.</p><p>The above argument implies that the the NF type will work well for the majority of the use cases. This concludes the analyses on the depth tests. Let’s move on to the implementation issues.</p><h3>Implementation of Logarithmic Depth Shaders</h3><h4>1. Sample Implementation of the NF type with gl_FragDepth</h4><p>The following is a sample vertex shader, which passes the Z-coordinates of VCS onto the fragment shader in the variable position_vcs_z.</p><pre>#version 330 core<br><br>in vec4 position_lcs;<br><br>uniform mat4 P;<br>uniform mat4 V;<br>uniform mat4 M;<br><br>out float position_vcs_z;<br><br>void main() {<br><br>    position_wcs = M * position_lcs;<br>    vec4 position_vcs = V * position_wcs;<br>    position_vcs_z = position_vcs.z;<br>    gl_Position  = P * position_vcs;<br>}</pre><p>And the following is a sample fragment shader that sets the logarithmic depth of the NF type with the (interpolated) Z-coordinates in VCS in position_vcs_z. It sets the depth value to gl_FragDepth.</p><pre>#version 330 core<br><br>in float position_vcs_z;<br><br>uniform float log_far;  // = log( 1.0e6  );<br>uniform float log_near; // = log( 1.0e-1 );<br><br>out vec4 color_out;<br><br>void main()<br>{<br><br>    float log_z = log( max( 1.0e-30, -1.0 * position_vcs_z ) );<br>    gl_FragDepth = ( log_z - log_near ) / ( log_far - log_near );<br><br>    color_out = vec4( 1.0, 1.0, 1.0, 1.0 );<br>}</pre><h4>Issue: Early Depth Test can not be Applied.</h4><p>Due to the explicit assignment of a value to gl_FragDepth in the fragment shader, the early fragment test can not be enabled. This is true even with GL_ARB_conservative_depth as follows.</p><p>If GL_ARB_conservative_depth is enabled, you could redeclare gl_FragDepth as follows.</p><pre>#extension GL_ARB_conservative_depth : enable<br>layout(depth_less) out float gl_FragDepth;</pre><p>The attribute has to be ‘depth_less’, as |F(z)| &lt; |gl_Position.z/gl_Position.w| for the domain -far &lt; z &lt; -near. It will not enable the early depth test, as the fragment shader could bring the pixel forward with a less Z-coordinate in SCS. ( To enable the early depth test with the explicit assignment of gl_FragDepth in the fragment shader, the attribute should be ‘depth_greater’, assuming the ordinary <em>glDepthFunc(GL_LESS) </em>is specified.)</p><h4>2. Sample Implementation of type NF with gl_Position.z</h4><p>The following code snippet is a sample vertex shader, which assigns the logarithmic depth to gl_Position.z. Please note that the depth value assigned to gl_Position is not in SCS whose range is [0,1), but in NDCS, whose range is [-1, 1).</p><p>There is no task for the fragment shader, as the depth is implicitly set to 2.0 * gl_FragCoord.z/gl_FragCoord.w - 1.</p><pre>#version 330 core<br><br>in vec4 position_lcs;<br>uniform mat4 P;<br>uniform mat4 V;<br>uniform mat4 M;<br>uniform float log_far;  // = log( 1.0e6  );<br>uniform float log_near; // = log( 1.0e-1 );<br><br>void main() {<br>    position_wcs = M * position_lcs;<br>    vec4 position_vcs = V * position_wcs;<br>    gl_Position  = P * position_vcs;<br>    float log_z_vcs = log( max( 1.0e-30, -1.0 * position_vcs.z ) );<br>    float log_z_ndcs = (log_z_vcs - log_near)/(log_far - log_near) * 2.0 - 1.0;<br>    gl_Position.z = log_z_ndcs * gl_Position.w;<br>}</pre><h4>Issue: Geometric Distortion</h4><p>Assigning the depth in gl_Position enables the early fragment test, and hence it can reduce the GPU workload by reducing the number of invocations of the fragment shader. However, as the interpolation by the sampler &amp; the rasterizer before the fragment shader in the pipeline depends on the value in gl_Position, changing the Z-coordinate in it will distort the geometry. Especially, if the vertices are placed behind the camera, i.e., the Z-coordinates in VCS are positive, they have to be clamped to some negative values. The severity of the distortion is difficult to analyze quantitatively, but here’s a rule of thumb based on some experiments.</p><ul><li>The vertices of the objects to be rendered should reside in the view frustum. the closer to the center, the less distortion.</li></ul><p>For example, it will be reasonably distortion-free if you render a 3D object that consists of some fine meshes near the center of the screen. However you should avoid the following types of objects.</p><ul><li>Floor tiles that spans across the view frustum, or spans both positive and the negative Z regions.</li><li>Long beams that consist of long triangles or that reach both sides of the view frustum.</li><li>Grid patterns that consists of long and thin strips.</li></ul><p>In general, you should avoid assigning the depth in the vertex shader. If you really have to use this type, you have to be always aware that the geometry is distorted.</p><h3>Tools</h3><p>There are three accompanying tools that come with this article. They are found in the following repository in Github.</p><ul><li><a href="https://github.com/ShoYamanishi/ZFightingTools">[</a><a href="https://github.com/ShoYamanishi/ZFightingTools">github.com/ShoYamanishi/ZFightingTools</a><a href="https://github.com/ShoYamanishi/ZFightingTools">]</a></li></ul><h4>1. depth_test_interactive</h4><p>This tool visualizes the Z-fighting interactively based on the current configuration. This tool renders two quads, or planes that are centered at the Z-axis with 3 types of depth tests. You can change the Z-coodinates of the two planes and the parameters for the logarithmic depth interactively with the keyboard and the mouse wheels.</p><figure><img alt="The rendering with three panes, each renders two quadrilaterals with specific depths." src="https://cdn-images-1.medium.com/max/1024/1*l2JHhAhFzZDC4NStd7Ys6Q.png" /></figure><p>The figure above is a snapshot of the tool with the following parameter setting.</p><ul><li>Plane 1 (red) placed at z=-52.104729</li><li>Plane 2 (blue) placed at z=-52.104507</li><li>Far = 131954.781250 / Near = 0.1 / C = 0.001</li></ul><p>As you can see, the depth test with the ordinary perspective projection fails, while the two logarithmic depth tests succeed.</p><h4>2. depth_test_shader_comparator</h4><p>This tool visualizes the geometric distortion induced by the altered gl_Position with the logarithmic depth assigned to the Z coordinate.</p><figure><img alt="Rendering of the tool that has three panes, each of which rendered with different depth techniques. The center pane is distorted due to the distortion in the geometry." src="https://cdn-images-1.medium.com/max/1024/1*eM4wnZDcFEgAKvhpcNxoUA.png" /></figure><p>The figure above is a snapshot of the tool. It renders a composition of two cylindrical polytopes. There are three panes. The left pane is rendered with the normal perspective depth test. The center pane is rendered with the logarithmic depth of the NF type, with the depth value assigned to gl_Position in the vertex shader. The right pane is rendered with the NF type, but the value is assigned to gl_FragDepth in the fragment shader. As you can see, the rendering of the center pane has incorrect occlusions and the significantly distorted geometry of the red polytope.</p><p>You can change the following parameters interactively, and see the effect in real time.</p><ul><li>Length and the radius of the cylindrical polytopes.</li><li>Position and the orientation of the cylindrical polytopes</li><li>Position and the orientation of the camera.</li></ul><h4>3. depth_test_batch</h4><p>This is a command line batch tester to find the minimum gap by actually running the rendering quads to a frame buffer with OpenGL. For each point Z_vcs along the negative Z-axis in VCS, it finds the minimum gap Δz between two planes by a combination of the grid search and the binary search. To mitigate the effect of the false positives, it performs multiple tests (the number is specified by the command-line parameter ‘<em>-num_perturbed_samples</em>’. For each test, small random perturbation is added to the Z-coordinates of the planes. If all the tests have succeeded, then it is considered ‘pass’ for the Z-vcs and Δz.</p><p>The tool takes the following parameters.</p><ul><li>-depth_type &lt;”perspective”/”logfn”/”logcf”&gt;</li><li>-near &lt;near(positive)&gt;</li><li>-far &lt;far(positive)&gt;</li><li>-c &lt;parameter C for CF-type&gt;</li><li>-num_points &lt;num points&gt;</li><li>-num_perturbed_samples &lt;num samples&gt;</li></ul><p>Then the tool samples Δz for the Z-coordinates in VCS, or Z_vcs. The number of Z_vcs are given by the parameter ‘-num_points’, and the points are evenly distributed between -near and -far in the logarithmic scale. The results are printed to the standard error output.</p><p>The following is a sample invocation of the command used for the charts above.</p><pre>./depth_test_batch -depth_type perspective -near 1.0e-1 -far 1.0e10 -c 1.0 -num_points 100 -num_perturbed_samples 5</pre><h3>Conclusion</h3><p>This blog post covered the important points when dealing with Z-fighting for the practical use cases. The most care-free way to handle it is to use the logarithmic depth of type NF with gl_FragDepth. It should cover the most of the use cases. If it does not meet your performance requirement, then you can use other methods, but you should be aware of the drawbacks. Either way, I hope this post and the tools will help you analyze the issues with the Z-fighting and make better decisions when you have to cope with it.</p><p>Happy programming.</p><h3>References</h3><ul><li><a href="https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html">https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html</a> : The OG pioneering work by Outerra. This is one representative post, and there are some other interesting posts regarding the Z-Fighting there.</li><li>A <a href="https://threejs.org/examples/#webgl_camera_logarithmicdepthbuffer">sample code</a> provided by Three.js: This is a nice visual demo that runs on the web browsers. The near plane is set at 1.0E-6, and the far plane is at 1.0E27.</li><li><a href="https://registry.khronos.org/OpenGL/extensions/ARB/ARB_conservative_depth.txt">The original proposal and spec of GL_ARB_conservative_depth by Chronos group</a>.</li><li><a href="https://www.khronos.org/opengl/wiki/Early_Fragment_Test">Description of Early Depth Test by OpenGL.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43509504e065" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rigid Body Simulation Basics — Part 2: From Positional Constraints to Velocity Space Constraints]]></title>
            <link>https://medium.com/better-programming/rigid-body-simulation-basics-part-2-from-positional-constraints-to-velocity-space-constraints-d76b52a26fd5?source=rss-dffcfc53a82------2</link>
            <guid isPermaLink="false">https://medium.com/p/d76b52a26fd5</guid>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[physics-simulation]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <dc:creator><![CDATA[Shoichiro Yamanishi]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 00:12:38 GMT</pubDate>
            <atom:updated>2023-08-31T21:40:00.360Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rigid Body Simulation Basics — Part 2: From Positional Constraints to Velocity Space Constraints</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbD-Il5abVtGwhMSwD6sng.png" /><figcaption>Screen captures from constraint-based rigid body simulators by author</figcaption></figure><h3>Introduction</h3><p><a href="https://medium.com/@e92rodbearings/rigid-body-simulation-basics-part-1-from-newtons-law-to-a-constrained-optimization-problem-fc3b2148ad5d">In Part 1</a>, we covered the core idea of the velocity-space constraint-based rigid body simulation. We derived a constrained convex optimization problem from Newton’s Second Law and the velocity-space constraints. The problem was then converted to a mixed linear complementarity problem, and it was solved by an iterative or a pivot-based solver. We have not yet covered the main topic of Part 2:</p><p><em>How do we make velocity-space constraints?</em></p><p>In this article, we will derive velocity-space constraints from positional ones. We still limit our discussion to the two-dimensional linear motions and omit the treatment of the angles and orientations to focus on the core argument. However, applying it to the angular motions in the three-dimensional space should be easy once you have the basic idea.</p><p>This article is organized as follows. First, we introduce the positional constraints and study their characteristics briefly, and then we convert the positional constraints into the velocity space by <a href="https://dl.acm.org/doi/10.1145/293701.293721">the <em>linearization</em> technique</a>.</p><p>Finally, we look at the part of the code of the sample program where the constraints are generated. Let’s begin.</p><h3>Positional Constraints</h3><p>Assume we are given a positional constraint between two rigid bodies, k0 and k1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5A300ZunOFU8LO-gfJ4QXw.png" /></figure><p>Or, if it is between one rigid body k0 and a fixture in the world coordinate space, we have the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4zJTOWfjlvL1AqgtXu1Bw.png" /></figure><p>where <strong>x</strong>ₖ₀(t) and <strong>x</strong>ₖ₁(t) are the positions of the center of mass of the rigid bodies k0 and k1 at time step t, respectively, and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tq59vp6K80t_e8j_c2CIg.png" /></figure><p>indicates either ≥(inequality) or =(equality) for notational convenience. The <strong>n</strong>ᵢ₀ ∈ R², <strong>n</strong>ᵢ₁ ∈ R², and bᵢ ∈ R are the parameters of the linear constraint. As you can see, we deal with the linear constraints, i.e., LHS is the linear function of <strong>x. </strong>Let’s also introduce the following three new vectors for notational convenience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcCP0sI2ogfMCH8F6Tlw3w.png" /></figure><p>Then, the constraint above will be more compact, and it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMQhdOPA12Epv_ESvNBlqA.png" /></figure><p>For the constraints with a single term on the LHS of the equation (2), we can conceptually use a dummy rigid body k1 for <strong>x</strong>ₖ₁(t) and set <strong>n</strong>ᵢ₁ to 0.<br>We want to convert it to a velocity-space constraint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jaEReI7JE8VxV5EBJekrUw.png" /></figure><p>And we would like Fᵢ to be a linear function of <strong>v</strong>ₖ₁(t). We will later find out this is indeed the case. The converted velocity-space constraint will be expressed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-6uYbargGudWHbhtjWL6Q.png" /></figure><p>First, let’s examine the characteristics of the vector <strong>n</strong>ᵢ and the scalar bᵢ briefly. Please take a look at Fig. 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_kxQpeZGRMAWnUp_x2-BQ.png" /><figcaption>Figure 1: <strong>n</strong>ᵢ₀, <strong>n</strong>ᵢ₁, and bᵢ as functions of <strong>x</strong>ₖ₀(t) and <strong>x</strong>ₖ₁(t).</figcaption></figure><p>As we still limit our discussion to the two-dimensional linear motions, <strong>n</strong>ᵢ₀ and <strong>n</strong>ᵢ₁ are usually in the opposite direction of each other and of equal length, often the unit length. Usually, <strong>n</strong>ᵢ∗ indicates the direction along which two objects should stay away or stay at the specified distance. And ∆t·bᵢ indicates the signed distance of <strong>x</strong>ₖ₁ from <strong>x</strong>ₖ₀ in the direction of <strong>n</strong>ᵢ₁, or vice versa. As we are dealing with rigid bodies, i.e., they don’t deform over time, <strong>n</strong>ᵢ and bᵢ are not functions of time t but functions of <strong>x</strong>ₖ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0wmihjeks_717AZtqvglA.png" /></figure><p>In fact, for the linear velocities, it is usually the case that only the relative position of <strong>x</strong>ₖ₁ to <strong>x</strong>ₖ₀ matters, i.e., they are translation-invariant. In this case, let <strong>x</strong>ᵣ = <strong>x</strong>ₖ₁ − <strong>x</strong>ₖ₀, and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruiYzDWH0-hcDAuaX84pZQ.png" /></figure><p>If the two objects are polygons, it is mostly the case that <strong>n</strong>ᵢ∗and bᵢ are constant in the vicinity of the current <strong>x</strong>ₖ₀, and <strong>x</strong>ₖ₁.</p><p>We have a rough idea about what <strong>n</strong>ᵢ∗and bᵢ look like. Now, let’s derive velocity-space constraints from positional ones.</p><h3>Conversion by Linearization</h3><p>This section will discuss the standard way to convert positional constraints to velocity-space ones. It is called ‘<em>linearization’</em> <a href="https://dl.acm.org/doi/10.1145/293701.293721">[SS98]</a>.</p><p>In preparation, we introduce three pairs of positions as follows. Please take a look at Fig. 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAJAmf09KndcyEbNcVfoCg.png" /><figcaption>Figure 2: <strong>x</strong>ₖ(t_c), <strong>x</strong>ₖ^*(t_c+∆t), and <strong>x</strong>ₖ(t_c+∆t).</figcaption></figure><ul><li><strong>x</strong>ₖ(t_c) denotes the pair of positions at the current time step t_c.</li><li><strong>x</strong>ₖ^*(t_c+∆t) denotes the pair of positions at the next time step t_c + ∆t found without the constraints, i.e., only by Newton’s Second Law. The <strong>x</strong>ₖ^*(t_c+∆t) may violate some of the constraints.</li><li><strong>x</strong>ₖ(t_c+∆t) is the pair we want to find for the next time step in the feasible region.</li></ul><p>Please note that <strong>x</strong>ₖ(t_c) and <strong>x</strong>ₖ^*(t_c+∆t) are known, and <strong>x</strong>ₖ(t_c+∆t) is unknown at this point in the simulation.</p><p>Let</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zV0-svP0jUYzPoPlRr3RA.png" /></figure><p>Then, the positional constraints will become:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpse2pi3K0wM0oSjMfjvTQ.png" /></figure><p>Let’s take the gradient of aᵢ(<strong>x</strong>ₖ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36c50ejFw7Jzb7AMUcUFiA.png" /></figure><p>This shows the rate of the change of <strong>a</strong>ᵢ(<strong>x</strong>ₖ) if we moved <strong>x</strong>ₖ slightly in each axis of <strong>x</strong>ₖ.</p><p>Now, let’s approximate aᵢ(<strong>x</strong>ₖ(t_c+∆t)) from aᵢ(<strong>x</strong>ₖ^*(t_c+∆t)) and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_x2SCiGs2QC_h1Var-og1g.png" /></figure><p>by the first-order Taylor expansion (hence <em>’linearization’</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sStZwyTDcexzdZ4-MupyaA.png" /></figure><p>From here on, we denote</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_x2SCiGs2QC_h1Var-og1g.png" /></figure><p>by ∇^∗aᵢ(<strong>x</strong>ₖ), and denote <strong>x</strong>ₖ^*(t_c+∆t) by <strong>x</strong>ₖ^* to avoid cluttering the equation. Then the equation (10) will become:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewImkA4c5rjtHkootiVfhw.png" /></figure><p>We want to express the constraint in terms of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1SGh5nHMBLssxGiaFkNZPQ.png" /></figure><p>And therefore, we want to have it in the LHS of equation 11. Let’s take the term with <strong>x</strong>ₖ(t_c+∆t), which we want to eliminate from LHS, as it’s an unknown value. For that, we apply the first-order Taylor<br>expansion backwards from t_c+∆t to t_c as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lJ5Bh-g6u5JZXu5ae06ig.png" /></figure><p>Then substitute <strong>x</strong>ₖ(t_c+∆t) in equation (11) with equation (12), and we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2eHFwpC35ZT7z9Db3lgTQ.png" /></figure><p>and then sort the terms to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKn0CeIcggFS1INMQdCwvQ.png" /></figure><p>This is the velocity space constraint we wanted to find. We know <strong>x</strong>ₖ(t_c), and can easily calculate <strong>x</strong>ₖ^*. The only tricky part is ∇^∗aᵢ(<strong>x</strong>ₖ), which is usually calculated from the curvature of the two rigid bodies.</p><p>If <strong>n</strong>ᵢ and bᵢ stay constant, for most cases of the polygon-polygon contact, we can simplify it further with the following argument.</p><p>Since <strong>n</strong>ᵢ and bᵢ stay constant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukfoUTU48oVzXcZCixLBOg.png" /></figure><p>therefore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAKWaax58pL49pidQmKJLg.png" /></figure><p>and the equation gets simplified as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBLnj0qlSBId_lNBciAMfg.png" /></figure><p>As aᵢ(<strong>x</strong>ₖ^*) = <strong>n</strong>ᵢ · <strong>x</strong>ₖ^* + bᵢ, the equation can be further simplified to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zDHz3s00GsozTb9UkXe6AA.png" /></figure><p>This is the most useful form of the constraints in the velocity space we wanted to find. It works well for cases where the curvature of the contact surface is not significant, such as polygon-polygon contacts. Even for curved contacts such as sphere-sphere contacts, we can apply this technique with the caveat described in the section Practical Tips below.</p><h3>Example</h3><p>Now, let’s look at a simple unilateral constraint in action. Please take a look at Fig. 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4Ot0HAJpZicH-gzmiBzuA.png" /><figcaption>Figure 3: Colliding Contact</figcaption></figure><p>It solves the collision of a falling disc against a slope. The following parametric form of s expresses the slope floor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYNSHSuHwvMGrZWz3OiXWA.png" /></figure><p>where <strong>p_</strong>f is a point on the floor surface, <strong>n_</strong>f is the surface normal, and <strong>n</strong>_f^⊥ is the unit vector perpendicular to <strong>n_</strong>f. The disc’s radius is denoted by rₖ. Then, the signed distance of the disc to the floor is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ixDXsTH8d7UsRA3n11rgQ.png" /></figure><p>Assume we have detected a collision of the disc to the floor at the time step t_c+∆t as shown in Fig. 3, i.e., aᵢ(t_c+∆t) &lt; 0. Also, assume the collision detector has given us the contact normal <strong>n_</strong>f. Then, the velocity-space unilateral constraint to solve the collision will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HgNW1k0S1QY5OCCe2Dbnuw.png" /></figure><p>We can apply the same argument to the collisions between two rigid bodies and the joints with bilateral constraints. Chapter 7 of [ESHD05], especially Sections 7.5 to 7.9, contains the comprehensive treatment of the constraints for most joint types.</p><h3>Sample Program</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LtXk7Hg5Pwn1B3fiaquIQ.png" /></figure><p><em>The code is available in </em><a href="https://github.com/ShoYamanishi/RigidBodySimulationBasics"><em>my GitHub repo</em></a><em>. See </em><a href="https://github.com/ShoYamanishi/RigidBodySimulationBasics/blob/main/README.md"><em>README</em></a><em> for the installation instructions. Take a look at the section ‘Sample Porgram’ in </em><a href="https://medium.com/@e92rodbearings/rigid-body-simulation-basics-part-1-from-newtons-law-to-a-constrained-optimization-problem-fc3b2148ad5d"><em>my previous article</em></a><em> first if you haven’t.</em></p><p>Let’s resume our exploration of the code. In the previous article, we briefly looked at the code organization in <a href="https://github.com/ShoYamanishi/RigidBodySimulationBasics/tree/main/SampleApp01/SampleApp01/Simulation">Simulation</a> and its top-level function Simulator::update(). This article will examine the construction of unilateral and bilateral constraints. The unilateral constraints are used to solve the collisions among the discs and against the walls, and the bilateral constraints keep the seven small discs chained together.</p><h4>Construction of the unilateral constraints</h4><p>Please see the code snippet below. Simulator::update() calls detectCollisions() at (1), which in turn calls detectCollisionPair() at (2) and detectCollisionAgainstWalls() at (3). These latter two functions generate unilateral constraints.</p><pre>class Simulator {<br>    ...<br>    void update( ... ) {<br>        ...<br>        detectCollisions( delta_t ); // &lt;= (1)<br>        ...<br>    }<br>    ...<br>    void detectCollisions( const float delta_t )<br>    {<br>        for ( int i = 0; i &lt; m_discs.size(); i++ ) {<br><br>            for ( int j = i + 1; j &lt; m_discs.size(); j++ ) {<br><br>                detectCollisionPair( m_discs[i], m_discs[j], delta_t );// &lt;=(2)<br>            }<br>            detectCollisionAgainstWalls( m_discs[i], delta_t ); // &lt;= (3)<br>        }<br>    }<br>};</pre><p>Let’s start with the simplest one: detectCollisionAgainstWalls(), which checks one disc for possible collisions against four walls: left, right, upper, and lower. Let’s look at the test against the left wall as an example.</p><pre>    void detectCollisionAgainstWalls( ChainedDisc* d0, const float delta_t )<br>    {<br>        if ( d0-&gt;m_com_tmp.x - d0-&gt;m_radius &lt;= -0.5f * m_area_width ) {// &lt;=(4)<br><br>            const auto signed_dist = d0-&gt;m_com.x - d0-&gt;m_radius + 0.5f * m_area_width; // &lt;= (5)<br>            const Vec2 n0{ 1.0f, 0.0f }; // &lt;= (5)<br><br>            auto* constraint = new VelocityConstraint{ VelocityConstraint::Unilateral, d0, nullptr, n0, n0, -1.0f * signed_dist / delta_t };<br>            m_constraints.push_back( constraint );<br>        }<br>        ...<br>    }</pre><p>This code is best explained graphically. Please take a look at Fig. 4 below.</p><p>The ‘if’ condition at (4) tests if there is an overlap between the left wall and the left side of the disc. Please note that d0-&gt;m_com_tmp holds the temporary position xₖ^*(t_c+∆t) at the next time step t_c+∆t with no constraints applied, while d0-&gt;m_com holds the position xₖ(t_c) at the current time step t_c.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-jVAdmt6m0hZTDDSb3KeQ.png" /></figure><p>If there is an overlap (often called penetration), then we make one unilateral constraint. The signed_dist and n0 at (5) in the code above correspond to the value of aᵢ(xₖ(t_c)) and nᵢ in equation (18). You can see that the vector n0 is oriented such that the impulse is directed to move the disc further against the wall. We perform the same tests for the other three walls.</p><p>Next, let’s look at the disc-disc collisions in detectCollisionPair().</p><pre>    void detectCollisionPair( ChainedDisc* d0,  ChainedDisc* d1, const float delta_t )<br>    {<br>        if ( d0-&gt;m_next == d1 || d0-&gt;m_prev == d1 || d1-&gt;m_next == d0 || d1-&gt;m_prev == d0 ) { // &lt;= (6)<br>            return;<br>        }<br><br>        const auto v_1_to_0_tmp = d0-&gt;m_com_tmp - d1-&gt;m_com_tmp;<br>        const auto sq_len_tmp   = v_1_to_0_tmp.sq_length();<br>        const auto min_dist = d0-&gt;m_radius + d1-&gt;m_radius;<br><br>        if ( sq_len_tmp &lt;= min_dist * min_dist + EPSILON ) { // &lt;= (7)<br><br>            const auto v_1_to_0 = d0-&gt;m_com - d1-&gt;m_com; // &lt;= (8)<br>            const auto len = v_1_to_0.length(); // &lt;= (9)<br>            if ( len &gt;= EPSILON ) { // &lt;= (11)<br>                const auto signed_dist = len - min_dist; // &lt;= (10)<br>            <br>                const auto n0 = v_1_to_0 / len;<br>                const auto n1 = n0 * -1.0f;<br><br>                auto* constraint = new VelocityConstraint{ VelocityConstraint::Unilateral, d0, d1, n0, n1, -1.0f * signed_dist / delta_t };<br>                m_constraints.push_back( constraint );<br>            }<br>        }<br>    }</pre><p>The check at (6) excludes the collision tests between two chained discs. The code at (7) tests if there is a penetration between two discs in the temporary positions <strong>x</strong>ₖ^*(t_c+∆t). If there is, then we construct one unilateral constraint.</p><p>At (8), (9), and (10), we generate the parameters for the unilateral constraints. The reason why m_com instead of m_com_tmp is used will be described below in Practical Tips.</p><p>The check at (11) avoids cases where the two discs are almost concentric. We simply ignore those cases as the vector v_1_to_0 degenerates to a point, and we can’t get the direction information from it. In a more robust simulator, we would have to deal with those cases using other information, such as velocity.</p><h4>Practical tips for the contact generation for the curved contacts</h4><p>We must be careful when applying the ‘linearization’ with equation (14) if the contact surfaces are significantly curved. The disc-disc contacts with small radii above fall in those cases. To apply equation (14), let’s find the gradient of aᵢ(xᵣ) using xᵣ = x₁ − x₀. The aᵢ(xᵣ), which can be interpreted as the closest distance between two discs, is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qcz8yr806KQxlz5cgEogFg.png" /></figure><p>where r₀ and r₁ are the radii of the discs. The gradient of aᵢ(<strong>x</strong>ᵣ) is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wuKIfwDrKSZ0xhRUDMnTQg.png" /></figure><p>Then using the equation (14),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKEXcHVrTSEpbdnShTBWfw.png" /></figure><p>The asterisk version of xᵣ corresponds to v_1_to_0_tmp in the code above. However, at (8), (9), and (10), we use v_1_to_0, which corresponds to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3sIC7XOeOkz4VSNU2YBemQ.png" /></figure><p>If the curvature of the surface curves is significant, we can no longer apply the linearization, i.e., the difference between <strong>x</strong>ᵣ/||<strong>x</strong>ᵣ|| and <strong>x^*</strong>ᵣ/||<strong>x^*</strong>ᵣ|| becomes nonnegligible. In this case, equation (25) empirically provides a more stable simulation. The simulation would become particularly unstable if the radii of the discs were small or if the time step is big.</p><h4>Construction of the bilateral constraints</h4><p>Now, let’s look at the bilateral constraints. Bilateral constraints are used to chain the seven small discs together.</p><pre>class Simulator {<br>    ...<br>    void update( ... ) {<br>        ...<br>        constructBilateralConstraints( delta_t );<br>        ...<br>    }<br>    ...<br><br>    void constructBilateralConstraints( const float delta_t )<br>    {<br>        for ( auto* disc : m_discs ) {<br><br>            if ( disc-&gt;m_next != nullptr ) {<br><br>                linkTwoDiscs( disc, disc-&gt;m_next, delta_t );<br>            }<br>        }<br>    }<br><br>    void linkTwoDiscs( ChainedDisc* d0, ChainedDisc* d1, const float delta_t )<br>    {<br>        const auto v_1_to_0    = d0-&gt;m_com - d1-&gt;m_com;<br>        const auto len         = v_1_to_0.length();<br>        const auto signed_dist = len - ( d0-&gt;m_radius + d1-&gt;m_radius );<br>            <br>        const auto n0 = v_1_to_0 / len;<br>        const auto n1 = n0 * -1.0f;<br><br>        auto* constraint = new VelocityConstraint{ VelocityConstraint::Bilateral, d0, d1, n0, n1, -1.0f * signed_dist / delta_t };<br>        m_constraints.push_back( constraint );<br>    }<br>};</pre><p>The function linkTwoDiscs() generates one bilateral constraint. In fact, the only difference from the constraint generated by detectCollisionPair() is the equality instead of inequality. The equality means that the two discs be kept at a specific distance (signed distance of 0 in this case).</p><p>That’s pretty much it for the contact generation. We have covered a few simple cases, but the basic principle is the same when we deal with more complex cases using a proper collision detector. It’s also similar when we expand the simulation to the angular motions. We can apply the same techniques described in this article.</p><h3>Conclusion</h3><p>In this article, we have covered the topics of velocity-space linear constraints. We have discussed some crude intuitive meanings of <strong>n</strong>ᵢ and bᵢ, which is useful when you start building constraints from collisions and joints.</p><p>We have used the linearization technique to convert the positional constraints to the velocity ones. Finally, we have seen a simple example of a collision of a disc against a floor and derived a unilateral constraint in the velocity space.</p><p>We have also looked at the potential risk of applying the linearization to the curved contacts and discussed a practical way to handle those cases. Then, we looked at the code of the sample programs where the unilateral constraints are generated for the collisions, and the bilateral constraints are generated to keep the seven discs chained together.</p><p>I hope you enjoyed reading the article and playing with the sample program. In the coming articles, I plan to expand the argument to include angular motions and orientations in the two-dimensional space or dig a bit deeper into the MLCP solvers.</p><p>Happy programming.</p><h3>Further Reading</h3><p>· <strong>[ESHD05] Book: <em>Physics-based Animation</em> by Erleben, et al., Charles River Media</strong><br>Section 7.3 <em>Linearizing</em> treats the linearization of the constraints. I hope my take on this article will be easy to follow and understand. Chapter 7 contains the most comprehensive treatment of the frictional cone and the joint constraints I know.</p><p><strong>· </strong><a href="https://dl.acm.org/doi/10.1145/293701.293721"><strong>[SS98] Article: A Constraint-based Approach to Rigid Body Dynamics for Virtual Reality Applications by Sauer &amp; Schömer, VRST’98</strong></a><br>Section 2.4 <em>Linearization of the contact condition</em> introduces the original linearization technique of the constraints.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d76b52a26fd5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/rigid-body-simulation-basics-part-2-from-positional-constraints-to-velocity-space-constraints-d76b52a26fd5">Rigid Body Simulation Basics — Part 2: From Positional Constraints to Velocity Space Constraints</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rigid Body Simulation Basics — Part 1: From Newton’s Law to a Constrained Optimization Problem]]></title>
            <link>https://medium.com/better-programming/rigid-body-simulation-basics-part-1-from-newtons-law-to-a-constrained-optimization-problem-fc3b2148ad5d?source=rss-dffcfc53a82------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc3b2148ad5d</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <category><![CDATA[physics-simulation]]></category>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[opengl]]></category>
            <dc:creator><![CDATA[Shoichiro Yamanishi]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 22:03:38 GMT</pubDate>
            <atom:updated>2024-07-27T02:23:52.013Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rigid Body Simulation Basics — Part 1: From Newton’s Law to a Constrained Optimization Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbD-Il5abVtGwhMSwD6sng.png" /><figcaption>Screen captures from constraint-based rigid body simulators by author</figcaption></figure><p>This article is intended to be the first article in a series where I plan to discuss some important topics on real-time physics simulation and build an engine incrementally. This first article attempts to explain the core idea of the velocity-space constraint-based physics simulation. It has a small sample program that works on Linux, OpenGL, and iOS with ARKit &amp; Metal <a href="https://youtu.be/Ucx28kM88hQ">[Demo Video]</a>. The core simulation part is written in plain C++.</p><p>With this article and the sample code, I hope the readers will be able to not only deduce the equations and recreate the algorithms by themselves but also to be able to understand the entire working code for a small simulation so that they can get a wholesome perspective view of the simulation technique and can apply the technique to their own games, interactive applications, and visual effects.</p><p>One thing not covered in this article: <em>How to construct velocity-space constraints from the positional constraints?</em></p><p>That will be the topic for the second article.</p><h3>Background</h3><p>There are already many great books, such as physics-based animation by Erleben, Sporring, &amp; Henriksen 2005 [ESHD05], and tutorials on the net, such as <a href="https://siggraphcontact.github.io/">SIGGRAPH course nodes</a>. They usually cover a wide range of topics regarding the physics engine, including affine transformations, geometric tests &amp; operations, torques, orientation in quaternion, inertia tensor, collision detections, etc.</p><p>That’s a vast amount of information, and when the readers get to the parts where the constraint-based model is discussed, they may find it a bit challenging to grasp the core idea of the constraint-based model. Also, as the constraint-based model is presented in the context of full-fledged 3D simulation that involves both local and global coordinate systems, orientation, inertia tensor, etc., the equations presented in the text are cluttered and difficult to follow.</p><p>On the other hand, the lecture notes and course notes are usually compact and very well organized, but for first-time learners, it may be difficult to follow, as the math is usually in generalized compact forms, and there are lots of omissions that are obvious for the experienced practitioners and researchers. Either way, the LCP, and the Lagrangian multipliers are taken for granted, with little argument as to why they are introduced.</p><p>In my view, what’s missing is a compact introductory material with which interested readers can follow the flow of the argument without being stuck in the minutiae and can grasp the core idea of the velocity-space constraint-based physics simulation. That was the motivation for this article.</p><h3>Organization</h3><p>This article is organized as follows. We limit the argument to the two-dimensional linear motions and omit the treatment of the angular motions and orientations.</p><ol><li>We derive the numerical integration step as the initial value problem of the ODE derived from Newton’s second law.</li><li>We introduce the linear constraints in the velocity space and the concept of the feasible region.</li><li>We find the best feasible solution by minimizing the total momentum applied to make corrections.</li><li>We model it as a constrained quadratic optimization problem.</li><li>We solve the problem for the Lagrangian multipliers with an MLCP solver.</li><li>We describe a basic framework for one simulation step, which can be transformed into a computer implementation.</li><li>We briefly look at the code in C++ in the sample program.</li></ol><h3>Intended Audience</h3><p>Anybody interested in the real-time physics engine with a basic understanding of elementary classical mechanics, elementary Calculus, elementary Geometry, and elementary linear algebra.</p><h3>Starting Point: Newton-Euler’s Second Law of Motion</h3><p>The most important equations are given in Newton-Euler’s second law of motion as follows:</p><figure><img alt="First equation: fi=miai, ai=(d/dt)vi Second equation: ti=Iiai+wixIiwi, ai=(d/dt) wi" src="https://cdn-images-1.medium.com/max/1024/1*O1MY4ERTw09VTvR4EQWQnA.png" /></figure><p>where <strong>f</strong>ᵢ is the force applied to the center of mass of the rigid body i, mᵢ is the mass, and <strong>a</strong>ᵢ is the acceleration, <strong>v</strong>ᵢ is the linear velocity. On the 2nd equation, <strong>τ</strong>ᵢ is the torque applied around the center of mass of the rigid body i, <strong>α</strong>ᵢ is the angular acceleration, <strong>ω</strong>ᵢ is the angular velocity, and Iᵢ ∈ R³ˣ³ is the inertia tensor, which changes dynamically depending on the orientation of the rigid body relative to the world coordinate system.</p><p>The relationship between the linear velocity <strong>v</strong>ᵢ and the position <strong>x</strong>ᵢ of the center-of-mass of the rigid body i is defined as follows.</p><figure><img alt="d/dt xi=vi" src="https://cdn-images-1.medium.com/max/1024/1*XC39f0BPEuxPGhwU3ZYHdA.png" /></figure><p>And the relationship between the angular velocity <strong>ω</strong>ᵢ and the orientation qᵢ in quaternion can be defined as follows:</p><figure><img alt="1/2[0,wi]T multiplied by qi=(d/dt)qi" src="https://cdn-images-1.medium.com/max/1024/1*15uxVzMMuS3jZZn6LRIqIA.png" /></figure><p>You don’t have to understand this article&#39;s equations (2) and (4). The point is that we can treat the linear and angular motions independently. This article limits our discussion to the two-dimensional linear velocity and position. If we included the treatment of angles in quaternion, inertia tensor, torque, etc., then the equations would be very cluttered and harder to follow. In the future articles, we will expand the argument to include the two-dimensional rotation and orientation, and then three-dimensional orientation &amp; rotation incrementally.</p><p>If you want to learn the angular motions by (2) and (4) now, I recommend you read Chap. 22, <em>“Basic Classical Mechanics”</em> of the book [ESHD05].<br>There are also plenty of good tutorials available on the internet for those topics.</p><h3>What a Rigid-Body Physics Engine Does</h3><p>A physics engine generates the positions and velocities of rigid bodies at discrete time steps (t₀, t₁, t₂, …), usually at the frame rate of 20–60 [fps] or sometimes higher. The behavior of the physics engine is mainly governed by Newton’s second law of motion as in the equation (2) and (5).<br>This is the most important equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdfeONeLsKFRpkiEpg1h-A.png" /></figure><p>In this article, we handle something called velocity-space constraint-based physics simulation, meaning we integrate the equation above repeatedly to find vᵢ(t) at the given time steps.</p><figure><img alt="(d/dt)v(t)=f/m" src="https://cdn-images-1.medium.com/max/1024/1*Qs0GkIDJzpFmK1TAbLKwsQ.png" /></figure><p>The position is then derived by integrating the following equation 7 after <strong>v</strong>ᵢ(t) has been found.</p><figure><img alt="(d/dt)x(t)=v" src="https://cdn-images-1.medium.com/max/1024/1*wc07aSDmZWf_pxncx4UwkA.png" /></figure><p>On the contrary, the positions are directly solved in the ‘position-based’ physics simulation. It’s been an active research area. In this article, we deal with the velocity-space simulation, as, in my view, it is still the main technique in the industry, and it is easier to understand.</p><p>The integration of equation (6) derives the following initial value problem, where t_c is the current time, and t_c+∆t is the next time step for which we want to find the velocities and positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*en_mlzK91QXO1BCSG-XrAQ.png" /></figure><p>The problem is essentially to find <strong>v</strong>ᵢ(t_c + ∆t) from <strong>v</strong>ᵢ(t_c) and <strong>f</strong>ᵢ(t), t_c ≤ t ≤ t_c + ∆t. There are several ways to solve this numerically, such as <a href="https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods">Runge-Kutta</a> method. In particle physics simulation, the <a href="https://en.wikipedia.org/wiki/Verlet_integration">Verlet integration</a> has been widely used. The Verlet integration requires the positions of the bodies at the previous time step t_c−∆t. If you are interested in the numerical integration of ODEs, you can read Chap. 8 of <a href="https://www.wiley.com/en-us/Elementary+Numerical+Analysis%2C+3rd+Edition-p-9780471433378">[AH05]</a>. In this article, we use the simplest one, called the Euler method, as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDnw08jiG4RSUVQUU0A1iQ.png" /></figure><p>where O(t²) denotes the error term, and the position is derived in the same way as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwnYQn7W3tvbvMNe-L0dVg.png" /></figure><p>and with the Euler method,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbZaXgIdY9piJBv_OIhuCg.png" /></figure><p>The error term of the Euler method is the highest of all the numerical integration methods. For example, the error term for Runge-Kutta is O(t⁴). This is usually not a problem for most of the use cases, as the errors will be corrected by the constraints, which will be described later.</p><p>However, if you want to simulate some trajectories accurately, for example, if you want to simulate the behavior of a javelin thrown by an athlete in a game, you would like to use a more accurate method than Euler.</p><p>This is the basis of the rigid body simulation. With only the numerical integration of Newton-Euler’s second law, we can merely express some orbital planetary motions, but nothing interesting that you want to see in the interactive applications can happen. One way to achieve more realistic and interesting behavior is to add constraints. Let’s look at the constraints in the next section.</p><h4>Velocity space constraints</h4><p>In the rigid body simulation, constraints keep a coffee cup resting on a table from falling through it. Constraints also keep the attachments of a joint together. As we are dealing with ‘<em>velocity-space’ </em>simulation, the constraints are expressed in terms of velocity.</p><h4>Unilateral and bilateral constraints</h4><p>The following is a unilateral (inequality) constraint i between rigid bodies k0 and k1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C23JjroY5OXmrvotok88Qw.png" /></figure><p>This defines the relationship between the velocities <strong>v</strong>ₖ₀ and <strong>v</strong>ₖ₁ of two rigid bodies, k0 and k1. The <strong>a</strong>ᵢ,ₖ₀ and <strong>a</strong>ᵢ,ₖ₁ are usually the unit vectors along which the impulse is applied. Intuitively, the scalar bᵢ can be considered a kind of ‘tightness’ of the constraint. The less the value is, the looser the constraint is, i.e., the more breathing space or margin the constraint has. The greater the value is, the tighter the constraint is, i.e., the more impulse will have to be applied to keep the rigid bodies under the constraint.</p><p>I will explain the impulses later. Such a crude interpretation of <strong>a</strong> and b can be useful later when you start working on the implementation.</p><p>And the following is called a bilateral (equality) constraint i between two objects k0 and k1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y0qX55m6dcQDeQMxcD5Iig.png" /></figure><p>The bilateral constraints are mainly used for joints. The only difference from the unilateral constraints is the equality ‘=’. The intuitive interpretation of the scalar bᵢ is a bit different for the bilateral constraints. The negative values mean that the impulses in the opposite directions to <strong>a</strong>ᵢ,ₖ₀ and <strong>a</strong>ᵢ,ₖ₁ will more likely to be applied. The positive values mean that the impulses in the same directions to <strong>a</strong>ᵢ,ₖ₀ and <strong>a</strong>ᵢ,ₖ₁ will more likely to be applied. You will understand this later when we talk about the impulses.</p><p>If you want to define constraints between one rigid body k0 against the world, i.e., against a static fixture, rather than against another rigid body, then the constraints will have only one term as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4R7F-ixVceF28DuWZLqRw.png" /></figure><p>We could define constraints among three or more rigid bodies, but they would not be of any practical use. (Maybe it could be used if you want to confine three rigid bodies in a simplex or on the boundary of a simplex.)</p><p>At each time step t_c, you define a set of unilateral and bilateral constraints, which limits the region in which <strong>v</strong>ₖ(t_c+∆t), 0≤ k≤K are allowed to reside, assuming there are K rigid bodies. If we concatenate all <strong>v</strong>ₖ(t_c+∆t) into one big vector <strong>u</strong>(t_c+∆t), it will become a vector of dimension 2K, as we are dealing with two-dimensional linear velocity, and the set of unilateral and bilateral constraints defines the region in which it can reside. As the constraints are all in linear terms, the region is an open or closed polygon in the 2K-dimensional space. It is called a<em> feasible region </em>R.</p><p>If <strong>u</strong>(t_c+∆t) ∈ R, then <strong>u</strong>(t_c+∆t) is called a <em>feasible solution</em>.</p><h4>Conventional matrix notation</h4><p>Here I’d like to introduce a matrix <em>J</em> and a vector <strong>b</strong> to handle the constraints more succinctly and organized. They are the convention in the books and the literature. The matrix <em>J</em> aggregates all the coefficients <strong>a</strong> on the left-hand side of the constraints, and the vector <strong>b</strong> concatenates the right-hand side bᵢ, such that <strong>b</strong> = (b₀, b₁, · · ·, bₘ )ᵀ.</p><p>Also, as before, we concatenate the velocities of all the rigid bodies into one single vector <strong>u</strong> = (<strong>v</strong>₀ᵀ, <strong>v</strong>₁ᵀ, · · · , <strong>v</strong>_Kᵀ )ᵀ. Each row, <em>J</em>ᵢ, represents one constraint, and two consecutive columns <em>J</em>,₂ₖ,<em>J</em>,₂ₖ₊₁ represent the rigid body k. Each element bᵢ in <strong>b</strong> represents one RHS for the constraint i. Please note that each row in J is mostly empty (zero) except for two or four elements that correspond to the <strong>a</strong>ᵢ,ₖ₀ and possibly <strong>a</strong>ᵢ,ₖ₁.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcqbOxWZ20nXI-w2F28ILQ.png" /></figure><p>Now we can express all the constraints compactly by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbKMIc6bEkYV1KfjO_mFyQ.png" /></figure><p>where the operator in the middle of (17) is a notational convenience that denotes that the upper part is for the unilateral (inequality) constraints and the lower part is for the bilateral (equality) constraints.</p><h4>Construction of constraints</h4><p>The next problem is how to express the constraints you want to apply in the velocity terms. After all, it is much more intuitive for us to express the constraints in positions. Please see Fig. 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wooOdvACQ6kWfg9QMYVT7g.png" /><figcaption>Figure 1 : Positional Constraints</figcaption></figure><p>If the floor is placed at the height H₀, and if all the spherical rigid bodies must be above the floor, we can add a positional unilateral constraints such that yₖ (t + ∆t) &gt;= H₀ + rₖ, where yₖ and rₖ are the vertical positions and the radius of the rigid body k respectively. If the horizontal position of two rigid bodies, k0 and k1, must be aligned at their centers, then we can add a bilateral positional constraint such that xₖ₀(t+∆t)−xₖ₁(t+∆t) = 0.</p><p>How can we convert those positional constraints into the velocity space? Unfortunately, it is not straightforward, and I’ll explain how to convert them in the next article. For now, let’s assume we already have constraints in the velocity space in this article.</p><h3>Simulation Equations</h3><p>So far, we have introduced two sets of rules for the velocities. One is from Newton’s second Law and the Euler method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyXaWFA5BZbYx2RNEcQSRg.png" /></figure><p>and the other one is the set of velocity-space constraints</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJewL4kIrJvNFppwPUWxEQ.png" /></figure><p>where M ∈ R²ᴷˣ²ᴷ is a diagonal matrix in which the mass of each rigid body is repeated twice as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQ3fvnNFiBbv-EvNiWT-nQ.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSlC2BNkesCeBW5Xkr9WDg.png" /></figure><p>How can we combine those equations (18) and (19)? To put the conclusion first, equation (18) will be expanded to the following with the new term <em>M</em>⁻¹<em>J</em>ᵀ <strong>λ</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hq4mtuC_AMLLHzq_zeadqw.png" /></figure><p>The new term <em>M</em>⁻¹<em>J</em>ᵀ <strong>λ</strong> is introduced to keep <strong>u</strong>(t_c+∆t) in the feasible region, and the vector <strong>λ</strong> ∈ <em>R</em>ᴺ is called the Lagrangian multiplier, where N is the number of constraints.</p><p>What’s the reason for the new term <em>M</em>⁻¹<em>J</em>ᵀ <strong>λ</strong>, and how to find <strong>λ</strong>? Before answering those questions, we have a more fundamental question:</p><p><em>Where should </em><strong><em>u</em></strong><em>(t_c+∆t) be after introducing the constraints?</em></p><p>It must satisfy all the constraints, i.e., it must reside in the feasible region. If there are only bilateral constraints, and there is no energy consumed or added to the system, we can use an argument called the principle of virtual work. In this case, the bilateral constraints are called Holonomic constraints, and the derivation of the new term with the Lagrangian is described in the literature, such as in Section 1.4 of the book Classical Mechanics Third Edition by Goldstein, Poole, &amp; Safko [GPS01].</p><p>It is also often discussed in the simulation literature. However, this argument can not be applied to unilateral constraints in general, as the energy is often consumed during the simulation. For example, imagine an object falling onto a floor and it has come to rest on it after the collision is solved by a set of unilateral constraints that have absorbed the object&#39;s kinetic energy. We need a different approach to the problem.</p><p>Anyway, let’s think about a simple situation as an example: an object is flying along a parabolic trajectory and eventually coming into contact with the floor. Please see Fig. 2, in which the rigid body comes into contact with the floor between t6 and t7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vg9NHzFfKmKFnHJElXzBmA.png" /><figcaption>Figure 2. Trajectory</figcaption></figure><p>How should the collision be solved, and where should the object be positioned within the feasible region? Should that be <strong>x</strong>₁(t7), where the trajectory intersects with the floor plane? Or should that be <strong>x</strong>₃(t7) after a perfectly elastic bounce? Or somewhere else? In any case, how the velocity <strong>v</strong>(t7) be calculated? Let’s find one way of finding the location in the next section.</p><h3>Minimizing the Change in the Total Momentum</h3><p>Let <strong>u^</strong>∗(t_c+∆t) be the concatenated velocities of all the rigid bodies according to only Newton’s second law as if there were no constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31zSrlQoiUIHRYk-lD7yxQ.png" /></figure><p>Let <strong>u</strong>(t_c+∆t) be the yet unknown velocity we try to find within the feasible region. And let the change in the concatenated momenta <strong>p</strong> of all the rigid bodies be defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CoG6ekvn1sw_ot1Cu-0FQ.png" /></figure><p>and its magnitude is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDT2FgpXKSu_bvDC_fpUmA.png" /></figure><p>The<strong> p</strong> is the concatenated set of impulses required to correct the velocity from <strong>u^</strong>∗(t_c+∆t) to <strong>u</strong>(t_c+∆t). We want to find a <strong>p</strong> of the minimum magnitude, i.e. we want to find the smallest set of impulses, just enough to bring <strong>u</strong>(t_c + ∆t) into the feasible region.</p><p>Then we can model the problem of finding <strong>u</strong>(t_c + ∆t) as the following constraint minimization problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cloCG95CeovF2lT97kzJg.png" /></figure><p>or in an equivalent but more tractable form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lW6qgIU2WHSaylwKdm7k9Q.png" /></figure><p>where (t_c+∆t) is omitted for clarity, and <em>J</em>ᵤ and<em> J</em>_b are the unilateral and bilateral part of <em>J,</em> respectively such that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hrub6xYLUGKdhEMqNNziRw.png" /></figure><p>and in the same way,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*her0LIOxrHIhH0xO3aDizQ.png" /></figure><p>This (25) is a <a href="https://en.wikipedia.org/wiki/Quadratic_programming">constrained convex (quadratic) optimization problem</a>, which can be solved by a Lagrangian as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-abwRj1Dl2Oc3Ze22o1HAQ.png" /></figure><p>By taking the derivatives of this Lagrangian, we can derive the following equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3M1HbQUZAg1Q3quBUQ8RLA.png" /></figure><p>The new variable <strong>w</strong> is called <em>the slack variable</em>, which is paired with <strong>λ</strong>ᵤ. With the slack variable, the unilateral constraints can be expressed by <em>J</em>ᵤ<strong>u</strong> − <strong>b</strong>ᵤ = <strong>w</strong>, <strong>w</strong> ≥ 0. The Lagrangian multiplier for the unilateral constraints <strong>λ</strong>ᵤ must be non-negative. Also, for each element λᵢ ∈ <strong>λ</strong>ᵤ, and the corresponding element in the slack variable wᵢ ∈ <strong>w</strong>, only one of two is allowed to be strictly positive, i.e., λᵢwᵢ = 0.</p><p>This is called the complementarity condition, compactly denoted by 0 ≤ <strong>λ</strong>ᵤ⊥<strong>w</strong> ≥ 0. The reason for the complementarity condition is explained with the active/inactive argument in Appendix 4. <em>Optimality Conditions for Smooth Optimization Problems</em> in <a href="http://www-personal.umich.edu/~murty/books/linear_complementarity_webbook/lcp-complete.pdf">[MY97]</a>. You can read this part independently from the rest of the book.</p><p>From the first partial differential equation in (27), the following is derived:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQFNN1sF_nwPLFUZvpbr8g.png" /></figure><p>Substitute <strong>u^</strong>∗(t_c+∆t) in (28) with (21),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fI-yMxZgft63ovx5Q-XD7Q.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TlJYEF5hd4HmkYFY9-VCQ.png" /></figure><p>This is what we wanted to derive. The reason why we form the Lagrangian for the constrained minimization problem and how to derive those equations is best explained in Appendix 4 of Murty’s book <a href="http://www-personal.umich.edu/~murty/books/linear_complementarity_webbook/lcp-complete.pdf">[MY97]</a>. I would recommend you read through the chapter once.</p><p>In this section, we have covered the reason for the new term <em>J</em> ᵀ<strong>λ</strong>. Let’s try to find <strong>λ</strong> in the next section.</p><h3>Solving <strong>λ</strong> with MLCP</h3><p>Now, let’s find <strong>λ</strong>. Let’s see what we have now. From equation (29),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDjT0kVrxtT0UOUkvluZZg.png" /></figure><p>and from the second and third equations in (27),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5i_4lvUk2uAwlteGh6V67A.png" /></figure><p>We want to eliminate <strong>u</strong>(t_c+∆t). For that, we substitute <strong>u</strong>(t_c+∆t) in the two constraints (30) with equation (29) as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZBhFaj8f4_ZW7xKJz73UA.png" /></figure><p>Let’s join those two into a more compact notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Opbg_IULluaxEKa1FiqSQ.png" /></figure><p>Let</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2NSg_7wzvkmPghnIGM-QA.png" /></figure><p>Then we found the following mixed linear complementarity problem or MLCP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mxi9LflzGt_PNeKEl-U-A.png" /></figure><p>Since the entries of the diagonal matrix <em>M</em>⁻¹ are all positive, <em>A</em> is a PD matrix, and an iterative solver can be used. One of the most commonly used is called <em>projected Gauss-Seidel</em>. Later, when we start treating frictions with friction cones, we have to augment the matrix <em>A</em> with the friction cones, making the <em>A</em> non-symmetric. The Gauss-Seidel-based iterative solvers can not be used for non-symmetric matrices, and a pivot-based solver, notably Lemke solver should be used. (It’s not clear to me if any of the fixed-point iterative methods can be used for this type of matrices.</p><p>Chap 9 of <a href="http://www-personal.umich.edu/~murty/books/linear_complementarity_webbook/lcp-complete.pdf">[MY97]</a> discusses the conditions in which the solution by the iterative solvers converge, but it’s unclear to me if any of those cases can be applied to A. According to my experiments using some real data with hexagonal frictional cones, the solutions by the PGS solver did not converge. So for non-symmetric matrices, using a pivot-based solver is safe.) However, the pivot-based algorithms can solve only LCP problems, i.e., problems with only inequality constraints. In this case, we will have to decompose A and eliminate z_b by the Schur complement.</p><p>Let’s decompose the equation (34) by partitioning it into the unilateral and bilateral components as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ufyd7z8At4uPlmuaHoXi1Q.png" /></figure><p>and separate it into two:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiuyuHgVU1ykoWzufr9F2w.png" /></figure><p>From the equation (37),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-xdi7s_GcJGxccauMPoeQ.png" /></figure><p>Substitute <strong>z_</strong>b in the equation (36) with equation (38) to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eM2mWp_GJ_ptQIa2VFCWjg.png" /></figure><p>This is a pure LCP problem for <strong>z</strong>ᵤ, which can be solved by the Lemke solver. The inverse of A₄ is usually found by Cholesky factorization, which may become costly if A₄ is large. After <strong>z</strong>ᵤ is found, we can find <strong>z_</strong>b by equation (38), and then we can advance the simulation for the time step t+∆t with equation (29).</p><p>If you want to use an iterative solver with friction, i.e., if you want to keep the matrix <em>A</em> PD and want to handle friction, then something called boxed constraint can be used, which will be described in a future article. Or you can read 1.7 <em>The Boxed Linear Complementarity Problem Model</em> in <a href="https://siggraphcontact.github.io/">SIGRAPH’22 Course Notes</a>.</p><h3>Recap on Theory</h3><p>So far, we have covered the core idea of the velocity-space constraint-based rigid body simulation. Let’s recap what we have discussed. The physics engine finds the velocities at the next time step based on a numerical integration of Newton-Euler’s second law and on the constraints. To handle the constraints, we have modeled the problem as a minimization of the total momentum to correct the velocities such that they stay in the feasible region.</p><p>The Lagrangian is formed as a constrained quadratic optimization problem, then transformed into the mixed linear complementarity problem. The MLCP problem is solved by mainly two types of solvers: PGS (iterative) and Lemke (pivot).</p><p>In an actual implementation, one iteration for the time step t_c+∆t can consist of the following steps:</p><ul><li>Find the force <strong>f</strong>ₖ for each rigid body k.</li><li>Update <strong>u^</strong>∗(t_c+∆t) and <strong>x</strong>^∗(t_c+∆t) from Newton-Euler second law with the Euler step.</li><li>Run collision detection to find contact pairs based on <strong>u^</strong>∗(t_c+∆t) and <strong>x</strong>^∗(t_c+∆t).</li><li>Construct unilateral and bilateral constraints in <em>J</em> and <strong>b</strong> for the contact pairs and the joints.</li><li>From <em>J</em>, <strong>b</strong>, and <strong>u^</strong>∗(t_c+∆t), form an MLCP into A<strong>z</strong>+<strong>q</strong>=[<strong>w</strong>|0]ᵀ</li><li>Solve the MLCP for <strong>z</strong>, i.e., <strong>λ</strong>.</li><li>Update <strong>u</strong>(t_c+∆t) and <strong>x</strong>(t_c+∆t) from Newton-Euler’s second law with the Euler step with the induced impulses <em>J</em>ᵀ <strong>λ</strong>.</li></ul><h3>Sample Program</h3><p><a href="https://youtu.be/Ucx28kM88hQ">[Link to video]</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LtXk7Hg5Pwn1B3fiaquIQ.png" /></figure><p>Now, let the fun part begin. Grab the code for the sample programs from <a href="https://github.com/ShoYamanishi/RigidBodySimulationBasics">my GitHub repo</a>. It comes in two types: a command line OpenGL program for Linux (including MacOS with no guarantee) and an AR App for iOS.</p><p>The program shows ten discs confined in a rectangular region. They roll around based on Newton’s second law. For the discs to avoid collisions against each other and the walls, unilateral constraints are applied. The seven small discs are linked together to form a chain. A set of bilateral constraints realizes the chain. There are two types of forces applied to each disc. One is the gravity which is controlled by the iOS device&#39;s tilt or the mouse cursor&#39;s location relative to the center of the screen. The other is the torsional forces applied to the seven chained discs. Those forces make a pool noodle like behavior for the chained discs.</p><h4>Build and Run</h4><p><strong>iOS</strong></p><p>For iOS, open <a href="https://github.com/ShoYamanishi/RigidBodySimulationBasics/tree/main/SampleApp01/SampleApp01.xcodeproj">SampleApp01/SampleApp01.xcodeproj</a> with XCode, plug an iOS device in, build and run. It’s an AR App. After opening the App, hold it steady for a short while to let AR calibrate itself. You will get a screen with a camera image and ten superimposed discs. Tilt the device to let the discs roll with gravity. The slider below controls the strength of the torsional forces applied to the seven small discs chained together. I tested it with iPhone 13 mini &amp; iOS 16.6 on Mac mini M1, 2020 Ventura 13.5, and XCode 14.3.1.</p><p><strong>Linux</strong></p><p>For Linux, open a terminal, go to <a href="https://github.com/ShoYamanishi/RigidBodySimulationBasics/tree/main/SampleApp01/SampleApp01/LinuxOpenGL">SampleApp01/SampleApp01/LinuxOpenGL</a> and follow the usual CMake process.</p><pre>$ cd &lt;path/to&gt;/SampleApp01/SampleApp01/LinuxOpenGL<br>$ mkdir build<br>$ cd build<br>$ cmake ..<br>$ make VERBOSE=1<br>$ ./sample_app_01</pre><p>You need to have GLEW, GLFW, and GLM installed on the machine (and lots of dependent packages), usually installed by the package manager. For Ubuntu, I tested it with Ubuntu 22.04.3 on Intel Core i5 and Intel 640. See the README in the repo.</p><p><strong>Notes on macOS</strong>: It also works on my Mac (Mac mini M1, 2020, Ventura 13.5), but it may be a bit tricky to get it up and running. OpenGL is no longer officially supported, and you may encounter some problems around GLFW. <a href="https://github.com/ShoYamanishi/RigidBodySimulationBasics/blob/main/SampleApp01/SampleApp01/LinuxOpenGL/CMakeLists.txt">CMakeLists.txt</a> is configured to use a locally-built GLFW for macOS.</p><p>Start the command ./sample app 01. A window will pop up with ten discs in it. The forces are applied to the discs according to the cursor&#39;s location relative to the center of the screen. The forces depend on the direction and the distance from the center of the screen. Arrow keys control the strength of the torsional forces applied to the seven small discs chained together. The current strength is printed to the console. ‘Up’ and ‘Left’ increases the forces, and ‘Down’ and ‘Right’ decreases it.</p><h4>Code overview</h4><p>Now, let’s take a look at the code briefly. In this article, we will briefly examine the code organization relevant to the rigid body simulation and one function corresponding to one step of the physics simulation.</p><p>The iOS App and the Linux program share the same code for the simulation. They are found in <a href="https://github.com/ShoYamanishi/RigidBodySimulationBasics/tree/main/SampleApp01/SampleApp01/Simulation">SampleApp01/SampleApp01/Simulation</a>. It contains two C++ header files and a directory, which in turn contains seven small C++ header files as follows.</p><pre>/SampleApp01/Simulation<br>    Simlator.hpp<br>    ChainedDisc.hpp<br>    Common/<br>        Vec2.hpp<br>        Vec3.hpp<br>        Vec4.hpp<br>        RigidBody.hpp<br>        VelocityConstraint.hpp<br>        ConstraintSolver.hpp<br>        MLCPSolverVanillaPGS.hpp</pre><ul><li>Simulator is the top-level class that constructs the discs and advances the simulation at each time step.</li><li>ChainedDisc represents one disc. It is a subclass of RigidBody.</li><li>RigidBody represents one rigid body. It holds the position, velocity, forces, etc., and it is responsible for the physics behavior.</li><li>VelocityConstraint holds all the data necessary for one unilateral or bilateral constraint.</li><li>ConstraintSolver receives the VelocityConstraints and solves them for λ.</li><li>MLCPSolverVanillaPGS is an iterative MLCP solver invoked by ConstraintSolver.</li></ul><p>The most important part of the code for this article is the following in Simulator to advance the simulation for a time step. The function&#39;s body is annotated with the items in Recap on Theory above so that you can check which part of the code corresponds to which step above:</p><pre>    void  Simulator::update( const float delta_t, const Vec2&amp; accel, float torsional_spring_strength )<br>    {<br>        updateAreaSize();<br><br>        // &quot;Find the forces f_k for each rigid body k&quot;<br>        for ( auto* disc : m_discs ) {<br><br>            disc-&gt;resetForcesAndImpulses();<br>            disc-&gt;accumulateForce( accel * disc-&gt;m_mass * G );<br>            addTorsionalSpringForce( disc, torsional_spring_strength );<br>        }<br><br>        // &quot;Update u^*(tc + t) and x^*(tc + t) from Newton-Euler 2nd Law with the Euler step.&quot;<br>        for ( auto* disc : m_discs ) {<br><br>            disc-&gt;updatePhaseSpaceTmp( delta_t );<br>        }<br><br>        // &quot;Run collision detection to find contact pairs.&quot;<br>        detectCollisions( delta_t );<br><br>        constructBilateralConstraints( delta_t );<br><br>        // &quot;Construct unilateral and bilateral constraints in J and b for the contact pairs and the joints.&quot;<br><br>        // &quot;From J, b, and u^*(tc + t), form an MLCP into Az+q=[w|0].&quot;<br>        m_constraints_solver.reset();<br>        for ( auto* c : m_constraints ) {<br><br>            m_constraints_solver.add( c );<br>        }<br><br>        // &quot;Solve the MLCP for z, i.e., lambda&quot;<br>        m_constraints_solver.run( delta_t );<br><br>        for ( auto* c : m_constraints ) {<br><br>            if ( c-&gt;m_body_0 != nullptr ) {<br>                 c-&gt;m_body_0-&gt;addImpulse( c-&gt;m_n0 * c-&gt;m_lambda );<br>            }<br><br>            if ( c-&gt;m_body_1 != nullptr ) {<br>                 c-&gt;m_body_1-&gt;addImpulse( c-&gt;m_n1 * c-&gt;m_lambda );<br>            }<br>            delete c;<br>        }<br>        m_constraints.clear();<br><br>        // &quot;Update u(tc + t) and x(tc + t) from Newton-Euler 2nd Law with the Euler step with the induced impulses J^Tlambda&quot;<br>        for ( auto* disc : m_discs ) {<br><br>            disc-&gt;updatePhaseSpace( delta_t );<br>        }<br>    }</pre><p>The code in <em>Simulator</em> and under it is pretty small, with just over 1,000 lines of code, and it would not be too much hustle to read them through. Anyway, that’s pretty much about it for this article. Let’s dig deeper into the parts for the velocity-space constraints in the next article.</p><h3>Conclusion</h3><p>In this article, we have covered the core idea of the ‘velocity-space constraint-based rigid body simulation’ from the theory to the working implementation in C++. We have not covered how to construct the velocity-space constraints, which will be the main topic of the next article. I hope you enjoyed this article and the program and have a rough idea of what’s happening inside a rigid-body physics engine.</p><p>Happy programming.</p><h3>Further Reading</h3><p>· <strong>[ESHD05] Book: <em>Physics-based Animation</em> by Erleben, et al., Charles River Media</strong></p><p>Chapter 7 deals with the velocity-space constraint-based simulation. One thing to note is that this chapter contains the most comprehensive treatment of the frictional cone and the joint constraints that I know.</p><p><a href="https://siggraphcontact.github.io/"><strong>· SIGGRAPH’22 Course: Contact and Friction Simulation for Computer Graphics by Andrews, Erleben &amp; Ferguson</strong></a></p><p>This is a very concise note with a nice video that covers a wide range of topics. However, it might be challenging for the 1st time learners, as the math is understandably a bit dry and terse. It is interesting to see that there is a treatment of the soft bodies in terms of convex optimization in 4.2.2 and 4.2.3.</p><p><a href="https://dl.acm.org/doi/10.1145/3450508.3464571">· <strong>SIGGRAPH’21 Course: Contact and Friction Simulation for Computer Graphics by Andrews &amp; Erleben</strong></a></p><p>This is another important note with a much richer treatment of the MLCP solvers than the ’22 notes. In 3.2 Fixed-point methods, they derive a solver for the boxed constraints as a simple min-max projection. The original article is <a href="https://link.springer.com/chapter/10.1007/978-3-642-25382-9_15">[here]</a>.</p><p>In 3.1 Pivoting Methods, they also discuss the solution with the pivoting solvers for the boxed constraints. In principle, in each iteration, they sort <strong>z</strong> to free and bound (lower or upper), partition the matrix <em>A</em> accordingly, and solve the system for the free variables.</p><p><a href="http://www.cs.cmu.edu/~baraff/"><strong>· Prof. Baraff’s Tutorials</strong></a></p><p>There is a collection of PDF files and slides available on his website. This is an OG site, and it used to be one of the go-to places for the physics simulation. The article <a href="http://www.cs.cmu.edu/~baraff/pbm/constraints.pdf"><em>An Introduction to Physically Based Modeling: Constrained Dynamics</em></a> by Prof. Andrew Witkin handles the bilateral constraints with the principle of virtual work.</p><p><a href="http://www-personal.umich.edu/~murty/books/linear_complementarity_webbook/lcp-complete.pdf"><strong>· [MY97] Book: Linear Complementarity Linear and Nonlinear Programming: Internet Edition by Murty &amp; Yu</strong></a></p><p>This is the comprehensive treatment of the linear complementarity problem. Each chapter is very clearly written, but it may take too long to follow all the theorems and proofs. Section 2.2<em> The Complementarity Pivot Algorithm</em> describes the Lemke’s algorithm and Chap 9.</p><p><em>Iterative Methods for LCPs</em> covers the iterative solvers. Especially, 9.3.2 <em>Application to Convex Quadratic Program Subject to General Constraints</em> describes the iterative solvers into which the Projected Gauss-Seidel solver falls. Appendix 4.</p><p><em>Optimality Conditions for Smooth Optimization Problems</em> treat the constrained optimization problem in terms of the KKT condition and Lagrangian. This chapter is the best explanation of Lagrangian and the KKT condition that I know.</p><p><strong>· [GPS01] Book: Classical Mechanics Third Edition by Goldstein, Poole, &amp; Safko.</strong></p><p>This book has often been cited by major articles about physics simulation. The 1st chapter deals with the constraints where no work is done by them (called <em>Holonomic constraints</em>.). Chap 1.4 deals with <em>the principle of virtual work</em>. If you were interested, read the 1st chapter to make your understanding solid with a proper physics book.</p><p><strong>· [AH05] Book: Elementary Numerical Analysis by Atkinson &amp; Han Wiley</strong></p><p>If you have time, I would recommend you read through Chap. 8 <em>Ordinary Differential Equations</em> to get the hang of the numerical methods for the ODEs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc3b2148ad5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/rigid-body-simulation-basics-part-1-from-newtons-law-to-a-constrained-optimization-problem-fc3b2148ad5d">Rigid Body Simulation Basics — Part 1: From Newton’s Law to a Constrained Optimization Problem</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Tessellation with Metal: Dynamic B-Spline Surface]]></title>
            <link>https://medium.com/better-programming/advanced-tessellation-with-metal-dynamic-b-spline-surface-79451d19b236?source=rss-dffcfc53a82------2</link>
            <guid isPermaLink="false">https://medium.com/p/79451d19b236</guid>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[tessellations]]></category>
            <dc:creator><![CDATA[Shoichiro Yamanishi]]></dc:creator>
            <pubDate>Sat, 12 Aug 2023 02:02:26 GMT</pubDate>
            <atom:updated>2023-08-16T17:48:17.724Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced Tessellation With Metal: Dynamic B-Spline Surface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ill81hfhUHVSfw55MSnhLg.png" /><figcaption>Figure 1: Real-time Shallow Water Simulation and Cloth (Flag) Simulation on iPhone 13Mini</figcaption></figure><p>Tessellation is a GPU-supported technique for generating a fine mesh surface from much fewer control points. It is achieved by geometrically subdividing a rectangular or triangular area called patch into much smaller triangles by automatic triangulation. This article focuses on the rectangular patches called ‘quad patches.’ Following are some examples of the surfaces rendered by tessellation.</p><ul><li><strong>Real-time water simulation </strong><a href="https://youtu.be/174dhVL5fFE">[video]</a> — See the picture with a duckling above. This is a simulation of the water surface by the shallow water equations <a href="https://doi.org/10.1007/s003710100131">[LM02]</a>. The dimension of the original grid of the control points is 80 x 80. The tessellation can theoretically expand to 5,120 x 5,120 for rendering.</li><li><strong>Real-time cloth simulation </strong><a href="https://youtu.be/rXWQZb6ER6Q">[video]</a> — See the picture with a flag above. This is a simulation of cloth by a simple spring model. The dimension of the original grid of the control points is 22 x 18. The tessellation can expand up to 1,408 x 1,152.</li></ul><p>The examples above utilize B-Spline interpolation with the tessellation for rendering. The true power of tessellation comes when combined with B-Spline interpolation techniques. I’ll walk you through the key concepts and techniques for dynamically rendering B-Spline surfaces in this article. Finally, I present a sample implementation for some elementary water surface simulations in AR. You can use it as a basis for your apps with cool surface effects and simulations.</p><h4>Intended Audience</h4><p>I assume you are familiar with the rendering with Metal and its tessellation. If you are not yet familiar with the tessellation, I recommend you try the <a href="https://metalbyexample.com/tessellation/">following tutorial at <em>Metal by Example</em></a> first and then come back here again.</p><p>This is a super nice and compact tutorial that comes with some sample code.</p><h4>Organization</h4><p>In this article, I touch briefly on the basic tessellation first, and then I’ll go through B-Spline and B-Spline surface so that you can write your own interpolation code in the vertex shader. In the end, I present a demo App for water surface animation that illustrates tessellation and go through some important points in the implementation. The Xcode project for the demo app and the Python scripts used in this article can be downloaded from my <a href="https://github.com/ShoYamanishi/MetalTessellationSample">git repository</a>.</p><h3>Brief Description of Tessellation</h3><p>In a normal rendering shader pipeline, you give it an array of vertex data such as point, color, and surface normal in a buffer, and also an array of indices into the vertex data to specify the triangles (or triangle strip, lines, or points in some cases). The vertex shader is invoked per vertex.</p><p>On the other hand, in a rendering pipeline with the tessellation, you give an array of control points similar to the vertex data and an array of indices into the control points to specify the set of control points per patch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNwltuQ6g7sRs7k1Fhfv-Q.png" /><figcaption>Figure 2: Render API Diagram (All images by author)</figcaption></figure><p>See Fig. 2 above for the schematic diagram of the API. The user defines the control points&#39; semantics, format, and size. In this article, we use 16 control points per quad-patch, and one control point consists of just one point (x, y, z, 1.0) in LCS or local coordinate system.</p><p>The vertex shader is invoked per vertex of the subdivided triangles. To be precise, the vertex shader is given all 16 control points and a local point in the (u,v) coordinates in the patch. For the quad-patch, the (u,v) is normalized within the range of (0.0, 0.0)-(1.0, 1.0). In the vertex shader, you generate the geometric data for the vertex of the triangles, such as the point in the projected coordinate system, surface normal in GCS, global coordinate system, texture coordinates, etc.</p><p>Again, if you are unfamiliar with any of those concepts, please read <a href="https://metalbyexample.com/tessellation/"><em>Introduction to Tessellation in Metal</em></a>.</p><h3>B-Spline and B-Spline Surface</h3><h4>B-Spline basics</h4><p>B-Spline is a set of functions called basis functions of the same order n. Roughly speaking, the order n defines the smoothness of the functions. In this article, we distinguish the functions in the same set (i.e., the same order n) by k, or knot index. The basis functions can be best explained graphically with the graphs Fig. 3, 4, and 5 below and the following three tiny sample scripts in Python. Those scripts are found in <a href="https://github.com/ShoYamanishi/MetalTessellationSample/tree/main/python">my git repo</a>. Those scripts plot the graphs below. You need Python 3 and Matplotlib to run those scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pb-Xp6dDvT4W-TZbENi1HQ.png" /><figcaption>Figure 3: Basis Functions of Order 0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHiLcnMkXcZKEh6j2Exohg.png" /><figcaption>Figure 4: Basis Functions of Order 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGbX6miD9nniwtnKk5BQCQ.png" /><figcaption>Figure 5: Basis Functions of Order 2</figcaption></figure><ul><li><a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/python/basis_order_0.py">basis_order_0.py</a>: sample script to plot the basis functions of order 0.</li><li><a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/python/basis_order_1.py">basis_order_1.py</a>: sample script to plot the basis functions of order 1.</li><li><a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/python/basis_order_2.py">basis_order_2.py</a>: sample script to plot the basis functions of order 2.</li></ul><p>Fig. 3, 4, and 5 show sample basis functions of order 0, 1, and 2, respectively. Each basis function is determined by the points called ‘knots’ indexed by ‘know index.’ Those three graphs share the same knots at the following points. The knots are shown as green or orange dots in the graphs.</p><p>[-15.0, -13.0, -11.5, -7.0, -5.0, -1.0, 3.0, 4.0, 4.5, 5.5, 7.0, 9.5, 13.0, 15.0]</p><p>See the function definitions N_order0(knots, k, u), N_order1(knots, k, u), and N_order2(knots, k, u) in the scripts. Those define the basis functions for each order. As you can see in the code, the basis functions of order n depend on the basis functions of order n-1 recursively.</p><p>Those graphs show the following characteristics of the basis functions:</p><ul><li>The strictly positive part of each basis function starts at knot k and ends at knot k + 1 + n, where n denotes the order 0, 1, or 2.</li><li>For any u, the sum of all the basis functions is always 1.0.</li><li>For any u, there are exactly n + 1 strictly positive basis functions.</li><li>If n = 2, which we use in this article, the basis function crosses at k+2 and k+3, and peaks between k + 2 and k + 3.</li></ul><p>This article uses only the knots at the regular unit interval (…, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,… ). The offset 0.5 is added to the knots so that the peaks occur at (…, -1.0, 0.0, 1.0, …). In fact, with this simplification, the peak of each function conveniently occurs at u = float(k), and we can get rid of the explicit array of knots (called ‘knot vector’). Those simplified unit basis functions are implemented in the following Python scripts, which generate the plots in Fig. 6, 7, and 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLgp9Tu58_l-jsY3EY1zjg.png" /><figcaption>Figure 6: Unit Basis Functions of Order 0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pqL_GxyXE0BdzHS64I9aag.png" /><figcaption>Figure 7: Unit Basis Functions of Order 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJB7GRSKNE4e5WDZIPi6Tw.png" /><figcaption>Figure 8: Unit Basis Functions of Order 2</figcaption></figure><ul><li><a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/python/basis_order_0_unit.py">basis_order_0_unit.py</a></li><li><a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/python/basis_order_1_unit.py">basis_order_1_unit.py</a></li><li><a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/python/basis_order_2_unit.py">basis_order_2_unit.py</a></li></ul><p>As you can see in the scripts, the basis functions are no longer defined recursively. They are piece-wise polynomials of order n. The following is a snippet from the scripts that define the basis function of order 2.</p><pre>def N_order2_unit( k : int, u : float) -&gt; float:<br><br>    &#39;&#39;&#39;Basis function of order 2.<br>       :param k: knot index.<br>       :param x: input<br>       :returns: output       <br>    &#39;&#39;&#39;<br><br>    fk = float(k) + 0.5<br><br>    if fk - 2.0 &lt;= u and u &lt; fk - 1.0:<br>        return 0.5 * ( u - (fk - 2.0) ) * ( u - (fk - 2.0) )<br><br>    if fk - 1.0 &lt;= u and u &lt; fk:<br>        return -1.0 * ( u - (fk - 1.0) ) * ( u - (fk - 1.0) ) + ( u - (fk - 1.0)) + 0.5<br><br>    if fk &lt;= u and u &lt; fk + 1.0:<br>        return 0.5 * ( u - fk ) * ( u - fk ) - ( u - fk ) + 0.5<br><br>    return 0.0</pre><p>That’s pretty much it about the B-Spline basis functions.</p><h4>B-Spline Curve</h4><p>Now we are ready to interpolate a list of points <strong>p</strong>ₖ = (uₖ,xₖ) in (u,x)-coordinates, where the u-coordinates must be consecutively aligned in integer as in <strong>p</strong>ₖ = (k,xₖ). The ‘<em>k’</em>s represent knot indices (and hence knots themselves) for the simplified basis functions. Here’s an example of points to be interpolated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwkEcPwzdEuEg0yO_GO4fg.png" /></figure><p>Those points are called control points. Now we can calculate the x-coordinate of the interpolated point for any u as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRqxc_cTV1FEhjQGki1vIw.png" /></figure><p>The lower charts of Fig. 6, 7, and 8 show sample interpolations generated by those Python scripts. In this article, we use the interpolation with the basis functions of order 2. Please note that the interpolated curves with order 2 may not coincide with the points <strong>p</strong>ₖ unless three consecutive xₖ have the same value. This is obvious because the peak of the basis functions never reaches 1.0 for order 2, as shown in Fig. 8.<br>Since only three basis functions are strictly positive for any u for the basis functions of order 2, if u ∈ [−0.5 + k, 0.5 + k], then the summation is only over the following three basis functions and their associated control points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MKlprdg-vUq2_NRD3mPXg.png" /></figure><p>This is pretty much all there is to know about the basics of the B-Spline interpolation in one dimension. If we expand the control points by one more dimension as in <strong>p</strong>ₖ = (k, xₖ, yₖ ) in (u, x, y)-coordinates, then we can get a B-Spline curve ( x_{interp}(u), y_{interp}(u) ) in the parametric form of u on the two-dimensional surface. If we expand the control points by two dimensions as in <strong>p</strong>ₖ = (k, xₖ, yₖ, zₖ ) in (u, x, y, z)-coordinates, then we can get a B-Spline curve ( x_{interp}(u), y_{interp}(u), z_{interp}(u) ) in the parametric form of u in the three-dimensional space.</p><p>Let’s move on to the B-Spline surface interpolation in the next section.</p><h4>B-Spline Surface</h4><p>We can expand the same argument to a 2D surface in the 3D space as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vcz2ov7b_N0jqbHb0pmp-Q.png" /></figure><p>Fig. 9 shows an example of a 3x3 patch (4x4 control points) where the 11 x 11 points in the center patch are interpolated from the surrounding 4x4 control points. It is generated by the Python script <a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/python/2d_patch.py">2d_patch.py</a>. The pale blue triangles represent the grid of 4x4 control points, and B-Spline interpolates the brown surface in the center patch.</p><p>Here we have to distinguish three coordinate systems:</p><ol><li>The 2-dim integer [i,j]-coordinates that express the knots and the location of the control points. In this example, the integer [i,j]-coordinates are in the range of [0,0]-[3,3], in which one control point is assigned at each [i,j].</li><li>The 2-dim real (u,v)-coordinates in the range of (0.0,0.0)-(1.0,1.0) in the case of Metal. Those values are used to offset the quad patch you want to interpolate. For example, if you want to interpolate the center patch [1,1]-[2,2] in the [i,j]-coordinates as in the sample demo program described later, then the interpolation occurs at the coordinates (1.0 + u, 1.0 + v). The u-axis is aligned with the i-axis, and the v-axis is aligned with the j-axis.</li><li>The 3-dim real (x,y,z)-world coordinates system in which the geometric surface you want to render resides. The control points <strong>p</strong>(i,j) are in this (x,y,z)-coordinate system.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xm4NnhWd4XBXte10C8LcWQ.png" /><figcaption>Figure 9: Interpolated Surface for the Center Patch of 3x3 Grid</figcaption></figure><h4>Surface tangents</h4><p>Since equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xAgqZKXjd1Krv4iWH_K4Q.png" /></figure><p>is an explicit parametric surface equation of (u, v), we can take the partial derivatives of (u,v) to obtain the surface tangent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnDi3gN1YDuQN79LcqX-0A.png" /></figure><p>where Dₖ(t) = dNₖ(t)/dt. Following is a sample code of Dₖ(t) in Python in <a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/python/2d_patch.py">2d_patch.py</a>.</p><pre>def D_Unit_Order2( k: int, t: float ) -&gt; float:<br><br>    &#39;&#39;&#39;1st derivative of the basis function: D(t) = (d/dt)N.<br>       :param k: knot.<br>       :param t: input<br>       :returns: output       <br>    &#39;&#39;&#39;<br><br>    fk = float(k) + 0.5<br><br>    if fk - 2.0 &lt;= t and t &lt; fk - 1.0:<br><br>        return 0.5 * 2.0 * ( t - (fk - 2.0) )<br><br>    if fk - 1.0 &lt;= t and t &lt; fk:<br><br>        return -1.0 * 2.0 * ( t - (fk - 1.0) )+ 1.0<br><br>    if fk &lt;= t and t &lt; fk + 1.0:<br><br>        return 0.5 * 2.0 * ( t - fk ) - 1.0<br><br>    return 0.0</pre><p>If you have difficulty understanding it, imagine u has slightly moved to u + ∆u. Then <strong>p</strong>(u + ∆u, v) will slightly change from <strong>p</strong>(u, v) by (∆x, ∆y, ∆z), then the direction of the change can be expressed by ( ∆x/∆u, ∆y/∆u, ∆z/∆u ). This direction approaches the tangent ∂<strong>p</strong>/∂u as we make ∆u smaller and smaller. The same argument applies to v with ∆v. The green and blue vectors in Fig. 10 show the (normalized) tangent vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NrN5uBfoO5_o3wVDNf5JjA.png" /><figcaption>Figure 10: Interpolated Tangent Vectors and Normal</figcaption></figure><h4>Surface normal</h4><p>The surface normal is found by taking the normalized cross-product of those tangents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dKYN8MAbYtGxwgiNdDh35g.png" /></figure><p>This comes from the normal being perpendicular to both tangent vectors. The orientation is such that (tᵤ(u, v), tᵥ(u, v), n(u, v)) forms a right-hand coordinate system. The red vectors in Fig. 10 show the normal vectors. Those vectors are calculated in the function sample_surface_tangents_and_normal_in_patch() in <a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/python/2d_patch.py">2d_patch.py</a>.</p><p>Now we have covered enough of B-Spline surface interpolation. Let’s look at the code of the sample app.</p><h3>Sample App: Tessellation in Action</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*iTviISR8G7qzrJNQCmY5CA.png" /><figcaption>Figure 11: Screen Capture of Our Sample App</figcaption></figure><p>Now, let’s look at the sample code in action <a href="https://youtu.be/mDAg5b831W8">[video]</a>. Please download the Xcode project from my <a href="https://github.com/ShoYamanishi/MetalTessellationSample">GitHub repo</a>, build it, and run it on an iPhone or iPad. I have tested it with iPhone 13 Mini and iOS 16.3.1, and it should work on any recent iOS devices. It renders an animated water surface in the AR environment.</p><p>The app’s orientation is fixed to Portrait to simplify the code. After starting the app, hold it steady for a while to let the device calibrate for AR, and bring the camera somewhere with a flat surface for the device to detect it. After a surface has been detected, it starts showing the animated water surface on the screen. It has three controls:</p><ul><li>The slider Factor controls the overall granularity of the tessellation of the patches rendered. The less the value, the finer the mesh becomes. The greater the value, the coarser the mesh.</li><li>The slider Intensity control the animation. The greater the value, the more agitated the surface gets.</li><li>The toggle switch Show Wireframe shows the wireframe of the triangulated meshes. The wireframe shows the underlying tessellation more clearly. If you move the camera around, you can see how the triangulation of the patches changes depending on the Factor and the distance of the patch from the camera.</li></ul><h4>Code organization</h4><p>Before going into the details of the parts of the code for the tessellation, let me give you an overview of the code organization. The demo App is based on <a href="https://github.com/ShoYamanishi/ARWithMetalAndSwiftUI">the template in my repo</a> to use ARKit with SwiftUI instead of Storyboard.<br>Take a look at Fig. 11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLtf5G2RZpgiQh1Et6dxLw.png" /><figcaption>Figure 12: Code Organization of the Sample App</figcaption></figure><p>There are three important classes in the demo:</p><ul><li>TessellationRender takes care of the rendering of the surface with tessellation. The main topic of this article.</li><li>TessellationFactors takes care of finding the tessellation factors for the patches. This has been isolated from TessellationRender for better readability of the code.</li><li>WaterSurfaceAnimator takes care of the control points. It constructs the control points and updates repeatedly to animate the surface.</li></ul><p>Those three objects are managed by TessellationMain, which coordinates the communication among the three objects and with WorldManager.<br>Before going into the code for those classes, let me briefly explain the overall architecture of the template code for ARKit + SwiftUI.</p><h4>Template code for ARKit + SwiftUI</h4><p>The template is found in <a href="https://github.com/ShoYamanishi/ARWithMetalAndSwiftUI">my GitHub repo</a>. The top-level class is TessellationSampleApp, which instantiates WorldManager and ContentView. ContentView instantiates MetalView, which is a SwiftUI adaptor to MTKView. MetalView instantiates TouchMTKView and ARCoordinator. TouchMTKView is derived from MTKView to handle screen touches and provide a canvas for rendering to Metal.</p><p>ARCoordinator takes care of all the AR-related tasks and events. It also renders the images captured by the camera onto the screen in TouchMTKView, on which the water surface will be super-imposed. All the events, such as the user inputs to SwiftUI, Metal-related, and AR-related events are sent to WorldManager, which coordinates actions with TessellationMain. The code for each class is relatively small, and it should be easy for you to read through the entire code and understand what’s going on.</p><h4>Arrangement of the control points and the indices</h4><p>Probably the most cumbersome but important, yet not well-documented part is the arrangement of the control points and the indices to the control points. It is best explained graphically in Fig. 13.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*nNbeSM1-tODUwuhglixQXA.png" /><figcaption>Figure 13: Arrangement of Control Points and Indices</figcaption></figure><p>Conceptually, the control points are laid out as a grid of N x M, as shown in the upper part of Fig. 13. There are in total (N-3)*(M-3) patches, each of which consists of 4x4 control points. As you can see, the same control point can appear up to 16 patches. In the buffer, the control points are arranged in a one-dimensional array in the column-major format as in CP_{buf} in Fig. 13. Each patch is specified in the 16 consecutive elements in the index array as in Index_{buf}. Since there are (N-3)*(M-3) patches, the length of Index_{buf} is (N-3)*(M-3)*16.</p><p>In the sample code, the buffer of the control points CPbuf corresponds to the following:</p><ul><li>WaterSurfaceAnimator.buffersControlPoints</li><li>TessellationFactors.bufferControlPoints</li><li>TessellationRender.bufferControlPoints</li></ul><p>And the buffer of the control point indices Index_{buf} corresponds to the following:</p><ul><li>TessellationFactors.bufferControlPointIndices</li><li>TessellationRender.bufferControlPointIndices</li></ul><p>In the render pipeline, the vertex shader can access the control points (not the indices) as if they are arranged consecutively as an array of 16 elements in patch_control_point&lt;CP&gt; cp [[statge in]] as shown in Fig. 13. The vertex function is invoked in parallel many times for the same 16 control points and the patch id. The number of invocations is the number of vertices in the subdivided and triangulated quad patch. Each vertex, hence each invocation, is identified by the (u,v) coordinates given in the argument const float2 uv [[ position in patch ]].</p><h4>Vertex shader</h4><p>Let’s look at the vertex shader in <a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/TessellationSample/Tessellation/tessellation_render.metal">tessellation render.metal</a>. This is one of the most important parts of the code:</p><pre>typedef struct _ControlPoint {<br>    float4 pos [[ attribute(0) ]]; // &lt;= (3)<br>} ControlPoint;<br><br>[[ patch( quad, 16 ) ]] // &lt;= (1)<br>vertex VertexOut vertex_tessellation (<br><br>    patch_control_point&lt;ControlPoint&gt; control_points [[ stage_in ]], // &lt;= (2)<br>    constant float4x4&amp;                M_model        [[ buffer( 1 ) ]],<br>    constant float4x4&amp;                M_view         [[ buffer( 2 ) ]],<br>    constant float4x4&amp;                M_proj         [[ buffer( 3 ) ]],<br>    const    float2                   uv             [[ position_in_patch ]] // &lt;= (4)<br><br>) {<br>    const auto u = 1.0f + uv.x; // [1.0 &lt;= u &lt;= 2.0] for the center patch &lt;= (5)<br>    const auto v = 1.0f + uv.y; // [1.0 &lt;= v &lt;= 2.0] for the center patch &lt;= (5)<br><br>    float3 P_interp { 0.0f, 0.0f, 0.0f };<br>    float3 T_u      { 0.0f, 0.0f, 0.0f };<br>    float3 T_v      { 0.0f, 0.0f, 0.0f };<br><br>    for ( int32_t j = 0; j &lt; 4; j++ ) { // along j-axis<br><br>        const auto Nj = N_Unit_Order2( j, v );<br>        const auto Dj = D_Unit_Order2( j, v );<br><br>        for ( int32_t i = 0; i &lt; 4; i++ ) { // along i-axis<br><br>            const auto Ni = N_Unit_Order2( i, u );<br>            const auto Di = D_Unit_Order2( i, u );<br><br>            const auto P_ij = control_points[ j * 4 + i ].pos.xyz;<br><br>            P_interp += ( P_ij * ( Ni * Nj ) );<br>            T_u      += ( P_ij * ( Di * Nj ) );<br>            T_v      += ( P_ij * ( Ni * Dj ) );<br>        }<br>    }<br><br>    const auto N_lcs = normalize( cross(T_u, T_v) ); // &lt;= (6)<br><br>    const auto N_gcs = M_model * float4( N_lcs,    0.0f );<br>    const auto P_gcs = M_model * float4( P_interp, 1.0f );<br><br>    return VertexOut {<br>        .position         = M_proj * M_view * P_gcs,<br>        .world_position   = P_gcs.xyz / P_gcs.w,<br>        .normal           = N_gcs.xyz<br>    };<br>}</pre><p>The attribute at (1) is to indicate that this function is for tessellation with quad patches, and each patch is given 16 control points. The parameter (2) is the spacial stage_in argument for the control points. In this vertex shader, you can access the control points in the array control_points as if the elements were arranged in the order specified in controlPointIndexBuffer of drawIndexedPatches().</p><p>The type of control points is specified in the bracket ControlPoint, which has only one member with an attribute index 0 at (3). This corresponds to the vertex descriptor given to the render pipeline descriptor in TessellationRender.createRenderPipelineState(). The parameter uv at (4) is another special argument that specifies one point inside the triangulated quad patch. It is normalized in (0.0, 0.0) − (1.0, 1.0). Since we need the (u,v)-coordinates for the center patch specified by [1, 1] − [2, 2] in the [i,j]-coordinates, we add 1.0 to each of u and v at (5).</p><p>In the body of the function, we calculate the surface point and the tangents to P_interp, T_u, and T_v in the local coordinate system. The normal N_lcs is calculated by taking the cross product of T_u and T_v at (6). The rest is the standard coordinate transformation by the model, view, and projection matrices.</p><h4>Fragment shader</h4><pre>fragment float4 fragment_tessellation(<br>    VertexOut          in       [[ stage_in  ]],<br>    constant float4x4&amp; M_camera [[ buffer( 1 ) ]]<br>) {<br>...<br>    // diffuse<br>    const auto cos_theta = dot( in.normal, light_direction * -1.0f );<br>    const auto diffuse_coeff = cos_theta * cos_theta; // hack to emphasize the surface gradient &lt;= (7)<br>    const auto diffuse_color = material_color * diffuse_coeff * 0.7f;<br>...<br>}</pre><p>There is not much to comment on the fragment shader as there is no special treatment required for the tessellation. The function is fragment_tessellation() in <a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/TessellationSample/Tessellation/tessellation_render.metal">tessellation_render.metal</a>. It is a simplified standard ambient-diffuse-specular model using the vertex normal we calculated in the vertex shader. One thing to note is that the diffuse coefficient is changed to use cos2(x) instead of cos(x) to emphasize the slight change on the surface gradient when it’s almost flat at (7).</p><h4>Compute shader for tesellation factors</h4><p>This is an extra task with a compute shader for the rendering with the tessellation. This task calculates the six tessellation factors per patch, which control the granularity of the triangulation. The closer the patch to the camera, the finer the granularity. The further the patch, the coarser the triangulation. The calculated factors are then given to setTessellationFactorBuffer() of the encoder in the render pipeline. The per-patch data is defined by MTLQuadTessellationFactorsHalf in Metal, which consists of six half-floats. (Apparently, there is no counterpart structure defined in Swift.)</p><pre>kernel void find_tessellation_factors(<br><br>    constant     TessellationConfig&amp;<br>                           config                [[ buffer( 0 ) ]],<br>    constant     float4x4&amp; M_model               [[ buffer( 1 ) ]],<br>    constant     float4x4&amp; M_view                [[ buffer( 2 ) ]],<br>    device const float4*   control_points        [[ buffer( 3 ) ]],<br>    device const int32_t*  control_point_indices [[ buffer( 4 ) ]],<br>    device       MTLQuadTessellationFactorsHalf*<br>                           factors               [[ buffer( 5 ) ]],<br>    uint                   tid                   [[ thread_position_in_grid ]]<br><br>) {<br>    if ( static_cast&lt;int32_t&gt;( tid ) &lt; config.num_patches ) {<br><br>        const auto Mvm = M_view * M_model;<br><br>        const int32_t control_point_indices_begin = tid * 16;<br>        const auto i_09 = control_point_indices[control_point_indices_begin +  9 ];// &lt;= (8)<br>        const auto i_05 = control_point_indices[control_point_indices_begin +  5 ];// &lt;= (8)<br>        const auto i_06 = control_point_indices[control_point_indices_begin +  6 ];// &lt;= (8)<br>        const auto i_10 = control_point_indices[control_point_indices_begin + 10 ];// &lt;= (8)<br><br>        const auto p_09_gcs = ( Mvm * control_points[ i_09 ] ).xyz;// &lt;= (9)<br>        const auto p_05_gcs = ( Mvm * control_points[ i_05 ] ).xyz;// &lt;= (9)<br>        const auto p_06_gcs = ( Mvm * control_points[ i_06 ] ).xyz;// &lt;= (9)<br>        const auto p_10_gcs = ( Mvm * control_points[ i_10 ] ).xyz;// &lt;= (9)<br><br>        const auto dist_09_05 = length( (p_09_gcs + p_05_gcs ) * 0.5f ); // edge factor [0] &lt;= (10)<br>        const auto dist_05_06 = length( (p_05_gcs + p_06_gcs ) * 0.5f ); // edge factor [1] &lt;= (10)<br>        const auto dist_06_10 = length( (p_06_gcs + p_10_gcs ) * 0.5f ); // edge factor [2] &lt;= (10)<br>        const auto dist_10_09 = length( (p_10_gcs + p_09_gcs ) * 0.5f ); // edge factor [3] &lt;= (10)<br><br>        const auto dist_avg = ( dist_09_05 + dist_05_06 + dist_06_10 + dist_10_09 ) / 4.0f;<br><br>        const auto F = static_cast&lt;float&gt;( config.max_tessellation_factor );<br><br>        factors[tid].edgeTessellationFactor[0] = min( F, max( 1.0f, F / ( dist_09_05 * config.factor_coeff ) ) );<br>        factors[tid].edgeTessellationFactor[1] = min( F, max( 1.0f, F / ( dist_05_06 * config.factor_coeff ) ) );<br>        factors[tid].edgeTessellationFactor[2] = min( F, max( 1.0f, F / ( dist_06_10 * config.factor_coeff ) ) );<br>        factors[tid].edgeTessellationFactor[3] = min( F, max( 1.0f, F / ( dist_10_09 * config.factor_coeff ) ) );<br><br>        factors[tid].insideTessellationFactor[0] = min( F, max( 1.0f, F / ( dist_avg * config.factor_coeff ) ) );<br>        factors[tid].insideTessellationFactor[1] = min( F, max( 1.0f, F / ( dist_avg * config.factor_coeff ) ) );<br>    }<br>}</pre><p>Let’s take a look at the shader code. That’s the function find_tessellation_factors() in <a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/TessellationSample/Tessellation/tessellation_factors.metal">tessellation_factors.metal</a>. It’s invoked per patch, i.e., one thread ID is assigned per patch. The first thing to do is to find the four control points surrounding the center quad of the grid formed by the 16 control points. The indices surrounding the center patch can be found in Fig. 14.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0kQlKcjROefb-QSdXIWgA.png" /><figcaption>Figure 14: Arrangement of Control Point Indices Per Patch</figcaption></figure><p>The offsets from the beginning are 5, 6, 10, and 9 in a counterclockwise pattern. Part (8) retrieves those four indices. Then four control points in the view coordinate system are retrieved from those indices at (9). In the view coordinate system, the camera is located at the origin (0,0,0). Then the distance to the midpoints of each of the four edges formed by the four control points is calculated at (10). The rest of the code calculates the tessellation factors based on those distances.</p><h4>Compute shaders for animation</h4><p>This is for mimicking the water surface by repeatedly updating the height (y-component) of the control points. There are two shaders. The first one is to initialize the control points. Since the buffers for the control points are created with .private attributes, the best way to construct the initial control points in those buffers is to use a compute shader. The shader is invoked per control point, i.e., the thread is assigned to each control point.</p><p>The grid is made such that the z-axis corresponds to the i-axis and u-axis (denoted by the primary axis at (11)), the x-axis corresponds to the j-axis and v-axis (denoted by the secondary axis at (12)), and the y-axis is along the height/depth of the water surface. The height is initialized to zero. We arrange those three private buffers for the control points as a circular buffer: previous, current, and new (13).</p><pre>kernel void water_surface_init(<br><br>    constant WaterSurfaceAnimationConfig&amp;<br>                   config              [[ buffer( 0 ) ]],<br>    device float4* control_points_prev [[ buffer( 1 ) ]], // &lt;= (13)<br>    device float4* control_points_cur  [[ buffer( 2 ) ]], // &lt;= (13)<br>    device float4* control_points_new  [[ buffer( 3 ) ]], // &lt;= (13)<br>    uint           tid                 [[ thread_position_in_grid ]]<br><br>) {<br>    const auto w = config.width;<br>    const auto h = config.height;<br><br>    const auto hw = static_cast&lt;float&gt;( w ) * 0.5f;<br>    const auto hh = static_cast&lt;float&gt;( h ) * 0.5f;<br><br>    const auto i = static_cast&lt;float&gt;( tid % w );<br>    const auto j = static_cast&lt;float&gt;( tid / w );<br><br>    if ( static_cast&lt;int32_t&gt;( tid ) &lt; w * h ) {<br><br>        const float4 p{<br>            ( j - hh ) * config.edge_length, // secondary axis. &lt;= (12)<br>            0.0f,                            // height<br>            ( i - hw ) * config.edge_length, // primary axis. &lt;= (11)<br>            1.0f<br>        };<br><br>        control_points_prev[ tid ] = p;<br>        control_points_cur [ tid ] = p;<br>        control_points_new [ tid ] = p;<br>    }<br>}</pre><p>The second shader is repeatedly invoked to update the control points for animation. The update is based on a simplified surface wave equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8T_D7pfS8U0dGT-hxNvHWA.png" /></figure><p>The height of each control point is updated from its previous value and four surrounding points.</p><pre>kernel void water_surface_animate(<br><br>    constant WaterSurfaceAnimationConfig&amp;<br>                         config              [[ buffer( 0 ) ]],<br>    device const float*  agitation           [[ buffer( 1 ) ]],<br>    device const float4* control_points_prev [[ buffer( 2 ) ]],<br>    device const float4* control_points_cur  [[ buffer( 3 ) ]],<br>    device float4*       control_points_new  [[ buffer( 4 ) ]],<br>    uint                 tid                 [[ thread_position_in_grid ]]<br><br>) {<br>    const auto w = config.width;<br>    const auto h = config.height;<br><br>    const int32_t i = tid % w;<br>    const int32_t j = tid / w;<br><br>    if ( static_cast&lt;int32_t&gt;( tid ) &lt; w * h ) {<br><br>        const auto iC = j * w + i; // center<br>        const auto iN = clamp( j + 1, 0, h - 1 ) * w + i; // north<br>        const auto iS = clamp( j - 1, 0, h - 1 ) * w + i; // south<br>        const auto iE = j * w + clamp( i + 1, 0, w - 1 ); // east<br>        const auto iW = j * w + clamp( i - 1, 0, w - 1 ); // west<br><br>        const auto C = control_points_cur[ iC ].y + agitation[ iC ];<br>        const auto N = control_points_cur[ iN ].y + agitation[ iN ];<br>        const auto S = control_points_cur[ iS ].y + agitation[ iS ];<br>        const auto E = control_points_cur[ iE ].y + agitation[ iE ];<br>        const auto W = control_points_cur[ iW ].y + agitation[ iW ];<br><br>        const auto Cprev = control_points_prev[ iC ].y;<br><br>        control_points_new[ iC ].y = ( C * 2.0f + ( E + W + N + S - C * 4.0f ) * config.coeff - Cprev ) * config.decay;<br>    }<br>}</pre><h4>Render pipeline arrangement</h4><p>We have covered the shader part. Let’s take a look at the pipelines in Swift. Especially the render pipeline, which has some key differences from the normal render pipeline. Let’s look at the function createRenderPipelineState() below, which builds the render pipeline once the pixel formats of the destination become available. The main difference is in the vertex descriptor.</p><p>Please take a look a the code marked by (19). We only have one attribute of type float4 for the control points. Other differences are the five new parameters for the tessellation in (20).</p><ul><li>tessellationFactorStepFunction = .perPatch: the factors specified per patch.</li><li>maxTessellationFactor = maxNumTessellationFactor: max number of divisions. The hardware limit is 64.</li><li>tessellationPartitionMode = .pow2: the edges and area are split recursively by 2.</li><li>tessellationOutputWindingOrder = .counterClockwise: the vertices of the subdivided triangles are assumed to be in CCW.</li><li>tessellationControlPointIndexType = .uint32: the index array is of type uint32 t.</li></ul><p>Now, let’s look at the function TessellationRender.encode() in <a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/TessellationSample/Tessellation/TessellationRender.swift">TessellationRender.swift</a>, which is called repeatedly, mostly at the frame rate.</p><pre>    public init( ... ) {<br>        ...<br>        var indirectArguments = MTLDrawPatchIndirectArguments( // &lt;= (17)<br>            patchCount:    UInt32(numPatches), // &lt;= (21)<br>            instanceCount: 1,<br>            patchStart:    0,<br>            baseInstance:  0<br>        )<br>        ...<br>        bufferIndirectArguments = device.makeBuffer( // &lt;= (18)<br>            bytes:   &amp;indirectArguments,<br>            length:  MemoryLayout&lt;MTLDrawPatchIndirectArguments&gt;.stride,<br>            options: .storageModeShared<br>        )<br>        ...<br>    }<br><br>    public func createRenderPipelineState( ... )<br>    {<br>        ...<br>        let vertexDescriptor = MTLVertexDescriptor() // &lt;= (19)<br>        vertexDescriptor.attributes[0].format      = .float4 // &lt;= (19)<br>        vertexDescriptor.attributes[0].offset      = 0 // &lt;= (19)<br>        vertexDescriptor.attributes[0].bufferIndex = 0 // &lt;= (19)<br>        vertexDescriptor.layouts[0].stride       = MemoryLayout&lt;SIMD4&lt;Float&gt;&gt;.stride // &lt;= (19)<br>        vertexDescriptor.layouts[0].stepFunction = .perPatchControlPoint // &lt;= (19)<br>        pipelineDescriptor.vertexDescriptor                  = vertexDescriptor // &lt;= (19)<br>        ...<br>        pipelineDescriptor.tessellationFactorStepFunction    = .perPatch // &lt;= (20)<br>        pipelineDescriptor.maxTessellationFactor             = maxNumTessellationFactor // &lt;= (20)<br>        pipelineDescriptor.tessellationPartitionMode         = .pow2 // &lt;= (20)<br>        pipelineDescriptor.tessellationOutputWindingOrder    = .counterClockwise // &lt;= (20)<br>        pipelineDescriptor.tessellationControlPointIndexType = .uint32 // &lt;= (20)<br>        ..<br>    }<br><br>    public func encode(<br>        encoder       : MTLRenderCommandEncoder,<br>        controlPoints : MTLBuffer,<br>        ...<br>    ) {<br>        ...<br>        encoder.setTessellationFactorBuffer(<br>            bufferTessellationFactors, offset: 0, instanceStride: 0) // &lt;= (14)<br>        encoder.setVertexBuffer( controlPoints, offset: 0, index: 0 )<br>        ...<br>        encoder.drawIndexedPatches( // &lt;= (15).<br>            numberOfPatchControlPoints:    16,<br>            patchIndexBuffer:              nil,<br>            patchIndexBufferOffset:        0,<br>            controlPointIndexBuffer:       bufferControlPointIndices,<br>            controlPointIndexBufferOffset: 0,<br>            indirectBuffer:                bufferIndirectArguments, // &lt;= (16)<br>            indirectBufferOffset:          0<br>        )<br>        ...<br>    }</pre><p>There are two key differences. One difference is at (14) where the buffer for the tessellation factors is set by .setTessellationFactorBuffer( ). The tessellation factors have been calculated in finding the tessellation factors() explained above. The other is the draw call drawIndexedPatches() at (15), which takes an indirect argument in MTLBuffer at (16). It is set up once and for all in init() at (17) and (18) and does not change. The most important parameter is patchCount at (21), which specifies the number of quad patches to render.</p><h4>A bit about AR</h4><p>The demo app uses the basic functionalities of ARKit to make it more fun. Using AR may be a better way to look at 3D objects from different angles than using some sliders and 3D wheels, and other controls. All the AR-related things are done in the <a href="https://github.com/ShoYamanishi/MetalTessellationSample/blob/main/TessellationSample/ARCoordinator.swift">ARCoordinato</a>r object. It uses just the bare minimum functionality for the demo. It does not manage the AR session properly, but it just monitors the state of the camera. I’ll briefly go through how the demo uses AR in iOS. Let’s look at the code snippet below:</p><pre>import ARKit<br>class ARCoordinator: ... ARSessionDelegate {<br>    ...<br>    var arSession:                  ARSession!<br>    init(...) {<br>        ...<br>        arSession = ARSession() // &lt;= (22)<br>        arSession.delegate = self<br>    }<br><br>    func mtkView(...) {<br>        ...<br>        let arConfiguration = ARWorldTrackingConfiguration()  // &lt;= (22)<br>        arConfiguration.planeDetection = [ .horizontal ] // &lt;= (22)<br>        arSession.run( arConfiguration ) // &lt;= (22)<br>    }<br><br>    func draw(...) {<br>        guard let currentFrame = arSession.currentFrame else {<br>            return<br>        }<br>        if arSession.currentFrame?.camera.trackingState != .normal { // &lt;= (23)<br>            surfaceTransform = nil<br>            return<br>        }<br>        if surfaceTransform == nil {<br>            for anchor in arSession.currentFrame!.anchors { // &lt;= (24)<br>                if let planeAnchor = anchor as? ARPlaneAnchor {<br>                    surfaceTransform = planeAnchor.transform // &lt;= (24)<br>                    break<br>                }<br>            }<br>        }<br>        ...<br>        let V = arSession.currentFrame!.camera.viewMatrix( for: .portrait )  // &lt;= (25)<br>        let P = arSession.currentFrame!.camera.projectionMatrix( for: .portrait, ...) // &lt;= (25)<br>        let T = arSession.currentFrame!.camera.transform // &lt;= (25)<br>        ...<br>    }<br>    ...<br>}</pre><ul><li>Create and configure a session to detect surfaces at (22).</li><li>Monitor the state of the camera tracking at (23).</li><li>Try to get one detected surface and keep it at (24).</li><li>Get the current camera location and the orientation at (25). It also provides convenience properties for the camera’s view and projection matrices.</li></ul><h3>Recap</h3><p>In this article, we have covered all the important points for using the tessellation with B-Spline from some theories to the code in the sample app. In my view, there are two crucial points we should understand clearly as follows:</p><ul><li>Clear distinction of [i,j], (u,v), and (x,y,z) coordinate spaces.</li><li>The arrangement of the control points and the indices in the Metal buffers.</li></ul><p>I hope those points are clear now after you have read this article this far.</p><p>Also, as a practical tip, we should keep the implementation of the basis functions as simple as possible, like the ones we used above. We should not add special conditions to the basis functions to treat the endpoints, as it may unnecessarily complicate the code and make it harder to debug. Instead, I think we should repeat the same values at both ends. Anyway, I hope you enjoyed this article and the sample app, and I hope you will make some apps with the tessellation. I appreciate your feedback.</p><p>Happy programming.</p><h3>References</h3><p>There are already a few good tutorials available for the basics of tessellation. Here they are:</p><ul><li><a href="https://metalbyexample.com/tessellation/"><em>Introduction to Tessellation in Metal</em></a><em>. </em>This is a super nice compact tutorial that comes with some sample code.</li><li><a href="https://www.kodeco.com/books/metal-by-tutorials/v2.0/chapters/11-tessellation-terrains"><em>Metal by Tutorials: 11. Tessellation &amp; Terrains</em></a><em>. </em>This is behind a paywall.</li><li><a href="https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual">Official guide by Apple</a>.</li></ul><p>The sample app is based on the following template:</p><ul><li><a href="https://github.com/ShoYamanishi/ARWithMetalAndSwiftUI">Template Xcode Project</a> for ARKit, Metal, and SwiftUI (without Storyboard)</li></ul><p>An article on shallow water simulation.</p><ul><li><a href="https://doi.org/10.1007/s003710100131"><em>A numerically efficient and stable algorithm for animating water waves</em>, A.T. Layton, M. van de Panne, Visual Comp 18, 41–53 (2002)</a>.</li></ul><p>The program for <a href="https://www.youtube.com/watch?v=174dhVL5fFE">this video</a> with the duckling is based mainly on this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79451d19b236" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/advanced-tessellation-with-metal-dynamic-b-spline-surface-79451d19b236">Advanced Tessellation with Metal: Dynamic B-Spline Surface</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>