<?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>Bugfree.dk - Ronnie Holm&#039;s blog &#187; Math</title>
	<atom:link href="http://www.bugfree.dk/blog/tag/math/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bugfree.dk/blog</link>
	<description>Not anti-anything, just pro-quality</description>
	<lastBuildDate>Mon, 28 Nov 2011 07:32:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Generating 2D random fractal terrains with F#</title>
		<link>http://www.bugfree.dk/blog/2009/03/06/generating-2d-random-fractal-terrains-with-f/</link>
		<comments>http://www.bugfree.dk/blog/2009/03/06/generating-2d-random-fractal-terrains-with-f/#comments</comments>
		<pubDate>Thu, 05 Mar 2009 22:14:48 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2009/03/06/generating-2d-random-fractal-terrains-with-f/</guid>
		<description><![CDATA[In Generating 2D random fractal terrains with C# I implemented 1D midpoint displacement in an imperative language. Since I&#8217;m currently making my way through Robert Pickering&#8216;s Foundations of F#, in this post I want to redo it in F#. The first step along the way is the maxDisplacements function that, given a number of splits [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.bugfree.dk/blog/2009/02/23/generating-2d-random-fractal-terrains-with-c">Generating 2D random fractal terrains with C#</a> I implemented 1D midpoint displacement in an imperative language. Since I&#8217;m currently making my way through <a href="http://strangelights.com/blog">Robert Pickering</a>&#8216;s <a href="http://www.amazon.com/dp/1590597575?tag=strangelights-20&amp;camp=14573&amp;creative=327641&amp;linkCode=as1&amp;creativeASIN=1590597575&amp;adid=1T0HP42WA17EB83RZNFC&amp;">Foundations of F#</a>, in this post I want to redo it in F#.</p>
<p>The first step along the way is the maxDisplacements function that, given a number of splits of line segments, returns a list of maximum displacements. Here <a href="http://en.wikipedia.org/wiki/List_comprehension">list comprehension</a> comes in handy as a way to generate maximum displacements where the next is half of that of the previous, starting with 0.5:
</p>
<pre class="prettyprint lang-fs">
    let maxDisplacements n = [for i in 1 .. n -&gt; 2.0**(float)(-i)]
</pre>
<p>Next is the composeCoordinates function whose job it is to infer the x coordinates from the y coordinates. When splitting line segments, as defined later by the split function, only y coordinates need to be dealt with. But for displaying the result as a list of points, e.g., as input to a graphing program, composeCoordinates generates the (x, y) coordinate pairs given a list of y coordinates. Again list comprehension is used to uniformly distribute the x coordinates in the range 0 to 1. Next, the x and y coordinates are fused using the build-in zip function, i.e., [x1; x2] and [y1; y2] become [(x1, y1); (x2, y2)].
</p>
<pre class="prettyprint lang-fs">
    let composeCoordinates (ys : list&lt;float&gt;) =
        let dx = 1.0 / (float)(ys.Length - 1)
        let xs = [for x in 0 .. ys.Length - 1 -&gt; (float)x * dx]
        List.zip xs ys
</pre>
<p>Now for the crux of the fractal generation process: the split function. As is customary with functional languages, looping is done using recursion and split is no exception. Passing in a list of y coordinates, a maximum displacement as generated by maxDisplacements, and a random number generator, split is defined as:
</p>
<pre class="prettyprint lang-fs">
    let rec split (ys : list&lt;float&gt;) displacement (random : Random) =
        match ys with
        | a :: b :: tail -&gt;
            let m = b - a / 2.0
            let r = random.NextDouble() * displacement
            a :: a + m + r :: split (b :: tail) displacement random
        | a -&gt; a
</pre>
<p>Using <a href="http://en.wikipedia.org/wiki/Pattern_matching">pattern matching</a>, an if-then-else construct on steroids, split examines its input of y coordinates to determine if the inductive or the base case of the recursive implementation needs to be invoked. The first pattern matches a list starting with elements a and b following by zero or more elements. In case this pattern matches, a new list is returned. It&#8217;s composed of the original a element, a new displaced element, the original b element, and split applied to the original list with its first element removed. Removing one element at a time, at some point only one element is left in the list in which case the base case is invoked. When this happens, all the original line segments have been split in two.
</p>
<p>Finally, the main function ties together the previous ones. Given an initial line segment, the number of times to apply split to it, and a random number generator, the actual splitting is done using the build-in <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">fold_left</a> function. fold_left is an example of <a href="http://codebetter.com/blogs/matthew.podwysocki/archive/2009/02/14/fun-with-folds.aspx">fun with folds</a> and a function that is itself recursively defined to make looping implicit.
</p>
<pre class="prettyprint lang-fs">
    let main() =
        let initial = [0.0; 0.0]
        let splits = 8
        let r = new Random()
        let ys = List.fold_left (fun s d -&gt; split s d r) initial (maxDisplacements splits)
        print_any (composeCoordinates ys)
</pre>
<p>While initially hard to grog, the use of fold_left becomes clearer when applied to a list of integers to compute their product. Of the three arguments to fold_left the first is a function defined by a lambda expression (here the predefined multiplication operator is also applicable but less explicit). The second argument is the initial value of an accumulator. And finally, the third argument is the list to work on.
</p>
<pre class="prettyprint lang-fs">
    List.fold_left (fun x y -&gt; x * y) 1 [1;2;3]
    List.fold_left (*) 1 [1;2;3]
</pre>
<p>What fold_left does is recursively call itself passing along the first argument as is. The second argument is the new value of the accumulator, computed by passing to the function of the first argument the original value of the accumulator and the first element of the list. That way it&#8217;s up to the function passed as the first argument to decide what operation to apply to the elements in the list. The third argument is the original list with the first element removed. The recursive chain of calls with their arguments then takes on this form:
</p>
<pre class="prettyprint lang-fs">
    List.fold_left (fun 1 1 -&gt; 1 * 1) 1 [1;2;3]
    List.fold_left (fun 1 2 -&gt; 1 * 2) 1 [2;3]
    List.fold_left (fun 2 3 -&gt; 2 * 3) 2 [3]
</pre>
<p>Within the main function the first argument to fold_left is a lambda expression that applies the split function to a list. The second argument, the accumulator, isn&#8217;t a scalar like with the product example, but a list of line segments to be passed to split. Finally, the third argument is the maximum displacement list. And so for the original line segment to be split n times, n maximum displacements must be provided by the maxDisplacements function.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F03%2F06%2Fgenerating-2d-random-fractal-terrains-with-f%2F&amp;title=Generating%202D%20random%20fractal%20terrains%20with%20F%23" id="wpa2a_2"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/03/06/generating-2d-random-fractal-terrains-with-f/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Generating 2D random fractal terrains with C#</title>
		<link>http://www.bugfree.dk/blog/2009/02/23/generating-2d-random-fractal-terrains-with-c/</link>
		<comments>http://www.bugfree.dk/blog/2009/02/23/generating-2d-random-fractal-terrains-with-c/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 00:11:37 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2009/02/23/2d-fractal-terrain-generation-using-midpoint-displacement/</guid>
		<description><![CDATA[Back in 1999, when I was learning C++ and MFC, I remember spending a great deal of time writing an application that displayed the Mandelbrot set, probably the most famous of all fractals. And when I learned Remote Procedure Call, I even converted the application into a distributed Mandelbrot generator (which made sense given the [...]]]></description>
			<content:encoded><![CDATA[<p>Back in 1999, when I was learning C++ and MFC, I remember spending a great deal of time writing an application that displayed the <a href="http://en.wikipedia.org/wiki/Mandelbrot_set">Mandelbrot set</a>, probably the most famous of all fractals. And when I learned Remote Procedure Call, I even converted the application into a distributed Mandelbrot generator (which made sense given the CPU speed of the time).</p>
<p>What’s so fascinating about the Mandelbrot set, and other fractals, is that the often simple equations that define them are able to give birth to such complex creations.</p>
<p>In general, a <a href="http://en.wikipedia.org/wiki/Fractal">fractal</a> is defined as:</p>
<blockquote><p>“[…] &#8216;a rough or fragmented <a href="http://en.wikipedia.org/wiki/Shape">geometric shape</a> that can be split into parts, each of which is (at least approximately) a reduced-size copy of the whole,&#8217; a property called <a href="http://en.wikipedia.org/wiki/Self-similarity">self-similarity</a>. A fractal often has the following features: it has a fine structure at arbitrarily small scales; it is too irregular to be easily described in traditional <a href="http://en.wikipedia.org/wiki/Euclidean_geometry">Euclidean geometric</a> language; it is self-similar (at least approximately or <a href="http://en.wikipedia.org/wiki/Stochastic">stochastically</a>); [… and] it has a simple and <a href="http://en.wikipedia.org/wiki/Recursive_definition">recursive definition</a>. […] Natural objects that approximate fractals to a degree include clouds, mountain ranges, lightning bolts, coastlines, and snowflakes.”</p></blockquote>
<p>The Mandelbrot set is an example of a fractal whose definition contains no stochastic element, i.e., the fractal looks the same every time it’s generated. Recently, though, I came across a simple  algorithm that claimed to generate fractal terrains by adding randomness to the equation. So, given my history with fractals, I wanted to play with the algorithm that&#8217;s based on progressive refinement through <a href="http://gameprogrammer.com/fractal.html#midpoint">midpoint displacement in one dimension</a>:</p>
<pre>
    Start with a single horizontal line segment
    Repeat for a sufficiently large number of times
        Repeat over each line segment
            Find the midpoint of the line segment
            Displace the midpoint in y by a random amount
        Reduce the range for random numbers
</pre>
<p>Here’s my implementation of the algorithm in C#:</p>
<pre class="prettyprint lang-cs">
    class Program {
        static void Main() {
            var ys = new List&lt;double&gt;(new double[] { 0.0, 0.0 } );
            double displacement = 1.0;
            Random random = new Random();

            for (int i = 0; i &lt; 8; i++)
                ys = Split(ys, displacement *= 0.5, random);
            ComposeCoordinatePairs(ys);
        }

        static List&lt;double&gt; Split(List&lt;double&gt; ys, double displacement, Random random) {
            if (ys.Count &lt; 2)
                throw new ArgumentException("&gt;= 2 coordinates required");
            var r = new List&lt;double&gt;();
            for (int i = 0; i &lt; ys.Count - 1; i++) {
                double dy = (ys[i + 1] - ys[i]) / 2.0;
                double d = random.NextDouble() * displacement;
                r.Add(ys[i]);
                r.Add(ys[i] + dy + d);
            }
            r.Add(ys.Last());
            return r;
        }

        static void ComposeCoordinatePairs(List&lt;double&gt; ys) {
            double dx = 1.0 / (ys.Count - 1);
            for (int i = 0; i < ys.Count; i++)
                Console.WriteLine("{0:0.000} {1:0.000}", i * dx, ys[i]);
        }
</pre>
<p>Splitting line segments, the C# code doesn't store the x-component of the coordinate pairs because it can be inferred from the number of y-components and the fact that x-components go from 0 to 1, both inclusive. Hence, starting with the line segment (0,0)-(1,0), the code splits it by calling the Split method passing in a list of y-components of the line segment. After the first iteration the single line segment becomes two, then four, then eight, and so on until the line segments have undergone eight iterations of splitting. Generally, after the i'th iteration the number of line segments is 2^i and so after eight iterations we end with 256 line segments.</p>
<p>As prescribed by the algorithm, merely splitting line segments doesn’t give rise to a mountain. The mountain emerges because each time a line segment is split in two, a random displacement is added to the y-component at the center of the line segment. Assigning an upper limit to the maximum displacement within an iteration is what defines the roughness of the generated terrain. For the above implementation, the maximum displacement is defined as half of that of the previous iteration starting with 0.5. Thus, the first couple of iterations roughly define the terrain and additional iterations fill in the details.</p>
<p>In animated form the transformations from two to 256 line segments looks like so:</p>
<p><img src="http://www.bugfree.dk/blog/wp-content/uploads/2009/02/a-ridgeline-emerges.gif" /></p>
<p>Among the practical applications of such a random fractal terrain generator are computer games. Not necessarily for generating 2D ridgelines, but for generating entire 3D terrains or even clouds. It works by generalizing 1D midpoint displacement to 2D in the form of the <a href="http://gameprogrammer.com/fractal.html#diamond">diamond-square algorithm</a>. Then a cloud, for instance, can be derived from the 3D terrain by applying a height map to it; a height map in which different heights get assigned different colors.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2009%2F02%2F23%2Fgenerating-2d-random-fractal-terrains-with-c%2F&amp;title=Generating%202D%20random%20fractal%20terrains%20with%20C%23" id="wpa2a_4"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/02/23/generating-2d-random-fractal-terrains-with-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Real time physics in games</title>
		<link>http://www.bugfree.dk/blog/2007/06/14/real-time-physics-in-games/</link>
		<comments>http://www.bugfree.dk/blog/2007/06/14/real-time-physics-in-games/#comments</comments>
		<pubDate>Thu, 14 Jun 2007 15:19:22 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Gaming]]></category>
		<category><![CDATA[Math]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2007/06/14/real-time-physics-in-games/</guid>
		<description><![CDATA[I was watching the interview with Brian Beckman on real time physics simulation in games over at Channel 9. In the video Brian explains the challenges involved in creating an accurate, real time physics model in games, specifically for flight simulators and race car games. Although the math is quite involved, Brian does a superb [...]]]></description>
			<content:encoded><![CDATA[<p>I was watching the <a href="http://channel9.msdn.com/Showpost.aspx?postid=314874">interview</a> with <a href="http://weblogs.asp.net/brianbec/articles/440296.aspx">Brian Beckman</a> on real time physics simulation in games over at <a href="http://channel9.msdn.com">Channel 9</a>. In the video Brian explains the challenges involved in creating an accurate, real time physics model in games, specifically for flight simulators and race car games.  Although the math is quite involved, Brian does a superb job of transforming the material into something digestible and fascinating.</p>
<p>In summary, <a href="http://en.wikipedia.org/wiki/Moore%27s_law">Moore’s law</a> enables game designers to use real time physics in games to accurately simulate something as complicated as a race car. Simulating an airplane has been possible for well over twenty years, but that&#8217;s only because the airplane moves smoothly through the air and is composed of simple components, such as a wing and a fuselage, which translates into few and simple equations to solve for each frame. </p>
<p>A race car, on the other hand, has four wheels touching the ground and connected to the car through some kind of suspension. Hence each wheel has to be accounted for independently. In addition, the clutch, gear box, and aerodynamics of the car, not to mention the terrain, have a profound impact on the physics model, calling for a more involved set of <a href="http://phors.locost7.info ">equations</a> to solve.</p>
<p>As computes have become fast enough to match the frame rate given this challenging set of equations, race car games have become as realistic as flight simulators. With more horsepower, however, comes a need for even more realism. So even though computers become faster/fatter at an exponential rate, simplifying the model is, and probably always will be, worth striving for.</p>
<p>This is where <a href="http://rigsofrods.blogspot.com">Rigs of Rods</a> enters the video at time index 00:56:10. The game takes the opposite approach of using advanced equations, with the risk of introducing divergence or singularities into the model when, say, the denominator of a fraction approaches zero. Instead the game uses simple/simpler equations, such as <a href="http://en.wikipedia.org/wiki/Harmonic_oscillator">harmonic oscillators</a>, as a mean of modeling airplanes, cars, trucks, etc. using sticks and stones (or rigs of rods, hence the name).<br />
<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/TR9jqGv05H4"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/TR9jqGv05H4" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object><br />
<br />
The sticks and stones approach works by assigning mass to the stones and connecting them using the sticks, and then adding textures on top. This more general, but also more computationally intensive, model creates a very realistic experience.</p>
<p>I’ve been playing the game for a couple of days now, and although it initially appears simple it’s surprisingly entertaining. A lot of time goes into exploring the scenery using the various modes of transportation.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.bugfree.dk%2Fblog%2F2007%2F06%2F14%2Freal-time-physics-in-games%2F&amp;title=Real%20time%20physics%20in%20games" id="wpa2a_6"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2007/06/14/real-time-physics-in-games/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

