<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>code-spot &#187; Game Development</title>
	<atom:link href="http://code-spot.co.za/category/game-development/feed/" rel="self" type="application/rss+xml" />
	<link>http://code-spot.co.za</link>
	<description>a programming blog</description>
	<lastBuildDate>Sun, 27 Feb 2011 07:18:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>A Simple Trick for Moving Objects in a Physics Simulation</title>
		<link>http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/</link>
		<comments>http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 19:24:24 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[damper]]></category>
		<category><![CDATA[force]]></category>
		<category><![CDATA[game programming]]></category>
		<category><![CDATA[physics]]></category>
		<category><![CDATA[PID controller]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=1013</guid>
		<description><![CDATA[(Original Image by Valerie Everett) It is sometime necessary to move an object in a physics simulation to a specific point. On the one hand, it can be difficult to analyse the exact force you have to apply; on the other hand it might not look so good if you animate the object&#8217;s position directly. [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/10/29/force-field-editor-v10/' rel='bookmark' title='Permanent Link: Force Field Editor v1.0'>Force Field Editor v1.0</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-1035" title="springs" src="http://code-spot.co.za/blog/wp-content/uploads/2010/07/springs2.png" alt="" width="488" height="257" /></p>
<p>(<a href="http://www.flickr.com/photos/valeriebb/248282508/sizes/o/">Original Image</a> by <a href="http://www.flickr.com/photos/valeriebb/">Valerie Everett</a>)</p>
<p>It is sometime necessary to move an object in a physics simulation to a specific point. On the one hand, it can be difficult to analyse the exact force you have to apply; on the other hand it might not look so good if you animate the object&#8217;s position directly.</p>
<p>A compromise that works well in many situations is to use a spring-damper system to move the object.</p>
<p>The trick is simple: we apply two forces—the one is proportional to the displacement; the other is proportional to the velocity. Tweaked correctly, they combine to give realistic movement to the desired point.</p>
<p><span id="more-1013"></span></p>
<p>The <a href="http://en.wikipedia.org/wiki/Hookes_law"><em>spring force</em></a> is proportional to the difference between the current position and the position where we want the object:</p>
<img src='http://s.wordpress.com/latex.php?latex=F_s%20%3D%20-k%28x%20-%20x_0%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='F_s = -k(x - x_0)' title='F_s = -k(x - x_0)' class='latex' />
<p>Here, <img src='http://s.wordpress.com/latex.php?latex=k&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='k' title='k' class='latex' /> is a positive value called the <em>spring constant</em>.</p>
<p>As you can see, the force gets smaller as our object approaches the desired position, and becomes zero when it reaches that position. Unfortunately, in the absence of friction or drag, the <em>velocity</em> is not zero at this point, so the object overshoots the desired position, and moves past it. The force becomes bigger, but in the opposite direction. The object keeps on moving, slowing down, and finally starts moving in the opposite direction towards the desired position. This goes on indefinitely.</p>
<p>When there is friction or drag, we might be lucky enough for the system to slow down the object sufficiently so that its velocity becomes zero when the object reaches the desired position. This can be tricky to accomplish, though, and might impact the simulation environment in undesirable ways.</p>
<p>It is better to add a counteracting force explicitly. We add a <em>damper force</em> that is propostional to the velocity of the object, again opposite in direction. Here <img src='http://s.wordpress.com/latex.php?latex=c&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c' title='c' class='latex' /> is the <em>viscous damping coefficient</em>, also a positive number.</p>
<img src='http://s.wordpress.com/latex.php?latex=F_d%20%3D%20-cv&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='F_d = -cv' title='F_d = -cv' class='latex' />
<p>We then apply the sum of the forces to our object:</p>
<img src='http://s.wordpress.com/latex.php?latex=F_t%20%3D%20F_s%20%2B%20F_d&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='F_t = F_s + F_d' title='F_t = F_s + F_d' class='latex' />
<p>The trick is to choose <img src='http://s.wordpress.com/latex.php?latex=c&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c' title='c' class='latex' /> to get the behaviour we want.</p>
<p>Fortunately, this is easy. The following table summarizes how the damping constant affects behaviour. Here, <img src='http://s.wordpress.com/latex.php?latex=m&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='m' title='m' class='latex' /> is the mass of the object.</p>
<table>
<tbody>
<tr>
<td><img src='http://s.wordpress.com/latex.php?latex=c%20%3D%200&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c = 0' title='c = 0' class='latex' /></td>
<td>The object oscillates.</td>
</tr>
<tr>
<td><img src='http://s.wordpress.com/latex.php?latex=0%20%3C%20c%20%3C%202%5Csqrt%7Bmk%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='0 &lt; c &lt; 2\sqrt{mk}' title='0 &lt; c &lt; 2\sqrt{mk}' class='latex' /></td>
<td>The object oscillates, but the oscillations die down.</td>
</tr>
<tr>
<td><img src='http://s.wordpress.com/latex.php?latex=c%20%3D%202%5Csqrt%7Bmk%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c = 2\sqrt{mk}' title='c = 2\sqrt{mk}' class='latex' /></td>
<td>The object moves to the desired position without oscillating in minimum time.</td>
</tr>
<tr>
<td><img src='http://s.wordpress.com/latex.php?latex=c%20%3E%202%5Csqrt%7Bmk%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c &gt; 2\sqrt{mk}' title='c &gt; 2\sqrt{mk}' class='latex' /></td>
<td>The object moves to the desired position without oscillating, and takes longer as c increases.</td>
</tr>
</tbody>
</table>
<p>If you want to see an explanation of how this works, see the Wikipedia article on <a href="http://en.wikipedia.org/wiki/Damping">damping</a>.</p>
<p>By choosing <img src='http://s.wordpress.com/latex.php?latex=c%20%3D%202%5Csqrt%7Bmk%7D&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='c = 2\sqrt{mk}' title='c = 2\sqrt{mk}' class='latex' />, we are left with only one parameter to tweak (the spring constant), with which we can adjust the time it will take for the object to reach the desired spot.</p>
<p>A simple implementation of this idea is given by the following function. The function should be called for every simulation frame, until we are satisfied that the object reached its spot:</p>
<pre>private void MoveTo(Rigidbody rigidbody, Vector3 newPosition,
      float springConstant)
{
  Vector3 desiredDisplacement = rigidbody.position - newPosition;
  Vector3 springForce = -springConstant * desiredDisplacement;

  float viscousDampingCoefficient
    = 2 * sqrt(rigidbody.mass * springConstant);

  Vector3 dampingForce
    = -viscousDampingCoefficient * rigidbody.velocity;

  Vector3 totalForce = springForce + dampingForce;
  rigidbody.AddForce(totalForce);
}</pre>
<p>This will work even when there is drag or friction, except that the object will move slower (in this case we can decrease the artificial damping, although it is a bit risky). When there is an external force applied to the object, the object will come to rest at some point away from the desired position. By increasing the spring constant, the distance between this point and the desired point can be made smaller. Thus, we can also use this scheme to maintain objects at a certain height, for example, which can give a rather realistic simulation of a hovercraft or even a drifting object.</p>
<p><strong>Update: </strong>This is an example of a <a href="http://en.wikipedia.org/wiki/PID_controller">PID controller</a> (proportional–integral–derivative controller), for which there is a C++ implementation in my <a href="http://code.google.com/p/specialnumbers/">Special Numbers Library</a>.</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/10/29/force-field-editor-v10/' rel='bookmark' title='Permanent Link: Force Field Editor v1.0'>Force Field Editor v1.0</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Region Quadtrees in C++</title>
		<link>http://code-spot.co.za/2010/06/15/region-quadtrees-in-c/</link>
		<comments>http://code-spot.co.za/2010/06/15/region-quadtrees-in-c/#comments</comments>
		<pubDate>Tue, 15 Jun 2010 11:14:14 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Image Processing]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[Dev.Mag]]></category>
		<category><![CDATA[image partitioning]]></category>
		<category><![CDATA[quadtree]]></category>
		<category><![CDATA[quadtrees]]></category>
		<category><![CDATA[spatial partitioning]]></category>
		<category><![CDATA[sum]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=983</guid>
		<description><![CDATA[(Original image by GoAwayStupidAI). Below are four C++ implementations of the region quadtree (the kind used for image compression, for example). The different implementations were made in an attempt to optimise construction of quadtrees. (For a tutorial on implementing region quadtrees, see Issue 26 [6.39 MB zip] of Dev.Mag). NaiveQuadtree is the straightforward implementation. AreaSumTableQuadtree [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2008/10/06/quadtrees/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
<li><a href='http://code-spot.co.za/2008/11/15/quadtrees-2/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
<li><a href='http://code-spot.co.za/2008/12/15/a-simple-texture-algorithm-faster-code-and-more-results/' rel='bookmark' title='Permanent Link: A simple texture algorithm – faster code and more results'>A simple texture algorithm – faster code and more results</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="display: inline; border: 0px;" title="quadtree" src="http://code-spot.co.za/blog/wp-content/uploads/2010/06/quadtree.png" border="0" alt="quadtree" width="491" height="375" /></p>
<p>(<a href="http://www.flickr.com/photos/goawaystupidai/3106598088/">Original image</a> by <a href="http://www.flickr.com/photos/goawaystupidai/">GoAwayStupidAI</a>).</p>
<p>Below are four C++ implementations of the <a href="http://www.voronoi.com/wiki/index.php?title=Quadtree">region quadtree</a> (the kind used for image compression, for example). The different implementations were made in an attempt to optimise <em>construction </em>of quadtrees. (For a tutorial on implementing region quadtrees, see <a href="http://www.devmag.org.za/uploads/DevMag_Issue26.zip" class="broken_link">Issue 26</a> [6.39 MB zip] of <a href="http://devmag.org.za/">Dev.Mag</a>).</p>
<ul>
<li><strong>NaiveQuadtree </strong>is the straightforward implementation.</li>
<li><strong>AreaSumTableQuadtree </strong>uses a <a href="http://en.wikipedia.org/wiki/Summed_area_table">summed area table</a> to perform fast calculations of the mean and variance of regions in the data grid.</li>
<li><strong>AugmentedAreaSumTableQuadtree </strong>is the same, except that the area sum table has an extra row and column of zeros to prevents if-then logic that slows it down and makes it tricky to understand.</li>
<li><strong>SimpleQuadtree </strong>is the same as AugmentedAreaSumTableQuadtree , except that no distinction is made (at a class level) between different node types.</li>
</ul>
<p><span id="more-983"></span>The interfaces of all quadtrees are the same, but I did not want to extend from a base class. (Instead, a compile time check is performed on the classes, using <a href="http://www.boost.org/doc/libs/1_43_0/libs/concept_check/concept_check.htm">boost concepts</a>).</p>
<p>The results of the performance (on my machine!) of the trees are as follows:</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td style="text-align: left;" width="100" valign="top">(milliseconds)</td>
<td style="text-align: right;" width="100" valign="top"><strong>N</strong></td>
<td style="text-align: right;" width="100" valign="top"><strong>S</strong></td>
<td style="text-align: right;" width="100" valign="top"><strong>AST</strong></td>
<td style="text-align: right;" width="100" valign="top"><strong>AAST</strong></td>
</tr>
<tr>
<td style="text-align: right;" width="100" valign="top"></td>
<td style="text-align: right;" width="100" valign="top">3</td>
<td style="text-align: right;" width="100" valign="top">4</td>
<td style="text-align: right;" width="100" valign="top">4</td>
<td style="text-align: right;" width="100" valign="top">3</td>
</tr>
<tr>
<td width="100" valign="top"><strong>64×64</strong></td>
<td style="text-align: right;" width="100" valign="top">14</td>
<td style="text-align: right;" width="100" valign="top">14</td>
<td style="text-align: right;" width="100" valign="top">14</td>
<td style="text-align: right;" width="100" valign="top">13</td>
</tr>
<tr>
<td width="100" valign="top"><strong>128×128</strong></td>
<td style="text-align: right;" width="100" valign="top">55</td>
<td style="text-align: right;" width="100" valign="top">52</td>
<td style="text-align: right;" width="100" valign="top">55</td>
<td style="text-align: right;" width="100" valign="top">52</td>
</tr>
<tr>
<td width="100" valign="top"><strong>256×256</strong></td>
<td style="text-align: right;" width="100" valign="top">229</td>
<td style="text-align: right;" width="100" valign="top">233</td>
<td style="text-align: right;" width="100" valign="top">218</td>
<td style="text-align: right;" width="100" valign="top">214</td>
</tr>
<tr>
<td width="100" valign="top"><strong>512×512</strong></td>
<td style="text-align: right;" width="100" valign="top">950</td>
<td style="text-align: right;" width="100" valign="top">1036</td>
<td style="text-align: right;" width="100" valign="top">937</td>
<td style="text-align: right;" width="100" valign="top">922</td>
</tr>
<tr>
<td width="100" valign="top"><strong>1024×1024</strong></td>
<td style="text-align: right;" width="100" valign="top">4064</td>
<td style="text-align: right;" width="100" valign="top">4459</td>
<td style="text-align: right;" width="100" valign="top">5396</td>
<td style="text-align: right;" width="100" valign="top">3891</td>
</tr>
</tbody>
</table>
<p>As it turns out, the different implementations do not differ significantly. Constructing the nodes takes long, and not so much the calculations necessary to determine whether a node should split or not, and what data should be in the node. Had I profiled properly before I started I would not have gone through this exercise…</p>
<p>Between these four implementations, the NaiveQuadtree is the one I recommend; I left in the other implementations for anyone interested.</p>
<p>The one good thing that came from this experiment is that I found out that using a zero-augmented summed area table can increase performance quite a bit. This is useful for <a href="http://code-spot.co.za/2010/04/16/simple-fast-approximate-minimum-maximum-filters/">max-filters</a> and other algorithms that use these tables.</p>
<p>You can download the source code:</p>
<p><a href="http://www.code-spot.co.za/downloads/cpp/Quadtree.zip">Quadtree.zip</a> (44 KB, Visual Studio).</p>
<p>(It requires the <a href="http://www.boost.org/users/download/">boost library</a> for concept checking, but nothing else. Everything will still work if you remove all references to the boost library. If you already have boost, just hook up to the include path in Visual Studio).</p>
<p>&#8230;or read the <a href="http://www.code-spot.co.za/downloads/cpp/quadtrees/html/index.html">online documentation</a>.</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2008/10/06/quadtrees/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
<li><a href='http://code-spot.co.za/2008/11/15/quadtrees-2/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
<li><a href='http://code-spot.co.za/2008/12/15/a-simple-texture-algorithm-faster-code-and-more-results/' rel='bookmark' title='Permanent Link: A simple texture algorithm – faster code and more results'>A simple texture algorithm – faster code and more results</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2010/06/15/region-quadtrees-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Experimental Tool for Removing Unwanted Artefacts in Textures</title>
		<link>http://code-spot.co.za/2010/04/15/experimental-tool-for-removing-unwanted-artefacts-in-textures/</link>
		<comments>http://code-spot.co.za/2010/04/15/experimental-tool-for-removing-unwanted-artefacts-in-textures/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 13:36:40 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Image Processing]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[filtering]]></category>
		<category><![CDATA[game tools]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=849</guid>
		<description><![CDATA[Many textures used for 3D art start from photographs. Ideally, such textures should be uniformly lit so that the texture does not interfere with the lighting applied by the 3D software. Often, lighting artefacts must be removed by hand. This can be tedious and time consuming. The tool provided here aims to automate this process. [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/05/27/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-example-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2009/10/24/guerrilla-tool-development/' rel='bookmark' title='Permanent Link: Guerrilla Tool Development'>Guerrilla Tool Development</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" title="texture" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/texture.png" border="0" alt="texture" width="491" height="321" /></p>
<p>Many textures used for 3D art start from photographs. Ideally, such textures should be uniformly lit so that the texture does not interfere with the lighting applied by the 3D software. Often, lighting artefacts must be removed by hand. This can be tedious and time consuming.</p>
<p>The tool provided here aims to automate this process. It is still in an experimental phase, so it is very crude. Below you can see some of the before and after pictures.</p>
<p><span id="more-849"></span></p>
<p>I will say more about how these work in a later post.</p>
<p>If you want to give it a try, go <a href="http://code-spot.co.za/image-restoration-tool/" class="broken_link">here</a> to download (caveats: command-line only; Windows only; requires ImageMagick.)</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="hair" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/hair.jpg" border="0" alt="hair" width="240" height="240" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="hair_std_" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/hair_std_.png" border="0" alt="hair_std_" width="240" height="240" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="pebbles" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/pebbles.jpg" border="0" alt="pebbles" width="240" height="209" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="pebbles_minmax" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/pebbles_minmax.png" border="0" alt="pebbles_minmax" width="240" height="209" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="paper" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/paper.jpg" border="0" alt="paper" width="240" height="320" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="paper_mean_" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/paper_mean_.png" border="0" alt="paper_mean_" width="240" height="320" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="metal" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/metal.jpg" border="0" alt="metal" width="240" height="117" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="metal_mean_" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/metal_mean_.png" border="0" alt="metal_mean_" width="240" height="117" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="metal2" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/metal2.jpg" border="0" alt="metal2" width="240" height="109" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="metal2_mean_" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/metal2_mean_.png" border="0" alt="metal2_mean_" width="240" height="109" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="machinery" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/machinery.jpg" border="0" alt="machinery" width="240" height="240" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="machinery_minmax" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/machinery_minmax.png" border="0" alt="machinery_minmax" width="240" height="240" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="paint" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/paint.jpg" border="0" alt="paint" width="240" height="180" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="paint_mean_" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/paint_mean_.png" border="0" alt="paint_mean_" width="240" height="180" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="wood" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/wood.jpg" border="0" alt="wood" width="240" height="320" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="wood_std_" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/wood_std_.png" border="0" alt="wood_std_" width="240" height="320" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="color" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/color.jpg" border="0" alt="color" width="240" height="213" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="color_mean_2" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/color_mean_2.png" border="0" alt="color_mean_2" width="240" height="213" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="color" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/color.jpg" border="0" alt="color" width="240" height="213" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="color_mean_value_" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/color_mean_value_.png" border="0" alt="color_mean_value_" width="240" height="213" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="scene" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/scene.jpg" border="0" alt="scene" width="240" height="240" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="scene_mean" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/scene_mean.png" border="0" alt="scene_mean" width="240" height="240" /></td>
</tr>
<tr>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="grass" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/grass.jpg" border="0" alt="grass" width="240" height="160" /></td>
<td width="250" valign="top"><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="grass_mean_" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/grass_mean_.png" border="0" alt="grass_mean_" width="240" height="160" /></td>
</tr>
</tbody>
</table>
<p>The tool can also improve artefacts in tileable textures:</p>
<p><strong>BEFORE </strong>(distracting horizontal striping)</p>
<p><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="texture1" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/texture1.png" border="0" alt="texture1" width="500" height="375" /></p>
<p><strong>AFTER</strong> (reduced striping)</p>
<p><img style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" title="texture2" src="http://code-spot.co.za/blog/wp-content/uploads/2010/04/texture2.png" border="0" alt="texture2" width="500" height="375" /></p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/05/27/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-example-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2009/10/24/guerrilla-tool-development/' rel='bookmark' title='Permanent Link: Guerrilla Tool Development'>Guerrilla Tool Development</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2010/04/15/experimental-tool-for-removing-unwanted-artefacts-in-textures/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Tips for Designing and Implementing a Stimulus Response Agent</title>
		<link>http://code-spot.co.za/2009/10/25/tips-for-designing-and-implementing-a-stimulus-response-agent/</link>
		<comments>http://code-spot.co.za/2009/10/25/tips-for-designing-and-implementing-a-stimulus-response-agent/#comments</comments>
		<pubDate>Sun, 25 Oct 2009 20:35:41 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[artificial intelligence]]></category>
		<category><![CDATA[convolution]]></category>
		<category><![CDATA[filtering]]></category>
		<category><![CDATA[Kalman filter]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[PID controller]]></category>
		<category><![CDATA[racing game ai]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[random steering]]></category>
		<category><![CDATA[response curve]]></category>
		<category><![CDATA[Special Numbers Library]]></category>
		<category><![CDATA[stimilus response agent]]></category>
		<category><![CDATA[system design]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=776</guid>
		<description><![CDATA[(Original Image by everyone’s idle.) This post was a originally published on Luma Labs, now dead. As old as stimulus-response techniques are, they still form an important part of many AI systems, even if it is a thin layer underneath a sophisticated decision, planning, or learning system. In this tutorial I give some advice to [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/11/11/5-tips-for-prototyping-slow-algorithms/' rel='bookmark' title='Permanent Link: 5 Tips for Prototyping Slow Algorithms'>5 Tips for Prototyping Slow Algorithms</a></li>
<li><a href='http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/' rel='bookmark' title='Permanent Link: Generating Random Numbers with Arbitrary Distributions'>Generating Random Numbers with Arbitrary Distributions</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="display: inline; border-width: 0px;" title="brain" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/brain.png" border="0" alt="brain" width="500" height="366" /><br />
(<a href="http://www.flickr.com/photos/mgdtgd/3507973704/">Original Image</a> by <a href="http://www.flickr.com/photos/mgdtgd/">everyone’s idle</a>.)</p>
<p><em>This post was a originally published on Luma Labs, now dead.</em></p>
<p>As old as stimulus-response techniques are, they still form an important part of many AI systems, even if it is a thin layer underneath a sophisticated decision, planning, or learning system. In this tutorial I give some advice to their design and implementation, mostly out of experience gained from implementing the AI for some racing games.</p>
<p>A <em>stimulus response agent</em> (or a <em>reactive agent</em>) is an agent that takes inputs from its world through sensors, and then takes action based on those inputs through actuators. Between the stimulus and response, there is a processing unit that can be arbitrarily complex. An example of such an agent is one that controls a vehicle in a racing game: the agent “looks” at the road and nearby vehicles, and then decides how much to turn and break.</p>
<p><span id="more-776"></span></p>
<p>This definition is so broad that it is hard to think of agents that are <em>not</em> stimulus response agents. Some agents base their actions not on inputs, but on their internal state alone. See for example how <a href="http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/">random steering algorithms</a> can lead to interesting behaviour.</p>
<p>Some agents don&#8217;t act. They just digest. The only way they can be useful if we look at what they are “thinking”. In fact, they are often designed with the sole purpose of “telling” us what they think, and they are not usually called <em>agents</em>, but rather decision systems. A face recognition system is an example of this. Of course, if we consider “telling” or “deciding” an action, these decision system become stimulus response agents too – but since we do not think of them as agents, the distinction is useful.</p>
<h2>Design</h2>
<h3>1. Do not design your system around an overly simplistic view</h3>
<p>The typical presentation of a stimulus response agent looks like this:</p>
<p><img style="display: inline; border-width: 0px;" title="SRA_simple" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/SRA_simple.png" border="0" alt="SRA_simple" width="303" height="52" /></p>
<p>This presentation, while technically correct, is suitable only for flowers blowing in the wind. A real-world stimulus-response agent might look more like this:</p>
<p><img style="display: inline; border-width: 0px;" title="sra_complex" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/sra_complex.png" border="0" alt="sra_complex" width="436" height="332" /></p>
<p>Note that there are five factors that influence decisions:</p>
<ul>
<li><strong>Game state</strong> is the mode of the game. For example, when an agent can be in a PLAY state (actively competing against the player) or a CHILL state (after taking over from the player at the end of the game.</li>
<li><strong>Global world state </strong>is the current conditions of the world, such as the weather or time of day.</li>
<li><strong>Local world</strong> <strong>state</strong> is what is normally thought of as the “stimulus”. It is the properties of the world around the agent that changes as the agents moves or otherwise acts in the world. For example, the shape of the path near a path following agent is part of the local world state.</li>
<li><strong>Agent parameters</strong> constitute the fixed limits of the agent&#8217;s sensory processing, and reactionary systems. For example, how far can the AI see, how quickly will it react, and how high can it jump. These parameters often describe the bounds for a state variable.</li>
<li><strong>Agent state</strong> is the changing parameters of the agent&#8217;s behaviour.</li>
</ul>
<p>Note that all these can be mapped to the simplistic view of our agent. However, it is important to recognise the differences in these groups of variables, because the agent is made aware of them (connected to them) in different ways.</p>
<p>The world state is not sensed, but communicated through passed parameters, or a query to the world state object.</p>
<p>The game state is enforced by the game system, and typically the agent does not query or sense the game state – it is communicated from the outside.</p>
<p>The local world state is sensed by the agent through its sensors. Typically this means the agent must have hooks into the world. This data can be noisy or incomplete, so the agent might use filtering, and hence will store its own processed copy of the data.</p>
<p>The agent parameters are partially hard-coded, and partially generated on construction, or read from a file. These do not change over the agent&#8217;s life time.</p>
<p><img style="display: inline; border-width: 0px;" title="agent_state" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/agent_state.png" border="0" alt="agent_state" width="171" height="105" /></p>
<p>The agent state is calculated on updates. It has two parts:</p>
<ul>
<li>The <strong>discrete state</strong> is usually implemented as a state machine. In a vehicle driving agent, the discrete states can be PULL_AWAY, NORMAL, WRONG_WAY, and so on.</li>
<li>The <strong>continuous state</strong> of an agent is the state determined by a set of parameters. For a vehicle driving agent, these can include “deviation_from_path”, “distance_from_closest_player”, “aggressiveness” and so on. Note that the continuous state for every discrete state can be described by a different set of parameters, possibly overlapping.In general, a different set of response equations will be used for every discrete state. In fact, the sole purpose of the state machine is to select the correct set of response equations for every situation.</li>
</ul>
<p>The table below summarises the factors that influence a stimulus response agent&#8217;s decisions.</p>
<table border="0" cellspacing="0" cellpadding="2" width="492">
<tbody>
<tr>
<td width="145" valign="top"><strong>Factor</strong></td>
<td width="345" valign="top"><strong>Source</strong></td>
</tr>
<tr>
<td width="145" valign="top">Game state</td>
<td width="345" valign="top">Game system</td>
</tr>
<tr>
<td width="145" valign="top">Global world state</td>
<td width="345" valign="top">World</td>
</tr>
<tr>
<td width="145" valign="top">Local world state</td>
<td width="345" valign="top">Sensors</td>
</tr>
<tr>
<td width="145" valign="top">Physical parameters</td>
<td width="345" valign="top">Hard-coded / File / Generated</td>
</tr>
<tr>
<td width="145" valign="top">Agent state</td>
<td width="345" valign="top">Calculated</td>
</tr>
<tr>
<td width="145" valign="top">
<ul>
<li><span style="font-size: 10.8333px;">Discrete State</span></li>
<li><span style="font-size: 10.8333px;">Continuous State</span></li>
</ul>
</td>
<td width="345" valign="top">State machine transitions<br />
Equations</td>
</tr>
</tbody>
</table>
<h3>2. Clearly distinguish between objects that have state, and those that do not (or should not)</h3>
<p>It is easy to build objects that have states when they should not. It is, for example, reasonable to design a path-following object so that it keeps track of an agent&#8217;s progress along the path (such as the last node reached), to simplify communication between the agent and the path. In this scenario, the communication looks like this:</p>
<p><img style="display: inline; border-width: 0px;" title="state_wrong1" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/state_wrong1.png" border="0" alt="state_wrong1" width="285" height="114" /></p>
<p>There are at least two problems with this set-up:</p>
<ul>
<li>every agent must have its own copy of the path; and</li>
<li>the agent can&#8217;t ask any path information that violates the path object&#8217;s assumption about where the agent is.</li>
</ul>
<p>To illustrate the last point, consider the situation where the path keeps track of the last node reached by the agent, and updates that node as the agent reports its position to the path object. It uses this node and the next node to interpolate a suitable position for the agent to move to. All is fine, until the agent needs information about the future, for example, it&#8217;s projection one second from now on the path. One second from now, the agent may have reached another node, something this simple system cannot handle properly.</p>
<p>Another way to do this, is for the agent to store the last node reached and pass it along its position in queries:</p>
<p><img style="display: inline; border-width: 0px;" title="state_wrong2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/state_wrong2.png" border="0" alt="state_wrong2" width="288" height="150" /></p>
<p>This does not solve the problem really – must the agent now store a separate node for queries into the future?</p>
<p>The best solution is to have a path manager. It has two responsibilities:</p>
<ul>
<li>to store any agent state information relating to the path – the last node reached, in our example; and</li>
<li>to handle calculations for queries (based only on data from the path).</li>
</ul>
<p><img style="display: inline; border-width: 0px;" title="states_correct" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/states_correct.png" border="0" alt="states_correct" width="511" height="131" /></p>
<p>Now, when the agent asks the path manager about its projection 1 second from now, the path manager can check against the path whether a node will be reached, and perform the correct calculation. [In practise, the agent will transform time into distance travelled in time at its current velocity, so that the path manager only needs to know about distance, not time].</p>
<p>Every agent must have its own path manager, but the path managers can share the same path.</p>
<p>Consider another, slightly different, example. A certain agent has a “angriness” factor, which is randomised every 10 updates between two fixed extremes. Every type of agent has a different set of extremes (a monster will have higher extremes than a cow, for example), which helps determine the agent&#8217;s “personality”. It is easy to dump the extremes and the current value in one object (typically, the agent object). This is a poor design for two reasons:</p>
<ul>
<li>There is unnecessary duplicated data, with the associated disadvantages (such as making network packets bulkier, making save files of the game state bigger, and so on).</li>
<li>The distinction between of agent state and agent parameters gets muddy. This makes it easier to make mistakes, overcomplicate the design, and introduce unnecessary inefficiencies.</li>
</ul>
<p>A better design is to put the extremes into an “angriness profile” object, which can be shared by agents of the same type; in the example there will be two instances, one for cows and one for monsters.</p>
<p>Note that this issue goes hand-in-hand with preferring composition over inheritance hierarchies.</p>
<h3>3. Draw pictures to show the ideal response to a given stimulus situation</h3>
<p>It is very important to define clearly what you want the agent to do given some stimulus. The following graphs shows a few examples for a vehicle steering agent.</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline; border-width: 0px;" title="steering_graph" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/steering_graph.png" border="0" alt="steering_graph" width="160" height="159" /></td>
<td width="166" valign="top"><img style="display: inline; border-width: 0px;" title="nitro_graph" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/nitro_graph.png" border="0" alt="nitro_graph" width="160" height="159" /></td>
<td width="166" valign="top"><img style="display: inline; border-width: 0px;" title="nitro_graph2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/nitro_graph2.png" border="0" alt="nitro_graph2" width="160" height="159" /></td>
</tr>
<tr>
<td width="166" valign="top"><span style="color: #408080;">Steering as a function of angular deviation from path.</span></td>
<td width="166" valign="top"><span style="color: #408080;">Nitrous usage as a function of angular deviation from path (reckless driver).</span></td>
<td width="166" valign="top"><span style="color: #408080;">Nitrous usage as a function of angular deviation from path (conservative driver).</span></td>
</tr>
</tbody>
</table>
<p>Most variables will depend on more than one other variable. Do not worry too much about that when drawing these diagrams. Focus on typical cases, and jot down any requirements or assumptions.</p>
<p>Also, do not try to write down any equations for your graphs. Any relationship can always be represented by a <em>response curve</em>, something that is much quicker to set up and easy to implement. A response curve is essentially a look-up table with linear interpolation. It can be used to approximate arbitrary functions by specifying the input range, and a number of output samples. The idea is discussed more thoroughly in <a href="http://introgamedev.com/resource_aiwisdom.html">AI Programming Wisdom 1</a> (<em>The beauty of Response Curves </em>by Bob Alexander).</p>
<h3>4. Draw System Diagrams to show how variables relate</h3>
<p>In a complicated system, it is easy to lose track of how variables relate. A forgotten relationship can often lead to behaviour that is hard to understand. Having an easy-to-reference diagram will be a great help in debugging faulty behaviour.</p>
<p><img style="display: inline; border-width: 0px;" title="flow_diagram" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/flow_diagram.png" border="0" alt="flow_diagram" width="537" height="486" /></p>
<p>The diagram above distinguishes between relationships under AI control, and relationships that are under physics control – i.e. Relationships that cannot be changed by the agent. The diagram also indicates whether a relationship is positive (i.e. more of the one will result in more of the other), or negative (i.e. more of one will result in less of the other).</p>
<h3>5. Use a spreadsheet to graph response curves to typical situations</h3>
<p>Once you have your equations, you have to make sure that they actually describe the curves you intend. Also, in complicated formulas, it is important to check how these curves behave on typical data sets – <em>especially if you employ filtering </em>(see below).</p>
<p><img style="display: inline; border-width: 0px;" title="spread_sheet_graph" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/spread_sheet_graph.png" border="0" alt="spread_sheet_graph" width="479" height="358" /></p>
<h3>6. Eliminate unimportant feedback loops.</h3>
<p>Feedback is important for proper control in most systems. However, every loop makes it more difficult to analyse and understand the system – something that becomes apparent when things go wrong. If your system is complex, try to remove some of the loops (by removing some of the dependencies). You can always complicate your system <em>once you have it working</em>.</p>
<h3>7. Prototype your agent on a computer algebra system</h3>
<p>A computer algebra system (CAS) is the perfect environment to prototype a stimulus response agent:</p>
<ul>
<li>The high-level syntax, dynamic variables, and fat libraries allows you develop designs quickly, so that you can try out more designs.</li>
<li>The built-in graph plotting capabilities are useful for debugging (see below) and understanding complex designs.</li>
<li>You can simulate scenarios that are hard to obtain in the actual game, leading to a design that is much more robust.</li>
</ul>
<h2>Filtering</h2>
<h3>8. Filtering input, output, and intermediate values can drastically improve behaviour</h3>
<p>There are several reasons to use filtering in your agent:</p>
<ul>
<li>To reduce noise that might confuse your agent about the state the world (or it) is in.</li>
<li>To smooth out (and hence fill in) incomplete data. For example, a path made of line segments can be “filtered” so that it appears smooth to the agent.</li>
<li>To make the actions of the agent seem more determined. An agent that changes it&#8217;s mind 10 times a second is not very believable.</li>
<li>To prevent abrupt reactions to changes in the world that will make the agent less believable.</li>
</ul>
<p>There are several approaches to filtering. One approach that works well in many cases is to change a variable only by some maximum amount, like this:</p>
<pre>updateFilteredX(x)
{
   filteredX += clamp(x – filteredX, -maxIncX, maxIncX);
}</pre>
<p>Here maxIncX is much smaller than typical values of x (using a tenth is a good starting point).</p>
<p>When you have many filtered variables, it becomes unmanageable to filter them all in this way – for every variable you want to filter, you need three extra variables, and you need to remember to use the right updating technique whenever the variable changes. It is better to encapsulate the filtering in a special class (as has been done in the <em>Special Numbers Library </em>– see <a href="http://code.google.com/p/specialnumbers/">http://code.google.com/p/specialnumbers/</a>).</p>
<p>Other approaches to filtering include:</p>
<ul>
<li>statistical filtering techniques, such as <a href="http://en.wikipedia.org/wiki/Recursive_least_squares_filter">least squares</a> and <a href="http://en.wikipedia.org/wiki/Kalman_filter">Kalman</a> filtering;</li>
<li><a href="http://en.wikipedia.org/wiki/Digital_filter">convolutional filters</a>; and</li>
<li><a href="http://en.wikipedia.org/wiki/PID_controller">PID controllers</a>.</li>
</ul>
<h3>9. Make your filtering technique frame-rate independent, and do it from the start</h3>
<p>The rate of updates of filters can have a dramatic effect on resulting behaviour. This rate can either fluctuate naturally (as it goes with frame rate), or be the difference between a Debug and Release versions of your application.</p>
<p>The resulting changes in behaviour makes it hard to:</p>
<ul>
<li>debug faulty behaviour; and</li>
<li>spot problems to begin with (because it always works fine on <em>your</em> machine!).</li>
</ul>
<p>How you make your filtering frame-rate independent depends on the method of filtering used. For the system explained above, it merely means updating with an amount proportional to the elapsed time (between updates).</p>
<pre>updateFilteredX(x, elapsedTime)
{
   filteredX += clamp(x – filteredX,
                -maxIncX*elapsedTime, maxIncX*elapsedTime);
}</pre>
<p>The updateFilteredX function above will use a smaller value for maxIncX than the one that does not compensate for time. It is for this reason that you should implement frame-rate independence <em>from the start</em>. Otherwise you will need to re-tweak all your values increment values <em>again</em>.</p>
<h3>10. Do not filter the channels of n-dimensional data separately</h3>
<p>If you filter a position, for example, by the method described above, you might be tempted to do something like the following:</p>
<pre>updateFilteredXYZ(point)
{
   filteredPoint.x += clamp(point.x – filteredPoint.x,
                               -maxInc, maxInc);
   filteredPoint.y += clamp(point.y – filteredPoint.y,
                               -maxInc, maxInc);
   filteredPoint.z += clamp(point.z – filteredPoint.z,
                               -maxInc, maxInc);
}</pre>
<p>The above code will lead to strange behaviour. Consider for example,</p>
<ul>
<li>filteredPoint = (0, 0, 0),</li>
<li>point = (2, 1, 0) (for the next 4 updates)</li>
<li>maxInc = 0.5</li>
</ul>
<p>The variable filteredPoint will now go through these values on the next four updates:</p>
<p>(0.5, 0.5, 0)</p>
<p>(1.0, 1.0, 0)</p>
<p>(1.5, 1.0, 0)</p>
<p>(2.0, 1.0, 0)</p>
<p>If this filteredPoint represents an agent trying to reach (2, 1, 0). Notice that the points do not lie in a straight line, the agent will first move to point (1, 1, 0), and then <em>turn</em> before moving further. An onlooker will not understand this strange behaviour.</p>
<p>The correct way to implement filtering for multi-dimensional data is to add a clamped amount of difference between the value and the filteredValue to the filtered value.</p>
<pre>updateFilteredXYZ(point)
{
   updateAmount = clamp((filteredPoint – point).len(),
                        0, maxInc)
   filteredPoint += (point – filteredPoint) * updateAmount;
}</pre>
<p>Now the next four values of filteredPoint lie in a straight line:</p>
<p>(0.316, 0.632, 0)</p>
<p>(0.632, 1.265, 0)</p>
<p>(0.948, 1.897, 0)</p>
<p>(1, 2, 0)</p>
<h3>11. Beware of filtering that reduces the range of a variable</h3>
<p>Some kinds of filtering can reduce the range of a variable – for example, instead of reaching zero, a variable may merely come <em>close</em> to zero. This is important in checks that assumes variables will come to a have certain value <em>eventually – </em>these checks must be modified to compensate for the range discrepancies.</p>
<h3>12. Beware of accumulated latency when filtering variables through various layers of logic</h3>
<p>Filtering usually results in some latency. Where filtering is used in a layered system, these latencies can add up, and produce a system that is slow to respond. In many situations these latencies can be reduced or eliminated if you can make accurate predictions about the future.</p>
<p>You can reduce the filtering by using it only where it is really important – not everywhere. You can also exchange smoothness for a quicker response. How you accomplish this depends on the method of filtering you use; in the filtering described above you can increase the value of the increment.</p>
<p>If you feel adventurous, you can try out a system that filters only after it becomes aware that it is necessary. For example, the amount of filtering you apply can depend on the amount of noise measured over the last number of frames. In many situations you can approximate the amount of noise by the amount energy of the measured signal. Systems like these can be hard to make robust without resorting to difficult mathematics or special software.</p>
<p>You can also switch to a more sophisticated filtering approach, such as a Kalman filter or PID controller. PID controllers uses prediction to reduce latency; Kalman filtering uses a system model that makes it more effective in complicated scenarios.</p>
<h3>13. Be Careful When filtering combined signals</h3>
<p>You might want to add (or combine otherwise) several signals, filter this combination, and work on this filtered combined signal. This is a mistake when the signals have typical data transitions at different frequencies: one signal&#8217;<span style="font-size: 13.3333px;">s noise is another&#8217;s data.</span></p>
<p>To illustrate the problem, look at the two signals below. Signal 1 is a low frequency signal, with a spike of noise. Signal 2 is a pure high frequency signal. The noise is clearly visible in the combined signal. Also shown are several filtered versions of the combined signal. Notice that the more we filter, the more we reduce the high frequency signal. And if we do not filter enough, the noise is still very present.</p>
<p>The solution is to filter the signals separately – the low frequency signal can be filtered much more than the high frequency signal – and only then combine the filtered sequences. The result is shown in the last figure.</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="166" valign="top"><span style="color: #408080;"> <img style="display: inline; border-width: 0px;" title="signal1" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/signal1.png" border="0" alt="signal1" width="160" height="140" /> </span></td>
<td width="166" valign="top"><span style="color: #408080;"><img style="display: inline; border-width: 0px;" title="signal2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/signal2.png" border="0" alt="signal2" width="160" height="140" /> </span></td>
<td width="166" valign="top"><span style="color: #408080;"><img style="display: inline; border-width: 0px;" title="combined_signal" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/combined_signal.png" border="0" alt="combined_signal" width="160" height="140" /> </span></td>
</tr>
<tr>
<td width="166" valign="top"><span style="color: #408080;">Signal 1</span></td>
<td width="166" valign="top"><span style="color: #408080;">Signal 2</span></td>
<td width="166" valign="top"><span style="color: #408080;">Combined signal</span></td>
</tr>
<tr>
<td width="166" valign="top"><span style="color: #408080;"><img style="display: inline; border-width: 0px;" title="filtered_0_1" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/filtered_0_1.png" border="0" alt="filtered_0_1" width="160" height="140" /></span></td>
<td width="166" valign="top"><span style="color: #408080;"><img style="display: inline; border-width: 0px;" title="filtered_0_5" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/filtered_0_5.png" border="0" alt="filtered_0_5" width="160" height="140" /> </span></td>
<td width="166" valign="top"><span style="color: #408080;"><img style="display: inline; border-width: 0px;" title="combined_signal" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/combined_signal1.png" border="0" alt="combined_signal" width="160" height="140" /> </span></td>
</tr>
<tr>
<td width="166" valign="top"><span style="color: #408080;">Combined signal filtered (0.1)</span></td>
<td width="166" valign="top"><span style="color: #408080;">Combined signal filtered (0.5)</span></td>
<td width="166" valign="top"><span style="color: #408080;">Combined signal filtered (1.0)</span></td>
</tr>
<tr>
<td width="166" valign="top"><span style="color: #408080;"><img style="display: inline; border-width: 0px;" title="filtered_separately" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/filtered_separately.png" border="0" alt="filtered_separately" width="160" height="140" /> </span></td>
<td width="166" valign="top"><span style="color: #408080;"> </span></td>
<td width="166" valign="top"><span style="color: #408080;"> </span></td>
</tr>
<tr>
<td width="166" valign="top"><span style="color: #408080;">Signals filtered before combined.</span></td>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
</tr>
</tbody>
</table>
<h3>14. Avoid if-then logic in response calculations.</h3>
<p>If-then logic signifies one of two things:</p>
<ul>
<li>a state difference that should be implemented as proper discrete state of the state machine; or</li>
<li>the need for a step function.</li>
</ul>
<p>In the first case, your state should be broken up into two states, with proper transitions. A stimulus response agent is complex enough with you having to track trough various conditions to understand behaviour. Every state should have one response that depends continuously on the stimulus. Because state machines scale so badly, introducing more states is not very desirable either. There are of course several ways to organise states properly to alleviate the scaling problem, but this is the topic of another tutorial.</p>
<p>If your if-then logic is against the value of a variable (for example &#8216;if x &gt; 0&#8242;), you can replace it with an appropriately chosen step function. Using step functions instead of if-then logic simplifies the design, and can be replaced with drop-in “smooth” versions when it becomes evident that it is necessary.</p>
<h2>Testing and Debugging</h2>
<h3>15. Rendering the current state-machine state on screen.</h3>
<p>It is a small point, but often strange behaviour results not from incorrect response to stimulus, but from incorrect state transitions. When implementing your agent inside the game, having state transitions visible on screen will make that kind of bug that much easier to spot.</p>
<h3>16. Graph variables and their internal states on screen.</h3>
<p>Graphing variables (filtered and unfiltered) over time on screen will save you hours of debugging time. Whenever your agent does something funny, you can see at a glance if there are variables with unexpected values that could explain the agent&#8217;s actions, perhaps using the CAS prototype as a reference.</p>
<p>Unfortunately, this tip becomes less useful as the system gets more complex. Having twenty plots on your screen will do little to spot problems.</p>
<h3>17. Use unit tests to ensure correct implementation of formulas.</h3>
<p>Stimulus response agents are perfect candidates for unit testing, especially when using the CAS prototype as a reference implementation. Unit testing your assumptions about the system will ensure correctness, and will help to make you aware of changes that break the system early. It will also make it easier to change and optimise formulas, or change them with smoother or sharper versions. Having a constant reference against which you can tweak parameters also allows you to be daring and make aggressive changes.</p>
<h3>18. Use generators to mock the agent&#8217;s environment.</h3>
<p>A generator is a object that generates a sequence of values. Typically it has a getValue() method, which returns a different value every time it is called. Generators are very similar to iterators, except that they usually generate values on the fly, rather than pointing to members of a container (although reading values from a container is one valid way to generate values). Generators are often used to implement iterators.</p>
<p>To implement unit tests and a CAS prototype, you need to mock various aspects of the game, the game world, and other agents. Using generators for this purpose makes mocking unbelievably easy and quick. Use generators to generate streams of</p>
<ul>
<li>elapsed times;</li>
<li>path angle deviations;</li>
</ul>
<ul>
<li>positions and velocities of other agents; and</li>
<li>state transitions.</li>
</ul>
<p>You can even mock parts of your agent to test sections in isolation. It helps if you build a library of generators and functions (response curves) that can be stacked together. You will do good to implement at least the following functions:</p>
<ul>
<li>step, line, and ramp;</li>
<li>clamped line and sigmoid (or atan);</li>
<li>cos, square, and saw tooth;</li>
<li>exponential and exponential decay;</li>
</ul>
<p>You should implement the following generators:</p>
<ul>
<li>a general generator that generates values from a function;</li>
<li>a constant generator;</li>
<li>a sum and product generator (generates the sum or product of two generators); and</li>
<li>generators that generate random values of various distributions.</li>
</ul>
<h2>Conclusion</h2>
<p>A complex stimulus response agent can be a challenge to design and implement properly; every approach has its set of headaches, and every solution brings other considerations to the table. Solving problems is just half the fun – <em>not</em> solving them is the other half!</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/11/11/5-tips-for-prototyping-slow-algorithms/' rel='bookmark' title='Permanent Link: 5 Tips for Prototyping Slow Algorithms'>5 Tips for Prototyping Slow Algorithms</a></li>
<li><a href='http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/' rel='bookmark' title='Permanent Link: Generating Random Numbers with Arbitrary Distributions'>Generating Random Numbers with Arbitrary Distributions</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/10/25/tips-for-designing-and-implementing-a-stimulus-response-agent/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Guerrilla Tool Development</title>
		<link>http://code-spot.co.za/2009/10/24/guerrilla-tool-development/</link>
		<comments>http://code-spot.co.za/2009/10/24/guerrilla-tool-development/#comments</comments>
		<pubDate>Sat, 24 Oct 2009 16:18:45 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[ai editor]]></category>
		<category><![CDATA[Dev.Mag]]></category>
		<category><![CDATA[level editor]]></category>
		<category><![CDATA[tool development]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=750</guid>
		<description><![CDATA[Tools for editing game levels and AI for your own games are nice to have, but it is not always practical to implement these for small projects, nor is it affordable to buy them off-the-shelf or bundled with expensive middleware. In the Dev.Mag article Guerrilla Tool Development, I give some ideas for getting some useful [...]


Related posts:<ol><li><a href='http://code-spot.co.za/about-me/' rel='bookmark' title='Permanent Link: About Me'>About Me</a></li>
<li><a href='http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2009/05/27/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-example-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="border-right: 0px; border-top: 0px; display: inline; margin: 0px 10px 0px 0px; border-left: 0px; border-bottom: 0px" title="guerrilla_tools" src="http://code-spot.co.za/blog/wp-content/uploads/2009/10/guerrilla_tools1.png" border="0" alt="guerrilla_tools" width="142" height="142" align="left" /> Tools for editing game levels and AI for your own games are nice to have, but it is not always practical to implement these for small projects, nor is it affordable to buy them off-the-shelf or bundled with expensive middleware.</p>
<p>In the Dev.Mag article <a href="http://devmag.org.za/2009/10/23/guerrilla-tool-development/">Guerrilla Tool Development</a>, I give some ideas for getting some useful tools on a tight budget. Check it out!</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/about-me/' rel='bookmark' title='Permanent Link: About Me'>About Me</a></li>
<li><a href='http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2009/05/27/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-example-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/10/24/guerrilla-tool-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting More out of Seamless Tiles</title>
		<link>http://code-spot.co.za/2009/05/28/getting-more-out-of-seamless-tiles/</link>
		<comments>http://code-spot.co.za/2009/05/28/getting-more-out-of-seamless-tiles/#comments</comments>
		<pubDate>Thu, 28 May 2009 08:46:07 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Image Processing]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Snippet]]></category>
		<category><![CDATA[blending]]></category>
		<category><![CDATA[Dev.Mag]]></category>
		<category><![CDATA[grids]]></category>
		<category><![CDATA[tiles]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=620</guid>
		<description><![CDATA[I wrote an article for Dev.Mag covering some techniques for working with seamless tile sets such as making blend tiles, getting more variety with procedural colour  manipulation, tile placement strategies, and so on.  Check it out! The Python Image Code has also been updated with some of the algorithms explained in the article. Related posts:Quadtrees Quadtrees Cellular Automata [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2008/10/06/quadtrees/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
<li><a href='http://code-spot.co.za/2008/11/15/quadtrees-2/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
<li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-622" title="tiles_header_small" src="http://code-spot.co.za/blog/wp-content/uploads/2009/05/tiles_header_small.png" alt="tiles_header_small" width="142" height="142" />I wrote an article for Dev.Mag covering <a href="http://www.devmag.org.za/articles/70-GETTING-MORE-OUT-OF-SEAMLESS-TILES/">some techniques for working with seamless tile sets</a> such as making blend tiles, getting more variety with procedural colour  manipulation, tile placement strategies, and so on. </p>
<p>Check it out!</p>
<p>The <a href="http://code-spot.co.za/python-image-code/">Python Image Code</a> has also been updated with some of the algorithms explained in the article.</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2008/10/06/quadtrees/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
<li><a href='http://code-spot.co.za/2008/11/15/quadtrees-2/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
<li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/05/28/getting-more-out-of-seamless-tiles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cellular Automata for Simulation in Games</title>
		<link>http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/</link>
		<comments>http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 08:34:57 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[blending]]></category>
		<category><![CDATA[cellular automata]]></category>
		<category><![CDATA[Conway's game of life]]></category>
		<category><![CDATA[Dev.Mag]]></category>
		<category><![CDATA[diffusion]]></category>
		<category><![CDATA[discrete dynamics]]></category>
		<category><![CDATA[disease simulation]]></category>
		<category><![CDATA[fire simulation]]></category>
		<category><![CDATA[force]]></category>
		<category><![CDATA[Game Maker]]></category>
		<category><![CDATA[grids]]></category>
		<category><![CDATA[optimisation]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[sampling]]></category>
		<category><![CDATA[social dynamics]]></category>
		<category><![CDATA[sum]]></category>
		<category><![CDATA[tiles]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=499</guid>
		<description><![CDATA[A cellular automata system is one of the best demonstrations of emergence. If you do not know what cellular automata (CA) is, then you should go download Conway&#8217;s Game of Life immediately: Conway’s Game of Life Essentially, CA is a collection of state machines, updated in discrete time intervals. The next state of one of [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/' rel='bookmark' title='Permanent Link: A Simple Trick for Moving Objects in a Physics Simulation'>A Simple Trick for Moving Objects in a Physics Simulation</a></li>
<li><a href='http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/' rel='bookmark' title='Permanent Link: Estimating a Continuous Distribution from a Sample Set'>Estimating a Continuous Distribution from a Sample Set</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img style="display: inline" title="header" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/header1.png" alt="header" width="500" height="371" /></p>
<p>A cellular automata system is one of the best demonstrations of emergence. If you do not know what cellular automata (CA) is, then you should go download Conway&#8217;s Game of Life immediately:</p>
<p><a href="http://psoup.math.wisc.edu/Life32.html">Conway’s Game of Life</a></p>
<p>Essentially, CA is a collection of state machines, updated in discrete time intervals. The next state of one of these depends on the current state as well as the states of neighbours. Usually, the state machines correspond to cells in a grid, and the neighbours of a cell are the cells connected to that cell. For a more detailed explanation, see <a href="http://en.wikipedia.org/wiki/Cellular_automata">the Wikipedia article</a>.</p>
<p>Even simple update rules can lead to interesting behaviour: patterns that cannot be predicted from the rules except by running them. With suitable rules, CA can simulate many systems:</p>
<ul>
<li>Natural phenomena: weather, fire, plant growth, migration patterns, spread of disease.</li>
<li>Socio-economic phenomena: urbanisation, segregation, construction and property development, traffic, spread of news.</li>
</ul>
<p><span id="more-499"></span></p>
<p>In games, these can be used as game elements (such as fire and disease), or they can also add some decorative life to a game (such as city development in a simulation game).</p>
<p>The great thing about CA systems is that they are not hard to implement, and they have intrinsic fun value (I mean here, for the programmer!).</p>
<p>Before we get into the details, let me add a small disclaimer here:</p>
<ul>
<li>This tutorial is not comprehensive. I only touch on a few ideas in a wide field. See some of the resources at the end for more information.</li>
<li>This tutorial is not representative. I merely chose topics I found interesting or thought would be useful for game developers.</li>
<li>I am not suggesting that using cellular automata is the best way to simulate any of the examples given here. For any problem, there might be solutions that are faster, easier to implement, or yield better results.</li>
</ul>
<h2>Implementation</h2>
<p>To implement a CA system, you need to do the following:</p>
<ul>
<li>Use a suitable system to store states, for example, a 2D array.</li>
<li>Decide on a suitable neighbourhood shape, and work out some preliminary rules. Decide how you will handle edges.</li>
<li>Implement a suitable way to describe your rules.</li>
<li>Implement an update function that hooks into the main game loop.</li>
<li>Implement a visualisation scheme (for example, drawing tiles depending on states in the array).</li>
</ul>
<p>Some details of these are described below.</p>
<h3>Grid</h3>
<p>A typical implementation uses two grids for storing states. One is the current world state; the other is the new world state. Once all cells have been updated for the current iteration, pointers to the arrays can be swapped. This way updating the cells one by one will not have an effect on other cells until the next iteration, and you do not have to create a new array in each iteration.</p>
<p>Using grids with square cells are the easiest to implement, but the concept is also applicable to other grids: hexagonal and triangular grids are also common, and even polar grids have been used to simulate spiral star systems.</p>
<p>It is also possible to use irregular systems, although the implementation then becomes a challenge. One example of an irregular system is a presentation based on a Poisson distribution of points. The trick here is to find an efficient way to locate neighbours. Fortunately, this problem has already been solved in creating the points (see the <a href="http://devmag.org.za/2009/05/03/poisson-disk-sampling/">Poisson Sampling tutorial in Dev.Mag</a> and download code from <a href="http://www.luma.co.za/labs/tag/poisson-disk/" class="broken_link">Luma Labs</a>). It is in fact done by using an invisible grid! Of course, visualising a state is also a bit more difficult.</p>
<h3>Neighbourhoods</h3>
<p>For 2D cellular automata, the most common neighbourhoods are the Von Neumann neighbourhood and the Moore neighbourhood, shown below (the blue cell’s neighbourhood is shown in red). Other neighbourhoods are also possible.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="vonneumann" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/vonneumann.png" alt="vonneumann" width="88" height="88" /></td>
<td width="166" valign="top"><img style="display: inline" title="moore" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/moore.png" alt="moore" width="88" height="88" /></td>
<td width="166" valign="top"><img style="display: inline" title="road" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/road.png" alt="road" width="88" height="88" /></td>
</tr>
<tr>
<td width="166" valign="top">Von Neumann neighbourhood</td>
<td width="166" valign="top">Moore neighbourhood</td>
<td width="166" valign="top">Extended Von Neumann neighbourhood</td>
</tr>
</tbody>
</table>
<p>The cell can be included in the neighbourhood or not. It is advisable to keep the neighbourhoods as small as possible: not only does the neighbourhood size impact performance, it also affects the number of rules to be specified and thus the tweaking complexity.</p>
<h3>Specifying Update Rules</h3>
<p>Specifying the rules concisely is the most challenging part of implementing CA. With very simple models, you might want to use a few if/else statements. This, however, makes it hard to modify (tweak or extend), and is therefore not suitable for more complicated systems.</p>
<p>It is best to implement rules as a table that can be indexed using the neighbourhood states.</p>
<p><strong>Table as an array.</strong> In this method, each row represents the combined state of the surrounding cells. The final entry in the row is the new state of the current cell. Each of the remaining columns represents a state. The entries in these columns represent the number of cells surrounding the current cell in that state.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="125" valign="top">Dry Bush</td>
<td width="125" valign="top">Burning Bush</td>
<td width="125" valign="top">Charcoal</td>
<td width="125" valign="top">New State</td>
</tr>
<tr>
<td width="125" valign="top">4</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">Dry Bush</td>
</tr>
<tr>
<td width="125" valign="top">3</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
<tr>
<td width="125" valign="top">3</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">Dry Bush</td>
</tr>
<tr>
<td width="125" valign="top">2</td>
<td width="125" valign="top">2</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
<tr>
<td width="125" valign="top">2</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">1</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
<tr>
<td width="125" valign="top">2</td>
<td width="125" valign="top">0</td>
<td width="125" valign="top">2</td>
<td width="125" valign="top">Burning Bush</td>
</tr>
</tbody>
</table>
<p>A cell surrounded with three cells in the Dry Bush state and one cell in the Burning Bush state will go into the Burning Bush state.</p>
<p>This table can be quite large, so that you must take care to implement lookups efficiently. Keep the table sorted, and perform binary search to lookup entries. Below are some improvements on this scheme.</p>
<p><strong>Table as a tree.</strong> In the table above, it is easy to see that if there are three dry bush nodes, there are two possibilities for the other states (either 1 0, or 0 1). We can use this to implement a tree. Each level in the tree represents a state. A value in a node represents how many cells in the neighbourhood are in that state. A path from root to leaf fully describes the states of the entire neighbourhood. We do not add nodes for the last state, as it is uniquely determined by the other states.</p>
<p>Below is a tree corresponding to the piece of table above.</p>
<p>BB = Burning Bush</p>
<p>DB = Dry Bush</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="41" valign="top">root</td>
<td width="45" valign="top">+&#8212;</td>
<td width="50" valign="top">DB 4</td>
<td width="50" valign="top"></td>
<td width="49" valign="top"></td>
<td width="171" valign="top">DB</td>
</tr>
<tr>
<td width="42" valign="top"></td>
<td width="45" valign="top">+&#8212;</td>
<td width="50" valign="top">DB 3</td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 1</td>
<td width="171" valign="top">BB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top">|</td>
<td width="50" valign="top"></td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 0</td>
<td width="171" valign="top">DB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top">+&#8212;</td>
<td width="50" valign="top">DB 2</td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 2</td>
<td width="171" valign="top">BB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top"></td>
<td width="50" valign="top"></td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 1</td>
<td width="171" valign="top">BB</td>
</tr>
<tr>
<td width="41" valign="top"></td>
<td width="45" valign="top"></td>
<td width="50" valign="top"></td>
<td width="50" valign="top">+&#8212;</td>
<td width="49" valign="top">BB 0</td>
<td width="171" valign="top">BB</td>
</tr>
</tbody>
</table>
<p>This is a more efficient implementation; unfortunately, it is also more complicated. It is inconvenient to specify the tree in a tree-friendly format (XML or s-expressions, for example). You still need to specify it in table format (space separated text file, for example) and build the tree from that.</p>
<p><strong>Implementation as a hash table.</strong> Here you use tuples of state counts as keys. For example, the third entry in the table above can be accessed with the tuple (3, 0, 1). If your implementation language does not support tuples, you might need to implement them yourself. Be sure to make them immutable!</p>
<p><strong>Implementation as an N-dimensional array.</strong> This is a very simple method, although it wastes a lot of memory. N is the number of states, and we use the state counts to index into the array. In our example, we will use a 3D array, so that the third element can be accessed using transition_array[3, 0, 1].</p>
<p>The method above can be used even when the implementation language does not provide N dimensional arrays. Simply use a 1D array, and interpret the state counts as the digits of a base-4 number. Thus, the third row will be located at 3*16 + 0*4 + 1*1 = 49.</p>
<p>Note that since the numbers are restricted by the requirement that they add to four, there will be unused array positions in both these last two methods. You can save memory by not using the last state to index (since it is uniquely determined by the other states). Thus, we can use a 2D array, and access the 3,0,1 rule with 3,0 alone: transition_array[3, 0]. Alternatively, if we need to use a 1D array, we can store the rule in the position 3*4 + 0*1 = 12. Although the same scheme is possible for the hash table implementation, I would advise you to use the full indexing scheme instead, since it will not waste more memory if you do, and it is somewhat easier to understand if you use full indices.</p>
<p>Some rules do not need the detailed tables above. For instance, in a system of only two states, where transitions depend on the count of the states of the neighbourhood, we can use a simple array, indexed by one of the states’ counts. Many other schemes are possible: in general, aim for quick lookups and easy specification.</p>
<h3>Edges</h3>
<p>The edges of your simulation might present some problems: edges often serve as unwanted sources, sinks or stabilisers.</p>
<p>A <strong>source</strong> is the origin of outward growth (states change progressively to a specific state in an outward direction).</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="125" valign="top"><img style="display: inline" title="growth4" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth41.png" alt="growth4" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth3" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth31.png" alt="growth3" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth21.png" alt="growth2" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth1" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth11.png" alt="growth1" width="88" height="88" /></td>
</tr>
</tbody>
</table>
<p>A <strong>sink</strong> is the exact opposite:</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="125" valign="top"><img style="display: inline" title="growth1" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth11.png" alt="growth1" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth2" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth21.png" alt="growth2" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth3" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth31.png" alt="growth3" width="88" height="88" /></td>
<td width="125" valign="top"><img style="display: inline" title="growth4" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/growth41.png" alt="growth4" width="88" height="88" /></td>
</tr>
</tbody>
</table>
<p>Sources and sinks are emergent properties of the CA system, and are not physical attributes of the cells.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="screenshot186" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1861.png" alt="screenshot186" width="144" height="108" align="left" /> A <strong>stabiliser</strong> is a section that keeps neighbouring states fixed. For example, in the fire simulation (described below), there is an unnatural wall of fire around the edges at the end of the simulation.</p>
<p>There are several ways you can handle edges:</p>
<p><strong>Ignore them.</strong> When the edge anomalies are acceptable, it is best not to complicate the model. This is only possible if the rules are specified in a way that does not require state counts to sum to the size of the neighbourhood. For example, if there is a rule “if num_states_fire &gt; 1, then …”.</p>
<p><strong>Wrap around.</strong> This solution is very elegant, easy to implement, and its effects are easy to understand. However, it is usually easy to see that the world has been wrapped in this way, and hence it is not always a visually a satisfactory solution. It is possible, however, to simulate a grid bigger than displayed area (say about double). This will hide the fact that it is wrapped, but still give you the benefits of having a world without any discontinuities.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="wrapped" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/wrapped.png" alt="wrapped" width="88" height="88" align="left" /> In the CA system shown left, we want to calculate the next state of the grey cell. Two neighbours fall outside the edges. If we wrap around, we use the four red squares as shown.</p>
<p><strong>Reflection.</strong> Use a neighbouring state to perform calculations.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="reflect" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/reflect.png" alt="reflect" width="88" height="88" align="left" /> The CA system shown left is the same situation as above. If we use neighbouring states for the cells beyond the edges, we use the state of the grey cell (twice!), in addition to the two red cells shown.</p>
<p><strong>Fix their states. </strong>The edges can be given special, constant states that make the CA behave as intended. Finding the right state(s) for the edges might be difficult.</p>
<p>An implementation trick that applies to the last three edge-handling techniques is to include a border in your simulation. For the Von Neumann and Moore neighbourhoods, this border is only one cell thick.</p>
<p>This border is used for updates like all other cells, but is itself updated differently. The update rules for wrapping and reflection will simply copy states from the right places; the border for fixed states will never be updated.</p>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="edges_implementation" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/edges-implementation.png" alt="edges_implementation" width="123" height="123" align="left" /> In the figure, hatched cells are updated according to the special rules of the edge-handling scheme – in this case, wrapping is used, so they are simply copied from the appropriate cells. All other cells are updated normally. Note that here we do not need special logic for updating the grey cell.</p>
<h2>A Few Examples</h2>
<p>(Also see the downloads at the bottom of the post).</p>
<h3>Heat</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="screenshot210" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot210.png" alt="screenshot210" width="144" height="108" align="left" /> Here, continuous states (floats between 0 and 1) are used. Every cell is updated to a weighted average of its Moore neighbourhood cells: corners have a smaller weight than other cells. For this simulation, heat sinks and sources have been added: they keep the cell’s temperature at 0 and 1 respectively.</p>
<h3>City Roads</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="roads" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/roads.png" alt="roads" width="144" height="108" align="left" /> This simulation use separate neighbourhoods for creating and destroying a road. The creation neighbourhood is an extended Von Neumann neighbourhood; the destruction neighbourhood is a Moor neighbourhood. Creation and destruction is according to probabilities based on the count of neighbouring roads.</p>
<h3>Influence</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="anger" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/anger.png" alt="anger" width="288" height="216" align="left" /></p>
<p>This simulation models human emotion as influenced by others. A character has an internal state, and an externally visible state. Characters can only observer the external state of their neighbours. The internal state is then a modified: a character surrounded by angry people will itself become angry, and so on. The external state is probabilistically determined by the internal state.</p>
<h3>Disease Spread</h3>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="epeidemic" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/epeidemic.png" alt="epeidemic" width="288" height="216" align="left" /> For our game <a href="http://www.luma.co.za/labs/2007/10/15/epidemic/" class="broken_link">Epidemic</a>, <a href="http://blog.cunnington.co.za/">Chris</a> and I used a simple diffusion model. We used a floating-point number for the state, and represented the number of infected people in a cell. We used different colours for different ratios to visualise infection. At each time step, a cell would become infected by an amount proportional to that of the neighbourhood, with some random scaling.</p>
<h2>Visualising States</h2>
<h3>Versions of tiles</h3>
<p>A very effective way of making CA simulations more impressive is to have more than one tile for each state, and display them randomly. This is especially helpful for hiding regularity in off-line simulations. Tile sets with different versions for corners, edges, and central regions can drastically improve the look of the game, although it complicates choosing the correct tile version. In addition, it means you need tiles for various combinations of states. Assuming we can rotate and reflect tiles, in the fire example with three states, we need the following tiles:</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="250" valign="top">3 centre tiles</td>
<td width="59" valign="top"><img style="display: inline" title="centre" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/centre1.png" alt="centre" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 straight-edge tiles</td>
<td width="59" valign="top"><img style="display: inline" title="edge" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/edge1.png" alt="edge" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 diagonal line tiles</td>
<td width="59" valign="top"><img style="display: inline" title="diagonal" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/diagonal1.png" alt="diagonal" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 cross tiles</td>
<td width="59" valign="top"><img style="display: inline" title="cross" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/cross1.png" alt="cross" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">6 corner tiles</td>
<td width="59" valign="top"><img style="display: inline" title="corner" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/corner1.png" alt="corner" width="49" height="49" /></td>
</tr>
<tr>
<td width="250" valign="top">3 half-straight tiles</td>
<td width="59" valign="top"><img style="display: inline" title="half_edge" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/half-edge1.png" alt="half_edge" width="49" height="49" /></td>
</tr>
</tbody>
</table>
<p>This is 21 tiles for only three states. It is advisable to automate tile creation.</p>
<h3>Tile <a name="_Toc226913823"></a></h3>
<p>States can be animated. Instead of displaying a single tile, display an animation sequence. You will need to think about how to start and stop these animations so that they are seamless. For instance, you can make all animation sequences the same length, and only update states between animation sequences.</p>
<p>You can also increase the seamlessness of the simulation by animating transitions between states. This can be as easy as blending between two tiles over a period of time (assuming that updates are made far enough apart).</p>
<h3>No Tiles</h3>
<p>Instead of using tiles to represent a state of a cell, you can put objects in a cell. For instance, in a plant growth simulation, you can put a number of trees in the cell depending on the state. The advantages of this are:</p>
<ul>
<li>You do not have to create dozens of tiles for variety.</li>
<li>The player can interact with the objects. For instance, the plant placement of trees can hinder a player’s movement.</li>
</ul>
<p><img style="display: inline; margin: 5px 10px 0px 0px" title="detail" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/detail1.png" alt="detail" width="140" height="108" align="left" /> This shows a simple forest simulation. Trees grow and die depending on the surrounding trees. This system uses a grid, but not tiles: trees can grow in random positions in tiles. For this simulation, three random coordinates have been chosen for each cell at the beginning of the simulation. Depending on the states, one, two, or three trees will be drawn at these points. Choosing a fixed set of points makes it easier to draw trees at the same coordinates every tick. A somewhat more complicated simulation can choose new points whenever a new tree comes into being.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot191" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1911.png" alt="screenshot191" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot193" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1931.png" alt="screenshot193" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot196" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1961.png" alt="screenshot196" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<h2>CA Enhancements</h2>
<p>The images below show three frames from a simple fire simulation.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot181" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1811.png" alt="screenshot181" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot182" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1821.png" alt="screenshot182" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot183" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1831.png" alt="screenshot183" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>The green is grass (Dry Bush), the orange is fire (Burning Bush) and the brown is burnt grass (Charcoal).</p>
<p>As you can see, the simulation captures some features of a fire:</p>
<ul>
<li>fire grows outward,</li>
<li>grass only burns once,</li>
<li>grass needs fire to catch fire (there is no spontaneous combustion).</li>
</ul>
<p>Even so, the symmetry and regularity makes this fire very unconvincing. Below we look at some ideas to enhance a simple CA simulation.</p>
<h3>Probabilistic State Transitions</h3>
<p>Instead changing to some specific state based on the surrounding states, you can change to any state with some probability. These probabilities depend on the surrounding states, and can possibly be zero.</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot167" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1671.png" alt="screenshot167" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot168" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1681.png" alt="screenshot168" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot169" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1692.png" alt="screenshot169" width="144" height="108" /></td>
</tr>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot170" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1702.png" alt="screenshot170" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot171" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1712.png" alt="screenshot171" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot172" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1721.png" alt="screenshot172" width="144" height="108" /></td>
</tr>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot173" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1731.png" alt="screenshot173" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot174" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1741.png" alt="screenshot174" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot175" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1751.png" alt="screenshot175" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>Adding probability to the mix can have several advantages:</p>
<p><strong>It introduces variability in patterns.</strong> This means a specific (perhaps the start-up pattern) will not always produce the same results.</p>
<p><strong>It can enhance the organic look of the system.</strong> Cross and squares patterns are common in deterministic CA systems. For many purposes, this is unsatisfactory (have you ever seen a fire spreading as a growing square?) Adding probabilistic state changes will make the patterns more organic and varied.</p>
<p><strong>It can make discreet behaviour more continuous.</strong> For example, two common &#8220;problems&#8221; with CA systems are exponential growth (where all cells go to a certain state outwards very quickly), or sudden death (where all cells go to a certain state very quickly inwards). The problem is often that a single change in the update rules results in a exponential growth system to become a sudden death system, with seemingly no way to get a &#8220;sweet spot&#8221;. If states can only change with a certain probability, tweaking the probabilities allows you to get intermediate patterns (stable growth, equilibrium, or stable death).</p>
<p><strong>It allows you to control the speed of the simulation.</strong> It is especially helpful to slow down a simulation without making it more granular (in the time dimension). It is useful to multiply all your probabilities with a global parameter that you can tweak to control the speed.</p>
<p>Note that in the example above, certain cells did not burn at all – per chance, they did not caught fire when their neighbours were burning. Timers (see below) can reduce or eliminate this effect.</p>
<p>Adding randomness can increase the emergence, and hence also unwanted emergence, so care must be taken that the simulation is always valid.</p>
<h3>Tile Interpolation</h3>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot169" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1693.png" alt="screenshot169" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot170" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1703.png" alt="screenshot170" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot171" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1713.png" alt="screenshot171" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>Normally, you want your simulation to be as simple as possible. However, when such simple simulations are displayed (visualised), the results can be unsatisfactory. One way to get better visual quality is to use tile (cell) interpolation to make the simulation seem more complicated than it really is. When combined with a bit of randomisation, the effects can be very convincing.</p>
<p>The basic idea is to simulate only every nth cell with the CA approach. Other cells are interpolated. The number of interpolated cells can be adjusted, depending on the detail level required (balanced with the combinatorial number of tiles required!)</p>
<p>In the fire simulation, using only three states makes the simulation seem very primitive. Suppose that we simulate only every second row, and in these, only every second column, and fill the remaining cells depending on their neighbours. We have to create a function that will return a tile for each combination of surrounding tiles:</p>
<p>get_center_tile(north, east, south, west)</p>
<p>Interpolation rules are similar to update rules of the simulation, and hence can easily be as complicated. If this is the case, you would do better to implement more states and not do any interpolation. Interpolation should only be used if it significantly reduces the implementation complexity.</p>
<h3>Timers</p>
<table border="0" cellspacing="0" cellpadding="0">
<tbody></tbody>
</table>
</h3>
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="166" valign="top"><img style="display: inline" title="screenshot177" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1771.png" alt="screenshot177" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot178" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1781.png" alt="screenshot178" width="144" height="108" /></td>
<td width="166" valign="top"><img style="display: inline" title="screenshot179" src="http://code-spot.co.za/blog/wp-content/uploads/2009/04/screenshot1791.png" alt="screenshot179" width="144" height="108" /></td>
</tr>
</tbody>
</table>
<p>Some interesting effects can be obtained if each cell has a timer, that is, each cell only updates once the timer expires. Some rule determines when the timer is reset. For instance, the timer can be set:</p>
<ul>
<li>randomly,</li>
<li>as a function of the state,</li>
<li>as a function of the surrounding cells,</li>
<li>as a function of another property of the tile (*1),</li>
<li>as a function of some external process (*2).</li>
</ul>
<p>(*1) For instance, if each cell has an associated &#8220;burning capacity&#8221; parameter, (simulating material types), a fire state timer can be set in proportion to this parameter.</p>
<p>(*2) For example, we can set timers according to a wind factor.</p>
<p>Timers can have the following effects:</p>
<ul>
<li>add some randomness to a simulation,</li>
<li>slow the simulation down,</li>
<li>smear the simulation (for example, in the fire simulation, the burning border is much thicker, and no cells are skipped).</li>
</ul>
<p>Although you can often implement your grid cells as classes (or structs, or whatever aggregating construct your language provides) with states and timers embedded, it is simpler (on more efficient) to have separate integer grids – one for states and one for timers.</p>
<p>Note that if timers do not have the same expiration time, you the CA system is asynchronous and the behaviour can differ dramatically from a synchronous CA system. Thus, you should include timers early in the development process, so that their effect does not force you to re-tweak all the parameters.</p>
<h2><a name="_Toc226913828"></a></h2>
<p>If your world is big, you cannot run the CA for the whole world at every time step – it will kill performance. Below are some ideas for improving performance.</p>
<h3><a name="_Toc226913829"></a></h3>
<p>Instead of simulating the entire world, you can only simulate the part that is relevant to the game, usually the visible region of the game. A simple technique is to use a wrapped grid, similar to the grids used for the visual port in scrollable 2D games. This grid can be slightly larger than the visible grid, so that it allows cells to update naturally for a few iterations before they become visible, and so increase the illusion of a persistent world.</p>
<p>To hide that fact that you are only simulating a very small piece of the world, you must update “new” cells appropriately. There are several options:</p>
<p><strong>Update cells to a natural starting state.</strong> In many cases, this solution is adequate, especially if you simulate a slightly larger grid than is visible.</p>
<p><strong>Copy states from the existing simulation.</strong> Here you can copy neighbouring cells, or randomly from a nearby region. Copying from nearby cells promotes spatial coherence.</p>
<p><strong>Initialise states statistically.</strong> Based on a neighbourhood of cells, each cell is initialised probabilistically. For example, each cell can be initialised randomly to one of three neighbouring cell’s states.</p>
<p><strong>Use hierarchical modelling.</strong> Use another CA system that represents the entire world in very low detail, and use this to initialise the cells of the high detail version. Note that both the states and the update rules will differ for the high and low detail simulations. Use probabilities to prevent homogeneous systems. You can even use several levels of detail, and incorporate them as needed. Beware the extra implementation complexity, though!</p>
<p>This technique does not work when the world is should be changed permanently.</p>
<h3><a name="_Toc226913830"></a></h3>
<p>Instead of only simulating a part of the world, you can only update a part of the world. This requires enough memory for the whole world, but only processing power for the cells you wish to update. This method has the advantage of real persistence, thus permanent changes can be reliably simulated. Which cells you update will determine how your simulation will play out:</p>
<ul>
<li>Update all visible cells (or a slightly larger region). This is the most natural update scheme, and its effects are similar to partial simulation described above.</li>
<li>Divide the world into discontiguous regions, and update a different region each time step. For example, divide the world into two sets: one contains every other cell, the other the rest, and update these two sets alternately. To save a significant amount of processing, you need many sets. To hide patterns in the updates that might break the illusion of a continuous world, the sets should be irregular. This method has the advantage that real things happen off screen. On the down side, it slows down the simulation significantly.</li>
<li>Combine the two methods above.</li>
</ul>
<p>Partial updating, like the inclusion of timers, lead to an asynchronous system, and hence the behaviour might be very different from that of a fully updated system.</p>
<h3><a name="_Toc226913831"></a></h3>
<p>In certain cases, simulations can be baked offline and be used in games. This means you perform the simulation before the time, and record each frame. The game then reads these frames, and plays them back.</p>
<p>Various schemes are possible to get more with less. For instance, you can also interpolate the simulation in time. With some thought, you can simulate events in a way that they can be looped, stacked together, and started and stopped unobtrusively. This means you can blend them with the interaction in a way that will not make it obvious that the simulation has been performed off-line.</p>
<h3>Unwanted Emergence</h3>
<p>Not all emergence is good, and you might find it hard to prevent certain behaviours. If the unwanted behaviour is only visual, and it occurs only rarely, it might be acceptable. However, if behaviour impacts play negatively, it must be prevented.</p>
<p>As with all tweaking, you should not spend too much time fumbling around. To proceed more &#8220;scientifically&#8221;, ask yourself the following questions:</p>
<ul>
<li>Is there a way to detect (measure objectively) the unwanted behaviour?</li>
<li>Instead of tweaking your CA, can you detect-and-recover system be used?</li>
<li>Is the behaviour continuous? In other words, is there a degree of badness, or is it either good or bad?</li>
<li>If it is continuous, is it feasible to kick in a preventative system? (When the badness goes above a threshold, updates are processed differently).</li>
<li>Is it feasible to find a set of parameters through an optimisation algorithm (for instance, genetic programming)? It might even be possible to search exhaustively for a solution.</li>
<li>Is my model too complex? Try to eliminate states and simplify transition rules. You might even consider breaking your simulation into two or more independent CA systems.</li>
<li>If you find yourself struggling to tweak the parameters for too long, you should perhaps look for a better model that is less sensitive to the exact parameters.</li>
</ul>
<h2>Links</h2>
<h3>Online Demo</h3>
<p><a href="http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata">http://blog.soulwire.co.uk/laboratory/flash/2d-cellular-automata</a> Browswer-based demo with ActionScript source code.</p>
<h3>General</h3>
<p><a href="http://cell-auto.com/">http://cell-auto.com/</a> A nice breakdown of various topics related to Cellular Automata. The article on <a href="http://cell-auto.com/optimisation/">optimisation</a> is especially interesting.</p>
<p><a href="http://www.collidoscope.com/modernca/">http://www.collidoscope.com/modernca/</a> Contains many non-traditional variations of cellular automata.</p>
<p><a href="http://www.fourmilab.ch/cellab/">http://www.fourmilab.ch/cellab/</a> Application for exploring cellular automata.</p>
<h3>Applications and Implementation</h3>
<p><a href="http://realtimecollisiondetection.net/blog/?p=57">http://realtimecollisiondetection.net/blog/?p=57</a> Path finding using cellular automata.</p>
<p><a href="http://www.ibm.com/developerworks/java/library/j-camusic/">http://www.ibm.com/developerworks/java/library/j-camusic/</a> Cellular Automata and music (interesting way of creating procedural music).</p>
<p><a href="http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html">http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html</a> About using lazy, infinite containers for cellular automata.</p>
<p><a href="http://madeira.cc.hokudai.ac.jp/RD/takai/automa.html">http://madeira.cc.hokudai.ac.jp/RD/takai/automa.html</a> Graphics applications for cellular automata – lots of videos!</p>
<h3>Game Design</h3>
<p><a href="http://www.gamestudies.org/0102/pearce/">http://www.gamestudies.org/0102/pearce/</a> An article about game design.</p>
<p><a href="http://www.cp.eng.chula.ac.th/~vishnu/gameResearch/Sweetser_Thesis.pdf">http://www.cp.eng.chula.ac.th/~vishnu/gameResearch/Sweetser_Thesis.pdf</a> A thesis that looks at game design from a emergence perspective.</p>
<p><a href="http://fora.tv/2006/06/26/Will_Wright_and_Brian_Eno#chapter_01">http://fora.tv/2006/06/26/Will_Wright_and_Brian_Eno#chapter_01</a> Will Wright and Brian Eno on generative systems.</p>
<h2>Downloads</h2>
<h3>Game Maker Demos</h3>
<ul>
<li>Requires Game Maker 7.</li>
<li>Contains 9 demos.</li>
</ul>
<p><a href="http://www.code-spot.co.za/downloads/game_maker/ca_demos.zip">ca_demos.zip</a> (135 KB)</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2010/07/27/a-simple-trick-for-moving-objects-in-a-physics-simulation/' rel='bookmark' title='Permanent Link: A Simple Trick for Moving Objects in a Physics Simulation'>A Simple Trick for Moving Objects in a Physics Simulation</a></li>
<li><a href='http://code-spot.co.za/2009/04/15/estimating-a-continuous-distribution-from-a-sample-set/' rel='bookmark' title='Permanent Link: Estimating a Continuous Distribution from a Sample Set'>Estimating a Continuous Distribution from a Sample Set</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to Turn XSI Mod Tool into a  Level Editor for your XNA Games: Updated for XNA 3.0.</title>
		<link>http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/</link>
		<comments>http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/#comments</comments>
		<pubDate>Wed, 08 Apr 2009 11:22:00 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[art pipeline]]></category>
		<category><![CDATA[editor]]></category>
		<category><![CDATA[game tools]]></category>
		<category><![CDATA[level editor]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[XSI Mod Tool]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=457</guid>
		<description><![CDATA[Last year I wrote a tutorial explaining how to use XSI Mod Tool as a level editor, specifically for XNA. Below is the same tutorial, updated for XNA 3.0. There are only a few minor changes: You need not copy compiled assets from the batch file as before. A section is included that describes how [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/05/27/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-example-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2008/09/14/google-app-engine-for-games/' rel='bookmark' title='Permanent Link: Google App Engine for Games'>Google App Engine for Games</a></li>
<li><a href='http://code-spot.co.za/2009/10/24/guerrilla-tool-development/' rel='bookmark' title='Permanent Link: Guerrilla Tool Development'>Guerrilla Tool Development</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-643" title="header" src="http://code-spot.co.za/blog/wp-content/uploads/2009/06/header.png" alt="header" width="500" height="371" /></p>
<p>Last year I wrote a <a href="http://www.luma.co.za/labs/2008/05/08/xsi-mod-tool-as-level-editor-for-xna-20/trackback/" class="broken_link">tutorial</a> explaining how to use <a href="http://www.softimage.com/products/modtool/">XSI Mod Tool</a> as a level editor, specifically for <a href="http://creators.xna.com/en-GB/">XNA</a>. Below is the same tutorial, updated for XNA 3.0. There are only a few minor changes:</p>
<ul>
<li>You need not copy compiled assets from the batch file as before.</li>
<li>A section is included that describes how to use the content pipeline classes for easy reading of XML files (useful for level files, etc.).</li>
</ul>
<p>I also corrected quite a few typos.<br />
<span id="more-457"></span></p>
<h2>Link</h2>
<p>The article <a href="http://www.gamedev.net/reference/programming/features/XSIinXNA/" class="broken_link">Integrating Your XNA Engine With XSI ModTool</a> is very relevant to this tutorial. Among other things, it explains how to make XNA shaders work in XSI.</p>
<h2>Download</h2>
<h3>PDF Tutorial</h3>
<p><a href="http://www.code-spot.co.za/downloads/tutorials/How to Turn XSI Mod Tool into a Level Editor for your XNA Games v3.pdf">How to Turn XSI Mod Tool into a Level Editor for your XNA Games v3.pdf (463 KB)</a></p>
<h3>Example</h3>
<p>(XSI Plug-in and C# code. Includes the tutorial PDF)</p>
<p><a href="http://www.code-spot.co.za/downloads/tutorials/XSIModToolLevelEditor3.zip">XSIModToolLevelEditor3.zip (5.2 MB)</a>.</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/05/27/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-example-updated-for-xna-30/' rel='bookmark' title='Permanent Link: How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.'>How to Turn XSI Mod Tool into a Level Editor for your XNA Games: Example Updated for XNA 3.0.</a></li>
<li><a href='http://code-spot.co.za/2008/09/14/google-app-engine-for-games/' rel='bookmark' title='Permanent Link: Google App Engine for Games'>Google App Engine for Games</a></li>
<li><a href='http://code-spot.co.za/2009/10/24/guerrilla-tool-development/' rel='bookmark' title='Permanent Link: Guerrilla Tool Development'>Guerrilla Tool Development</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2009/04/08/how-to-turn-xsi-mod-tool-into-a-level-editor-for-your-xna-games-updated-for-xna-30/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Random Steering &#8211; 7 Components for a Toolkit</title>
		<link>http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/</link>
		<comments>http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/#comments</comments>
		<pubDate>Sun, 07 Dec 2008 17:47:26 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[artificial intelligence]]></category>
		<category><![CDATA[blending]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Game Maker]]></category>
		<category><![CDATA[Perlin noise]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[random distribution]]></category>
		<category><![CDATA[random motion]]></category>
		<category><![CDATA[random steering]]></category>
		<category><![CDATA[response curve]]></category>
		<category><![CDATA[Reynolds]]></category>
		<category><![CDATA[sampling]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[steering bahaviors]]></category>
		<category><![CDATA[steering behaviours]]></category>
		<category><![CDATA[vector field]]></category>
		<category><![CDATA[wander]]></category>
		<category><![CDATA[white noise]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=339</guid>
		<description><![CDATA[Random steering is often a useful for simulating interesting steering motion. In this post we look at components that make up a random steering toolkit. These can be combined in various ways to get agents to move in interesting ways. You might want to have a look at Craig Reynolds&#8217; Steering Behaviour for Autonomous Characters — the [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/' rel='bookmark' title='Permanent Link: Generating Random Numbers with Arbitrary Distributions'>Generating Random Numbers with Arbitrary Distributions</a></li>
<li><a href='http://code-spot.co.za/2009/10/25/tips-for-designing-and-implementing-a-stimulus-response-agent/' rel='bookmark' title='Permanent Link: Tips for Designing and Implementing a Stimulus Response Agent'>Tips for Designing and Implementing a Stimulus Response Agent</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img">
<p class="zemanta-img-attribution"><a href="http://commons.wikipedia.org/wiki/Image:Vector_field.svg"></a></p>
<p><img class="alignnone size-full wp-image-340" title="random_motion_header_pic" src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot100.png" alt="" width="500" height="350" /></div>
<div class="zemanta-img">
<p>Random steering is often a useful for simulating interesting steering motion. In this post we look at components that make up a random steering toolkit. These can be combined in various ways to get agents to move in interesting ways.</p></div>
<p>You might want to have a look at <a href="http://www.red3d.com/cwr/papers/1999/gdc99steer.html">Craig Reynolds&#8217; Steering Behaviour for Autonomous Characters</a> — the wander behaviour is what is essentially covered in this tutorial. The main difference is that we control the angle of movement directly, while Reynolds produce a steering force. This post only look at steering — we assume the forward speed is constant. All references to velocity or acceleration refers to angular velocity and angular acceleration.</p>
<p>Whenever I say “a random number”, I mean a uniformly distributed random floating point value between 0 and 1.</p>
<p><span id="more-339"></span></p>
<h2>1. Angular displacement, velocity and acceleration</h2>
<p>These are the variables we can alter to make the agent steer. For a fuller treatment of these basic quantities, see <a href="http://hyperphysics.phy-astr.gsu.edu/hbase/rotq.html">Basic Rotational Quantities</a>. You might also like to check the Wikipedia article <a href="http://en.wikipedia.org/wiki/Random_walk">Random Walk</a>.</p>
<h3>Angular Displacement</h3>
<p>Angular displacement is simply the current angle of the agent (relative to some fixed direction, such as the positive x-axis).</p>
<p>If you decide to make the angular displacement random, you calculate the new angle as:</p>
<p>angular_displacement = 2*max_displacement * (random() &#8211; 0.5)</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot101-custom.png" alt="screenshot101 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
</tr>
<tr>
<td width="166" valign="top">Motion produced by randomly altering the angular displacement.</td>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
</tr>
</tbody>
</table>
<p>As can be seen from the graphic above, the result is very erratic, and not very organic. We can get a better impression of intent if we limit the angles in a certain range (by setting the max_displacement to a lower value than 180), as shown below.</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot102-custom.png" alt="screenshot102 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot103-custom.png" alt="screenshot103 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot105-custom.png" alt="screenshot105 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Same as above, but with angle limited witin 10 degrees of the original displacement.</td>
<td width="166" valign="top">Angle limited to 30 degrees.</td>
<td width="166" valign="top">Angle limited to 90 degrees.</td>
</tr>
</tbody>
</table>
<h3>Angular Velocity</h3>
<p>Angular velocity is the difference between two displacements (measured in two consecutive simulation steps).</p>
<p>angular_velocity = angular_displacement1 – angular_displacement0</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot106-custom.png" alt="screenshot106 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot108-custom.png" alt="screenshot108 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot109-custom.png" alt="screenshot109 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Velocity is changed randomly, but clamped at 10 degrees.</td>
<td width="166" valign="top">Velocity clamped at 40 degrees.</td>
<td width="166" valign="top">Velocity clamped at 80 degrees.</td>
</tr>
<tr>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
</tr>
</tbody>
</table>
<p>Changing the velocity results in smoother behaviour. The smoothness depends on the maximum allowed velocity.</p>
<h3><strong>Angular Acceleration</strong></h3>
<p>Angular acceleration is the difference between two velocities (measured in two consecutive simulation steps).</p>
<p>angular_acceleration = angular_velocity1 – angular_velocity0</p>
<p>Changing the acceleration is even smoother than changing the velocity. If the acceleration is not clamped to a suitably low value, the agent might go off on a spin for a long time (read the <a href="http://en.wikipedia.org/wiki/Random_walk">Random Walk</a> article on Wikipedia to understand why).</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot114-custom.png" alt="screenshot114 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot115-custom.png" alt="screenshot115 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot116-custom.png" alt="screenshot116 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Acceleration modified randomly. Acceleration clamped at 0.5 degrees. Velocity clamped at 5 degrees.</td>
<td width="166" valign="top">Acceleration clamped at 1 degree. Velocity clamped at 5 degrees.</td>
<td width="166" valign="top">Acceleration clamped at 1 degree. Velocity clamped at 5 degrees.</td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot111-custom.png" alt="screenshot111 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot110-custom.png" alt="screenshot110 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot.png" alt="screenshot" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Acceleration clamped at 0.5 degrees. Velocity clamped at 10 degrees.</td>
<td width="166" valign="top">Acceleration clamped at 1 degree.  Velocity clamped at 10 degrees.</td>
<td width="166" valign="top">Acceleration clamped at 1 degree. Velocity clamped at 10 degrees.</td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot117-custom.png" alt="screenshot117 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot120-custom.png" alt="screenshot120 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot119-custom.png" alt="screenshot119 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Acceleration clamped at 0.5 degrees. Velocity clamped at 15 degrees.</td>
<td width="166" valign="top">Acceleration clamped at 1 degree. Velocity clamped at 15 degrees.</td>
<td width="166" valign="top">Acceleration clamped at 1 degree. Velocity clamped at 15 degrees.</td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot118-custom.png" alt="screenshot118 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
</tr>
<tr>
<td width="166" valign="top">Shows a situtation where the clamped acceleration is not low enough.</td>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
</tr>
</tbody>
</table>
<h2>2. Distributions</h2>
<p>Changing the distribution of the random numbers we use changes the motion.</p>
<h3>Smooth Noise</h3>
<p>Smooth noise is generated from uniformly distributed random numbers (white noise) by interpolating values.</p>
<p>For example, the sequence 0 1 0 0 can be smoothed out to 0 0.5 1 0.5 0 0 0, or for smoother result 0 0.25 0.5 0.75 1 0.75 0.5 0.25 0 0 0 0 0.</p>
<h3>Perlin Noise</h3>
<p>Perlin noise is very suitable for rugged organic types of motion. I won&#8217;t cover how to produce Perlin noise — see <a href="http://freespace.virgin.net/hugo.elias/models/m_perlin.htm">this tutorial</a>.</p>
<h3>Arbitrary Distributions</h3>
<p>We can also use a handcrafted distribution curve. See the post <a href="http://">Generating Random Numbers with an Arbitrary Distribution</a>.</p>
<h3>Discrete Distributions</h3>
<p>Instead of allowing all angles, we can limit the angles to a discrete set, for example only angles in the set 0, 90, 180, 270. Motion generated from a discrete set is very mechanical.</p>
<p>We can also map Perlin noise to a discrete set, leading to an agent that follows a direction for a longer time.</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot113-custom.png" alt="screenshot113 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot121-custom.png" alt="screenshot121 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"></td>
</tr>
<tr>
<td width="166" valign="top">Smooth noise.</td>
<td width="166" valign="top">Perlin noise.</td>
<td width="166" valign="top"></td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot161-custom.png" alt="screenshot161 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot162-custom.png" alt="screenshot162 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot163-custom.png" alt="screenshot163 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Arbitrary distribution curve used to modify displacement.</td>
<td width="166" valign="top">Arbitrary distribution curve used to modify velocity</td>
<td width="166" valign="top">Arbitrary distribution curve used to modify acceleration</td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot153-custom.png" alt="screenshot153 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot154-custom.png" alt="screenshot154 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot155-custom.png" alt="screenshot155 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Discrete distribution (90 degrees).</td>
<td width="166" valign="top">Discrete distribution (60 degrees).</td>
<td width="166" valign="top">Discrete distribution (30 degrees).</td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot156-custom.png" alt="screenshot156 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot157-custom.png" alt="screenshot157 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot158-custom.png" alt="screenshot158 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Discrete Perlin (90 degrees).</td>
<td width="166" valign="top">Discrete Perlin (60 degrees).</td>
<td width="166" valign="top">Discrete Perlin (30 degrees).</td>
</tr>
</tbody>
</table>
<h2>3. Vector Fields</h2>
<p>Random vector fields can be useful in certain cases. In general, it is impractical to generate a random vector for each pixel. Instead we generate vectors for a sample grid (say every 10<sup>th</sup> pixel in every 10<sup>th</sup> row), and use interpolation for the other pixels. The lower our sampling rate (i.e. the further sample pixels are apart) the smoother the motion will be.</p>
<ul>
<li>When setting the angular displacement from such a field, the agent will retrace a path whenever it visits a pixel that has already been visited. This can sometimes be distracting. It is easily fixed by offsetting the angle with a small random amount.</li>
<li>Random vector field can have sinks from which the agent cannot escape. This is especially true when the acceleration is set from a vector field. One way of resolving this problem is to switch between two or even three vector field at regular intervals. (It can be difficult to reliably detect when the agent is stuck).</li>
</ul>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot122-custom.png" alt="screenshot122 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot123-custom.png" alt="screenshot123 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot126-custom.png" alt="screenshot126 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Vector field used to alter displacement.</td>
<td width="166" valign="top">Vector field used to alter velocity.</td>
<td width="166" valign="top">Vector field used to alter acceleration.</td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot124-custom.png" alt="screenshot124 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
</tr>
<tr>
<td width="166" valign="top">Shows a sink in the vector field that permanently traps an agent.</td>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
</tr>
</tbody>
</table>
<p>Vector fields can also be used to bias random numbers. This is useful when the vector field represents landscape features. Thus the field will only “influence” the behavior of an agent, and not control it directly. One very easy way to do this is to use the following formula to adjust the angle:</p>
<p>displacement = r_1 * vec(x, y) + (1 – r_1) * r_2</p>
<p>Where vec(x, y) is the angle obtained from the vector field (possibly interpolated as described above), and r_1 and r_2 are two random numbers.</p>
<h2>4. Functions</h2>
<p>Instead of using random numbers, we can use functions that depend on time. These functions can be parameterised with random numbers.</p>
<p>The sine function have properties that makes it very convenient to use for this purpose:</p>
<ul>
<li>It is smooth.</li>
<li>Its range (the amplitude) is limited, and easily adjusted with a parameter.</li>
<li>The frequency is constant and easily tweaked with a parameter, making it easier to control things such as loops when combining different sine functions.</li>
<li>Different sine functions can be added to lead to complex motion.</li>
<li>It is easy to blend two sine functions with another function to simulate frequency changes (for example, A(t) * sin(10t) + (1 – A(t)) * sin(t) without unwanted phase effects. Alternatively, the blending can be done with a Perlin noise sequence.</li>
</ul>
<p>Saw tooth functions and square wave functions have all these properties, except that they are not smooth.</p>
<p>In the images below, the parameter t is incremented each time step.</p>
<p>sin(t) + sin(10t) + sin(50t)</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot128-custom.png" alt="screenshot128 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot129-custom.png" alt="screenshot129 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot130-custom.png" alt="screenshot130 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">sin(t)</td>
<td width="166" valign="top">sin(10t)</td>
<td width="166" valign="top">sin(50t)</td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot131-custom.png" alt="screenshot131 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot132-custom.png" alt="screenshot132 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot133-custom.png" alt="screenshot133 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">sin(t) + sin(10t) + sin(50t)</td>
<td width="166" valign="top">0.5sin(t) + 0.3sin(10t) + 0.2sin(50t)</td>
<td width="166" valign="top">0.5sin(t) + 0.5sin(50t)</td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot137-custom.png" alt="screenshot137 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot139-custom.png" alt="screenshot139 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot138-custom.png" alt="screenshot138 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top"></td>
<td width="166" valign="top">0.9perlin_noise(t)sin(t) + 0.1perlin_noise(T &#8211; t)sin(50t)</td>
<td width="166" valign="top">0.5perlin_noise(t)sin(t) + 0.5perlin_noise(T &#8211; t)sin(50t)</td>
<td width="166" valign="top"></td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot134-custom.png" alt="screenshot134 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot135-custom.png" alt="screenshot135 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot136-custom.png" alt="screenshot136 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">white_noise(t) * [0.5sin(t) +  0.5sin(50t)]</td>
<td width="166" valign="top">smooth_noise(t) * [0.5sin(t) +  0.5sin(50t)]</td>
<td width="166" valign="top">perlin_noise(t) * [0.5sin(t) +  0.5sin(50t)]</td>
</tr>
</tbody>
</table>
<h2>5. Timed Transitions</h2>
<p>Instead of changing the angular displacement (or velocity or acceleration) at every time step, we can change it only every “once in a while”. For example, we can change it when a fixed number of time steps have passed. More interestingly, we can change it only when a random number of time steps have passed.</p>
<p>The presence of many circular loops indicate long times of constant velocity. When we adjust the velocity or acceleration, this can happen when the intervals are too long in relation to the max angular velocity. When we adjust the acceleration, it can also happen when the max velocity is too low relative to the maximum acceleration – leading to quick “saturation”.</p>
<p>When combined with angles from a discrete distribution, we get the machine-like behaviour (similar to using Perlin noise mapped to a discrete set as above).</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot140-custom.png" alt="screenshot140 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot141-custom.png" alt="screenshot141 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot142-custom.png" alt="screenshot142 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Displacement</td>
<td width="166" valign="top">Velocity</td>
<td width="166" valign="top">Acceleration</td>
</tr>
<tr>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
<td width="166" valign="top"></td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot144-custom.png" alt="screenshot144 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot145-custom.png" alt="screenshot145 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot146-custom.png" alt="screenshot146 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Clamped velocity (low).</td>
<td width="166" valign="top">Clamped velocity (medium).</td>
<td width="166" valign="top">Clamped velocity (high).</td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot148-custom.png" alt="screenshot148 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot149-custom.png" alt="screenshot149 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot150-custom.png" alt="screenshot150 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Clamped velocity (very high).</td>
<td width="166" valign="top">Clamped acceleration and velocity (low velocity).</td>
<td width="166" valign="top">Clamped acceleration and velocity (high velocity).</td>
</tr>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot151-custom.png" alt="screenshot151 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot152-custom.png" alt="screenshot152 (Custom)" width="166" height="166" /></td>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot143-custom.png" alt="screenshot143 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="166" valign="top">Discrete set (90 degrees).</td>
<td width="166" valign="top">Discrete set (72 degrees).</td>
<td width="166" valign="top">Very regular movement when clamped acceleration is low relative to the clamped velocity.</td>
</tr>
</tbody>
</table>
<h2>6. Transition Tables and Functions</h2>
<p>Sometimes we would like to change the distribution of a randomly generated angle based on the current steering angle. We can use transition tables for this.</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="121" valign="top"></td>
<td width="127" valign="top">&lt;15</td>
<td width="125" valign="top">15&lt; &lt;30</td>
<td width="125" valign="top">30&lt;</td>
</tr>
<tr>
<td width="121" valign="top">&lt;15</td>
<td width="127" valign="top">0.9</td>
<td width="125" valign="top">0.07</td>
<td width="125" valign="top">0.03</td>
</tr>
<tr>
<td width="121" valign="top">15&lt; &lt;30</td>
<td width="127" valign="top">0.15</td>
<td width="125" valign="top">0.8</td>
<td width="125" valign="top">0.05</td>
</tr>
<tr>
<td width="121" valign="top">30&lt;</td>
<td width="127" valign="top">0.1</td>
<td width="125" valign="top">0.2</td>
<td width="125" valign="top">0.7</td>
</tr>
</tbody>
</table>
<p>The table above is an example of a transition table. It basically describes the probability that if the current steering angle is within a certain range, it will change to some other range. For example, if the current steering angle is smaller than 15 degrees, there is a probability of 0.9 that the next angle will also be smaller than 15 degrees. If the angle is greater than 30 degrees, the next angle will be smaller than 15 degrees with a probability of 0.1.</p>
<p>To implement this, we convert the probability table above to a accumulative probability table, where we sum over rows, like this:</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="123" valign="top"></td>
<td width="125" valign="top">&lt;15</td>
<td width="125" valign="top">15&lt; &lt;30</td>
<td width="125" valign="top">30&lt;</td>
</tr>
<tr>
<td width="123" valign="top">&lt;15</td>
<td width="125" valign="top">0.9</td>
<td width="125" valign="top">0.97 = 0.9 + 0.07</td>
<td width="125" valign="top">1 = 0.9 + 0.07 + 0.03</td>
</tr>
<tr>
<td width="123" valign="top">15&lt; &lt;30</td>
<td width="125" valign="top">0.15</td>
<td width="125" valign="top">0.95 = 0.15 + 0.8</td>
<td width="125" valign="top">1 = 0.15 + 0.8 + 0.15</td>
</tr>
<tr>
<td width="123" valign="top">30&lt;</td>
<td width="125" valign="top">0.1</td>
<td width="125" valign="top">0.3 = 0.1 + 0.2</td>
<td width="125" valign="top">1 = 0.1 + 0.2 + 0.7</td>
</tr>
</tbody>
</table>
<p>Now, at each simulation step, we check the current angle, and choose the appropriate row of the table to work with. Now we generate a (uniformly distributed) random number. Then we check it against the values in the row. The left most cell that is bigger than the random number is the one we want to work with – it denotes the range of the new angle. Then we simply generate a random number in this range. In practice we don;t need the last column.</p>
<p>The table above can be interpreted as follows:</p>
<ul>
<li>if the current angle is in a certain range, the probability is high that it will be again in that range;</li>
<li>if the range changes, it will more likely change to an adjacent range; and</li>
<li>if the range changes and there are two adjacent ranges, the left one is favored.</li>
</ul>
<p>We can smooth out the results by using a 2D response curve, but this can be tricky. Also, we need to specify many values to get the 2D distribution we want.</p>
<p>In a special case we can follow a two step process instead. We use two tables:</p>
<ul>
<li>one to describe the probability that an angle will change (base on the angle size);</li>
<li>and a simple transition table as above.</li>
</ul>
<p>This leads to fairly regular movement, as shown in the figures.</p>
<table border="0" cellspacing="0" cellpadding="2" width="461">
<tbody>
<tr>
<td width="166" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot164-custom.png" alt="screenshot164 (Custom)" width="166" height="166" /></td>
<td width="151" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot165-custom.png" alt="screenshot165 (Custom)" width="166" height="166" /></td>
<td width="142" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/12/screenshot166-custom.png" alt="screenshot166 (Custom)" width="166" height="166" /></td>
</tr>
<tr>
<td width="179" valign="top">Agent using the transition table above.</td>
<td width="160" valign="top">Agent using the transition table above but only change angles with probabilities 0.1, 0.2, 0.4 for the tree angle ranges.</td>
<td width="148" valign="top">Agent using the transition table above but only change angles with probabilities 1, 1 0.1 for the tree angle ranges.</td>
</tr>
</tbody>
</table>
<h2>7. Paths</h2>
<p>It is sometimes easier to steer towards a generated path than to control the steering directly. Using paths have several advantages:</p>
<ul>
<li>the agent&#8217;s future movement is always known, making it easier to predict; and</li>
<li>paths can be saved, and transmitted over a network. This can make it easier to keep networked simulations (such as multiplayer games) in synch, and support features that require determinism (such as replay).</li>
</ul>
<p>Steering on a path is covered in Reynold&#8217;s paper – here we look at a two simple random path generating algorithms.</p>
<h3>Fractals</h3>
<p>A simple path generating algorithm generates fractals:</p>
<ul>
<li>Start with a single segment – two points in a list</li>
<li>For each pair of adjacent points in the list (each representing a line segment), add some intermediate points (based on some algorithm – see below)</li>
<li>Repeat until the result is suitably detailed.</li>
</ul>
<p>The algorithm used to generate new points will determine the characteristics of the final path. Here are a few examples:</p>
<ul>
<li>For each point pair, generate a random point close to the midpoint.</li>
<li>For each point pair, generate two points close to the third and two third points, on opposite sides.</li>
</ul>
<h3>Functions</h3>
<p>Start with a line, a circle, or some other simple figure, and add sine functions to it. For example, a circle&#8217;s equation in polar coordinates is:</p>
<p>r = k</p>
<p>We can now add sine waves, like this:</p>
<p>r = k + r_1*sin(t) + r_2*sin(2t) + r_3*sin(4t) + …</p>
<p>r_i can be chosen constants, or randomly generated numbers.</p>
<p>Again, saw tooth and square wave functions are also suitable for adding to the base path. Other functions can also be used, although you should take care that they stay witin a predefined range.</p>
<h2>Download</h2>
<h3>Random Motion Game Maker File</h3>
<p>Most of the principles discussed here have been implemented in the following Game Maker file:</p>
<p><a href="http://www.code-spot.co.za/downloads/game_maker/random_movement.gmk">random_movement.gmk</a> 180 KB</p>
<p>Read the README file in the scripts folder (inside the Game Maker file).</p>
<h3>Reynolds&#8217; Open Steer Library</h3>
<p>This is a <a href="http://opensteer.sourceforge.net/">C++ implementation of Reynolds&#8217; steering behaviours</a> that can be plugged into a game or simulation.</p>
<h2>Links</h2>
<ul>
<li><a href="http://blog.soulwire.co.uk/laboratory/flash/as3-flocking-steering-behaviors">Flipping you the Boid</a> (ActionScript swarming behaviour demo &#8211; with source code).</li>
<li><a href="http://www.tom-carden.co.uk/2004/11/03/agents-behaviour-emergence-and-embodiment/">Agents, Behaviour, Emergence and Embodiment</a> (a list of resources).</li>
<li><a href="http://aigamedev.com/questions/simulating-crowd-flow-dynamics" class="broken_link">Simulating Crowd Dynamics: Flow Lanes and Character Animation</a>.</li>
<li><a href="http://www.virtualschool.edu/animation/Simulation%20and%20Visualization%20of%20Agents%20in%203D%20Environments.pdf">Simulation and Visualization of Agents in 3D Environments</a> (PDF 1.61 MB).</li>
<li><a href="http://vrlab.epfl.ch/~maim/v-crowds05.pdf">Steering a Virtual Crowd Based on a Semantically Augmented Navigation Graph</a> (PDF 3.96 MB).</li>
<li><a href="http://paper.ijcsns.org/07_book/200607/200607A11.pdf">A Microscopic Swarm Model Simulation and Fractal Approach towards Swarm Agent Behaviour</a> (PDF 622 KB).</li>
<li><a href="http://depts.washington.edu/dmgftp/publications/pdfs/mouse_class/mouse_thesis.pdf">The Experiments for Exploring Dynamic Behaviors in Urban Places</a> (PDF 12.83 MB).</li>
<li><a href="http://epubl.ltu.se/1404-5494/2005/53/LTU-HIP-EX-0553-SE.pdf">Simulating Crown Behaviour in Computer Games</a> (PDF 621 KB).</li>
<li><a href="http://pdcc.ntu.edu.sg/dsgrid06/doc/0064_cao-trafficsimulation.pdf" class="broken_link">Towards Building an Intelligent Traffic Simulation Platform</a> (PDF 154 KB).</li>
<li><a href="http://tecfa.unige.ch/perso/yvan/tanks/TankWars.pdf">Tank Wars</a> (PDF 435 KB).</li>
<li><a href="http://www.diva-portal.org/diva/getDocument?urn_nbn_se_liu_diva-4737-1__fulltext.pdf">REACT: Crowd Simulation System for Visual Effects</a> (PDF 846 KB).</li>
<li><a href="http://isg.cs.tcd.ie/dobbyns/Papers/SimonDobbynThesis.pdf">Hybrid Representations and Perceptual Metrics for Scalable Human Simulation</a> (PDF 5.39 MB).</li>
</ul>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2009/04/09/cellular-automata-for-simulation-in-games/' rel='bookmark' title='Permanent Link: Cellular Automata for Simulation in Games'>Cellular Automata for Simulation in Games</a></li>
<li><a href='http://code-spot.co.za/2008/09/21/generating-random-numbers-with-arbitrary-distributions/' rel='bookmark' title='Permanent Link: Generating Random Numbers with Arbitrary Distributions'>Generating Random Numbers with Arbitrary Distributions</a></li>
<li><a href='http://code-spot.co.za/2009/10/25/tips-for-designing-and-implementing-a-stimulus-response-agent/' rel='bookmark' title='Permanent Link: Tips for Designing and Implementing a Stimulus Response Agent'>Tips for Designing and Implementing a Stimulus Response Agent</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Force Field Editor v1.0</title>
		<link>http://code-spot.co.za/2008/10/29/force-field-editor-v10/</link>
		<comments>http://code-spot.co.za/2008/10/29/force-field-editor-v10/#comments</comments>
		<pubDate>Wed, 29 Oct 2008 15:46:01 +0000</pubDate>
		<dc:creator>herman.tulleken</dc:creator>
				<category><![CDATA[Downloads]]></category>
		<category><![CDATA[Game Development]]></category>
		<category><![CDATA[Simulation]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[AI]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[editor]]></category>
		<category><![CDATA[force field]]></category>
		<category><![CDATA[quadtree]]></category>
		<category><![CDATA[vector field]]></category>

		<guid isPermaLink="false">http://code-spot.co.za/?p=161</guid>
		<description><![CDATA[Vector fields are used in certain AI and simulation techniques. The tool below allows you to paint a vector field. These files can be saved in XML format, that can easily be loaded into another application. There are five brushes: The Set Direction brush keeps the size of the underlying vector the same, but changes [...]


Related posts:<ol><li><a href='http://code-spot.co.za/2010/06/15/region-quadtrees-in-c/' rel='bookmark' title='Permanent Link: Region Quadtrees in C++'>Region Quadtrees in C++</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/10/06/quadtrees/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/10/pull.png" alt="pull" width="500" height="357" /></p>
<p>Vector fields are used in certain AI and simulation techniques. The tool below allows you to paint a vector field. These files can be saved in XML format, that can easily be loaded into another application.</p>
<p><span id="more-161"></span></p>
<p>There are five brushes:</p>
<ul>
<li>The Set Direction brush keeps the size of the underlying vector the same, but changes the size to a constant value.</li>
<li>The Set Size brush keeps the size of the underlying vector the same, but changes the direction to a constant angle.</li>
<li>The Attract brush draws all the vectors closer to the mouse cursor.</li>
<li>The Repel brush pushes all vectors away from the mouse cursor.</li>
<li>The Comb brush moves vectors in the same direction as the mouse.</li>
</ul>
<p>The XML file arranges the field into a quadtree. The quadtree compression can be viewed from the program.</p>
<table border="0" cellspacing="0" cellpadding="2" width="500">
<tbody>
<tr>
<td width="250" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/10/normal.png" alt="normal" width="240" height="240" /></td>
<td width="250" valign="top"><img src="http://code-spot.co.za/blog/wp-content/uploads/2008/10/compressed.png" alt="compressed" width="240" height="240" /></td>
</tr>
</tbody>
</table>
<p>To change the brush size, use the &#8216;[' and ']&#8216; keys.</p>
<p>To change the brush options, use the &#8216;-&#8217; or &#8216;=&#8217; keys.</p>
<p>This is the first version of this program, so there are many missing features. For example, the size of the field can not be changed yet. If you find it useful, let me know in the comments!</p>
<h2>Download</h2>
<h3>Windows Executable</h3>
<p><a href="http://www.code-spot.co.za/downloads/tools/force_field_editor_v1_0.exe">force_field_editor_v1_0.exe 3.3 MB</a></p>
<p>Requires <a href="http://java.com/en/download/manual.jsp">Java Runtime Environment</a>.</p>


<p>Related posts:<ol><li><a href='http://code-spot.co.za/2010/06/15/region-quadtrees-in-c/' rel='bookmark' title='Permanent Link: Region Quadtrees in C++'>Region Quadtrees in C++</a></li>
<li><a href='http://code-spot.co.za/2008/12/07/random-steering-7-components-for-a-toolkit/' rel='bookmark' title='Permanent Link: Random Steering &#8211; 7 Components for a Toolkit'>Random Steering &#8211; 7 Components for a Toolkit</a></li>
<li><a href='http://code-spot.co.za/2008/10/06/quadtrees/' rel='bookmark' title='Permanent Link: Quadtrees'>Quadtrees</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://code-spot.co.za/2008/10/29/force-field-editor-v10/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

