tag:blogger.com,1999:blog-86439041483404147522019-03-26T14:46:05.269-07:00Physics For GamesEric Brownhttp://www.blogger.com/profile/00315121935974620846noreply@blogger.comBlogger7125tag:blogger.com,1999:blog-8643904148340414752.post-16281878672647172352010-06-24T08:29:00.000-07:002010-06-24T15:29:37.828-07:00Blending a Walk/Run cycleMy friend, Rory Aguilar, posed an interesting problem to me:<br /><br /><em><strong><span style="color:#ff6666;">"Suppose you have a walk animation, and a run animation, and you want to blend them together in such a way that you can smoothly go from walking to running without the feet sliding all over the place."</span></strong></em><br /><br />(Rory is kind of girly, so Rory quotes are hilighted in pink.)<br /><br />This is very interesting for character animation, since it becomes possible to smoothly vary the speed of a character, while maintaining realistic movement.<br /><br />Let's assume some things about our underlying animation system:<br /><br />1) it is possible to get the instantaneous pose on any frame, or intermediate frame, of a particular animation<br />2) it is possible to do this for multiple animations<br />3) it is possible to perform a weighted blend of the resulting poses on a per bone basis<br /><br />Now, let's assume some things about the walk and the run animations:<br /><br />1) both the walk and the run animations represent a single loop of the cycle<br />2) the walk animation does not need to have the same number of frames as the run animation. It will likely have many more frames.<br />3) the run animation does not need to cover the same amount of distance as the walk animation. It will likely cover a longer distance, since when you run you have a longer stride.<br />4) for now, we will assume that the footfalls happen at the same fraction, e.g. the right foot hits the ground 45% of the way throgh the animation on both animations.<br />5) The animations will contain translations off of the origin. In other words, we are not going to remove the translations off the origin, and then add them in after the fact.<br /><br />Ok, we're ready to go. Let's dive on in.<br /><br /><span style="font-size:130%;"><strong>Step 1 : define the blend parameter</strong></span><br /><br />We are going to define a blend parameter <em>b</em>, that defines how much we are walking or how much we are running. If <em>b = 0</em>, then we are walking. If <em>b = 1</em>, then we are running.<br /><br />You can relate the blend parameter to the variable speed you desire your character to go. Before doing this you need to calculate the speed of the walk animation, and the speed of the run animation. To calculate the speed of an animation that has <em>N</em> frames, runs at 30 fps and has distances <em>d</em> measured in feet, you do the following<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?v=\frac{d\,{\rm ft}}{N\,{\rm frames}}\frac{30\,{\rm frames}}{{\rm s}}=\frac{30d}{N}\frac{\rm ft}{\rm s}"/></div><br /><br />If you want the speed to be in units other than feet per second, then you can multiply this by an appropriate conversion factor. For instance, if you want to express the speed in miles per hour, then the speed becomes<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?v=\frac{225d}{11N}\frac{\rm m}{\rm h}"/></div><br /><br />You can express the blend parameter in terms of the variable velocity, and the velocities of the walk and run animations as follows<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?b = \frac{v - v_w}{v_r - v_w}"/></div><br /><br /><span style="font-size:130%;"><strong>Step 2 : unify the duration of the animations</strong></span><br /><br />When you are blending the two animations together, you wouldn't want to blend the beginning of the walk animation with the end of the run animation, because it would result in nonsense. However, the run animation is likely to end much quicker than the walk animation. What we would like to acheive is some type of temporal correspondence between the frames of the walk animation and the frames of the run animation. One way to acheive this is to slow down the run animation, so that it ends on precicely the same frame as the walk animation. The rate that acheives this is <br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?R=\frac{N_r}{T_w}"/></div><br /><br />This ratio represents the rate required to play the number of frames in the run animation <em>N<sub>r</sub></em> within the time it takes to complete a walk cycle <em>T<sub>w</sub></em>.<br /><br />The time it takes to complete a walk cycle is<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?T_w=\frac{N_w}{30\,{\rm fps}}"/></div><br /><br />So the rate is<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?R=\frac{N_r}{N_w}30\,{\rm fps}"/></div><br /><br />This rate represents the rate of the run animation when the blend value <em>b</em> is equal to <em>0</em>, i.e. we are in a full walk. For intermediate blend values, we not only need to slow down the run animation, we also need to speed up the walk animation. The blended rates for both animations are given as<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?R_w=\left(b\frac{N_w}{N_r} + \left(1-b\right)\right)30\,{\rm fps}"/></div><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?R_r=\left(b + \left(1-b\right)\frac{N_r}{N_w}\right)30\,{\rm fps}"/></div><br /><br />If you plug in a value of <em>b=0</em> into these equations, we see that the rate of the walk animation is 30 fps, and the rate of the run animation is exactly what we had calculated before. If we plug in a value of <em>b=1</em> we see that the run animation rate is now 30 fps, and the rate of the walk animation is modified.<br /><br />You can use these rate equations to calculate the animation frame that should be evaluated, given the time delta of the loop <em>Δt</em> measured in seconds, and the animation frame evaluated on the previous loop.<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?F_n=F_{n-1} + \left(R_x\right)\left(\Delta t\right)\left(30\,{\rm fps}\right)"/></div><br /><br />Using this calculation, you should be able to vary the value of <em>b</em> from one loop to the next, and still maintain temporal correspondence between the frames of the two animations, e.g. both animations should always cycle on the same loop, and the footfalls should always occur at the same time.<br /><br /><span style="font-size:130%;"><strong>Step 3 : unify the distance traversed by the animations</strong></span><br /><br />The footfalls of the independent animations are now happening at the same time, but the animations are not in the same place when this happens. As stated before, the stride of a run animation is probably longer than that of a walk animation.<br /><br />To synchronize the position of the charachter across the two animations, I will define a "target bone". This bone can be used to define the floor plane, the position of the character, the forward direction, and the up direction, on each frame of the animation.<br /><br />We will need to know the full joint matrix for the target bone (<em>T</em>), both in animation space <em>TA</em>, and in world space <em>TW</em>. These two are related by the animation origin <em>AO</em> through matrix multiplication<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?\mathbf{TW}=\left(\mathbf{TA}\right)\,\left(\mathbf{AO}\right)"/></div><br /><br />Each animation will have a unique independent animation origin, and the value of <em>TA</em> is the animation space representation of the target bone, evaluated at the frame determined by the rate calculated in the previous section. Therefore each animation will have a unique result for the value of <em>TW</em><br /><br />As we blend from one animation to the other, we want to transition which animation controls the world space value of the target bone matrix. To do this, we will blend the world space representation of the target bone.<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?\mathbf{TW}_b={\rm blend}\left(\mathbf{TW}_w, \mathbf{TW}_r, b\right)"/></div><br /><br />Blending a matrix is kind of tricky. If the matrix is composed of only translates and rotates, it is possible to decompose the matrix into a translate vector, and a rotation quaternion, both of which can be blended, and then recomposed back into a matrix.<br /><br />If we want the individual animations target bone to be the same as the blended target bone in world space, we will need to move the respective animation origins.<br /><br />Using the blended world space values of the target bone matrix, we can determine the incremental offset that needs to be applied to each of the animation origins. Use the formula<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?\mathbf{TW}_b=\left(\mathbf{TW}_x\right)\,\left(\mathbf{\Delta}_x\right)"/></div><br /><br />And solve for Δ.<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?\mathbf{\Delta}_x=\left(\mathbf{TW}_x\right)^{-1}\,\left(\mathbf{TW}_b\right)"/></div><br /><br />Now apply Δ to each animation origin to incrementally update it.<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?\mathbf{AO}_x =\left(\mathbf{AO}_x\right)\,\left(\mathbf{\Delta}_x\right)"/></div><br /><br />Finally, you need to find the animation origin for the blended animation. This can be done using the same <em>blend</em> function that was used for the world space target bone matrix.<br /><br /><div style="text-align:center;"><img src="http://www.codecogs.com/eq.latex?\mathbf{AO}_b = {\rm blend}\left(\mathbf{AO}_w, \mathbf{AO}_r, b\right)"/></div><br /><br />You are tracking and updating the animation origins of the walk and run animations independently, but the origin you use to actually position the animation in world space is the blended origin.<br /><br />Using this method, the blend parameter will determine which animation has more control over the actual world space position of the character. If we are in a full walk, then the run origin will continuously move backward, in order to conform to the position set by the walk animation. When we are in a full run, the walk animation origin will continuously move forward to conform to the position set by the run animation.<br /><br /><span style="font-size:130%;"><strong>Step 4 : The next level</strong></span><br /><br />We should now have a walk/run blend, with the only constraint on the animator being that the footfalls happen at the same fractional intervals on both animations. However, placing constraints on animators never turns out well in practice, so let's discuss how we might remove the "fractional interval" constraint on footfalls.<br /><br />Let's say we break the animation up into a set of events:<br /><br />Presumably, we start the cycle with the left foot down, and the right foot stepping forward. On some frame, the right foot becomes stationary relative to the ground. Later the left foot becomes stationary relative to the ground, and finally the animation ends.<br /><br />We can split the animation up into these four segments. Both the walk and the run animations should have these segments, and they should occur in the same order. We can either visually determine which frame each footfall happens on, and tag it, or we can have an automated process determine this for us. Either way, let's assume we know the exact number of frames in each of the four sub-intervals of each animation.<br /><br />The only portion of our process that needs to be modified is the rate calculation. Now, instead of requiring that both animations end at the same time, we require that they reach the first event at the same time. <br /><br />After reaching the first event, we recalculate the rates using the number of frames between the first and second events.<br /><br />After reaching the second event, we recalculate the rates using the number of frames between the seond and third events.<br /><br />After reaching the third event, we recalculate the rates using the number of frames between the third and fourth events.Eric Brownhttp://www.blogger.com/profile/00315121935974620846noreply@blogger.com1tag:blogger.com,1999:blog-8643904148340414752.post-33566893323759568192010-03-18T13:32:00.001-07:002010-03-25T15:55:56.711-07:00Narrow Phase: Sweeping a Sphere Against a PolygonBefore sweeping a sphere against a polygon, you should determine if the sphere is already intersecting the polygon. I will discuss the case where the sphere is <em>not</em> initially intersecting the polygon.<br /><br />We will use a 2D representation of the hypothetical setup, since it's easier to draw 2D pictures.<br /><br />In this setup, there is a sphere with radius <em>r</em> located at point <b>c</b>, a relative velocity vector <b>v</b> that represents the difference of velocity between the sphere and the polygon. This relative velocity can be considered as the velocity of the sphere from the point of view of the polygon. The velocity is given in units that represent how much the sphere will move over the course of a given frame. Thus, at the end of the frame, the center of the sphere should be positioned at the tip of the velocity vector. The polygon lies entirely within some plane, and we are projecting the setup in such a way that the plane occupies a single line. The polygon itself is the bold section of the line. The normal <strong>n</strong> of the plane is pointing out of the front side of the polygon.<br /><br /><a href="http://3.bp.blogspot.com/_36qPDq_KchI/S6KPkzafsRI/AAAAAAAAAA8/zOwrQeOU1Hw/s1600-h/sweep1.bmp"><img style="TEXT-ALIGN: center; MARGIN: 0px auto 10px; WIDTH: 320px; DISPLAY: block; HEIGHT: 320px; CURSOR: hand" id="BLOGGER_PHOTO_ID_5450076361511121170" border="0" alt="" src="http://3.bp.blogspot.com/_36qPDq_KchI/S6KPkzafsRI/AAAAAAAAAA8/zOwrQeOU1Hw/s320/sweep1.bmp" /></a><br />Before determining collision with the polygon, we will first determine collision with the plane. The first step is to find the point on the sphere that will first come into contact with the plane. This can be done scaling the normal of the plane by the radius of the sphere, and subtracting this from the center of the sphere.<br /><br /><br /><div style="TEXT-ALIGN: center"><img src="http://www.codecogs.com/eq.latex?\mathbf{p}_1=\mathbf{c}-\mathbf{n}r" /></div><br /><br /><a href="http://3.bp.blogspot.com/_36qPDq_KchI/S6KPlAkynXI/AAAAAAAAABE/l7iPUANbKUQ/s1600-h/sweep2.bmp"><img style="TEXT-ALIGN: center; MARGIN: 0px auto 10px; WIDTH: 320px; DISPLAY: block; HEIGHT: 320px; CURSOR: hand" id="BLOGGER_PHOTO_ID_5450076365043965298" border="0" alt="" src="http://3.bp.blogspot.com/_36qPDq_KchI/S6KPlAkynXI/AAAAAAAAABE/l7iPUANbKUQ/s320/sweep2.bmp" /></a><br /><br />We will sweep the point <strong>p</strong>1 forward. The sweep is accomplished by finding a line that passes through <strong>p</strong>1, and is parallel to <strong>v</strong>. We then find the point where the line intersects the plane. The point on the plane is the point where the sphere will first make contact with the plane.<br /><br /><a href="http://3.bp.blogspot.com/_36qPDq_KchI/S6KPljBERSI/AAAAAAAAABM/N_bxAEIa5Qo/s1600-h/sweep3.bmp"><img style="TEXT-ALIGN: center; MARGIN: 0px auto 10px; WIDTH: 320px; DISPLAY: block; HEIGHT: 320px; CURSOR: hand" id="BLOGGER_PHOTO_ID_5450076374289368354" border="0" alt="" src="http://3.bp.blogspot.com/_36qPDq_KchI/S6KPljBERSI/AAAAAAAAABM/N_bxAEIa5Qo/s320/sweep3.bmp" /></a><br /><br />The point <b>p</b>2 can be calculated using the following expression<br /><br /><div style="TEXT-ALIGN: center"><img src="http://www.codecogs.com/eq.latex?s=d-\mathbf{p}_1\cdot\mathbf{n}" /><br /><img src="http://www.codecogs.com/eq.latex?\mathbf{p}_2=\mathbf{p}_1+\mathbf{v}s" /></div><br /><br />Here <em>d</em> is the plane parameter, and can be found by dotting the plane normal with any point that resides on the plane, such as one of the <span id="SPELLING_ERROR_0" class="blsp-spelling-error">vertices</span> of the polygon.<br /><br />Before calculating <b>p</b>2, check if <em>s</em> is less than 0, or greater than 1. If it is then the collision is not going to happen during this frame, so you can return a false on your collision routine.<br /><br />If <em>s</em> is between 0 and 1, then go ahead and calculate <b>p</b>2 and continue with the operation.<br /><br />The next step is to find a point inside the polygon that is nearest to <b>p</b>2. The method for doing this is dependant on the polygon. If <b>p</b>2 already resides within the polygon, then the nearest point to <b>p</b>2 is just <b>p</b>2. Otherwise, the nearest point lies on the boundary of the polygon.<br /><br /><div style="TEXT-ALIGN: center"><img src="http://www.codecogs.com/eq.latex?\mathbf{p}_3={\rm%20nearestPoint}\left(\mathbf{p}_2\right)" /></div><br /><br /><span style="color:red;">NOTE: Finding the nearest point on the polygon to <strong>p</strong>2 does not actually work in 3D, since it is possible to have components of velocity that are tangent to the polygon plane.</span> To correct for this, you should try to find the point on the polygon that is closest to the ray that is cast from <strong>p</strong>1. This is done by finding which feature of the polygon (vertex, edge, or face) is closest to the line, and then finding the closest point on this feature to the line.<br /><br /><p></p><p><a href="http://3.bp.blogspot.com/_36qPDq_KchI/S6KPl_P3bmI/AAAAAAAAABU/u7DHYONtZC0/s1600-h/sweep4.bmp"><img style="TEXT-ALIGN: center; MARGIN: 0px auto 10px; WIDTH: 320px; DISPLAY: block; HEIGHT: 320px; CURSOR: hand" id="BLOGGER_PHOTO_ID_5450076381867634274" border="0" alt="" src="http://3.bp.blogspot.com/_36qPDq_KchI/S6KPl_P3bmI/AAAAAAAAABU/u7DHYONtZC0/s320/sweep4.bmp" /></a><br /><br />The point <strong>p</strong>3 is the point on the polygon that will first be touched by the sphere.<br /></p><p>Now we will sweep the point <strong>p</strong>3 backward, and see if it touches the sphere. This sweep is performed by finding a line that passes throw <strong>p</strong>3 and is parallel with <strong>v</strong>. This line will intersect the sphere in 0, 1, or 2 places.<br /><br /><a href="http://3.bp.blogspot.com/_36qPDq_KchI/S6KPmPf2sOI/AAAAAAAAABc/lD0vg96b-I0/s1600-h/sweep5.bmp"><img style="TEXT-ALIGN: center; MARGIN: 0px auto 10px; WIDTH: 320px; DISPLAY: block; HEIGHT: 320px; CURSOR: hand" id="BLOGGER_PHOTO_ID_5450076386229661922" border="0" alt="" src="http://3.bp.blogspot.com/_36qPDq_KchI/S6KPmPf2sOI/AAAAAAAAABc/lD0vg96b-I0/s320/sweep5.bmp" /></a><br />The formula for this sweep involves a square root. If the stuff we are trying to take the square root of is negative, then there is no intersection. So, we first check to see if this stuff is negative.<br /><br /><div style="TEXT-ALIGN: center"><img src="http://www.codecogs.com/eq.latex?\Delta%20=\left[\left(\mathbf{p}_3-\mathbf{c}\right)\cdot\mathbf{v}\right]^2-4\left(\mathbf{v}\cdot\mathbf{v}\right)\left[\left(\mathbf{p}_3+\mathbf{c}\right)\cdot\left(\mathbf{p}_3-\mathbf{c}\right)-r^2\right]" /></div><br />If this is negative, then there is no collision and we can return false. Otherwise, we will continue to calculate the fraction of the time step <em>t</em> at which the collision takes place<br /><br /><div style="TEXT-ALIGN: center"><img src="http://www.codecogs.com/eq.latex?t=\frac{\sqrt{\Delta}-2\left(\mathbf{p}_3-\mathbf{c}\right)\cdot\mathbf{v}}{2\mathbf{v}\cdot\mathbf{v}}" /></div><br /><br />This quantity should not be less than 0. It may however be greater than 1. If it is, then there will be a collision, but not during this time interval, so return false. If however, <em>t</em> is less than 1, you can proceed to determine the point <b>p</b>4 that represents the point that the sphere will first come into contact with the polygon.<br /><br /><div style="TEXT-ALIGN: center"><img src="http://www.codecogs.com/eq.latex?\mathbf{p}_4=\mathbf{p}_3-\mathbf{v}t" /></div><br /><br />At this point, we can move the sphere forward so that it just touches the polygon. The task now is to determine how to resolve this collision, by adjusting the velocity of the sphere. Once we have determined the new, resolved, velocity we continue to sweep the sphere for the remainder of the time step - checking for collisions with other polygons along the way.Eric Brownhttp://www.blogger.com/profile/00315121935974620846noreply@blogger.com2tag:blogger.com,1999:blog-8643904148340414752.post-66022863571329336992010-03-09T15:14:00.000-08:002010-03-11T13:38:52.093-08:00Collision OverviewCollision detection is one of the very key components of a physics engine. However, collision detection on its own is a much more broad topic. It is important to know what kinds of information your collision detection code should be providing, and the different means of accessing this information.<br /><br />Generally, the primary thing we want the collision system to do is notify us if two objects are intersecting. As a secondary part of this computation, we often would like to know how to keep the objects from intersecting.<br /><br />There are a couple of methods I have used, when writing collision systems, to deliver this information. <br /><br />The first is a direct query method, which has the possible functional prototype<br /><br /><span style="font-family:courier new;font-size:85%;"><span style="color:#3333ff;">bool</span> <span style="color:#339999;">CollisionSystem</span>::CollideObjects(<span style="color:#3333ff;">const</span> <span style="color:#339999;">PhysObj</span>& A, <span style="color:#3333ff;">const</span> <span style="color:#339999;">PhysObj</span>& B, <span style="color:#339999;">ColResData</span>* resolve = <span style="color:#660000;">NULL</span>);</span><br /><br />Such a function would return true if the two objects were intersecting. We may optionally pass in a data structure to retrieve information about how to resolve the collision.<br /><br />The second method is a bit more automatic. All collision information is passed to the user through callback functions. The collision system accumulates all motion of all objects, and automatically determines which objects need collision processing. If a collision event occurs, a callback function is called.<br /><br /><span style="font-family:courier new;font-size:85%;"><span style="color:#3333ff;">typedef</span> <span style="color:#3333ff;">void</span> (*<span style="color:#339999;">CollisionHandler</span>)(<span style="color:#339999;">PhysObj</span>&, <span style="color:#339999;">PhysObj</span>&, <span style="color:#339999;">ColResData</span>*);</span><br /><span style="font-family:courier new;font-size:85%;"><span style="color:#3333ff;">void</span> collisionHandler(<span style="color:#339999;">PhysObj</span>& A, <span style="color:#339999;">PhysObj</span>& B, <span style="color:#339999;">ColResData</span>* resolve);</span><br /><br />The physics objects are not passed in as <span style="font-family:courier new;font-size:85%;color:#3333ff;">const</span> because the collision handler may change the state of these objects in order to resolve the collision.<br /><br />We may want to have several different collision event handlers. For instance, we may want to handle an event which corresponds to objects touching, or an event which corresponds to the moment that they cease to touch. There are several different objects in the world, and we may want a different handler for different object types. Therefore, when we proved the collision system with collision handlers, we must supply the object types, and event types for which the collision handler applies<br /><br /><span style="font-family:courier new;font-size:85%;"><span style="color:#3333ff;">bool</span> <span style="color:#339999;">CollisionSystem</span>::AddHandler(<span style="color:#339999;">CollisionHandler</span> handler, <span style="color:#3333ff;">int</span> AType, <span style="color:#3333ff;">int</span> BType, <span style="color:#339999;">ColEventType</span> event);</span><br /><br />This function passes in a collision handler, and an int for the types of objects A and B. An int is used so that the user may map these types to any meaning desired. If the function returns false, it was not able to map the collision handler, probably because there is already a handler mapped to the given types and event. The <span style="font-family:courier new;font-size:85%;color:#339999;">ColEventType</span> is an enum that may contains events like<br /><br /><span style="font-family:courier new;font-size:85%;"><span style="color:#3333ff;">enum</span> <span style="color:#339999;">ColEventType</span></span><br /><span style="font-family:courier new;font-size:85%;">{</span><br /><span style="font-family:courier new;font-size:85%;"> <span style="color:#660000;">ColEvt_OnNear</span>,</span><br /><span style="font-family:courier new;font-size:85%;"> <span style="color:#660000;">ColEvt_Near</span>,</span><br /><span style="font-family:courier new;font-size:85%;"> <span style="color:#660000;">ColEvt_OnIntersect</span>,</span><br /><span style="font-family:courier new;font-size:85%;"> <span style="color:#660000;">ColEvt_Intersect</span>,</span><br /><span style="font-family:courier new;font-size:85%;"> <span style="color:#660000;">ColEvt_Resolve</span>,</span><br /><span style="font-family:courier new;font-size:85%;"> <span style="color:#660000;">ColEvt_OnSeperation</span>,</span><br /><span style="font-family:courier new;font-size:85%;"> <span style="color:#660000;">ColEvt_OnFar</span></span><br /><span style="font-family:courier new;font-size:85%;">};</span><br /><br />We may want to add more collision events, but these cover many of the bases. We want to know if two objects have just gotten near to each other, if they are near to each other, if they have just begun to intersect, if they are intersecting, if we want to resolve the collision, if they have just separated, and if they have just moved away from each other.<br /><br />The way that we actually process collisions is broken up into three distinct portions<br /><ol><li>Broadphase - rough estimation if objects are even close to each other</li><li>Midphase - determines which parts of a complex object might be colliding</li><li>Narrowphase - performs collision on convex primitives, and calculates resolution information</li></ol><p>In the following posts, I will discuss each of these topics.</p>Eric Brownhttp://www.blogger.com/profile/00315121935974620846noreply@blogger.com0tag:blogger.com,1999:blog-8643904148340414752.post-49650151392415145772010-03-04T14:48:00.000-08:002010-03-18T13:02:28.229-07:00Quaternion Tricks<strong><span style="font-size:130%;">Trick #1 : Optimizing the Quaternion Rotation Formula</span></strong><br /><br />The quaternion rotation formula is given as<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms">(0, <strong>v</strong>') = <strong>R</strong>(0, <strong>v</strong>)<strong>R</strong><sup>†</sup></div><br />This formula can be expressed in terms of standard 3D vector products such as scaling, dot products, and cross products. This equation involves two quaternion products, each of which requires 16 multiplies and 12 additions. Thus there are 56 operations in all.<br /><br />We can express the vector cross product in terms of the quaternion product. We know that if you switch the factors in a cross product, the product switches sign. Knowing this, you might accept without proof the following formula.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>q</strong><sub>V</sub> × <strong>p</strong><sub>V</sub> = (1/2) (<strong>qp</strong> - <strong>pq</strong>)</div><br />Indeed if you flip the order of the arguments, the product will change sign.<br /><br />We will use this relationship, in a rearranged form, on the first two factors in the quaternion rotation formula.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>R</strong>(0, <strong>v</strong>) = (0, 2<strong>R</strong><sub>V</sub> × <strong>v</strong>) + (0, <strong>v</strong>)<strong>R</strong></div><br />Inserting the expression on the right hand side into the quaternion rotation formula yields<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms">(0, <strong>v</strong>') = (0, 2<strong>R</strong><sub>V</sub> × <strong>v</strong>)<strong>R</strong><sup>†</sup> + (0, <strong>v</strong>)<strong>RR</strong><sup>†</sup></div><br />When examining the first term on the right hand side, it can be shown that the scalar portion is always zero. For the second term, we can use the fact that the rotation quaternion <strong>R</strong> obeys the identity <strong>RR</strong><sup>†</sup> = 1. Since all 3 terms have zero scalar component, we can now rewrite this expression in terms of vector operations.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>v</strong>' = <strong>v</strong> + 2[ <strong>R</strong><sub>S</sub>( <strong>R</strong><sub>V</sub> × <strong>v</strong> ) + <strong>R</strong><sub>V</sub> × ( <strong>R</strong><sub>V</sub> × <strong>v</strong> ) ]</div><br />This expression employs 18 multiplications and 12 adds, totalling 30 unique operations in all. This optimisation basically cuts the expense of the quaternion rotation formula in half.<br /><br />Here is a function that employs this omptimisation<br /><br /><pre style="COLOR: rgb(0,0,0);font-family:courier new;" ><span style="color:#339999;">Vector </span>rotateVector(<span style="color:#3333ff;">const</span> <span style="color:#339999;">Vector</span>& v, <span style="color:#3333ff;">const</span> <span style="color:#339999;">Quat</span>& q)<br />{<br /><span style="color:#ffffff;"> </span><span style="color:#339999;">Vector</span> result;<br /><span style="color:#ffffff;"> </span><span style="color:#3333ff;">float</span> x1 = q.y*v.z - q.z*v.y;<br /><span style="color:#ffffff;"> </span><span style="color:#3333ff;">float</span> y1 = q.z*v.x - q.x*v.z;<br /><span style="color:#ffffff;"> </span><span style="color:#3333ff;">float</span> z1 = q.x*v.y - q.y*v.x;<br /><br /><span style="color:#ffffff;"> </span><span style="color:#3333ff;">float</span> x2 = q.w*x1 + q.y*z1 - q.z*y1;<br /><span style="color:#ffffff;"> </span><span style="color:#3333ff;">float</span> y2 = q.w*y1 + q.z*x1 - q.x*z1;<br /><span style="color:#ffffff;"> </span><span style="color:#3333ff;">float</span> z2 = q.w*z1 + q.x*y1 - q.y*x1;<br /><br /><span style="color:#ffffff;"> </span>result.x = v.x + <span style="color:#660000;">2.0f</span>*x2;<br /><span style="color:#ffffff;"> </span>result.y = v.y + <span style="color:#660000;">2.0f</span>*y2;<br /><span style="color:#ffffff;"> </span>result.z = v.z + <span style="color:#660000;">2.0f</span>*z2;<br /><br /><span style="color:#ffffff;"> </span><span style="color:#3333ff;">return</span> result;<br />}</pre><br /><br />Let's express the scalar and vector portions of the quaternion in terms of the axis and angle of the rotation<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>R</strong><sub>S</sub> = cos( θ/2 )<br /><br /><strong>R</strong><sub>V</sub> = <strong>n</strong> sin( θ/2 )</div><br />Pluging these values into the optimized quaternion rotation formula, and using a little bit of trigonometric magic (double angle identity), the formula reduces to<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>v</strong>' = <strong>v</strong> + [ sin(θ) (<strong>n</strong> × <strong>v</strong>) + ( 1 - cos(θ) ) <strong>n</strong> × (<strong>n</strong> × <strong>v</strong>) ]</div><br />Using the vector triple product identity, and the fact the <strong>n</strong> is normalized, we can reduce it a bit further.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>v</strong>' = cos(θ)<strong>v</strong> + sin(θ)(<strong>n</strong> × <strong>v</strong>) + (1 - cos(θ)) (<strong>n</strong>•<strong>v</strong>) <strong>n</strong></div><br />This operation has 19 mults and 12 adds, totalling 31 operations. We didn't do anything to optimize the formula, but we were able to transform it into a form involving axis and angle.<br /><br /><strong><span style="font-size:130%;">Trick #2: Determining a Rotation From an Initial and Final Vector</span></strong><br /><br />One of the questions which I am asked most frequently is how to find a rotation which takes some initial vector into some final vector. There are several variants of this problem, including "I am pointing my gun at Bob, and I would like to point my gun at Jim." I have seen this problem solved in many different ways, many times involving inverse trig functions. We are going to solve this problem with quaternions - and it's really easy!<br /><br />We are going to call the initial vector <strong>A</strong>, and the final vector <strong>B</strong>. Both <strong>A</strong> and <strong>B</strong> are normalized 3D vectors.<br /><br />We are going to multiply these two 3D vectors together, and if you <a href="http://physicsforgames.blogspot.com/2010/02/quaternions-why.html">remember</a>, this is accomplished with a quaternion multiplication. To reitterate, our input vectors are just standard 3D vectors, but the output of the product is a quaternion, which represents the product of the inputs. Since the ordering matters, we are going to place <strong>A</strong> on the right, and <strong>B</strong> on the left.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>BA</strong> = -<strong>A</strong>•<strong>B</strong> - <strong>A</strong> × <strong>B</strong></div><br />We can relate the dot and cross products to functions involving the angle between <strong>A</strong> and <strong>B</strong>. If A and B are normalized, then their product has the following form<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>BA</strong> = - cos(θ) - <strong>n </strong>sin(θ)</div><br />The angle θ is the angle between the initial and final vector, and the vector <strong>n</strong> is a normalized vector that is perpendicular to the input vectors. This is the exact form of a rotation quaternion. Don't worry about the minus sign, since we can flip the sign without changing the rotation we are representing. In fact, this almost represents the quaternion that we are looking for. We need a quaternion with a half angle instead of a full angle.<br /><br />Instead of multiplying the initial vector <strong>A</strong> by the final vector <strong>B</strong>, let's instead find a vector that represents a halfway rotation between <strong>A</strong> and <strong>B</strong>. This is very easy to do - just find the average of <strong>A</strong> and <strong>B</strong>!<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>H</strong> = (1/2) (<strong>A</strong> + <strong>B</strong>)</div><br />Now, this <strong>H</strong> is not normalized, and it needs to be. If we are going to normalize it anyway, we don't need to worry about the factor of 1/2. The normalized version of <strong>H</strong> is<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>H</strong> = (<strong>A</strong> + <strong>B</strong>) / <strong>A</strong> + <strong>B</strong></div><br />Knowing that the angle between <strong>A</strong> and <strong>H</strong> is half of the angle between <strong>A</strong> and <strong>B</strong>, we can use our previous result to show that the rotation which takes <strong>A</strong> into <strong>B</strong> is given by<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>R</strong> = <strong>HA</strong></div><br />Here is a function that will give you the rotation quaternion that will rotate some initial vector into some final vector<br /><br /><pre style="COLOR: rgb(0,0,0);font-family:courier new;" ><span style="color:#339999;">Quat</span> getRotationQuat(<span style="color:#3333ff;">const</span> <span style="color:#339999;">Vector</span>& from, <span style="color:#3333ff;">const</span> <span style="color:#339999;">Vector</span>& to)<br />{<br /><span style="color:#ffffff;"> </span><span style="color:#339999;">Quat</span> result;<br /><br /><span style="color:#ffffff;"> </span><span style="color:#339999;">Vector</span> H = VecAdd(from, to);<br /><span style="color:#ffffff;"> </span>H = VecNormalize(H);<br /><br /><span style="color:#ffffff;"> </span>result.w = VecDot(from, H);<br /><span style="color:#ffffff;"> </span>result.x = from.y*H.z - from.z*H.y;<br /><span style="color:#ffffff;"> </span>result.y = from.z*H.x - from.x*H.z;<br /><span style="color:#ffffff;"> </span>result.z = from.x*H.y - from.y*H.x;<br /><span style="color:#3333ff;"><span style="color:#ffffff;"> </span>return</span> result;<br />}</pre><br />It doesn't get much easier than that folks.<br /><br /><span style="font-size:130%;"><strong>Trick #3: Tangent Space Compression / Quaternion Maps</strong></span><br /><br />Tangent space is a set of 3 vectors - normal, tangent, and bi-normal - which are used in lighting calculations such as bump mapping, or anisotropic shading techniques, like fur or hair shaders.<br /><br />The tangent space is a representation of the surface of the mesh. The tangent space vectors are stored per-vertex, and interpolated across the polygon for per-pixel operations. If you use floats to represent the components of the tangent space vectors, then you are dedicating 3 x 3 x 4 bytes = 36 bytes per vertex to the storage of tangent space.<br /><br />The tangent space vectors form an ortho-normal frame. Consider the rotation which will transform the ortho-normal frame of tangent space into the standard frame in world space. If this rotation is expressed as a matrix, then the 3 columns of this matrix represent the 3 tangent space vectors.<br /><br />If you can express a rotation as a matrix, then you can also express it as a quaternion. This immediately reduces the tangent space representation to 4 components = 16 bytes. When decompressing the vertex, use the <a href="http://physicsforgames.blogspot.com/2010/02/quaternions.html">quat->matrix conversion,</a> and pull out the 3 columns of the resulting matrix as your tangent space vectors. The quat->matrix conversion costs 13 multiplies and 15 subtractions. It may be worthwhile to determine if it is possible to optimize this conversion for shader operations.<br /><br />If you want to save more space, you can go even further, if you have the time - computationally speaking. Since rotation quaternions are normalized, there are only 3 degrees of freedom instead of 4. Thus you only really need to store 3 components of the quaternion, and the 4th can be calculated using the formula<br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms">w = sqrt(1 - x<sup>2</sup> - y<sup>2</sup> - z<sup>2</sup>)</div><br />This brings the tangent space size down to 12 bytes.<br /><br />Finally, if you are super hard pressed for space, you can take advantage of the fact that the components of a quaternion are within the range [-1,1], which may not require 32 bits to have a sufficient representation. You may possibly use 16 bit floats to represent these components. Doing so will reduce the size further - 6 bytes.<br /><br />With a 6-byte tangent space representation, it seems conceivable to employ quaternion texture maps, which store the tangent space directly in the texture, rather than using bump map data to perturb the interpolated tangent vectors. You could then apply a texture compression, like 3DC which gets 2:1 compression. Now tangent space only consumes 3-bytes of texture, and 0-bytes on the vertex. If you were previously using bump maps, and you replace them with quaternion maps, then you aren't really increasing the amount of texture memory used, and you have successfully removed all 36 bytes of tangent space data from the vertex.<br /><br />Of course, doing quaternion map lookups in the pixel shader would also mean doing the quat->matrix conversion in the pixel shader - or, alternatively recasting the pixel shader lighting equation in terms of quaternion algebra, rather than matrix algebra - whichever ends up being cheaper. To gain perspective on the cost of this conversion, you can perform 5 quat->matrix conversions in roughly the same amount of time as a single matrix multiply. A single quat->matrix conversion is about as costly as transforming 3 vectors with a matrix.<br /><br />The quaternion map would take the place of bump maps altogether, and would provide the added feature of having fine tuned control over tangent space on a per-pixel level. For anisotropic shaders, like hair, fur, and velvet shaders, you could introduce swirls and wiggles in the middle of a polygon.<br /><br />There are two rather large problems facing the idea of a quaternion map: 1) a lot of people get freaked out when you use the word quaternion. 2) I can't off the top of my head conceive of a way for an artist or content creator to generate such a map.<br /><br />At any rate, it seems like a very intriguing idea.Eric Brownhttp://www.blogger.com/profile/00315121935974620846noreply@blogger.com0tag:blogger.com,1999:blog-8643904148340414752.post-84315978992698390952010-02-27T22:00:00.000-08:002010-03-03T13:27:40.790-08:00True PhysicsOne of the vital organs of a physics engine is the code that integrates Newton's laws of motion. There are several techniques which employ approximations of calculus in order to numerically solve this problem. I am proposing a scheme which can solve this problem without approximation.<br /><br />In this article you will learn<br /><ul><li>How the stepping equations are derived from Newton's laws.</li><li>A good method for doing this approximation, which is very common in many third party physics engines.</li><li>The Kinematic Integrator method, which allows you to use unapproximated calculus in the force calculations. This enables extremely large time steps.<br /></li></ul>In this article I will just be talking about the linear motion, not the angular motion. If you want to see a pretty decent way to integrate the angular portion check out the last section of <a href="http://physicsforgames.blogspot.com/2010/02/quaternions.html">Quaternions: How</a>.<br /><span style="font-weight: bold;font-size:130%;" ><br />Newton's Laws</span><br /><br />Given in short:<br /><ol><li>Without external influences, objects preserve their state of motion. If the object is at rest, it remains so. If it is moving it will continue to move at that same speed.</li><li>If a force acts on an object, the object will change its state of motion. The amount of change induced by the force is related to the mass of the object. i.e. <div style="text-align: center; font-family: trebuchet ms;"><strong>F</strong> = m<strong>a</strong></div></li><li>If one body applies a force on another body, then the other body applies an equal and opposite force on the first body</li></ol>The third law is taken care of during resolution of collisions, and applications of forces, etc. The first two laws are handled in the integration stage.<br /><br />The net force acting on a body is directly proportional to acceleration. Acceleration is defined as the time derivative of velocity. In order to get the velocity of an object, given the acceleration, we need to integrate.<br /><br />Velocity is an important portion of the physical state of an object. Several forces require knowledge of the velocity. However, the most important quantity is the position, since this determines where we place the object in the world. The velocity is defined as the time derivative of position, so in order to get the position we must integrate the velocity.<br /><br />Since the information we start with is acceleration, and the information we desire is velocity and position, then we must integrate the acceleration two times. For this reason the equations of motion are usually second order equations. In order to fully solve a second order equation, we need to know two quantities. These two quantities are usually the initial position, and the initial velocity.<br /><br /><span style="font-size:130%;"><span style="font-weight: bold;">How do we integrate?</span></span><br /><br />When it comes to physics engines I always start my integration by taking a derivative. This may seem anti-intuitive, since an integral seems to be the opposite of a derivative. But with physics, the thing we are integrating can be expressed in terms of derivatives, and nothing is as easy to integrate as a derivative.<br /><br />The equations of motion can be expressed in terms of two differential equations<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>a</strong> = ∂<strong>v</strong>/∂t<br /><br /><strong>v</strong> = ∂<strong>x</strong>/∂t</div><br />In order to see how we solve these equations numerically, first consider the standard mechanism for taking a derivative.<br /><br /><div style="text-align: center; font-family: trebuchet ms;">∂f/∂t = (f<sub>1</sub> - f<sub>0</sub>) / (t<sub>1</sub> - t<sub>0</sub>) ; t<sub>1</sub> → t<sub>0</sub></div><br />Which defines the value of the derivative at <span style="font-family:trebuchet ms;">t<sub>0</sub></span>.<br /><br />On a computer, we have finite precision arithmetic, and so we cannot allow <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">1</sub> to get arbitrarily close to <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">0</sub>. Therefore, we can only approximate derivatives as finite differences.<br /><br /><div style="text-align: center; font-family: trebuchet ms;">∂f/∂t ≈ (f<sub>1</sub> - f<sub>0</sub>) / (t<sub>1</sub> - t<sub>0</sub>) ; t<sub>1</sub> = t<sub>0</sub> + Δt</div><br />Here <span style="font-family:trebuchet ms;">Δt</span> represents our time step. Obviously, the smaller the time step is, the closer we get to representing a true derivative. Making this simple approximation to the representation of the calculus has introduced an ambiguity. Is this the value of the derivative at <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">0</sub> or <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">1</sub>, or at some point in between? If we choose <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">0</sub>, then the approximation is called a forward, or <span style="font-style: italic;">explicit</span> derivative. If we choose <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">1</sub>, then the approximation is called a reverse, or <span style="font-style: italic;">implicit</span> derivative. The quality of the representation of the equations of motion ends up being tied to our choice.<br /><br />If we choose to use only explicit derivatives to represent the equations of motion, then we have<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>a</strong><sub>0</sub> = (<strong>v</strong><sub>1</sub> - <strong>v</strong><sub>0</sub>) / Δt<br /><br /><strong>v</strong><sub>0</sub> = (<strong>x</strong><sub>1</sub> - <strong>x</strong><sub>0</sub>) / Δt</div><br />In these expressions, we know we are using a forward derivative because the <strong style="font-family: trebuchet ms;">a</strong> and the <strong style="font-family: trebuchet ms;">v</strong> on the left hand sides are evaluated at <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">0</sub>. We can rewrite these equations, so that we can find the values of <strong style="font-family: trebuchet ms;">x</strong> and <strong style="font-family: trebuchet ms;">v</strong> at time <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">1</sub>, given that we know what the values are at time <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">0</sub>.<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>v</strong><sub>1</sub> = <strong>v</strong><sub>0</sub> + <strong>a</strong><sub>0</sub>Δt<br /><br /><strong>x</strong><sub>1</sub> = <strong>x</strong><sub>0</sub> + <strong>v</strong><sub>0</sub>Δt</div><br />These equations are called the explicit Euler stepping equations. We see that if the value of <strong style="font-family: trebuchet ms;">a</strong> is zero, then the equations will maintain the motion of an object, satisfying the first law. The solitary occurrence of <strong style="font-family: trebuchet ms;">a</strong> is the contribution from the second law, given that you calculate <strong><span style="font-family:trebuchet ms;">a</span></strong> as the net Force divided by mass.<br /><br />As it turns out, the explicit Euler stepping equations are very crappy. The acceleration ends up introducing energy into the system, causing it to be very volatile. This volatility can be managed by making the time step smaller, but this increases the computational expense.<br /><br />The current gold standard for integration in high profile physics engines is the semi-implicit, or symplectic, Euler stepping equations. These equations represent the acceleration with an explicit derivative, but the velocity is represented with an implicit derivative.<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>a</strong><sub>0</sub> = (<strong>v</strong><sub>1</sub> - <strong>v</strong><sub>0</sub>) / Δt<br /><br /><strong>v</strong><sub>1</sub> = (<strong>x</strong><sub>1</sub> - <strong>x</strong><sub>0</sub>) / Δt</div><br />Since on the left hand side, the acceleration is evaluated at <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">0</sub>, it is a forward or explicit derivative. Since the velocity on the left hand side is evaluated at <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">1</sub> it is a reverse, or explicit derivative. The combination of these two gives us the name <span style="font-style: italic;">semi-implicit</span>. These equations can be rearranged so that <strong style="font-family: trebuchet ms;">x</strong> and <strong style="font-family: trebuchet ms;">v</strong> at <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">1</sub> are functions of their values at <span style="font-family:trebuchet ms;">t</span><sub style="font-family: trebuchet ms;">0</sub><br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>v</strong><sub>1</sub> = <strong>v</strong><sub>0</sub> + <strong>a</strong><sub>0</sub>Δt<br /><br /><strong>x</strong><sub>1</sub> = <strong>x</strong><sub>0</sub> + <strong>v</strong><sub>1</sub>Δt</div><br />These equations are solvable, so long as we evaluate the velocity equation first, so that we have the result to plug into the position equation.<br /><br /><span style="font-size:130%;"><span style="font-weight: bold;">So how accurate are these stepping equations?</span></span><br /><br />The semi-implict Euler technique is a second order method, which means that the error is tied to the second power of the time step. If you cut the time step in half, you quadruple the accuracy of the method.<br /><br />Also, the semi-implicit Euler method obeys a different property, which makes it useful. It conserves energy on average. What this means is that, although the error you accumulate over the course of the time step might increase or decrease the effective energy of the system, over time the energy will average out to a constant. This property is where the <span style="font-style: italic;">symplectic</span> term comes from. I'm not going to explain what symplectic means, but if you are interested, search for Hamiltonian dynamics, the equations of which are used to prove that the semi-implicit Euler method conserves energy.<br /><br />We see in this instance that there is a defining difference between accuracy and stability. The semi-implicit Euler method may not be the most accurate method ever, but it is stable since it conserves energy. On the user end, we don't tend to see the tiny inaccuracies, but we do tend to notice if the physics wigs out and everything explodes. Therefore, we would like our inaccuracies to NOT lead to instabilities.<br /><span style="font-size:130%;"><br /><span style="font-weight: bold;">Can you have perfect integration?</span></span><br /><br />With numerical integration schemes, such as Euler based techniques, the only way we can get perfect integration is if we let the time step become zero, which we know we can't do. However, it is possible to achieve perfect integration in a computational simulation, and I will tell you how, but we will need to make a slight departure from the standard development of numerical integration. <br /><br />Let's start with a very simple example of perfect integration.<br /><br />Consider that you are writing the game <span style="font-style: italic;">Lunar Lander</span> where you must use thrusters on a spacecraft to guide it safely to the landing pad. In this game, the only forces that come into play are the gravitational force, and the thrusters on the spacecraft.<br /><br />Over the course of a single time step, we know which thrusters are on. We consider that the force due to a thruster is constant over the course of the time step. We also use a constant force for the gravitational force. Thus we have a full knowledge of the value of the force at all intermediate points during the simulation time step.<br /><br />Add all of the forces together to get the total force. Dividing the total force by the mass will give you the acceleration.<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>a</strong> = (<strong>F</strong><sub>grav</sub> + <strong>F</strong><sub>thruster</sub> + ...) / m</div><br />Now, we need not resort to any approximation of calculus in order to solve this problem. Since we know the form of the forces (constant) at all points during the simulation time step, we can solve the problem directly - analytically. The true solution and stepping equations without approximation are given by<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>v</strong><sub>1</sub> = <strong>v</strong><sub>0</sub> + <strong>a</strong>Δt<br /><br /><strong>x</strong><sub>1</sub> = <strong>x</strong><sub>0</sub> + <strong>v</strong><sub>0</sub>Δt + (1/2)<strong>a</strong>Δt<sup>2</sup></div><br />Anyone who has taken a physics class, even a beginning physics class, should recognize these equations. Restate: if you have taken a beginning physics classes you <span style="font-style: italic;">have</span> seen these equations before, even if you don't recognize them. They are called the kinematic equations of uniform acceleration, and are the primary feature of almost all beginning physics problems, especially problems involving a baseball, basketball, or any other type of sports related sphere.<br /><br />Here the <strong style="font-family: trebuchet ms;">a</strong> is constant, so we don't need to use a subscript to specify the point in time where we are evaluating it. These equations look almost like the stepping equations we were using before, except the position equation has an extra term involving acceleration. These equations are perfect, which means that there is no upper bound of accuracy that is related to the size of the time step. In a real application the upper bound on the size of the time step would not be related to the accuracy of the integration, but rather to the ability to perform collision with the landscape. Collision issues aside however, this method will give you the right answer, no matter how big the time step is.<br /><br />If these stepping equations are perfect, why don't we use them? The answer is that these equations are only perfect <span style="font-style: italic;">if</span> the forces are really constant. If we use these equations to simulate forces that are not constant, e.g. the spring force, we will not get very good results. If we decide to use these equations to step the physics of our system forward in time, we have essentially moved the approximation out of the calculus and into the representation of the forces. And the approximation applied to the forces ends up having worse results than applying the approximation to the calculus.<br /><br />In short: the kinematic equations rock for forces that are constant, but really suck for forces that aren't.<br /><br />If we can't use the kinematic equations all of the time, should we ditch them all together? Is it possible for constant forces to use the kinematic equations, and non-constant forces to use the semi-implicit Euler equations? Then our integration would be perfect with respect to the constant forces, at least. Under such a scheme, how would we go about mixing constant and non-constant forces?<br /><br />Consider once again the semi-implicit Euler equation. We can plug the velocity equation into the position equation, since they both involve <strong style="font-family: trebuchet ms;">v</strong><sub style="font-family: trebuchet ms;">1</sub>. The result is similar in appearance to the kinematic equations<br /><div style="text-align: center; font-family: trebuchet ms;"><strong>v</strong><sub>1</sub> = <strong>v</strong><sub>0</sub> + <strong>a</strong><sub>0</sub>Δt<br /><br /><strong>x</strong><sub>1</sub> = <strong>x</strong><sub>0</sub> + <strong>v</strong><sub>0</sub>Δt + <strong>a</strong><sub>0</sub>Δt<sup>2</sup></div><br />We now see a very striking resemblance to the kinematic equations. We actually have three terms that match exactly. The first term in the velocity equation, and the first two terms in the position equation. Only the terms that involve acceleration are different. It can be shown in a general case, that the three matching terms will always match, regardless of the form of acceleration. The form of the acceleration only affects the terms which involve acceleration.<br /><br />We now have a clue as to how we might combine a constant force with a non-constant force.<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>v</strong><sub>1</sub> = <strong>v</strong><sub>0</sub> + ( <strong>a</strong><sub>C</sub>Δt + <strong>a</strong><sub>NC</sub>Δt )<br /><br /><strong>x</strong><sub>1</sub> = <strong>x</strong><sub>0</sub> + <strong>v</strong><sub>0</sub>Δt + ( (1/2) <strong>a</strong><sub>C</sub>Δt<sup>2</sup> + <strong>a</strong><sub>NC</sub>Δt<sup>2</sup> )</div><br />Thus, the constant force gets the benefit of using the kinematic equations, and the non-constant force can use the semi-implicit Euler technique. You may see some simplification that can take place, since the acceleration terms contain common factors. Now, it is possible to analytically solve for the acceleration terms given other forms of acceleration. These terms may not have common factors, so I chose to keep the acceleration terms separated.<br /><br /><span style="font-size:130%;"><span style="font-weight: bold;">The Kinematic Integrator:</span></span><br /><br />The kinematic integration method is given as follows<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>v</strong><sub>1</sub> = <strong>v</strong><sub>0</sub> + d<strong>v</strong><br /><br /><strong>x</strong><sub>1</sub> = <strong>x</strong><sub>0</sub> + <strong>v</strong><sub>0</sub>Δt + d<strong>x</strong></div><br />Which will give us the new position and velocity, given we supply the value of the previous position and velocity as well as the two integral parameters <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span> and <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >v</span>. So what are <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span> and <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >v</span>? They are generalizations of the terms which involve integrals of acceleration.<br /><br />In Euler based integration techniques, you usually have a unique method to calculate each different kind of force. There might be a method for a spring force, and a method for a pulse, etc.. This resulting force is divided by the mass, and accumulated with whatever existing acceleration is already acting on the object.<br /><br />Using the kinematic integration technique, the entire point of the force calculation method is not to calculate the force, but to calculate <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >v</span> and <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span>. These are, likewise, accumulated with whatever existing <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >v</span>'s and <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span>'s that were previously acting on an object.<br /><br />The point of this generalization is to move the calculus out of the stepping equations, and into the force calculation, so that each different kind of force can give the true result of the acceleration integrals. This leaves the stepping equations in a form that is not dependent on the form of the input forces.<br /><br />A method which calculates a constant force will return the exact <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >v</span> and <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span> of a constant force. A method which calculates a spring force will return the exact <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >v</span> and <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span> of a spring force. This is really great, but what do we do if we don't know how to calculate the true integral of a given force? Simple, we just go back to using the semi-implicit Euler technique. We have already expanded this technique out into kinematic form, so we know what <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >v</span> and <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span> are.<br /><br /><div style="text-align: center; font-family: trebuchet ms;">d<strong>v</strong> = <strong>a</strong><sub>0</sub>Δt<br /><br />d<strong>x</strong> = <strong>a</strong><sub>0</sub>Δt<sup>2</sup> = d<strong>v</strong>Δt</div><br /><span style="font-size:130%;"><span style="font-weight: bold;">The spring force</span></span><br /><br />So how do we calculate the <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >v</span> and <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span> of a spring? As an example, consider a spring which connects a mass to the origin. The spring has a spring constant <span style="font-style: italic;">k</span>, which determines how tight it is. The force acting on the mass has the form<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>F</strong> = -k<strong>x</strong> = -mω<sup>2</sup><strong>x</strong></div><br />Here ω is the angular frequency of the spring, and the reason for defining it is because the form of motion of the spring is given by a sinusoidal function of the following form<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>x</strong> = <strong>A</strong> sin(ωt) + <strong>B</strong> cos(ωt)<br /></div><div style="text-align: center; font-family: trebuchet ms;"> </div><br />We can take the derivative of this expression to find the functional form of the velocity. Then we can use <strong style="font-family: trebuchet ms;">x</strong><sub style="font-family: trebuchet ms;">0</sub> and <strong style="font-family: trebuchet ms;">v</strong><sub style="font-family: trebuchet ms;">0</sub> as our initial conditions in order to fix the values of <span style="font-weight: bold;font-family:trebuchet ms;" >A</span> and <span style="font-weight: bold;font-family:trebuchet ms;" >B</span>.<br /><br /><div style="text-align: center; font-family: trebuchet ms;"><strong>v</strong><sub>1</sub> = <strong>v</strong><sub>0</sub> cos(ωΔt) - <strong>x</strong><sub>0</sub>ω sin(ωΔt)<br /><br /><strong>x</strong><sub>1</sub> = <strong>v</strong><sub>0</sub>/ω sin(ωΔt) + <strong>x</strong><sub>0</sub> cos(ωΔt)</div><br />These are the true, un-approximated results of the integration. We can use these to find the values of <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >v</span> and <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span>, merely by equating these results with the left hand side of the kinematic integrator equations. We find that<br /><br /><div style="text-align: center; font-family: trebuchet ms;">d<strong>v</strong> = <strong>v</strong><sub>0</sub> ( cos(ωΔt) - 1 ) - <strong>x</strong><sub>0</sub> ( ω sin(ωΔt) )<br /><br />d<strong>x</strong> = <strong>v</strong><sub>0</sub> ( sin(ωΔt)/ω - Δt ) + <strong>x</strong><sub>0</sub> ( cos(ωΔt) - 1 )</div><br />If the parameters of your spring do not change, and you are using a fixed time step, then the coefficients of <strong style="font-family: trebuchet ms;">x</strong><sub style="font-family: trebuchet ms;">0</sub> and <strong style="font-family: trebuchet ms;">v</strong><sub style="font-family: trebuchet ms;">0</sub> do not change, and should only need to be calculated once.<br /><br />Again, the accuracy of the stepping equations does NOT depend on the size of your time step, because we are using the exact result. I have compared the numerical result of the kinematic integrator with the exact result in the case of a spring, and there is literally zero error - no matter what the time step is, or how long the system runs.<br /><br /><span style="font-size:130%;"><span style="font-weight: bold;">Multiple forces: </span></span><br /><br />Now, there is a problem that arises when you try to apply two forces that depend on position or velocity. They both are integrated without a knowledge of the other. Therefore they are oblivious to the changes in intermediate position or velocity caused by the other force. These changes would have altered the final result, had they been taken into account.<br /><br />A good example of this is the example of having two springs.<br /><br />If one spring acts alone, the result of the kinematic integrator is exact, and so the result is always correct, regardless of the size of the time step. The story is different when two springs act simultaneously.<br /><br />The system begins to accumulate error, due to the misrepresentation of the forces. However, the error is very small, almost insignificant. In a test of such a system, I calculated that the error of the kinematic integrator was 12,000 times smaller than the error from the semi-implicit Euler method. Unlike the semi-implicit Euler method, however, the kinematic integrator is not guaranteed to preserve energy. Therefore these very small inaccuracies build up, and over a <span style="font-style: italic;">very</span> long time, the system diverges. Now, the introduction of even the smallest amount of friction to the system would conceal these tiny inaccuracies, however, there ends up being a better way.<br /><br />The error due to multiple forces is actually an error in the calculus. We can play the trick where we move the error out of the calculus and into the representation of the forces, by making an approximation of the force. The approximation I have in mind ends up introducing less error than the error due to multiple forces. Also, this approximation tends to remove energy from the system, which makes the system stable. With this method, you would still calculate <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >v</span> exactly, like before, but when you calculate <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span>, you do it like this<br /><br /><div style="text-align: center; font-family: trebuchet ms;">d<strong>x</strong> = (1/2) d<strong>v</strong>Δt</div><br />Using this method to calculate <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span> actually beats out calculating it exactly in cases where multiple forces that depend on position are in play. This method is called the <em>average acceleration method</em>. On a test performed on a system with two springs, the average acceleration method removed about 5% of the energy from the system. After about 3 hours. In the test I ran of this sample system, the error introduced by the average acceleration method was 58 million times smaller than the error introduced by the semi-implicit Euler method.<br /><br />It is recommended that forces which depend on position or velocity use the average acceleration method of calculating <span style="font-family:trebuchet ms;">d</span><span style="font-weight: bold;font-family:trebuchet ms;" >x</span>.<br /><br /><span style="font-size:130%;"><span style="font-weight: bold;">Conclusion:</span></span><br /><br />Using the kinematic integrator allows you to remove the process of integration from the stepping equations, and push it down into the force calculation. This enables you to taylor the integration method to each different type of force. Having this freedom allows you to provide exact solutions, if they are attainable. If the solutions are not attainable, you can still use the semi-implicit Euler method as a standby. <br /><br />This method introduces a trivial amount of extra computation, i.e. two or three operations per force applied. In the spectrum of numerical methods, this method has roughly the same computational expense as a first order method, and acheives results that far exceed the more expensive fourth order methods.<br /><br />Obviously this method only has utility if you know the form of the forces acting during a given simulation step, and also if the forces are integrable. Happily, most if not all of the forces that are used in run-time simulation are integrable.<br /><br />With some systems it is possible to completely eliminate error. In others, the error is a very small fraction to the error of other methods that have comparable computational expense. Thus, with the kinematic integrator you can use much larger time steps, and expect higher accuracy from integration.Eric Brownhttp://www.blogger.com/profile/00315121935974620846noreply@blogger.com8tag:blogger.com,1999:blog-8643904148340414752.post-41833347419627118882010-02-25T10:04:00.001-08:002010-02-26T13:59:42.068-08:00Quaternions: WhyBefore digging into the deep guts of the quaternion, I want to talk a little bit about complex numbers. Complex numbers are really only a step away from quaternions, and people are much less nervous around complex numbers. So it's a pretty good place to start.<br /><br /><strong><span style="font-size:130%;">A Bit About Complex Numbers:</span></strong><br /><br />A complex number has a real and an imaginary component.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms">z = x +<em>i</em>y</div><br />The presence of the <span style="font-family:trebuchet ms;"><em>i</em></span> makes these two components linearly independant. Thus we can begin to think of a complex number as a 2D vector. In fact it is convenient to represent a complex number as a <em>(real, imaginary)</em> pair.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms">z = (x, y)</div><br />We know that we can add and subtract complex numbers<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms">z<sub>1</sub> + z<sub>2</sub> = (x<sub>1</sub> + x<sub>2</sub>, y<sub>1</sub> + y<sub>2</sub>)<br /><br />z<sub>1</sub> - z<sub>2</sub> = (x<sub>1</sub> - x<sub>2</sub>, y<sub>1</sub> - y<sub>2</sub>)</div><br />and we acheive the same result as adding and subtracting 2D vectors. <br /><br />Complex numbers can do something that 2D vectors can't. You can <em>multiply</em> them.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms">z<sub>1</sub>z<sub>2</sub> = (x<sub>1</sub>x<sub>2</sub> - y<sub>1</sub>y<sub>2</sub>, x<sub>1</sub>y<sub>2</sub> + y<sub>1</sub>x<sub>2</sub>)</div><br />The existence of the multiplication rule promotes the complex numbers from a mere vector space to an <em>algebra</em>. An algebra is a linear space that has a multiplication rule.<br /><br />If we want the complex numbers to represent a 2D vector space we are missing something, and that's a dot product. In a 2D vector space, we have a dot product that tells us the length of the vectors, (or the length squared of the vectors to be more precise.)<br /><br />But wait!! We can determine the magnitude squared of a complex number as well:<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms">|z|<sup>2</sup> = zz<sup>*</sup> = (x<sup>2</sup> + y<sup>2</sup>, 0) = x<sup>2</sup> + y<sup>2</sup></div><br />Here the * represents a complex conjugate, which merely flips the sign of the imaginary component. The magnitude squared of a complex number is identical to the result of taking the dot product of a 2D vector with itself. Using this as your starting point, you can show that the vector dot product, defined in terms of a complex algebra is<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms">A•B = (1/2) (AB<sup>*</sup> + BA<sup>*</sup>)</div><br />When endowed with a dot product, the complex numbers truly do contain a full and complete representation of a 2D vector space, with the added bonus of having a well defined way of <em>multiplying</em> the vectors together.<br /><br />In other words, 2D vectors are not complex numbers, but complex numbers ARE 2D vectors which have the added power of multiplication.<br /><br /><strong><span style="font-size:130%;">So What Was Hamilton Thinking?</span></strong><br /><br />Often, when one is looking up information about quaternions, the story comes up about how W.R. Hamilton is walking along one day, and while crossing a bridge he suddenly comes up with the formula for quaternions. He then promptly vandalizes the bridge and goes on his merry way.<br /><br />How does someone just <em>come up</em> with quaternions? I will tell you.<br /><br />Hamilton was aware of the fact that the algebra of complex numbers supply a natural mechanism for multiplying 2D vectors, and he was wondering: How would a person multiply 3D vectors? We add and subtract 3D vectors, and we have a dot product for 3D vectors, but how do you <em>multiply</em> 3D vectors?<br /><br />Now, some people might be thinking, what about the cross product? Why can't the cross product be the multiplication rule for 3D vectors? The answer is: the cross product definitely holds a clue, but it is not the entire answer. Besides, it wasn't until after the invention of the quaternion that we even had a cross product, so Hamilton didn't know about them.<br /><br />So, as Hamilton is crossing the bridge it dawns on him how we might multiply 3D vectors together, and he writes the multiplication rules for the 3D basis vectors on the bridge. These multiplication rules are what we are talking about when we say the "definition of a quaternion"<br /><br /><strong><span style="font-size:130%;">So How Did Hamilton Come Up With the Formula?</span></strong><br /><br />Remember how we defined the 2D dot product in terms of the complex multiplication rule? Hamilton similarly decided that if a 3D multiplication rule exists, the result of multiplying a vector with itself should be a real number that is equal to the length squared of the vector. So, however the mutliplication works, it should result in the following formula<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>VV</strong><sup>†</sup> = x<sup>2</sup> + y<sup>2</sup> + z<sup>2</sup></div><br />The meaning of the † here is similar to that of the complex conjugate, but here it flips the signs of all of the basis vectors.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>V</strong><sup>†</sup> = -x<strong>I</strong> - y<strong>J</strong> - z<strong>K</strong></div><br />There are nine terms in the product, when the vector is expressed in terms of its 3 components<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>VV</strong><sup>†</sup> = -x<sup>2</sup><strong>I</strong><sup>2</sup> - y<sup>2</sup><strong>J</strong><sup>2</sup> - z<sup>2</sup><strong>K</strong><sup>2</sup> - xy(<strong>IJ</strong> + <strong>JI</strong>) - xz(<strong>IK</strong> + <strong>KI</strong>) - yz(<strong>JK</strong> + <strong>KJ</strong>)</div><br />By not combining the <strong>IJ</strong> and the <strong>JI</strong> terms, I am stating that they are possibly different.<br /><br />While crossing the bridge Hamilton realized that he could satisfy his initial postulate about the multiplication of 3D vectors, if the basis vectors satisfied the following multiplicaiton rules.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>I</strong><sup>2</sup> = <strong>J</strong><sup>2</sup> = <strong>K</strong><sup>2</sup> = -1<br /><br /><strong>IJK</strong> = -1</div><br />In other words, if he applied these rules, the first 3 terms would fall out correctly, and the last 6 terms would vanish.<br /><br />Hamilton was pretty stoked about this, because this meant that you could add, and subtract 3D vectors, but now you could also multiply them together!<br /><br /><strong><span style="font-size:130%;">So Where Does the Fourth Component Come From?</span></strong><br /><br />Using Hamiltons multiplication rules for the basis vectors, we can define a general multiplication rule for the product of arbitrary 3D vectors.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>AB</strong> = -<strong>A</strong>•<strong>B</strong> + <strong>A</strong>×<strong>B</strong></div><br />The first term is a scalar, and the second term is a 3 component vector, four components in all. It was probably this surprising discovery that the multiplication rules summoned the existence of a 4th component that prompted Hamilton to call them quaternions, which literally means "a group of 4."<br /><br />The existence of the 4th component in a general quaternion does not change the original meaning of the vector portion. The vector portion of a quaternion is truly a 3D vector, in every possible identification. It adds, subtracts, and has a dot product like a standard 3D vector. We can use it in every possible way that we can use any 3D vector. The only magic here is that we now have a multiplication law. This is a good thing, since we can use this multiplication law to make meaningful geometric statements about 3D vectors.<br /><br /><strong><span style="font-size:130%;">So What Do Quaternions Have To Do With Rotations?</span></strong><br /><br />At the very heart of the definition of the quaternion multiplication lies the postulate that it must somehow represent the length of the vector. The fundamental definition of a rotation is that it is a transformation which does not change the length of a vector. Thus the definition of quaternion mutliplication is very intimately connected to the concept of rotation.<br /><br />Let's build the rotation from the ground up. To begin with, we know that quaternion multiplication from the right is not the same as quaternion multiplication from the left. Thus, the general form of a transformation would look something like this<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>v</strong>' = <strong>AvB</strong></div><br />Where we have two transformation quaternions, one acting on the right, and one acting on the left.<br /><br />Since <strong>v</strong> is a 3D vector, we don't care what the scalar part is. However, the transformation should also not care. This means that the transformation should not change the value of the scalar part. If the scalar part starts at zero, the transformation should leave it zero. Placing this restriction on the general form of the transformation leads to the following condition.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>B</strong> = <strong>A</strong><sup>†</sup></div><br />And so our transformation law now looks like this<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>v</strong>' = <strong>AvA</strong><sup>†</sup></div><br />Finally, we require that the length of <strong>v</strong> is not changed by the transformation. This can be stated using Hamiltons initial postulate of 3D vector multiplication<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>v</strong>'<strong>v</strong>'<sup>†</sup> = <strong>vv</strong><sup>†</sup><br /><br /><strong>AvA</strong><sup>†</sup> (<strong>AvA</strong><sup>†</sup>) = <strong>AvA</strong><sup>†</sup><strong>Av</strong><sup>†</sup><strong>A</strong><sup>†</sup></div><br />We see that the only way our condition can be satisfied is if <strong>A</strong><sup>†</sup><strong>A</strong> = 1. In other words <strong>A</strong> must be normalized. An arbitrary normalized quaternin takes the form<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>N</strong> = cos(α) + <strong>n </strong>sin(α)</div><br />Here <strong>n</strong> is a normalized 3D vector.<br /><br />If we use this <strong>N </strong>to apply the transformation, we will see that we have successfully rotated <strong>v</strong> around the axis <strong>n</strong> by an angle of 2α. The reason for the factor of 2, is because there are 2 factors of <strong>N</strong> acting on <strong>v</strong>. To take this into account, we generally define rotation quaternions in terms of a half-angle.<br /><br /><div style="TEXT-ALIGN: center; FONT-FAMILY: trebuchet ms"><strong>r</strong> = cos(θ/2) + <strong>n</strong> sin(θ/2)</div><br /><strong><span style="font-size:130%;">Conclusion:</span><br /></strong><br />You now know the why behind quaternions. A 3D vector is not a quaternion, but a quaternion IS a 3D vector, with a multiplication law that requires an additional scalar component. Go now, and unleash your newfound power upon the helpless masses.Eric Brownhttp://www.blogger.com/profile/00315121935974620846noreply@blogger.com1tag:blogger.com,1999:blog-8643904148340414752.post-46393975732973846012010-02-24T13:33:00.000-08:002013-11-10T15:40:19.659-08:00Quaternions: HowGame developers have a love-hate relationship with quaternions. Most understand that they are somehow mathematically superior to Euler-Angles for representing rotations. Most also know that they are more compact, and easier to interpolate than rotation matrices. Other than that, quaternions remain a mystery.<br /><br />I have a very deep and powerful love relationship with quaternions. For me, knowing why they work is more important than knowing how they work. However, most programmers need to see the how of quaternions before they care to ask about why. I will attempt to bestow my quaternion mojo upon you at this time, if you are willing. For now, I will just talk about HOW.<br /><br />We will discuss the basic things that any game programmer actually does with quaternions, such as:<br /><br /><ul><li>Representing a rotation using an axis and an angle</li><li>Rotating vectors</li><li>Concatenating rotations</li><li>Blending between an initial and final rotation</li><li>Integrating quaternions using an angular velocity</li></ul><span style="font-size: 130%; font-weight: bold;">How to Represent a Quaternion:</span><br /><br />A quaternion can be represented by 4 numbers. A common <span style="color: #3333ff; font-family: courier new;">struct</span> definition might be<br /><br /><pre><div style="color: black; font-family: courier new;"><br /><span style="color: #3333ff;">struct</span> <span style="color: #339999;">Quat</span><br /><span style="font-family: courier new;">{</span><br /><span style="color: white;"> </span><span style="font-family: courier new;"><span style="color: #3333ff;">float</span> x;</span><br /><span style="color: white;"> </span><span style="font-family: courier new;"><span style="color: #3333ff;">float</span> y;</span><br /><span style="color: white;"> </span><span style="font-family: courier new;"><span style="color: #3333ff;">float</span> z;</span><br /><span style="color: white;"> </span><span style="font-family: courier new;"><span style="color: #3333ff;">float</span> w;</span><br /><span style="font-family: courier new;">};</span></div><br /></pre>The <span style="font-family: courier new;">x</span>, <span style="font-family: courier new;">y</span>, and <span style="font-family: courier new;">z</span> components of a quaternion represent coordinates in standard 3D space. Really. Some people might try to make it more complicated than that, but they are mistaken. When using a quaternion to represent a standard vector, it is customary, but unnecesary to set the w component to zero. It is convenient to define the quaternion with the <span style="font-family: courier new;">w</span> last, so that you can easily typecast it to a 3D vector. A quaternion IS a vector, in every sense of the term vector.<br /><br />You may ask: if a quaternion IS a vector, why all the fuss? That is an excellent question the answer of which plumbs the very foundations of the universe itself. (You think I'm joking, but I'm not!!) I will give you the answer when I'm ready to discuss the <em>why</em> of the quaternion.<br /><br />When talking about quaternions it is convenient to use <span style="font-style: italic;">(scalar, vector)</span> notation. The scalar I'm referring to is the w component, and the vector is the x, y, and z components. For instance, I might use the following notation<br /><br /><div style="font-family: trebuchet ms; text-align: center;"><strong>q</strong> = (w, <strong>V</strong>)</div><br />In order to use a quaternion to represent a rotation, you need to know the angle <span style="font-style: italic;">θ</span> of the rotation, and the axis <span style="font-weight: bold;">n</span> around which you are rotating. The axis <span style="font-weight: bold;">n</span> is a normalized 3D vector, and the angle <span style="font-style: italic;">θ</span> is e.g. a float. The rotation quaternion is defined as:<br /><br /><div style="font-family: trebuchet ms; text-align: center;"><strong>r</strong> = ( cos(<span style="font-style: italic;">θ</span>/2), <strong>n</strong> sin(<span style="font-style: italic;">θ</span>/2) )</div><br />Looking at this, you may think that it <span style="font-style: italic;">almost</span> makes sense; you wonder why <span style="font-style: italic;">θ</span>/2, and not just <span style="font-style: italic;">θ</span>? This is a wonderful question, and the answer is both beautiful and profound. (You think I'm joking, but I'm not!!) But I'm not answering <span style="font-style: italic;">why</span> yet, I'm just discussing <span style="font-style: italic;">how</span>. One thing that is very important about this formula: <span style="font-weight: bold;">the angle is in radians, NOT degrees!</span><br /><br />To generate a quaternion with a given axis and angle, you may envision creating a function like this<br /><br /><pre><div style="color: black; font-family: courier new;"><br /><span style="color: #339999;">Quat</span> QuatFromAxisAngle(<span style="color: #3333ff;">const</span> <span style="color: #339999;">Vector</span>& axis, <span style="color: #3333ff;">float</span> angleInRadians)<br />{<br /><span style="color: white;"> </span><span style="color: #339999;">Quat</span> result;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> angle = angleInRadians / <span style="color: #993300;">2.0f</span>;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> sinAngle = sin(angle);<br /><span style="color: white;"> </span><span style="color: #339999;">Vector</span> n = VecNormalize(axis);<br /><span style="color: white;"> </span>result.w = cos(angle);<br /><span style="color: white;"> </span>result.x = n.x * sinAngle;<br /><span style="color: white;"> </span>result.y = n.y * sinAngle;<br /><span style="color: white;"> </span>result.z = n.z * sinAngle;<br /><span style="color: white;"> </span><span style="color: #3333ff;">return</span> result;<br />}</div><br /></pre>You now have a quaternion that represents a rotation.<br /><br /><span style="font-size: 130%; font-weight: bold;">How To Rotate a Vector With a Quaternion</span><span style="font-size: 130%;">:</span><br /><br />Quaternions aren't just a set of 4 numbers, they are an <span style="font-style: italic;">algebra</span>. This means that there is a procedure defined to add and multiply these quantities. You can perform a vector rotation using a formula involving quaternion multiplication. But I'm not going to talk about that yet, because most of the time you aren't going to use the quaternion rotation formula.<br /><br />The first rule of rotating vectors with quaternions is: <span style="font-style: italic;">don't rotate vectors with quaternions</span>! Quaternions are great for representing rotations, but when you get to the point in your code where you are doing the actual rotation computation, it's better to convert to a matrix form. Using the quaternion multiplication rule to rotate a vector isn't too expensive, but nothing is more efficient than a matrix for transforming vectors. In fact, it is cheaper to convert the quaternion to a matrix, and use the matrix to rotate the vector, than to use the quaternion formula.<br /><br />As it turns out, most transforming of vectors is done by the graphics library and not by you. However, transformations are ubiquitously represented by matrices in graphics libraries. If you want to send your rotation to the graphics library, you will need to convert it to a matrix. Therefore it is essential for you to know how to convert a quaternion to a matrix.<br /><br />To convert a quaternion to a matrix use this function:<br /><br /><pre><div style="color: black; font-family: courier new;"><br /><span style="color: #339999;">Matrix</span> MatrixFromQuaternion(<span style="color: #3333ff;">const</span> <span style="color: #339999;">Quat</span><span style="color: black;">& q)</span><br />{<br /><span style="color: white;"> </span> <span style="color: #339999;">Matrix</span> result;<br /><span style="color: white;"> </span><span style="color: #009900;">//helper quantities - calculate these up front</span><br /><span style="color: white;"> </span><span style="color: #009900;">//to avoid redundancies</span><br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> xSq = q.x * q.x;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> ySq = q.y * q.y;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> zSq = q.z * q.z;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> wSq = q.w * q.w;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> twoX = <span style="color: #660000;">2.0f</span> * q.x;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> twoY = <span style="color: #660000;">2.0f</span> * q.y;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> twoW = <span style="color: #660000;">2.0f</span> * q.w;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> xy = twoX * q.y;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> xz = twoX * q.z;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> yz = twoY * q.z;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> wx = twoW * q.x;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> wy = twoW * q.y;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> wz = twoW * q.z;<br /><span style="color: white;"> </span><span style="color: #009900;">//fill in the first row</span><br /><span style="color: white;"> </span>result.m00 = wSq + xSq - ySq - zSq;<br /><span style="color: white;"> </span>result.m01 = xy - wz;<br /><span style="color: white;"> </span>result.m02 = xz + wy;<br /><span style="color: white;"> </span><span style="color: #009900;">//fill in the second row</span><br /><span style="color: white;"> </span>result.m10 = xy + wz;<br /><span style="color: white;"> </span>result.m11 = wSq - xSq + ySq - zSq;<br /><span style="color: white;"> </span>result.m12 = yz - wx;<br /><span style="color: white;"> </span><span style="color: #009900;">//fill in the third row</span><br /><span style="color: white;"> </span>result.m20 = xz - wy;<br /><span style="color: white;"> </span>result.m21 = yz + wx;<br /><span style="color: white;"> </span>result.m22 = wSq - xSq - ySq + zSq;<br /><span style="color: white;"> </span><span style="color: #3333ff;">return</span> result;<br />}</div><br /></pre>This function does not assume that the input quaternion is normalized. A quaternion only represents a rotation if it is normalized. If it is not normalized, then there is also a uniform scale that accompanies the rotation. Normalizing a quaternion is similar to normalizing a vector. You just have to take into account that the quaternion has 4 components. To be explicit, here is a function to normalize a quaternion.<br /><br /><pre><div style="color: black; font-family: courier new;"><br /><span style="color: #339999;">Quat</span> QuatNormalize(<span style="color: #3333ff;">const</span> <span style="color: #339999;">Quat</span>& q)<br />{<br /><span style="color: white;"> </span><span style="color: #339999;">Quat</span> result;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> sq = q.x * q.x;<br /><span style="color: white;"> </span>sq += q.y * q.y;<br /><span style="color: white;"> </span>sq += q.z * q.z;<br /><span style="color: white;"> </span>sq += q.w * q.w;<br /><span style="color: white;"> </span><span style="color: #009900;">//detect badness</span><br /><span style="color: white;"> </span>assert(sq > <span style="color: #660000;">0.1f</span>);<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> inv = <span style="color: #660000;">1.0f</span> / sqrt(sq);<br /><span style="color: white;"> </span>result.x = q.x * inv;<br /><span style="color: white;"> </span>result.y = q.y * inv;<br /><span style="color: white;"> </span>result.z = q.z * inv;<br /><span style="color: white;"> </span>result.w = q.w * inv;<br /><span style="color: white;"> </span><span style="color: #3333ff;">return</span> result;<br />}</div><br /></pre><br />Now, you may be wondering how I came up with this magic formula to convert quaternions to matrices. I can do it, because I know how to use the quaternion rotation formula. You may also be wondering why you would ever mess around with quaternions if you just are going to convert it to a matrix anyway. Keep reading... you will see.<br /><span style="font-size: 130%; font-weight: bold;"><br />How to Concatenate Rotations:</span><br /><br />When you multiply two transformation matrices together, the result (aside from any numerical error) is also a transformation matrix. Transformation matrices can rotate, translate, scale, and skew. However, in many cases the only operation being performed by a transformation matrix is a rotation.<br /><br />If you multiply two 3x3 rotation matrices together, there are 27 total terms that need to be evaluated. If you multiply 2 quaternions together, there are only 16. This number can actually be optimized a bit, but even with a naive approach you can perform about 1.5 quaternion multiplies for every matrix multiply. Thus, if you know your transformations only involve rotations, using a quaternion is a very good thing.<br /><br />The order of quaternion multiplication is important, so you need to keep track. Just remember, the first rotation is on the right, and the second rotation is on the left.<br /><br /><div style="font-family: trebuchet ms; text-align: center;"><strong>q</strong><sub>T</sub> = <strong>q</strong><sub>2</sub><strong>q</strong><sub>1</sub></div><br />This multiplication is a quaternion multiplication. The way that quaternion multiplication is defined is one of the things that makes quaternions good at representing rotations.<br /><br />You can express the quaternion multiplication in terms of standard vector operations, such as dot and cross products.<br /><br /><div style="font-family: trebuchet ms; text-align: center;"><strong>A</strong><sub>q</sub><strong>B</strong><sub>q</sub> = (ab - <strong>A</strong>•<strong>B</strong>, a<strong>B</strong> + b<strong>A</strong> + <strong>A</strong>×<strong>B</strong>)</div><br />A function which multiplies two quaternions together may be defined in terms of the components as follows:<br /><br /><pre><div style="color: black; font-family: courier new;"><br /><span style="color: #339999;">Quat</span> QuatMultiply(<span style="color: #3333ff;">const</span> <span style="color: #339999;">Quat</span>& q1, <span style="color: #3333ff;">const</span> <span style="color: #339999;">Quat</span>& q2)<br />{<br /><span style="color: white;"> </span><span style="color: #339999;">Quat</span> result;<br /><span style="color: white;"> </span>result.w = q1.w*q2.w - q1.x*q2.x - q1.y*q2.y - q1.z*q2.z;<br /><span style="color: white;"> </span>result.x = q1.w*q2.x + q1.x*q2.w + q1.y*q2.z - q1.z*q2.y;<br /><span style="color: white;"> </span>result.y = q1.w*q2.y + q1.y*q2.w + q1.x*q2.z - q1.z*q2.x;<br /><span style="color: white;"> </span>result.z = q1.w*q2.z + q1.z*q2.w + q1.x*q2.y - q1.y*q2.x;<br /><span style="color: white;"> </span><span style="color: #3333ff;">return</span> result;<br />}</div><br /></pre>This is just an expanded version of the vector operations given previously.<br /><br /><span style="font-size: 130%;"><span style="font-weight: bold;">How to Interpolate a Quaternion:</span></span><br /><br />This is a very huge topic, but I will boil it down for you and give you the goods.<br /><br />Interpolating a quaternion is useful when smoothly varying between an initial and final rotation. Interpolation is good for finding arbitrary in-between values of rotation. This is employed especially in character animation systems. It is possible to interpolate rotation matrices, but the interpolated matrix may not be a size and shape preserving matrix. Needless to say, interpolating a quaternion is a bajillion times easier than interpolating rotation matrices.<br /><br />There is one interesting property of quaternions that comes into play when dealing with interpolation. If a rotation can be represented by a quaternion <span style="font-weight: bold;">q</span>, then the quaterion -<span style="font-weight: bold;">q</span> also represents the same rotation. Why is that? I'm not going to explain it right now, other than to say that it is connected to the very fabric of reality. (You think I'm joking but I'm not!) What you need to worry about is which one of these quaternions you are going to use.<br /><br />To describe the difference between <span style="font-weight: bold;">q</span> and -<span style="font-weight: bold;">q</span>, consider that you turn a quarter turn to your left. Esentially this is the same as turning 3/4 turn to your right. One turn is the "short" turn and the other is the "long"one. When representing a static orientation it is irrelevant if a quaternion represents the short, or long path, because it just sits in the final position and you don't get to see the in-between values. However, when you are blending it surely does make a difference.<br /><br />When blending between an initial and a final quaternion, there is some ambiguity as to if we are taking the "short" way or the "long" way. It seems like the right thing to always blend on the shortest path. Given the two input quaternions, it is possible to determine which way we are going to blend. You can check this by examining the sign of the 4D dot product of the inputs. If the sign is negative, then you know you are going to be blending the long way.<br /><br />So, what do you do if you find out that you are blending the long way? Simply flip the sign on one of your input quaternions. remember <span style="font-weight: bold;">q</span> and -<span style="font-weight: bold;">q</span> represent the same rotation. Flipping the sign on one of your inputs will flip the sign of the 4D dot product.<br /><br />Now that we have discussed that little tid-bit, let's move on to interpolation formulas.<br /><br />There are a few different interpolation formulas, but two main ones: NLerp is a linear interpolation of the components that is followed by a normalization of the interpolated quaternion, to ensure that it represents a rotation. Slerp is a spherical interpolation which interpolates in a spherical space, rather than in the cartesian space of the coordinates. The interpolant of the slerp function moves at a constant motion, while the interpolant of the NLerp has some non-linear acceleration.<br /><br />Heres the quick and dirty: Don't mess around with Slerp, even though you think it might be the more "correct" thing to do. It is too expensive, and has too many special cases that need to be considered. There are some complicated schemes that try to closely approximate the Slerp function, but it just isn't worth it. Just use NLerp. Especially for computationally strapped code.<br /><br />In fact, I'm not even going to show you how to SLerp. You can consult google if you really want to know.<br /><br />Here is a blending function that uses NLerp<br /><br /><pre><div style="color: black; font-family: courier new;"><br /><span style="color: #339999;">Quat</span> QuatBlend(<span style="color: #3333ff;">const</span> <span style="color: #339999;">Quat</span>& i, <span style="color: #3333ff;">const</span> <span style="color: #339999;">Quat</span>& f, <span style="color: #3333ff;">float</span> blend)<br />{<br /><span style="color: white;"> </span><span style="color: #339999;">Quat</span> result;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> dot = i.w*f.w + i.x*f.x + i.y*f.y + i.z*f.z;<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> blendI = <span style="color: #660000;">1.0f</span> - blend;<br /><span style="color: white;"> </span><span style="color: #3333ff;">if</span>(dot < <span style="color: #660000;">0.0f</span>)<br /><span style="color: white;"> </span>{<br /><span style="color: white;"> </span><span style="color: #339999;">Quat</span> tmpF;<br /><span style="color: white;"> </span>tmpF.w = -f.w;<br /><span style="color: white;"> </span>tmpF.x = -f.x;<br /><span style="color: white;"> </span>tmpF.y = -f.y;<br /><span style="color: white;"> </span>tmpF.z = -f.z;<br /><span style="color: white;"> </span>result.w = blendI*i.w + blend*tmpF.w;<br /><span style="color: white;"> </span>result.x = blendI*i.x + blend*tmpF.x;<br /><span style="color: white;"> </span>result.y = blendI*i.y + blend*tmpF.y;<br /><span style="color: white;"> </span>result.z = blendI*i.z + blend*tmpF.z;<br /><span style="color: white;"> </span>}<br /><span style="color: white;"> </span><span style="color: #3333ff;">else</span><br /><span style="color: white;"> </span>{<br /><span style="color: white;"> </span>result.w = blendI*i.w + blend*f.w;<br /><span style="color: white;"> </span>result.x = blendI*i.x + blend*f.x;<br /><span style="color: white;"> </span>result.y = blendI*i.y + blend*f.y;<br /><span style="color: white;"> </span>result.z = blendI*i.z + blend*f.z;<br /><span style="color: white;"> </span>}<br /><span style="color: white;"> </span>result = QuatNormalize(result);<br /><span style="color: white;"> </span><span style="color: #3333ff;">return</span> result;<br />}</div><br /></pre>This function has a singularity when the difference between the initial and final quaternions is a 180 degree rotation. This is due to the fact that the axis of rotation for the blend becomes ambiguous. You could potentially detect for this case, and decide on using the "up" vector for the axis of the blend. Or you could break up the blend into a few steps. This singularity is something that shows up in any interpolation scheme, not just NLerp.<br /><br /><span style="font-size: 130%; font-weight: bold;">How to Integrate a Quaternion</span><span style="font-size: 130%;">:</span><br /><br />Updating the dynamical state of a rigid body is referred to as integration. If you represent the orientation of this body with a quaternion, you will need to know how to update it. This is done with the following quaternion formula.<br /><br /><div style="font-family: trebuchet ms; text-align: center;"><strong>q</strong>' = Δ<strong>q </strong><strong>q</strong><strong></strong></div><br />We calculate Δ<strong>q</strong> using a 3D vector <strong style="font-family: trebuchet ms;">ω</strong> whose magnitude represents the angular velocity, and whose direction represents the axis of the angular velocity. We also use the time step <em>Δt</em> over which the velocity should be applied. Δ<span style="font-weight: bold;">q</span> is still a rotation quaternion, and has the same form involving sines and cosines of a half angle. We use the angular velocity and time step to construct a vector <strong style="font-style: italic;">θ</strong>, whose magnitude is the half angle, and whose direction is the axis.<br /><br /><div style="font-family: trebuchet ms; text-align: center;"><strong style="font-style: italic;">θ</strong> = <strong>ω</strong><em>Δt/2</em></div><br />Note: I've included the factor of 1/2, which shows up inside the trig functions of the rotation quaternion. Expressing the rotation quaternion in terms of this vector you have<br /><br /><div style="font-family: trebuchet ms; text-align: center;">Δ<strong>q</strong> = ( cos(<strong style="font-style: italic;">θ</strong>), (<strong style="font-style: italic;">θ</strong>/|<strong style="font-style: italic;">θ</strong>|) sin(<strong style="font-style: italic;">θ</strong>) )</div><br />This works well, however this formula becomes numerically unstable as |<strong style="font-style: italic;">θ</strong>| approaches zero. If we can detect that |<strong style="font-style: italic;">θ</strong>| is small, we can safely use the Taylor series expansion of the sin and cos functions. The "low angle" version of this formula is<br /><br /><div style="font-family: trebuchet ms; text-align: center;">Δ<strong>q</strong> = (1 - |<strong style="font-style: italic;">θ</strong>|<sup>2</sup>/2, <strong style="font-style: italic;">θ</strong> - <strong style="font-style: italic;">θ</strong>|<strong style="font-style: italic;">θ</strong>|<sup>2</sup>/6)</div><br />We use the first 3 terms of the Taylor series expansion, so we should ensure that the fourth term is less than machine precision before we use the "low angle" version. The fourth term of the expansion is<br /><br /><div style="font-family: trebuchet ms; text-align: center;">|<strong style="font-style: italic;">θ</strong>|<sup>4</sup>/24 < ε</div><br />Here is a sample function for integrating a quaternion with a given angular velocity and time step<br /><br /><pre><div style="color: black; font-family: courier new;"><br /><span style="color: #339999;">Quat</span> QuatIntegrate(<span style="color: #3333ff;">const</span> <span style="color: #339999;">Quat</span>& q, <span style="color: #3333ff;">const</span> <span style="color: #339999;">Vector</span>& omega, <span style="color: #3333ff;">float</span> deltaT)<br />{<br /><span style="color: white;"> </span><span style="color: #339999;">Quat</span> deltaQ;<br /><span style="color: white;"> </span><span style="color: #339999;">Vector</span> theta = VecScale(omega, deltaT * <span style="color: #660000;">0.5f</span>);<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> thetaMagSq = VecMagnitudeSq(theta);<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> s;<br /><span style="color: white;"> </span><span style="color: #3333ff;">if</span>(thetaMagSq * thetaMagSq / <span style="color: #660000;">24.0f</span> < <span style="color: #666666;">MACHINE_SMALL_FLOAT</span>)<br /><span style="color: white;"> </span>{<br /><span style="color: white;"> </span>deltaQ.w = <span style="color: #660000;">1.0f</span> - thetaMagSq / <span style="color: #660000;">2.0f</span>;<br /><span style="color: white;"> </span>s = <span style="color: #660000;">1.0f</span> - thetaMagSq / <span style="color: #660000;">6.0f</span>;<br /><span style="color: white;"> </span>}<br /><span style="color: white;"> </span><span style="color: #3333ff;">else</span><br /><span style="color: white;"> </span>{<br /><span style="color: white;"> </span><span style="color: #3333ff;">float</span> thetaMag = sqrt(thetaMagSq);<br /><span style="color: white;"> </span>deltaQ.w = cos(thetaMag);<br /><span style="color: white;"> </span>s = sin(thetaMag) / thetaMag;<br /><span style="color: white;"> </span>}<br /><span style="color: white;"> </span>deltaQ.x = theta.x * s;<br /><span style="color: white;"> </span>deltaQ.y = theta.y * s;<br /><span style="color: white;"> </span>deltaQ.z = theta.z * s;<br /><span style="color: white;"> </span><span style="color: #3333ff;">return</span> QuatMultiply(deltaQ, q);<br />}</div><br /></pre><br />This is basically it! You now know how to accomplish all of the main tasks that any game programmer will usually bump up against relating to quaternions. If you are brave, you can move on to my next post, which covers a lot of details concerning the WHY of quaternions.Eric Brownhttp://www.blogger.com/profile/00315121935974620846noreply@blogger.com9