<?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></title>
	<atom:link href="http://britonia-game.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://britonia-game.com</link>
	<description></description>
	<lastBuildDate>Sun, 08 Aug 2010 09:10:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
<image>
  <link>http://britonia-game.com</link>
  <url>http://britonia-game.com/favicon.ico</url>
  <title></title>
</image>
		<item>
		<title>A Little Break</title>
		<link>http://britonia-game.com/?p=482</link>
		<comments>http://britonia-game.com/?p=482#comments</comments>
		<pubDate>Sun, 27 Jun 2010 20:41:59 +0000</pubDate>
		<dc:creator>Lintfordpickle</dc:creator>
				<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://britonia-game.com/?p=482</guid>
		<description><![CDATA[Well, as you may have noticed from the lack of articles I have had a bit of a break from Britonia in the last three months. I&#8217;ve had a few things to sort out in real life, I&#8217;ve just brought a house and should be moving in in a few months, and I&#8217;ve been sorting [...]]]></description>
			<content:encoded><![CDATA[<p>Well, as you may have noticed from the lack of articles I have had a bit of a break from Britonia in the last three months.  I&#8217;ve had a few things to sort out in real life, I&#8217;ve just brought a house and should be moving in in a few months, and I&#8217;ve been sorting out a few things for work.  There are a few little updates though ..</p>
<p><span id="more-482"></span></p>
<p><BR><br />
<strong><font  color="white">Galaxy Generation:</font></strong></p>
<p>On a slightly more upbeat note for Britonia I have made a start a few more things, the first of which is the actual galaxy generation.  This is going good and from the initial results I&#8217;m actually quite excited for getting it finished.  There are a few kinks to work out which seem sound in theory but I&#8217;m having trouble getting them to work in the game.  One such thing is the change / relationship between galaxy space and star system space.  </p>
<p>For example because double precision isn&#8217;t enough to cover the distance of an entire Galaxy, I must always have a point of reference for the camera to use as the world space origin.  It seems conceptually sound to say, have the main star in a solar system act as the point of reference for the world space, and then switch this PoF as the player warps aroung the galaxy, but actually generating the galaxy around the camera, without first knowing the exact location of a planet has got me a little stumpted.  I&#8217;ve got a few ideas, like having a perminant planet(s) which are always &#8216;there&#8217; regardless of the galaxy seed.  Another idea is to use markers to remember the locations of special planets (this was my idea for saving and loading games), but again &#8211; for them to work the galaxy must have already been generated to get this information.</p>
<p>Which continues on to the next problem I&#8217;ve run into which is the initial generation of the galaxy, and more specifically saving the player position within it.  I&#8217;m pretty confident I&#8217;ll get it working in time and once I fully concentrate on it again.  I will definately do another full article on the galaxy generation as it is a very large part of the game play.</p>
<p>The galaxy generation uses octrees to managing the placement of star (systems) based on the depth of the octree around the camera.  This is pretty much the same as Flavien Brebion outlined in his article <a href="http://www.infinity-universe.com/Infinity/index.php?option=com_content&#038;task=view&#038;id=106&#038;Itemid=26">here</a>.  I still have to define the function which will shape the galaxy.</p>
<p><BR><br />
<strong><font  color="white">Asteroid Rings</font></strong><br />
I wanted to add a little note on asteroid rings for planets as I have also got pretty nice results for this. Unfortunately again this isn&#8217;t finished yet and I still need to improve the performance, especially when rendering the individual asteroid geometry.  The geometry for the rings are defined in &#8216;real&#8217; size so they will offer pretty impressive visuals when encircling the planets.</p>
<p><BR><br />
<strong><font  color="white">The Story and Factions:</font></strong></p>
<p>I also made a start a few weeks back on the story and factions within the game.  I have gone with a classic Star Wars sytle galaxy plot, with two main factions battling on an &#8216;epic&#8217; scale.  As it seems to me to be too easy to make overcomplicated plots with space simulation games, I wanted to try and keep the number of factions and important characters to a minimum, plus I am not overly confident in my ability to create engaging story so I will be sticking with basics; good vs. bad.  There will be 4 four main factions in the game, 2 major and 2 minor:</p>
<p><BR><br />
<strong><font  color="white">The Galaxic Imperium:</font></strong><br />
The Galaxic Imperium rule the galaxy with an iron fist.  No single organisation or body can match the Imperium in terms of resources or military power, and their rule is absolute.</p>
<p><strong><font  color="white">The Revolutionary Alliance:</font></strong><br />
The revolutionary alliance directly oppose the Imperium.  Whilst they very rarely face the Imperium in open combat, the Revolutionary soldiers are oft involved in more covert operations of sabotage.  The RA seek to restore a people&#8217;s voice to the galaxy and reinstate a Repulic.</p>
<p><strong><font  color="white">The Union:</font></strong><br />
A collection of many powerful multinational companies with near limitless credits and heavy lobbying in the ruling Imperium.  The Union has arguably the most gifted scientists who are constantly prototyping new mechanical, biological and chemical weaponary, albeit using dubious and questionable work ethics.  The Union run the majority of star and trade ports throughout the galaxy.</p>
<p><strong><font  color="white">Chruch of the New Aeon:</font></strong><br />
A religious group bent on converting all the entire population to the Chruch&#8217;s beliefs.  The Church are openly hostile to all who repel their offerings of a new faith.  Unfortunately due to some high profile figures in the Chruch&#8217;s hierarchy, the Chruch seldom face finacial hardship.  The Chruch also have an advanced branch of technology not available to the Union or Imperium.  The original source and development of this technology is unknown.</p>
<p><BR><br />
As you can see the naming of the factions are nothing unique, but like I said, I am trying to keep the story quite basic.  I aim to let the player freely roam between helping any of the four main factions and letting them build repuatations.  There will be a main plot for three of the four factions in which the player can help tip the balance for a win.  More to come.</p>
<p><BR><br />
<strong><font  color="white">Things on the Side:</font></strong></p>
<p>On a last note, I&#8217;ve created a new blog which I will be using for writing up a little about some of my other, somewhat smaller projects.  I decided about a month ago that with Britonia taking so long, I&#8217;d like to try and make a few smaller games for release on Windows Phone 7 and the Xbox.  The blog is here:</p>
<p><a href="http://xnabits.wordpress.com/">http://xnabits.wordpress.com/</a></p>
<p>there&#8217;s not much on it yet, but hopefully that&#8217;ll change.</p>
]]></content:encoded>
			<wfw:commentRss>http://britonia-game.com/?feed=rss2&amp;p=482</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Creating a Planet : Geometry</title>
		<link>http://britonia-game.com/?p=448</link>
		<comments>http://britonia-game.com/?p=448#comments</comments>
		<pubDate>Thu, 20 May 2010 13:05:39 +0000</pubDate>
		<dc:creator>Lintfordpickle</dc:creator>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Procedural Content]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://britonia-game.com/?p=448</guid>
		<description><![CDATA[I have wanted to expand on my previous post regarding &#8216;Cube to Sphere Projection&#8217; for a while now, so in this article I am going to cover how I define the spherical geometry of the planets in more detail. You can read the previous article here. To be honest, I wasn’t very happy with details [...]]]></description>
			<content:encoded><![CDATA[<p>I have wanted to expand  on my previous post regarding &#8216;Cube to Sphere Projection&#8217; for a while now, so in this article I am going to cover how I define the spherical geometry of the planets in more detail.</p>
<p><span id="more-448"></span></p>
<p>You can read the previous article <a href="http://britonia-game.com/?p=16">here</a>.</p>
<p><BR><br />
To be honest, I wasn’t very happy with details of the last post and I’ve wanted to expand on it ever since.  The idea was to give people who wanted to work on a planet renderer enough information to make a start on their own project with ideas for the basic planet geometry.  As previously mentioned, my planets are based on quad trees which are orientated around the planet center to form a cube (therefore 6 quad trees are required, one for each cube face).  My LOD is then based on the distance of the camera to the particular node.  This is slightly contrary to &#8216;traditional&#8217; quadtrees which are usually split based on a number of objects assigned to a particular node.</p>
<p>There are many different implementations for both flat and spherical terrains (<a href="http://vterrain.org/LOD/spherical.html">more information</a>), but I find this method my favorite because of the ease of working with the different nodes of the quad tree; knowing that the size of a node is n^2+1 means texturing is easily accomplished and finding specific vertices in the grid becomes trivial.  In this article I’m going to cover the planet geometry again, albeit in more detail.</p>
<p><BR><br />
<strong><font color="white">Quad trees:</font></strong><br />
Quad trees can be a huge help in optimizing terrain rendering.  The basic idea is that we want to define a series of bounding boxes which contain parts of the terrain at different scales, which get progressively smaller (each node will be 1/4 the size of its parent node).  We can use the bounding boxes to check which parts of the terrain are visible, starting at the root (the largest BB) and recursively calling the children all the way down to the tree leafs where all our geometry and sceneobjects lie.</p>
<p><BR><br />
<strong><font color="white">Implementation :</font></strong><br />
We start by defining the root node of the tree which encompasses the entire area of the terrain (remember we are working with a 2d plane now &#8211; so this can be done the XZ axis).  Each node has four child nodes (which can be null in the case of the leaf nodes) and a bounding box volume which defines the extents of the node along each of the two axis.  It can also be beneficial to store the center point of each node, which I&#8217;ll come to later.</p>
<p>The general flow goes like: starting with the root node, subdivide it to produce 4 children of equal size which fit within the current BB and pass in the new bounding information from the root node to each child.  This subdividing of nodes happens &#8216;n&#8217; number of times.  n can be either a predefined depth variable for how many levels the quadtree will have, or a minimum amount of objects allowed in a node.  Once we subdivide down to this depth level we have reached a leaf node.  The leaf node should contain the terrain geometry and possibily a collection of sceneobjects within its bounding volume.</p>
<p>One representation of a quadtree would be:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=qtTerrain.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/qtTerrain.jpg" border="0" alt="Photobucket"></a></p>
<p><BR><br />
Rendering this terrain now only requires one call the draw function on the root node, where a bounding box check will be done with the camera view frustum.  If the BB is within or even partially within the frustum we call the draw function of each of the children in the tree.  This happens right down the tree until a leaf node is reached.  Once at the leaf node, we know it is visible by the camera and so we can render the terrain mesh and the sceneobjects attached to the node.  </p>
<p>This can save a lot of work; imagine that for a high level node which isn’t within the camera frustum, we can immediately cull this along with all its children saving all those draw calls.  You can also further benefit for the fact that if a particular bb is fully within the camera frustum, you can go straight to the leaf nodes and draw them, saving on furter BB.Intersection() calls.</p>
<p>Using quadtrees can also narrow down the amount of work needed between scene object interactions because each scene object is assigned to the node within whos bounds they lie.  When it comes to doing things like collision checks then you only need check each object with the other objects in the same node.</p>
<p>Storing the scene objects and the terrain mesh in the leaf node isn&#8217;t the only way to do this as you could also store them in each of the nodes at different depths (like chunked LOD).  But as there are many ways of doing this, your implementation will depend greatly on what you want to achieve.</p>
<p><BR><br />
<strong><font color="white">Defining the Planet Geometry</font></strong><br />
The above example of the quadtree works quite well for traditional terrains but for the purpose of creating a planet we need to actually define the spherical geometry based on a cube.  This means defining the cube first <em>and then</em> transforming the vertices to form a sphere. In order to do this and make sure the LOD is sufficent to get down to one meter at surface level we need to calculate the size of the cube.  </p>
<p>This is done using a binary logarithm of the radius of the planet, taking the gridsize of each node into account.  A binary logarithm will tell you by what power or exponential you need to raise a base number to get the desired number.  (or simply put, how many times must I subdivide a number to get to two).  This is easy to work out:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
float _iRadius = 32;
int _iMaxLOD = (int)Math.Log2(iRadius * 2.0f);
</pre>
<p><BR><br />
This function will tell us that we need to subdivide a cube of size 64 (radius = 32), six times to get to a resolution of two (meters);</p>
<p>The only problem now is that 6 will subdivide the cube down to a resolution of 2 &#8211; but what if the patch grids have a size of 32^2?  This would mean the resolution of the vertices on the surface would actually be a lot smaller than our desired 1 meter.  To correct this we simply take the binary logarithm of the gridsize (n^2) and subtract it from _iMaxLOD.  Luckily, these LOD functions only need to be called when initialing the planets, so we don&#8217;t really need to worry about performance.</p>
<p><BR><br />
<strong><font color="white">Defining a cube of vertex Grids:</font></strong><br />
Defining a cube using quadtrees isn&#8217;t particually hard once you get used to it, but it can be a pain getting the orientation of the cubes quite right.  Each of my terrain patches has a buildMesh() function which, when called, generates a grid of vertices around a center position <strong>on a given plane</strong>.  The individual planes are very important as they will define which quadtree belong to what cube size. The function looks similar to:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
private void BuildMesh(Vector3 centerPos, Vector3 axisX, Vector3 axisZ)
{
    // temp array for demonstraion
    VertexPositionTextureNormal[] vertices = new VertexPositionTextureNormal[width*height];

    int index = 0;
    for(int u = 0; u < height; u++)
    {
        for(int v = 0; v < width; v++)
        {
            vertices[index].Position = new Vector3(centerPos + (axisX / width) * (v - width / 2) + (axisZ / height) * (u - height / 2));

            index++;
        }
    }
}
</pre>
<p><BR><br />
Calling this function 6 times passing in the correct local orientations should produce a cube made up of 6 grids of vertices like this, where the red denotes the local X axis and the blue denotes the local Z axis.  The back faces are missing in the diagram:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=cube.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/cube.jpg" border="0" alt="Photobucket"></a></p>
<p><BR><br />
Based on the size of the cube which we calculated above, you should ensure that when defining a quadtree cube face, at least one component is equal to CubeSize / 2, and that the other two components are CubeSize.  This will help created a closed cube.</p>
<p><BR><br />
<strong><font color="white">Making the World Round:</font></strong><br />
Projecting the vertices from a cube out to a sphere is very easy.  Consider the following diagram and the instructions to see how to do this:</p>
<p><a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=makingitspherical.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/makingitspherical.jpg" border="0" alt="Photobucket"></a></p>
<p>1) Center the cube on zero (0,0,0).<br />
2) Normalize each vertex in the grid.  This will create a unit sphere.<br />
3) Multiply the vertex position by the radius of the planet + the height of the terrain at this point, which will scale the sphere to the desired dimensions of your planet.</p>
<p>and all this convets to a simple function:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
private Vector3 GetWorldSpaceCoordinate(Vector3 cubePos, float height)
{
    cubePos.Normalize();
    return cubePos * _fRadius + height;
}
</pre>
<p><BR><br />
The height above can come from a variety of sources.  I use 3d perlin noise in a number of shaders which render the heightmaps for each patch to several rendertargets of varing sizes.  I then use the corresponding texture values are coord U,V to get the height for the terrain grid at X,Y.  As long as the size of the rendertarget matches the patch nodes this seems to work fine.</p>
<p>Following the above instructions, you should be able to generate spheres which resemble the following image:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=SphericalGrid.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/SphericalGrid.jpg" border="0" alt="Photobucket"></a></p>
<p><BR><br />
<strong><font color="white">LOD Selection:</font></strong><br />
As with everything else, there are numerous methods for calculating when to split each quadtree node into smaller pieces.  I don't think this has to be particularly complicated to get good results.  One thing I would suggest though is splitting the nodes of the quadtree based on the distance from the camara to the center of the closest edge on the bounding box.  Using calculations which depend on the distance of the camera from the center of the node can cause huge differences at higher LOD levels when the camera is stradling the borders of nodes.</p>
<p><BR><br />
<strong><font color="white">Other Little bits:</font></strong><br />
Of course this article only outlines the way I have defined planet mesh geometry and there are still many things left to do after this.  Here are a few of the many things needed to get this geometry resembling a planet:</p>
<p><BR><br />
<a href="http://britonia-game.com/?p=60">CPU heightmaps</a> - I wrote this article to describe how to generate heightmap textures using the CPU.</p>
<p><a href="http://britonia-game.com/?p=207">GPU heightmaps</a> - the same again, just adapted to work on the GPU</p>
<p><a href="http://britonia-game.com/?p=24">Real Scales and Imprecision</a> - If you want to create realistically scaled planets, you will inevitably encounter issues with 32-bit imprecission which I discuss a little in this article.</p>
<p><a href="http://britonia-game.com/?p=251">Depth Buffers</a> - This is another important issue when using realistic scales because all that distance between planets wont fit correctly into a 16-bit / 32-bit depth buffer.</p>
]]></content:encoded>
			<wfw:commentRss>http://britonia-game.com/?feed=rss2&amp;p=448</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Ship Thrusters and Fuel Consumption</title>
		<link>http://britonia-game.com/?p=436</link>
		<comments>http://britonia-game.com/?p=436#comments</comments>
		<pubDate>Thu, 29 Apr 2010 15:48:59 +0000</pubDate>
		<dc:creator>Lintfordpickle</dc:creator>
				<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://britonia-game.com/?p=436</guid>
		<description><![CDATA[I decided to write this article in response to a comment by Robert on my previous &#8216;Ship Lists&#8217; article. He brought up the fact that just calculating the specific physical properties of a ship doesn&#8217;t tell the whole story of space flight without first considering fuel and payload. You can read the original comment here. [...]]]></description>
			<content:encoded><![CDATA[<p>I decided to write this article in response to a comment by <a href="http://www.liandri.org/">Robert</a> on my previous &#8216;Ship Lists&#8217; article.  He brought up the fact that just calculating the specific physical properties of a ship doesn&#8217;t tell the whole story of space flight without first considering fuel and payload.  You can read the <a href="http://britonia-game.com/?p=379">original comment here.</a></p>
<p>Quite honestly I glossed over the fuel and payload section in the previous article because I knew it would be a problem and I hadn&#8217;t quite decided yet how to handle the issues in-game.  The question is of course &#8220;how realistic will the game be in terms of fuel and fuel consumption&#8221;? and &#8220;will be by fun/entertaining for the player to fill up the cargo hold full of fuel just to be able to leave the atmosphere of a planet&#8221;?  </p>
<p><BR><br />
The three approaches which are most obvious at this stage are:</p>
<p><font  color="white"><strong>1) Simulate Realistic Physics and Fuel Consumption :</strong></font> This is certainly an appealing approach and a lot of people would perhaps admire such a simulation for its realism, but will definately be off-putting for casual gamers.  Furthermore, accurately simulating spacecraft using real physics models is extremely complex and involve many factors; all of which aren&#8217;t really feasible or a benefit to simulate.  This would also introduce issues of ship design.  As an example, the thrusters required for huge spacecraft to launch would themselves be huge; and would have to appear to scale on the ship.  Add to this the need to place thrusters all around the ship for rotating and &#8216;strafing&#8217; etc. and the ships will no longer look slick and cool (yes cool) but like big masses of ugly efficient-functionality.</p>
<p>A few other less-than-fun issues introduced with this system are &#8216;what do you do if the player runs out of fuel?&#8217;  As always there are a few ways of handling this, but short of actually waiting for someone to come and pick you up would break the realism we were striving to achive in the first place.  This is a concern.</p>
<p><font  color="white"><strong>2) Forgo Fuel Consumption:</strong></font> This approach was adopted in the Elite series whereby conventional thrusters didn&#8217;t require fuel for acceleration; and this definiately had its merits.  For one, the player only needed to concern his/herself with purchasing fuel for hyperjumps to use the jump drive and there was nothing overly complicated with taking off and leaving a planet.  Just &#8216;launch&#8217;, rotate the ship upwards and fire!  As you can read in Robert&#8217;s previous comments, this eliminates the issue of taking off within a the gravational area of a planet.</p>
<p><font  color="white"><strong>3) Use a mixture of the two above.</strong></font> : Now I&#8217;m all for realism and I&#8217;ve read a lot of comments which go both ways on just how real to simulate things like this, but I&#8217;m just not convinced that simulating real space flight dynamics will be fun for the player.  Also, to pass up the issue of fuel will remove some of the element of &#8216;danger&#8217; and planning I think has the potential to be enjoyable.  So at the minute I plan on using a mixture of the above, but perhaps a little differently than tradional space sim games.</p>
<p><BR><br />
I am thinking about including three different engines types for flight, each of which will be mountable in one ship thruster slow/position.  Here are the three types (not including Jump-Drives):</p>
<p><BR><br />
<font size=+1  color="white"><strong>ION/Plasma Trusters</strong></font></p>
<p><a href="http://en.wikipedia.org/wiki/Ion_thruster">ION thrusters</a> are used in real life for long distance space flight.  They are typically favoured because of the relatively low fuel consumption when compared to traditional chemical engines.  This improvement in fuel consumption is because electic thrusters typically offer much higher specific impulse (this represents the change in momentum per unit amount of fuel).</p>
<p>There are a few draw backs with ION thrusters though, which when implemented in the game will lucky add a little diversity.  The first draw back is that they don&#8217;t provide as much thrust compared to chemical thrusters due to practical power source contraints.  The second draw back is that they only work in environments that are void of ionized particles, so if you decide to equip just ION thrusters on your ship, you wont be able to land on planets with atmospheres.</p>
<p>There are three kinds of ION thruster in real life (Electromagnetic,  Electrothermal/Plasma and Electrostatic). There will be diferent ION trusters available within the game but the differences will be purely cosmetic (different thruster description, different coloured beam), with all thrusters performing with the same characteristics:</p>
<p><font  color="white"><strong>Pros :</strong></font><br />
	Low fuel consumption (read: no-fuel consumption)</p>
<p><font  color="white"><strong>Cons :</strong></font><br />
	Cannot fly within atmosheres<br />
	Low thrust (force) output</p>
<p><font  color="white"><strong>Summary :</strong></font><br />
	A good option for beginning players as the there is no need to worry about fuel consumption and/or running out.  Hopefully more experienced players will want to eventually opt for more power chemical thrusters for greater acceration.</p>
<p><BR><br />
<font size=+1  color="white"><strong>Chemical Rocket Thrusters</strong></font></p>
<p>Currently all spacecraft use <a href="http://en.wikipedia.org/wiki/Rocket_engine">chemical rockets</a> for launch.  Chemical thrusters require a large amount of fuel to operate, but provide consideratly more thrust than ION thrusters.  In the context of the game, chemical thrusters will be required to navigate within the atmosphere of a planet, and will indeed require fuel to do so, although the fuel consumption may not be realistic:  </p>
<p><font  color="white"><strong>Pros :</strong></font><br />
	Provides much more power compared to the ION thruster.<br />
	Functions in atmospheric conditions (i.e. planets with atmospheres).</p>
<p><font  color="white"><strong>Cons :</strong></font><br />
	Requires fuel.<br />
        Would be plausible that the player can run-out of fuel and thus would need rescuing.</p>
<p><font  color="white"><strong>Summary :</strong></font><br />
	A good choice for players who want faster ships but requires a little more journey planning and management of fuel.</p>
<p><BR><br />
<font size=+1  color="white"><strong>Hybrid Thrusters</strong></font><br />
Whilst perhaps not currently technically possible I would like to include some kind of hybrid technology to make the game more sympathetic to new players who perhaps don&#8217;t want the hassile of outfitting different ships and just want to &#8216;shoot things&#8217;.  The hybrid engines will non consume fuel in outerspace, and will require significantly less fuel when within a gravatational area.  This will come at the expense of having significantly lower thrust outputs then the chemical or ION/plasma thrusters.</p>
<p><font  color="white"><strong>Pros :</strong></font><br />
	Offers both the benefit of power provided by the chemical engine and the ease of mind of a fuel-less alternative for emergencies.<br />
	No restricts on environment conditions</p>
<p><font  color="white"><strong>Cons :</strong></font><br />
	Provides less acceleration than either the electric or chemical engines of the same class.</p>
<p><BR><br />
<font size=+1  color="white"><strong>To Sum Up</strong></font></p>
<p>So hopefully with the details mentioned above it should be a little clearer to see what I intend to do.  If you decide you want to outfit one ship for space dog-fighting, then you may want to use chemical rocket engines and refuel often for the advantage of higher accelertion.  If you are a trader, then perhaps ION thrusters would be beneficial considering you needn&#8217;t worry about fuel on long journeys.  The last question which I haven&#8217;t address yet is the actual consumption of the chemical engines, however this will be fun-factor based so its a little too early to say.</p>
<p>-John</p>
]]></content:encoded>
			<wfw:commentRss>http://britonia-game.com/?feed=rss2&amp;p=436</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating the Ships List &#8211; I</title>
		<link>http://britonia-game.com/?p=379</link>
		<comments>http://britonia-game.com/?p=379#comments</comments>
		<pubDate>Fri, 16 Apr 2010 15:08:23 +0000</pubDate>
		<dc:creator>Lintfordpickle</dc:creator>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Britonia Development]]></category>

		<guid isPermaLink="false">http://britonia-game.com/?p=379</guid>
		<description><![CDATA[In this article I&#8217;ll be speaking about what I&#8217;ve been up to with regards to researching and defining the dimensions and specifications of the ships and engines. I aim to have engines and ship sizes which are both believable in size and capabilities, while not necessarily being so accurate as to be confusing for the [...]]]></description>
			<content:encoded><![CDATA[<p>In this article I&#8217;ll be speaking about what I&#8217;ve been up to with regards to researching and defining the dimensions and specifications of the ships and engines.  I aim to have engines and ship sizes which are both believable in size and capabilities, while not necessarily being so accurate as to be confusing for the player.  I&#8217;m writing this simultaneously with the ships list.</p>
<p><span id="more-379"></span></p>
<p><BR><br />
<font size=+1  color="white"><strong>Aim:</strong></font></p>
<p>My aim is to make a list of ships, similar in structure the one found <a href="http://home.flash.net/~rayearle/Ffiles/Frntrl2t.html">here</a>, which should offer a good overview of the capabilities of each ship.  As the ships in HORIZONS are to be modular (with interchangable components), each component should be believable in scale and capabilities, affecting the ship as one might expect.</p>
<p><BR><br />
<font size=+1  color="white"><strong>First Stumbling Steps:</strong></font></p>
<p>What is perhaps obvious, but easily overlooked, is that the physical attributes of a ship need to be reflected in the visual representation of that ship.  Initially I created a draft of the ship list and created a nice balanced amount of varied ship classes, even going so far as to defined the hull mass, engine classes and max acceleration/thrust.<br />
When I started to model the Locust I realised that it was quite hard to get the ship to match up with my expectations on paper.  That&#8217;s not to say it isn&#8217;t possible, but I felt modelling the ship first <em>and then</em> working out a set of matching attributes based on the model would ultimately be an easier endevour.</p>
<p>So now I calculate the attributes after I have setup the basic shape of the ships in <a href="http://www.Blender3D.org">Blender3D</a>, making sure that have the same dimenions as when they appear in game.  As an example of a scout ship, the &#8216;Locust&#8217; ship has dimensions of 26m / 12m / 6m, with 2 static hardpoints and 1 turret.</p>
<p><BR><br />
<font size=+1 color="white"><strong>Mass, Volume and Density:</strong></font></p>
<p>My first step was to look at what is needed to work out the acceleration of an object, as I was eager to define how fast each ship would be in-game.  This is given by the simple formula:</p>
<p><a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/?action=view&#038;current=b32480ecabf43568c4b8b99d83d62f69.png" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/b32480ecabf43568c4b8b99d83d62f69.png" border="0" alt="Photobucket"></a></p>
<p>The force (F) will be defined by the engine class and number of engines on the ship, so we can come back to this a little later. But first I would like to look at the volume and mass (m).</p>
<p>So how do you calculate the mass of an object?  A quick google search will reveal that mass is measured in Kg, and that mass is equal to the volume of the object multiplied by its density.  Well the density of an object is defined by the density of the materials used to make the object.  There will be six main parts which make up a ship in HORIZONS, so is the break down of what makes up the ships:</p>
<p><BR><br />
<strong><font size=+1  color="white">Hull:</font></strong> The shell of the ship, the hull, defines the basic hit-points (tons).  All ship hulls in HORIZONS will be constructed from <a href="http://en.wikipedia.org/wiki/Aluminium">aluminium</a>, which has a density of 2700 Kg/m3.  Taking the volume of the Locust, mentioned above, with a hull thickness of 5cm, the mass would be 135845.2Kg, or 133.7 tonnes (long)</p>
<p>There will also be an option of adding armour plating to the hull of a ship.  Armour plating will be made of <a href="http://en.wikipedia.org/wiki/Steel">steel</a>, which has a much higher density at 7850 Kg/m3 which should add a significant amount of tonnage.</p>
<p>It is obvious that just using the rectangle dimensions of the ship is not the most accurate (indeed it is actually quite inaccurate) but it will suffice for my uses as at least the ships will all have a relative amount of inaccuracy in their total masses.  It will of course be possible to tweak the overall masses etc. later for balancing out issues and inconsistancies.</p>
<p><BR><br />
<strong><font size=+1  color="white">Generators :</font></strong> Generators produce electrical energy for use by the different components of the ship.  The power generators will be constructed from <a href="http://en.wikipedia.org/wiki/Steel">steel</a>.  </p>
<p><BR><br />
<strong><font size=+1  color="white">Engine:</font> </strong> There are two different engines available; sub-light engines for relatively short distances of say, within a solar system, and then there&#8217;s jump drive engines.  Both types of engine will be constructed from steel, although it is very likely I&#8217;ll change the mass of the engines to tweak performace of the ships.</p>
<p>The engines will not take electrical power directly from the power generators, and so will work independantly, running on there own powers sources (hydrogen fuel, nuclear cells or whatever).</p>
<p><BR><br />
<strong><font size=+1  color="white">Components:</font></strong> There are many different components available, each adding different perks and features to your ship.  Component material is mainly <a href="http://en.wikipedia.org/wiki/Polyetheretherketone">Polyetheretherketone</a>, which is a plastic with a density of 1320Kg/m3.  The components will require a specific amount of electrical power to function.</p>
<p><BR><br />
<strong><font size=+1  color="white">Turrets/Pylons:</font></strong> Both turrets and missile pylons will be constrcted from steel again with a density of 8850Kg/m3.  I have picked a high density for turrets and missile pylons because heavily armed ships should really have a handicapped acceleration.</p>
<p><BR><br />
<strong><font size=+1  color="white">Static Hardpoints:</font></strong> The static hardpoints on the ships are what you fire when in the main view first person mode.  The number of hardpoints will vary, but typically a ship will have either 2 or 4.  For mass and density, they will be comparable to the turrets.</p>
<p>n.b. obviously the density of metals can vary depending on various alloying elements added (tungsten or chrome for example), but these values are taken for simplicities sake.</p>
<p><BR><br />
So that&#8217;s the different parts of the ship covered, let&#8217;s move onto the actual mass of the ship.  We can&#8217;t just calculate the ship&#8217;s mass from its volume (width*height*length) * denstiy, as this will give the density of a solid object.  For this reason it is necessary to calculate two volumes, one for the outer volume of the hull and the other for the inner volume; the empty space.  I do this by assigning a wall thickness parameter to the ship, which can be scaled by the player (for a cost in the ship yard) to gear the ship up as either a heavier, more armoured craft or a lightly amoured affair with a faster acceleration.</p>
<p>I mentioned above that I will be using steel as extra plating which can be installed around the ship to increase the hit points.  The plating added to a ship will be measured percentage (0% plated &#8211; 100% plated).  As with the hull thickness, the amount of plating (which has a high density) can be added to increase hit points at the expense of acceleration.  This will be available to players in the ship yards.</p>
<p>So now I have the mass of the empty ship (Kg) minus all turrets and components still, as well as the internal space (inner volume m3).  We still need to work out two more factors which weigh into the overall mass of the ship, those being fuel and payload.  I will not show that here, but instead cover cargo a bit further on as the fuel and cargo will also affect the acceleration of your ship when playing as they affect the overall mass of your ship.</p>
<p>As you can see though, to get the total mass we need to take the hull, components, hardpoints, engines and interior objects into account.</p>
<p><BR><br />
Next up is to define the Force that can be applied on the ship, then hopefully I&#8217;ll be able to work out some actual values for acceleration.</p>
<p><BR><br />
<font size=+1 color="white"><strong>Engines and Force</strong></font></p>
<p>I have created a first draft of proposed engine sizes and thrust generated.  I got the values for the engines based on the  <a href="http://en.wikipedia.org/wiki/Rocketdyne">Rocketdyne Wikipage</a> and this <a href="http://www.grc.nasa.gov/WWW/K-12/BGP/Donna/t_w_ratio_answers.htm">Boeing page</a> but I&#8217;ll undoubtidely have to change them when I have larger craft to fly because these are totally untested.  Here is an example of Engine classes and the thrust they produce:</p>
<table border="1">
<tr>
<td>Class</td>
<td>Thrust (N)</td>
</tr>
<tr>
<td>E7</td>
<td>670 KN</td>
</tr>
<tr>
<td>E6</td>
<td>980 KN</td>
</tr>
<tr>
<td>E5</td>
<td>200 MN</td>
</tr>
<tr>
<td>E4</td>
<td>350 MN</td>
</tr>
<tr>
<td>E3</td>
<td>530 MN</td>
</tr>
<tr>
<td>E2</td>
<td>770 MN</td>
</tr>
<tr>
<td>E1</td>
<td>1 GN</td>
</tr>
<tr>
<td>E0</td>
<td>7 GN</td>
</tr>
</table>
<p>n.b. the SI for force is Newtons (kilo-, mega- giga-)</p>
<p>So now we should be able to calculate the acceleration of a ship based on the engine class installed in the ship and its total mass.  Bare in mind that this is just the sub-light thrusters, and the jump-drives will not be influenced by the mass of the ship itself, but rather the mass of the target and the distance.</p>
<p>So, looking back, we get the acceleration from</p>
<p><a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/?action=view&#038;current=b32480ecabf43568c4b8b99d83d62f69.png" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/b32480ecabf43568c4b8b99d83d62f69.png" border="0" alt="Photobucket"></a></p>
<p>Let&#8217;s take a look at the Locust MK I ship.  it has by default 2 E7 class engine thrusters:</p>
<table border="1">
<tr>
<td><strong>Ship Name</strong></td>
<td><strong>Dimensions (m)</strong></td>
<td><strong>Hull Thickness(cm)</strong></td>
<td><strong>Num Engines</strong></td>
<td><strong>Indiv. Engine Thrust</strong></td>
<td><strong>Total Engine Thrust</strong></td>
<td><strong>Mass</strong></td>
<td><strong>Max Acceleration</strong></td>
</tr>
<tr>
<td> Locust MK I  </td>
<td>26m x 12m x 6m</td>
<td>10cm</td>
<td>3 (E7)</td>
<td>670,000 N</td>
<td>2010000 N</td>
<td>135845.2 Kg</td>
<td>F/m = 14.7963 m/s2</td>
</tr>
</table>
<p>And lets take a look at possibly one of the much larger ships in the game :</p>
<table border="1">
<tr>
<td>Ship Name</td>
<td>Dimensions (m)</td>
<td>Hull Thickness(cm)</td>
<td>Num Engines</td>
<td>Indiv. Engine Thrust</td>
<td>Total Engine Thrust</td>
<td>Mass</td>
<td>Max Acceleration</td>
</tr>
<tr>
<td> Big Battlestation</td>
<td>4,500m x 750m x 900m</td>
<td>120cm</td>
<td>12 (E1)</td>
<td>1,000,000,000 N</td>
<td>12,000,000,000 N</td>
<td>76232496100 Kg</td>
<td>F/m = 0.1536 m/s2</td>
</tr>
</table>
<p>And that&#8217;s pretty much how I plan on working out the acceleration when I create the rest of the ships.</p>
<p>I will cover jump drives in a later article, when I have made some more progress on the octree scene graph and galaxy generation.</p>
<p><BR><br />
<font size=+1 color="white"><strong>Cargobay, Components and Life Support</strong></font></p>
<p>Lastly I&#8217;d just like to cover some ideas I had for the cargo and transportation with the ship.</p>
<p>As you can see above I already have the interior volume.  The interior of the ship will be split into three areas.<br />
Here&#8217;s how I plan on assigning the interior space:</p>
<p><BR><br />
<strong><font size=+1  color="white">Life Support:</font> </strong> For each crew member and/or passenger seat on the ship an area of 4m3 will be set aside and used as living space.  Living quarters will be needed for all crew, passengers, captured pilots and purchasing slaves from the outer colonies on the black market.  So, if you have a small ship with only 4 meters^2, then you cannot pick up passenger missions because as the pilot you&#8217;ll already be using the living space.</p>
<p>It will be possible to extend the life support on your ship, but you&#8217;ll end up eating into the cargo bay space.<br />
Life support will be measured in seats, with passengers and pilots taking 4 square meters.  Space slaves and hostages will take 2 square meters.</p>
<p><BR><br />
<strong><font size=+1  color="white">Components:</font> </strong> In order to install additional components to your ship, you&#8217;ll need to ensure that you have the following:</p>
<ol>Enough space to install the component (taking from the interal volume)</ol>
<ol>A free component interface</ol>
<ol>Enough free electrical power</ol>
<p>Each of these 3 points are actually quite flexible, and providing the player has enough credits they&#8217;ll be able to install extra component interfaces for a fee (which increases with the total amount of interfaces already on the ship).  </p>
<p>There is a difference here between the space required and an interface.  The space will come directly out of the interior volume of your ship (so again eating your cargo space), but further to this, if you want to install 6 components you&#8217;ll have to first install 6 component interfaces.</p>
<p><BR><br />
<strong><font size=+1  color="white">Cargohold :</font> </strong></p>
<p>The remaining interior volume will be assigned as the cargohold (m^3), and it will be here that any trade goods will be held when transporting.  The amount of trade goods you can transport will be restricted only to the volume (not the mass/weight).</p>
<p>When purchasing and outfitting your ship, you&#8217;ll be able to set the percentage of interior volume (minus the life support) which will be assigned between cargo space and component space.</p>
<p><BR><br />
And thats about it.  One thing I&#8217;d like to say is that most of the information is based on what I have recently read on various websites (after apparently not paying enough in physics class at school).  If you happen to see any thing above that is plainly just wrong, or you feel could be done better then I appreciate any comments.</p>
<p>-John</p>
]]></content:encoded>
			<wfw:commentRss>http://britonia-game.com/?feed=rss2&amp;p=379</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Blender3D and XNA</title>
		<link>http://britonia-game.com/?p=333</link>
		<comments>http://britonia-game.com/?p=333#comments</comments>
		<pubDate>Mon, 29 Mar 2010 10:30:04 +0000</pubDate>
		<dc:creator>Lintfordpickle</dc:creator>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://britonia-game.com/?p=333</guid>
		<description><![CDATA[For the last three weeks I have started modeling the first in-game content for Horizons, the &#8216;Locust MK I&#8217;, using Blender3D and paint.NET. This time round, I&#8217;ll go over how I am exporting model and opaque data from blender, texturing the model with UV maps and paint.NET and importing them into XNA. Well, the time [...]]]></description>
			<content:encoded><![CDATA[<p>For the last three weeks I have started modeling the first in-game content for Horizons, the &#8216;Locust MK I&#8217;, using Blender3D and paint.NET.  This time round, I&#8217;ll go over how I am exporting model and opaque data from blender, texturing the model with UV maps and paint.NET and importing them into XNA.</p>
<p><span id="more-333"></span></p>
<p><BR><br />
Well, the time has finally come that I have started to model and texture in-game content.  This is the bane of the hobbyist programmer, but time and consideration are definitely in order when modeling content because if it doesn&#8217;t look good, nobody is going to want to play your game (oh how I loved the Amiga, when it wasn&#8217;t about graphics, it was about gameplay).</p>
<p>For me the decision to go with a particular set of software is usually pretty easy; the less it costs, the more likely I am to give it a chance.  Hey, I&#8217;m not a professional programmer, nor am I an artist and as Britonia is purely a hobby project, its just not viable to spend €1000s on professional software packages.  But alas, that doesn&#8217;t mean that I have to use a sub-standard set of tools.</p>
<p><BR><br />
<strong>Modelling:</strong></p>
<p>Many times when I browse any XNA forums, I run accross the same topics: &#8220;Which 3d modelling program is best?&#8221;, so this is where I&#8217;ll give my 2 cents and also run through some of the features which I have used so far, and how they can be used in conjuction with XNA.  </p>
<p>As stated above, my modeling tool of choice is Blender3d (<a href="http://www.blender.org/">website</a>).  The biggest negative point mentioned in the forums for Blender is that the learning curve is too hard, but I honestly don&#8217;t think its any harder than learning 3ds max.  Whether a beginner chooses to use Blender or Maya/3ds max it is going to be hard and time consuming; but that&#8217;s modelling.  Its just a question of which product you choose to invest more time in.  After a little while, and a run through the tutorials I found the blender interface quite intuitive; and it certainly doesn&#8217;t fall short on the features list.</p>
<p>One change I would definitely recommend making though is to modify the FBX export script to include opaque data when exporting to FBX files.  Opaque data are values which can be assigned to individual meshes within blender (and then imported with the model in the content pipeline).  This is pretty good because it allows the designer to specify different contraints on different meshes.  For example, in this video (<a href="http://www.youtube.com/watch?v=c6OnpytzV3k">youtube link</a>), you can see I have put white planes on the top of the ship which are to be turret points; and within the opaque data fields for this mesh I have specified:</p>
<p>Name: Turret<br />
Size: 1<br />
MeshName: <><br />
&#8230;</p>
<p>This is then read in in the content processor and used to fill a ship attributes class which is then stored in the Model.Tag.   So the content pipeline can see from this example that this is a turret mount point, with size and the name of the mesh.  I can then use the AbsoluteBoneTransform for this mesh when drawing a turret model and it should appear on the ship.</p>
<p><BR><br />
<strong>Exporting Opaque Data:</strong></p>
<p>Opaque data is not automatically exported with the default FBX export script, so we do have to make a few changes.  I found a nice article about modifing the export script to include this data (<a href="http://projectcyl.wordpress.com/2008/12/16/exporting-object-properties-with-blender/">link here</a>).  (thanks to Ronzan for giving me the link, and Kibix for writing it).</p>
<p>You can get a modifed version of the FBX exporter from that website, but I actually had a few problems with that exporter as it is, so I had to copy just the following parts into an unmodified version of the default FBX export script:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
# Edit by Kibix
// This is the part which writes the opaque data to the FBX file
properties = ob.getAllProperties()
for property in properties:
    if(property.getType() == "STRING"):
        file.write('\n\t\t\tProperty: "%s", "enum", "A+U", 0, "%s"' % (property.getName(), property.getData()))
    if(property.getType() == "FLOAT"):
        file.write('\n\t\t\tProperty: "%s", "float", "A+U", %s' % (property.getName(), property.getData()))
    if(property.getType() == "INT"):
        file.write('\n\t\t\tProperty: "%s", "int", "A+U", %s' % (property.getName(), property.getData()))
    if(property.getType() == "BOOL"):
        file.write('\n\t\t\tProperty: "%s", "bool", "A+U", %s' % (property.getName(), property.getData()))

End of edit
</pre>
<p>I&#8217;m not sure yet why it didn&#8217;t work, but you can see the author has made a few other changes to the exporter.  This was a quick fix for me and with this small change, you should be ready to go.</p>
<p>To actually add the opaque data within blender you must go to &#8216;object mode&#8217; (where selected objects have a pink outline) and open the logic tooltab (the pacman icon), which should look like this:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=blender3d_logictab.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/blender3d_logictab.jpg" border="0" alt="Photobucket"></a></p>
<p>You can see the options on the left handside of the tab to add strings, ints, floats, bools etc. to the mesh data.</p>
<p>To test this out, you could create a cube object and add some opaque data to the mesh.  Then use your new export script to create an ASCII FBX file which you can open in a texteditor.  You should then be able to see the following information in the new file like this :</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=fbxfile_acsii.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/fbxfile_acsii.jpg" border="0" alt="Photobucket"></a></p>
<p><BR><br />
<strong>Importing into XNA :</strong></p>
<p>Importing into XNA also requires a little work in the content pipeline, as the default FBX processor will not read the opaque data we just added to the FBX file.  Luckily this change is pretty easy.  Just create a new content pipeline importer and derive from the ProcessModel function and make the following changes:</p>
<p><BR><br />
<em>ContentProcessor.cs</em></p>
<pre name="code" class="c-sharp">
public override ModelContent Process(NodeContent input, ContentProcessorContext context)
{
    // Uncomment out if you want to debug (JIT)
    // System.Diagnostics.Debugger.Launch();

    SpaceShipAttributes _ShipAttributes = new SpaceShipAttributes();
    ModelContent model = base.Process(input, context);

    for (int i = 0; i < input.Children.Count; i++)
    {
        NodeContent node = input.Children[i];
        ReadShipInformation(ref _ShipAttributes, i, node);
    }

    // Copy the attributes into the model.tag property object.
    model.Tag = (SpaceShipAttributes)_ShipAttributes;
    return model;
}

private void ReadShipInformation(ref SpaceShipAttributes shipAttributes, int index, NodeContent node)
{
    if (node.OpaqueData.ContainsKey("ShipName"))
    {
        shipAttributes.ShipName = (string)node.OpaqueData["ShipName"];
    }
}
</pre>
<p><BR><br />
You can see here that we search each of the model's mesh nodes to see if they contain any of the tags which we predefined.  In this case, I am just searching for the shipname, which will be stored in the ShipAttributes class object.  If the node does, then we can read this data and store it in our own class.  Finally, this class is then casted in the Model.Tag.</p>
<p><BR><br />
<strong>A few things to watch for in Blender:</strong></p>
<p><BR><br />
<strong>Keeping an Eye on the current 'Space':</strong></p>
<p>For anybody who has used directX or XNA this is perhaps a no-brainer but I thought I would mention about the differences between working in world space and object space.  When creating your model, there are two spaces which you work within (at least, there are two which are exported to XNA), the first is called the world space and the second is the object space.</p>
<p>The <strong>world space</strong> is where the position, rotation and scale of the meshes are stored in world coordinates relative to the origin (0,0,0).  The world space is changed when you move the model in 'object mode' within blender.  You can see the axis of the model in world space below:</p>
<p><a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=blender_Worldspace.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/blender_Worldspace.jpg" border="0" alt="Photobucket"></a></p>
<p>Any transforms (translation, rotation and scale) made in object space will be stored in the AbsoluteBoneTransforms matrices in the model.</p>
<p><BR><br />
The <strong>object space</strong> is where the position, rotation and scale of the individual vertices are stored in object coordinates, that is, coordinates relative to the object origin (0,0,0).  The object positions are changed when you are in 'edit' mode within blender and you move the individual vertices, as below:</p>
<p><a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=blender_Objectspace.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/blender_Objectspace.jpg" border="0" alt="Photobucket"></a></p>
<p><BR><br />
Each vertex is actually already stored in object space, so there really isn't anything to do there, but you must remember to pass the correct world matrix to your effect when rendering each mesh.  As you can see in almost all the 3d samples on the creators club, this is done so:</p>
<p><BR></p>
<pre name="code" class="c-sharp">

// Copy the world transform into an arry of matrices.
_ShipModel.CopyAbsoluteBoneTransformsTo(_Transforms);

foreach (ModelMesh mesh in _ShipModel.Meshes)
{
  worldMatrix = _Transforms[mesh.ParentBone.Index];

  foreach (ModelMeshPart part in mesh.MeshParts)
  {
     Effect currentEffect = part.Effect;

     currentEffect.Parameters["xWorld"].SetValue(worldMatrix); // world matrix
     currentEffect.Parameters["xView"].SetValue(camera.View);
     currentEffect.Parameters["xProjection"].SetValue(camera.Projection);
  }

  mesh.Draw();
}
</pre>
<p><BR><br />
So with this in mind you can see that we can get the correct positions for all meshes (including our place holders) relative to the model.</p>
<p><BR><br />
<strong>UV Mapping:</strong><br />
Another big hurdle is how to UV map you models.  I guess there are many different ways and you'll only find which one best suits you by trying it out, but here is how I do it ...</p>
<p>Load up your model and centre on it in the 3D view.  Now if you right click on the seperator between the toolview and 3d view you can split the view port, then you should have something like this:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=blender3d_splitwindow.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/blender3d_splitwindow.jpg" border="0" alt="Photobucket"></a></p>
<p>I find this view makes it much easier to work with.  Now, I like to use the projective UV map button for actually defining the UV coordaintes.  Using the numpad, start off with the top (num7), then select the faces which you want to appear as an area within the UV map:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=blender3d_projectfromview.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/blender3d_projectfromview.jpg" border="0" alt="Photobucket"></a></p>
<p>Then press 'U' and choose 'project from this view'.  You can see that the same area is displayed in the UV screen, where you will be able to scale and move the selection around the texture reactangle. This process should be repeated for each of the faces in model, until every face has a unique area on the UV map (unless of course they should be sharing the same texture information).  This is an example:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/Articles/?action=view&#038;current=blender3d_uving.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/Articles/blender3d_uving.jpg" border="0" alt="Photobucket"></a></p>
<p>When you export this FBX file, the UV coordinates for each triangle will be saved in the vertex data.  Then you can use the TEXCOORD symentics in HLSL to properly texture each face.</p>
<p><BR><br />
<strong>Scaling:</strong></p>
<p>The last thing to note on the blender side is that models exported with the default FBX exporter need to be scaled down in XNA by 0.01f to get a 1:1 blender / xna unit scale.  It is possible to do this scaling in many different places, either in the content file properties in VS, or in the exporter OR manually before rendering the object, like this:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
worldMatrix = _Transforms[mesh.ParentBone.Index] * Matrix.CreateScale(0.01f);

// pass world mat to effect when rendering mesh
</pre>
<p><BR><br />
Well, that's it for now.  If you have any questions about the blender / XNA process then just leave a comment here or in the forums and as always I'll try and answer.</p>
<p>I have added a new page to the screenshots section on the site where I'll upload shots of ships as I make them.</p>
<p>-John</p>
]]></content:encoded>
			<wfw:commentRss>http://britonia-game.com/?feed=rss2&amp;p=333</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>SVN and Trac</title>
		<link>http://britonia-game.com/?p=326</link>
		<comments>http://britonia-game.com/?p=326#comments</comments>
		<pubDate>Mon, 29 Mar 2010 10:01:32 +0000</pubDate>
		<dc:creator>Lintfordpickle</dc:creator>
				<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://britonia-game.com/?p=326</guid>
		<description><![CDATA[A lot of developers I speak to often ask if I use a form of SVN (SVN wikipedia) and when I answer in the negative, they usually tell me of the benefits of doing so. Now I haven&#8217;t used it (much) before and I&#8217;ve never really had a reason to, being that I am working [...]]]></description>
			<content:encoded><![CDATA[<p>A lot of developers I speak to often ask if I use a form of SVN (<a href="http://en.wikipedia.org/wiki/Subversion_%28software%29">SVN wikipedia</a>) and when I answer in the negative, they usually tell me of the benefits of doing so.  Now I haven&#8217;t used it (much) before and I&#8217;ve never really had a reason to, being that I am working alone on Britonia and I only really use my main computer for development.  But I thought, if everyone&#8217;s doing it, maybe there are unseen benefits &#8230;</p>
<p>So I had a look around on the weekend for project hosting sites which offered free hosting using SVN, and I found a few.  Many of the project hosting sites however only offer only free hosting to open source projects, but I did manage to find one called <a href="http://www.projectlocker.com/">ProjectLocker</a>.  It seems to have everything I could need for hosting my project privately and it also offers an intergrating Trac system.  So I thought I&#8217;d give it a go.</p>
<p>For anybody who hasn&#8217;t heard of SVN, basically it offers a way to host your entire project (minus build and object files) on a server and using a tool like TortoiseSVN in windows, you can quick and easily download (checkout) or backup (commit) changes to this one central repository.  It also keeps a copy of all versions of a file and logs changes made.  </p>
<p>This makes it easy if say, you want to work on your project from several locations, or you have multiple developers working on a project.</p>
<p>For now, while I still haven&#8217;t setup it all up &#8211; I am hoping that the Trac system will help me focus on specific enhancements and bugs in Britonia.  I&#8217;m finding that when I sit down I spend a good 1-2 hours just playing with what is already &#8216;working&#8217;; tweaking the heightmaps, changing scattering colours, flying around the planets etc.</p>
<p><BR><br />
If you want to try it out, here are a few links to the tools which I am using :</p>
<p>TortoiseSVN: <a href="http://tortoisesvn.tigris.org/">http://tortoisesvn.tigris.org/</a><br />
This can be used to quickly upload/download files in your project.</p>
<p>AnkhSVN: <a href="http://ankhsvn.open.collab.net/">http://ankhsvn.open.collab.net/</a><br />
A plugin for Visual studio professional (does not work on VS Express <img src='http://britonia-game.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> )</p>
<p>Project Locker: <a href="http://www.projectlocker.com/">http://www.projectlocker.com/</a><br />
There are many hosting sites, but this is the one I choose because its private and free.</p>
<p>Trac: <a href="http://trac.edgewall.org">http://trac.edgewall.org</a><br />
Bug tracking system.</p>
]]></content:encoded>
			<wfw:commentRss>http://britonia-game.com/?feed=rss2&amp;p=326</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>A New Direction &#8230;</title>
		<link>http://britonia-game.com/?p=295</link>
		<comments>http://britonia-game.com/?p=295#comments</comments>
		<pubDate>Thu, 25 Feb 2010 20:02:50 +0000</pubDate>
		<dc:creator>Lintfordpickle</dc:creator>
				<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://britonia-game.com/?p=295</guid>
		<description><![CDATA[I have been thinking quite a lot recently about some of the upcoming aspects of Britonia, and some of the decisions I made at the beginning of the project.&#160; For a long time I&#8217;ve wanted to create a game with a sense of depth and emersion, somewhere you could go and play open-endedly, without a [...]]]></description>
			<content:encoded><![CDATA[<p>
I have been thinking quite a lot recently about some of the upcoming aspects of Britonia, and some of the decisions I made at the beginning of the project.&nbsp; For a long time I&#8217;ve wanted to create a game with a sense of depth and emersion, somewhere you could go and play open-endedly, without a sense of the end of the game drawing nearer the more you unraveled the story or progressed through a dungeon.&nbsp; Obviously, this is not as easy a task as it sounds, but thanks to procedural content, it is not totally out of the question.</p>
<p>I set myself no time limit for finishing the development of the game, piling on the features.&nbsp; I knew it would take a long time, but that didn&#8217;t bother me and indeed it still doesn&#8217;t; after all what is the point of making a game if you don&#8217;t enjoy it?&nbsp; </p>
<p>I spend quite a lot of my free time working on Britonia (or at least XNA related projects), but there are still a great many things required to get a full game working which I haven&#8217;t even started, and I think it would be better ( or faster) in the long run if I change the theme of the game before I get into the actual in-game content creation.</p>
<p>Therefore I am considering to change the theme / genre to a Space trading simulation, just like the old classic <a href="http://en.wikipedia.org/wiki/Elite_%28video_game%29">Elite by David Braben</a> and Ian Bell.&nbsp; </p>
<p>Luckily though, changing to a space sim wouldn&#8217;t require me to re-write reems of code, so everything I have done thus far will remain largely unchanged.&nbsp; Of course the &#8216;new&#8217; space game will have you landing in ground ports and/or flying around the surface of the planet looking for minerals and artefacts.</p>
<p><b>So why the change?</b></p>
<p>Simply put, after comparing the content required (models / textures / environments) for both a space sim and fantasy RPG, I think I have a much better chance of creating believable content for a space sim as opposed to the likes of human NPCs and monsters.&nbsp; Some of the other considerations are :</p>
<div align="center">
<table id="izy0" border="1" bordercolor="#000000" cellpadding="3" cellspacing="0" width="95%">
<tbody>
<tr>
<td>
</td>
<td style="text-align: center;" width="33.333333333333336%"><b>Medieval RPG</b>
</td>
<td style="text-align: center;" width="33.333333333333336%"><b>Space RPG</b>
</td>
</tr>
<tr>
<td><b>Planets</b>
</td>
<td width="20pt">Travel at low altitudes along the surface causes the planet quadtree to update often, and subdivision for quad nodes are always x4. Furthermore, because of the detph of the quadtree, a lot of memory is needed for the heightmaps/normal maps etc.</p>
<p>Adding to this, trees, npcs, towns and ground clutter &#8230;.</p>
<p>Planet based RPG&#8217;s don&#8217;t require realistic distances or accurate planetary movements (orbits/rotations).
</td>
<td width="33.333333333333336%">
</td>
</tr>
<tr>
<td><b>NPCs / Monsters</b>
</td>
<td width="33.333333333333336%"><b>Modeling </b>of NPC&#8217;s and Monsters is very complex, requiring many different animations (skinning).<br />
Creating <b>AI</b> to mimick human behaviour is even more difficult.</p>
<p>I don&#8217;t do faces &#8211; creating a good looking one would take me hell of a long time <img src='http://britonia-game.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> 
</td>
<td width="33.333333333333336%"><b>Modelling </b>Spaceships is conderably easier than organic lifeforms.&nbsp; AI is still a challenge, but that&#8217;s AI.</p>
<p><b>Animations </b>can be done using rigid bodies, and is typically turret points and/or landing gears.&nbsp; 
</td>
</tr>
<tr>
<td><b>Towns / Communities</b>
</td>
<td width="33.333333333333336%">A high level of unique geometry (models) would be required to create believable variation in different towns.&nbsp; Each individual building of a town in a medieval RPG would have to exist in full with all expected functions.&nbsp; (A tavern would need a bar, tables chairs etc. etc.)
</td>
<td width="33.333333333333336%">Cities can be represented with one (or a few) larger city meshes.&nbsp; Which means getting away with considerly less geometry.</p>
<p>One central spaceport <b>UI screen</b> contains all the different ammenities / services, once the player has &#8216;entered&#8217; the city.
</td>
</tr>
<tr>
<td><b>Travel / Distances</b>
</td>
<td width="33.333333333333336%">Travel between planets is achived via &#8216;stargates&#8217;.&nbsp; I do still very much like this idea.</p>
<p>Travel on the surface is slow and takes a long time.&nbsp; 
</td>
<td width="33.333333333333336%">Dude &#8211; Spaceships!
</td>
</tr>
<tr>
<td><b>Textures</b>
</td>
<td width="33.333333333333336%">Buildings are constructed from different materials each requiring a unique texture.&nbsp; Also different altitudes affect the colour of the texture (white of mountains etc.)
</td>
<td width="33.333333333333336%">It&#8217;s common knowlede that all spaces are grey with yellow windows.&nbsp; Easy
</td>
</tr>
</tbody>
</table>
</div>
<p>
I just wrote these off the top of my head, and I must admit it is hard to remain impartial after convincing myself a change is needed, but even looking at the above table I think the space sim would generally be faster and easier to implement.&nbsp; Although I made a few less-than-serious remarks above, some of the areas such as travel / distances are obviously made easier with the concept of space flight.</p>
<p>
Well, please let me know what you think because I still haven&#8217;t fully made up my mind yet.&nbsp; You have until the website theme changes to a space scene to leave me your comments <img src='http://britonia-game.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>
-John</p>
]]></content:encoded>
			<wfw:commentRss>http://britonia-game.com/?feed=rss2&amp;p=295</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Depth (Z-) Buffers</title>
		<link>http://britonia-game.com/?p=251</link>
		<comments>http://britonia-game.com/?p=251#comments</comments>
		<pubDate>Tue, 16 Feb 2010 12:47:26 +0000</pubDate>
		<dc:creator>Lintfordpickle</dc:creator>
				<category><![CDATA[Article]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://britonia-game.com/?p=251</guid>
		<description><![CDATA[As with all games, Z-buffering plays an important part when rendering the pixels to the screen. During the development of Britonia I have often run into a problems related to the Z-Buffer, so I thought it would be nice to share what I have learned about them and how to avoid these issues. What are [...]]]></description>
			<content:encoded><![CDATA[<p>As with all games, Z-buffering plays an important part when rendering the pixels to the screen.  During the development of Britonia I have often run into a problems related to the Z-Buffer, so I thought it would be nice to share what I have learned about them and how to avoid these issues.</p>
<p><span id="more-251"></span></p>
<p><BR><br />
<strong>What <em>are</em> Depth Buffers?</strong></p>
<p>Depth buffers (commonly referred to as Z- or W- buffers) are a means to check which pixels being rendered will occlude one another.  This is achieved by creating a separate surface the same size as the back(colour-) buffer where the depth of each rendered pixel is stored.  Then before any other colours competing for the same pixel are rendered, they must first pass the depth function test using the same position within the depth buffer.  Typically this check is passed if the new depth is less than or equal to the current depth in the depth buffer, although it is possible to change the pass conditions.</p>
<p>Enabling and setting the depth function with the following:</p>
<pre name="code" class="c-sharp">
// enable depth buffer checks
GraphicsDevice.RenderState.DepthBufferEnable = true;

// specify the pass criteria for pixels
GraphicsDevice.RenderState.DepthBufferFunction = CompareFunction.LessEqual;

// allow writing to the depth buffer
GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
</pre>
<p>Z-buffering is when the z component of a transformed pixel is stored as the depth.  This differs from W-buffering, which takes the homogeneous W-component as the depth value.  Because most of today&#8217;s hardware has support for Z-buffering it is the more commonly of the two.</p>
<p><BR><br />
<strong>Depth buffer Formats and Resolution:</strong></p>
<p>The precision that you will get from the depth buffer depends greatly on the format of the surface you choose to use as well as the near and far clip plane distances.  Depth buffers are non linear, and the depth stored in the depth buffer is relative to the z coordinate.  The maths can be a little confusing but put basically, you get more precision closer to the near plane as you do the further away you get.  There is a Z-buffer calculator on this site <a href="http://www.sjbaker.org/steve/omniv/love_your_z_buffer.html">here</a> so you can test it out for yourself.</p>
<p>In that article he talks about the resolution of z, so instead of covering the same equation, I thought I&#8217;d do a little picture representation of the resolution of Z:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/?action=view&#038;current=z-buffer16-bit.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/z-buffer16-bit.jpg" border="0" alt="Photobucket"></a><br />
<em>The depths are calculated using :<br />
depth value = (1 << depth_format) * ( zFar / (zFar - zNear) + zFar * zNear / (zNear - zFar) / distance_of_object )</em></p>
<p><BR><br />
The graph above shows a 16-bit depth buffer.  The closest depth (1.0f) has a value of 0, while the furthest depth (1000.0f) has a depth value of 65536 in the buffer.  As you can see on the left of the x-axis although the increments in distance are only relatively small (1.1, 1.2 etc.), we actually have a huge difference in the depth values assigned to these positions, whilst towards the furthest distances, the differences in depth value is very small.</p>
<p>Hopefully you can see form this graph the importance of selecting as high a value as possible for the zNear distance.  This is a pretty common mistake when starting out with directx/xna whereby the programmer defines a point extremely close to the camera for the zNear like 0.1f, but you can see from above that this wastes a lot of depth needlessly &#8211; especially considering that not many objects will actually be that close to the camera.</p>
<p>Similarly, you should also pick sensible values for the zFar distance.</p>
<p><BR><br />
<strong>Planet Rendering</strong></p>
<p>Of course when rendering planets, the distances involved mean you would very quickly have problems considering the depths distances involved if you were to use constant values as the near and far plane distances.  As you can imagine, this isn&#8217;t that difficult to overcome, but I wanted to mention it so you have a reference.  </p>
<p>For each individual planet in Britonia, I dynamically adjust the near and far clip plane distances based on the closest point on the planet sphere and the furthest point.  Even using 16-bit depth buffers and realistic planet sizes there are no visible artifacts (anymore).</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/?action=view&#038;current=ClipPLaneAssignment.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/ClipPLaneAssignment.jpg" border="0" alt="Photobucket"></a></p>
<p><BR><br />
<strong>Creating, Caching and Restoring the DepthBuffers</strong></p>
<p>Creating a depth buffer is very straight forward.  In XNA the depth buffer is created and on the graphics device like so:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
Graphics.GraphicsDevice.DepthStencilBuffer = new DepthStencilBuffer(Graphics.GraphicsDevice, width, height, DepthFormat.Depth16);
</pre>
<p>It is worth noting that if you wish to use a stencil buffer when rendering your scene, then this shares the same surface as the depthbuffer, and you will have to sacrifice some bits per pixel for this stencil buffer.  As example would be:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
Graphics.GraphicsDevice.DepthStencilBuffer = new DepthStencilBuffer(Graphics.GraphicsDevice, width, height, DepthFormat.Depth15Stencil1);
</pre>
<p>The last thing I&#8217;d like to mention is the ability to store the depth buffer for your scenes, which can be restored and used again later.  Again this is quite easy to do:</p>
<pre name="code" class="c-sharp">
// Cache the current depth buffer
DepthStencilBuffer old = GraphicsDevice.DepthStencilBuffer;

// Set our custom depth buffer
GraphicsDevice.DepthStencilBuffer = shadowDepthBuffer;
</pre>
<p>As an example of how this may be benefical: In britonia I store the depth buffer for each planet during the planet rendering phase.  This is then later restored when rendering the ground objects on the closest planet.  This is required because of the swapping of depth buffers with multiple planets as mentioned above.</p>
<p>I hope this article was at least partitially helpful.</p>
<p><BR><br />
If you feel like reading up some more, you can find the MSDN article <a href="http://msdn.microsoft.com/en-us/library/bb324459(VS.85).aspx">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://britonia-game.com/?feed=rss2&amp;p=251</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Procedural Generation – Textures on the GPU</title>
		<link>http://britonia-game.com/?p=207</link>
		<comments>http://britonia-game.com/?p=207#comments</comments>
		<pubDate>Mon, 01 Feb 2010 19:49:48 +0000</pubDate>
		<dc:creator>Lintfordpickle</dc:creator>
				<category><![CDATA[Procedural Content]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://britonia-game.com/?p=207</guid>
		<description><![CDATA[This small tutorial is really just an extension of the first article I wrote on 3d improved noise on the CPU.  More specifically we'll be getting it to work on the GPU this time.]]></description>
			<content:encoded><![CDATA[<p>This small tutorial is really just an extension of the first article I wrote on 3d improved noise on the CPU.  More specifically we&#8217;ll be getting it to work on the GPU this time.<br />
<span id="more-207"></span></p>
<p>In the last tutorial we looked at how improved 3d perlin noise works on the CPU, and how we can use this to generate various fractal like textures either at compile-time or run-time.  If you are not sure how perlin noise works, I would definitely recommend reading that article first <a href="http://britonia-game.com/?p=60">here</a>.  Noise on the CPU has many uses but it is slow when making multiple function calls with many octaves.  Often, you&#8217;ll find that performance will be seriously impaired when you regularly call the inoise function, but without all those extra octaves the resulting textures won&#8217;t appear all that great.  Further to this, there are some pretty cool effects which we can easily add (as long as we are sensible) when rendering models by using per-pixel noise.</p>
<p>As before, the code for generating noise can be split up into 4 sections:</p>
<ol>
<strong>1.  </strong>Getting the position within the cell and apply a fade curve to the fraction<br />
<strong>2.  </strong>Using the permutation table<br />
<strong>3.  </strong>Calculating the gradient values<br />
<strong>4.  </strong>Lerping and generating the noise</ol>
<p><BR><br />
<strong>Getting the position within the lattice:</strong></p>
<p>So the first task to calculate the position of the input value within a lattice (a 3d space).  As before, we need to find the integer position which will represent the lattice cell index.  We also need the fraction part of the input to use for the linear interpolation, and we need to remember to pass the fraction through the fade curve which will weight the fraction value towards 0 and 1 .  This is required to reduce artefacts when sampling across lattice cells which have sudden changes in gradient values.  (the fade curve function will be defined later):</p>
<p>HLSL:</p>
<pre name="code" class="c-sharp">
float3 P = fmod(floor(p), 256.0);
p -= floor(p);
float3 f = fade(p);

// Make sure that no component of the integer coordinate is larger than the
// dimensions of the permutation texture which we pass to the effect.
P = P / 256.0;
</pre>
<p><BR><br />
<strong>The permutation table:</strong></p>
<p>The first big change that is needed is the way we store the permutation table.  In the CPU version, we iterated through a for loop in the class constructor and &#8216;randomly&#8217; added the integer values between 0 &#8211; 255 to an array, which we called the permutation array.  For the GPU however, we will pass this &#8216;array&#8217; to the GPU as a texture, and use the tex2D to sample the information. Here is permTexture2D file that I be be using.</p>
<p><BR><br />
HLSL:</p>
<pre name="code" class="c-sharp">
// Hash Coordinates
float4 AA = perm2d(P.xy) + P.z;

float4 perm2d(float2 p)
{
    return tex2D(permSampler2d, p);
}
</pre>
<p>You can get a permutation texture <a href="http://britonia-game.com/Downloads/permTexture2D.dds">here</a>.</p>
<p><BR><br />
<strong>The Gradients:</strong></p>
<p>Again, looking back to the CPU tutorial, we calculated the gradients at each position in the lattice using the grad() function.  This used some fancy bit manipulation to return a scaler value which we used as the gradient.  This time on the GPU, we will take a similar approach as with the permutation table and pass in a 1D texture which can be sampled with the tex1D function. </p>
<p>When sampling the 1d texture we want to have as much of a random index as possible.  So we use the colour value from the permutation texture (which we sampled in part I) as the texture coordinates.  Like this:</p>
<p><BR><br />
HLSL:</p>
<pre name="code" class="c-sharp">
/// Calculate the gradient at this 'position' using the value sampled
/// from the permutation table.
float gradperm(float x, float3 p)
{
    return dot(tex1D(permGradSampler, x), p);
}
</pre>
<p>You can get a permGradTexture <a href="http://britonia-game.com/Downloads/permGradTexture.dds">here</a>.</p>
<p><BR><br />
<strong>Lerping and Generating the Noise</strong></p>
<p>This part is actually almost identical to the CPU version, with the exception of the change of function names.  Again you can see that 3d Perlin noise requires 7 linear interpolation calculations from the surrounding positions in the lattice:</p>
<p><BR><br />
HLSL:</p>
<pre name="code" class="c-sharp">
// AND ADD BLENDED RESULTS FROM 8 CORNERS OF CUBE
return lerp( lerp( lerp( gradperm(AA.x, p ),
                              gradperm(AA.z, p + float3(-1, 0, 0) ), f.x),
                       lerp( gradperm(AA.y, p + float3(0, -1, 0) ),
                              gradperm(AA.w, p + float3(-1, -1, 0) ), f.x), f.y),

                 lerp( lerp(gradperm(AA.x+(1.0 / 256.0), p + float3(0, 0, -1) ),
                              gradperm(AA.z+(1.0 / 256.0), p + float3(-1, 0, -1) ), f.x),
                       lerp( gradperm(AA.y+(1.0 / 256.0), p + float3(0, -1, -1) ),
                              gradperm(AA.w+(1.0 / 256.0), p + float3(-1, -1, -1) ), f.x), f.y), f.z);
</pre>
<p><BR><br />
And believe it or not, that is it.  There is not a lot of code required at all to get this up and running in an effect.  This version of the improved noise takes into consideration the optimisations mentioned <a href="http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter26.html">here</a>, and takes up just over 53 instructions, so this is still quite expensive.</p>
<p>The rest of the code for the effect file is taken up by the fractal functions like we covered in the last post.  They are fractal brownian motion (fBm), turbulence and ridged multi-fractal.</p>
<p><BR><br />
Here is the complete effect file:</p>
<p>HLSL:<br />
*note that < and > are represented below as &#8216;lb&#8217; and rb&#8217; respectively.</p>
<pre name="code" class="c-sharp">
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// TEXTURES - IMPORTANT! you must pass these textures to
// the effect before generating any values using the improved
// noise basis function (inoise()).
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
texture permTexture2d;
texture permGradTexture;

sampler permSampler2d = sampler_state
{
    texture =  lb permTexture2d rb; // lb and rb are left and right angled brackets
    AddressU  = Wrap;
    AddressV  = Wrap;
    MAGFILTER = POINT;
    MINFILTER = POINT;
    MIPFILTER = NONE;
};

sampler permGradSampler = sampler_state
{
    texture = lb permGradTexture rb; // lb and rb are left and right angled brackets
    AddressU  = Wrap;
    AddressV  = Wrap;
    MAGFILTER = POINT;
    MINFILTER = POINT;
    MIPFILTER = NONE;
};

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// FUNCTIONS
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
float3 fade(float3 t)
{
	return t * t * t * (t * (t * 6 - 15) + 10); // new curve
}

float4 perm2d(float2 p)
{
	return tex2D(permSampler2d, p);
}

float gradperm(float x, float3 p)
{
	return dot(tex1D(permGradSampler, x), p);
}

// Improved 3d noise basis function
float inoise(float3 p)
{
	float3 P = fmod(floor(p), 256.0);	// FIND UNIT CUBE THAT CONTAINS POINT
  	p -= floor(p);                      // FIND RELATIVE X,Y,Z OF POINT IN CUBE.
	float3 f = fade(p);                 // COMPUTE FADE CURVES FOR EACH OF X,Y,Z.

	P = P / 256.0;

    // HASH COORDINATES OF THE 8 CUBE CORNERS
	float4 AA = perm2d(P.xy) + P.z;

	// AND ADD BLENDED RESULTS FROM 8 CORNERS OF CUBE
  	return lerp( lerp( lerp( gradperm(AA.x, p ),
                             gradperm(AA.z, p + float3(-1, 0, 0) ), f.x),
                       lerp( gradperm(AA.y, p + float3(0, -1, 0) ),
                             gradperm(AA.w, p + float3(-1, -1, 0) ), f.x), f.y),

                 lerp( lerp( gradperm(AA.x+(1.0 / 256.0), p + float3(0, 0, -1) ),
                             gradperm(AA.z+(1.0 / 256.0), p + float3(-1, 0, -1) ), f.x),
                       lerp( gradperm(AA.y+(1.0 / 256.0), p + float3(0, -1, -1) ),
                             gradperm(AA.w+(1.0 / 256.0), p + float3(-1, -1, -1) ), f.x), f.y), f.z);
}

//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// FRACTAL FUNCTIONS
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// fractal sum
float fBm(float3 p, int octaves, float lacunarity = 2.0, float gain = 0.5)
{
	float freq = 1.0f,
	      amp  = 0.5f;
	float sum  = 0.0f;
	for(int i=0; i lb octaves; i++) {
		sum += inoise(p*freq)*amp;
		freq *= lacunarity;
		amp *= gain;
	}
	return sum;
}

float turbulence(float3 p, int octaves, float lacunarity = 2.0, float gain = 0.5)
{
	float sum = 0;
	float freq = 1.0, amp = 1.0;
	for(int i=0; i lb octaves; i++) {
		sum += abs(inoise(p*freq))*amp;
		freq *= lacunarity;
		amp *= gain;
	}
	return sum;
}

// Ridged multifractal
// See "Texturing &#038; Modeling, A Procedural Approach", Chapter 12
float ridge(float h, float offset)
{
    h = abs(h);
    h = offset - h;
    h = h * h;
    return h;
}

float ridgedmf(float3 p, int octaves, float lacunarity, float gain = 0.05, float offset = 1.0)
{
	float sum = 0;
	float freq = 1.0;
	float amp = 0.5;
	float prev = 1.0;
	for(int i=0; i lb octaves; i++)
	{
		float n = ridge(inoise(p*freq), offset);
		sum += n*amp*prev;
		prev = n;
		freq *= lacunarity;
		amp *= gain;
	}
	return sum;
}
</pre>
<p><BR><br />
This improved noise can be used as you saw in the last tutorial or in any number of other ways.  Just remember though that doing noice calculations at run-time can be very expensive so its best to do as much &#8216;work&#8217; as possible off-line.</p>
<p><BR><br />
References for this tutorial are:<br />
<a href="http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter26.html">http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter26.html</a></p>
<p><BR></p>
]]></content:encoded>
			<wfw:commentRss>http://britonia-game.com/?feed=rss2&amp;p=207</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Procedural Generation &#8211; Textures on the CPU</title>
		<link>http://britonia-game.com/?p=60</link>
		<comments>http://britonia-game.com/?p=60#comments</comments>
		<pubDate>Wed, 23 Dec 2009 00:50:22 +0000</pubDate>
		<dc:creator>Lintfordpickle</dc:creator>
				<category><![CDATA[Procedural Content]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://britonia-game.com/?p=60</guid>
		<description><![CDATA[In this tutorial I'll be covering how you can use perlin noise and various fractal functions for generating textures either at compile time or run time.  The full source code is provided at the end of the article, but I have tried to write it as such that you can follow through each step and steadily build up your own XNA 3.1 app.]]></description>
			<content:encoded><![CDATA[<p>In this tutorial I&#8217;ll be covering how you can use perlin noise and various fractal functions for generating textures either at compile time or run time.  This technique can be useful for generating natural looking textures (grass, wood, marble etc.) or heightmaps for your terrains.</p>
<p><span id="more-60"></span></p>
<p>The noise function that I&#8217;ll cover is implemented as per Ken perlin&#8217;s improved noise article <a href="http://mrl.nyu.edu/~perlin/noise/">here</a>.  The full source code is provided at the end of the article, but I have tried to write it as such that you can follow through each step and steadily build up your own XNA 3.1 app.</p>
<p>Generating complicated textures on the CPU is an expensive operation and can stall the application; especially if you attempt to generate large textures at run time &#8211; but learning about perlin noise is probably more straight forward on the CPU (as opposed to the GPU).  I&#8217;ll be covering noise generation on the GPU in a future article.</p>
<p><BR><br />
<strong>Step 1 &#8211; Setting up the Project:</strong></p>
<p>So let&#8217;s set up a new XNA 3.1 project where we can work from:</p>
<p><strong>File-&gt;New-&gt;Project</strong></p>
<p>Give it a name and make sure  you have selected the project type &#8216;XNA Game Studio 3.1&#8242; and press OK.  After the default workspace has been loaded you&#8217;ll  will be presented with the default project layout.</p>
<p>Before I get into the beef of the article, I&#8217;d just like to create the empty classes within the project so you have a view of the overall setup.  We will fill these classes in as we run through the tutorial.  Right mouse button on the project in the solution explorer (Ctrl+W then S) and create the following files:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/tutorials/?action=view&#038;current=solutionMap.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/tutorials/solutionMap.jpg" border="0" alt="Photobucket"></a></p>
<p><BR><br />
We will put all of the perlin noise and fractal functions in the Noise.cs class file.  The CreateTexture.cs is where we will define the code for mixing different fractals and producing the actual textures.  To make things easier for this tutorial I&#8217;ll be creating these two classes as static classes, which means we don&#8217;t need to create an instance of the classes to use them, we simply need to call the namespace.class.function() from anywhere in the project and it&#8217;ll work.</p>
<p><BR><br />
<strong>Step 2 &#8211; Exploring Perlin Noise:</strong></p>
<p>First we&#8217;ll look at the perlin noise class and go through the implementation that will enable us to produce the textures.  Perlin noise can be used to calculate pseudo-random values in any dimension, but the higher the dimension the more it will cost you in terms of performance.  Here we&#8217;ll be implementing a 3d improved noise basis function which takes 3 variables as input and uses 7 linear interpolations (lerps) per octave to obtain the end result.  Although we&#8217;ll be implementing 3d perlin noise, we can still use it to create 2d textures by passing in an x and y value and leaving the third component zero.</p>
<p>Perlin noise works by taking input values and returning one pseudo-random value in the range [-1,1].  It does this by using the input values as coordinates in a grid (usually called lattice) of gradient values.  Each gradient isn&#8217;t cimputed until we have the exact coordinate, but once we find the gradient at a particular coordinate referenced by the input, we can use linear interpolation with this and all its neighbouring gradients in the grid to obtain the apparently random end result.  Because we define this lattice of values the same for each instance of the class, we will always get the same output for a specific input.</p>
<p>In order to make sure that we get even further variety, instead of calculating the gradient vector based on the input coordinates directly, we use the input values as a reference into a hash table.  The hash table is called the permutation table, and we create it in the class constructor.</p>
<p>As an explanation; while cell indices 0 and 1 may be next to each other in an array of gradients, they will not necessarily be neighbours in the final grid, because 0 and 1 passed through the hash algorthm will return totally different results.  To achieve this we define a permutation array which contains the integer values 0 &#8211; 255 in a pseudo random order.</p>
<p>It is also important to note that if the permutation table is not the same between different instance of your application (i.e. not constant), you will get different results from the perlin noise function even if you use the same input coordinates for a particular texture.  For this reason we will use an instance of the .net Random class with a seeded constructor.</p>
<p>So let&#8217;s jump into the code for the Perlin noise.  Open up the Noise.cs class file and change the basic class template code to resemble this:<br />
<BR></p>
<pre name="code" class="c-sharp">
using System;

namespace TextureGeneration
{
    public static class c3DPerlinNoise
    {
        private static Random rand;

        private static int[] ms_p = new int[512];

        // The static class constructor
        static c3DPerlinNoise()
        {

        }
    }
}
</pre>
<p><BR><br />
Here we just defined a new static class and two static class members.  You can see that the permutation table we dicussed above is defined as being 512 in length.  Just something to note, static constructors in static classes are run the first time you try and use a function within the class itself.</p>
<p>Now we&#8217;ll look at filling up the constructor and creating our tables.  Let&#8217;s add the following code in the class constructor:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
// Create an instance of the random number generator, making sure to pass in a seed.
rand = new Random(42);

// Use the bitwise left shift operator to make sure the array of permutation values is a multiple of 2
int nbVals = (1 &lt;&lt; 8); // result is 256
int[] ms_perm = new int[nbVals];

// set values in temp perm array as "unused", denoted by -1
for (int i = 0; i &lt; nbVals; i++)
{
ms_perm[i] = -1;
}
</pre>
<p><BR><br />
First up we create an instance of the random class, remembering to pass into it the seed.  The seed can be any integer or float value, here I just used 42.  For those of you unsure of the &lt;&lt; operator, it shifts the bits of the right hand value, effectly incrementing it in multiples of 2.  This is used here just to make sure we defined the size as being a multiple of 2 (256).   Next we defined a temporary array half the size of the final permutation array.  We will use this to define the integer values between 0 and 255 in a random order, before copying them to the final permutation array.</p>
<p>Next we must fill the permutation array:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
for (int i = 0; i &lt; nbVals; i++)
{
// for each value, find an empty spot, and place it in it
while (true)
{
// generate rand # with max a nbvals
int p = rand.Next() % nbVals;
if (ms_perm[p] == -1)
{
ms_perm[p] = i;
break;
}
}
}

for (int i = 0; i &lt; nbVals; i++)
{
ms_p[nbVals + i] = ms_p[i] = ms_perm[i];
}
</pre>
<p><BR><br />
Here we iterative though a loop 256 times, and each time we try and find a free position within the temporary permutation table at a random location.  This loop ends when all the integer values between 0 and 255 have been randomly placed in the array.  The last part of the above code places the temporary permutation values in the final array, and fills it out so we have a full 512 values.</p>
<p>And that&#8217;s all for the constructor &#8211; pretty painless.  We basically end up with a permutation array with 512 cells of mixed up integer values and a static random number generator.</p>
<p>The next step is actually implementing the perlin noise based on what ever input the user provides.  The input I am refering to in 3D noise are three seperate values which are typically some sort of coordinate such as the position of a texel or vertex on a terrain etc.</p>
<p>There are three important things to note about the input to the noise function:</p>
<p>1. Integer values will always return zero.  You&#8217;ll see why this is true later, but basically we use the fraction part of the input as the amount to linear interpolate for the given gradient.  Therefore if the input value is an integer then there is no fraction part, and thus the lerp will return 0.<br />
2. Small variations between input values to the noise function will yield small changes in the output values.<br />
3. Large variations between input values to the noise function will yield apparently random output values.</p>
<p>We are counting on all of the above being true in order to produce nice generated textures.</p>
<p>Next up we&#8217;ll create the noise function which calculates the gradients and performs the linear interpolation.  Create a new static function within the c3DPerlinNoise class with:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
private static double Noise (double x, double y, double z)
{

}
</pre>
<p><BR><br />
The first step in the noise function is to take the input values and work out a coordinate within the lattice of gradient values.  We do this by using the integer part of each of the input coordinates (that is, we take the fraction part away from the input components).  Because the input values could very well be larger than the permutation array of hash values in any one dimension, we also need to also wrap the input integers and keep the range within [0,255].  Do this with the following code:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
int X = (int)x &amp; 255;
int Y = (int)y &amp; 255;
int Z = (int)z &amp; 255;
</pre>
<p><BR><br />
Now get the fraction part of each of the input values.  We will use later as the distance to linear interpolate into each gradient.  If you are unsure about the linear interpolation you can check it out <a href="http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/interpolation/">here</a>.  If you remember the three points we covered about a page back, this is point 2.  Add this code:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
    x -= Math.Floor(x);
    y -= Math.Floor(y);
    z -= Math.Floor(z);
</pre>
<p><BR><br />
Uisng what we have seen so far, try to imagine now calling the noise function 30 times using small increments in the input values, say from within two nested for loops.   Using the above code, you can see that we work out the lattice gradient using the integer part of the input, and the fraction is used in the lerp calculation.  Imagine that the first vector we linear interpolatie on is a vector which is &#8216;pointing&#8217; straight up.  So we carry on incrementing the input values and calling the noise function.  Once the incremented input values cross out of this lattice cell and into another cell (when the integer increments), the linear interpolation will be called on a gradient vector which is probably &#8216;pointing&#8217; in a completly different direction.  If the increments of the input values are exactly the same then you will see a noticable seam where the gradient changes.</p>
<p>To try and avoid this we run the fraction parts of the input through a fade curve (s-curve) which will weight the input towards 0 and 1.  This is needed to avoid seams in the output texture due to the transitions between lattice cells where the different gradients produce noticable jumps in the output values.  We will define the fade function a little later, but for now add this to the noise function:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
double u = fade(x);
double v = fade(y);
double w = fade(z);
</pre>
<p><BR><br />
Before we go on to calculate the gradient value, we need to pass our new integer values into the permutation table to get the hash values (remember, this should mix up the values even further, and help to add variation).  We do this with the following code:</p>
<pre name="code" class="c-sharp">
int A = ms_p[X    ] + Y, AA = ms_p[A] + Z, AB = ms_p[A + 1] + Z;
int B = ms_p[X + 1] + Y, BA = ms_p[B] + Z, BB = ms_p[B + 1] + Z;
</pre>
<p><BR><br />
Okay, so this is getting long winded but rest asured we are nearly there.  This is the final step and it is where we employ linear interpolation between the gradients.  As I said earlier, each extra dimension of noise introduces a performance overhead; this is because of the need to lerp between more surrounding points in the lattice, for 3d noise we must lerp between 7 gradients.  The last thing of note here is that we calculate the gradient values using the hash value and the input coordinates:</p>
<pre name="code" class="c-sharp">
return lerp(w, lerp(v, lerp(u, grad(ms_p[AA  ], x  , y  , z   ),
                                      grad(ms_p[BA  ], x-1, y  , z   )),
                             lerp(u, grad(ms_p[AB  ], x  , y-1, z   ),
                                      grad(ms_p[BB  ], x-1, y-1, z   ))),
                   lerp(v, lerp(u, grad(ms_p[AA+1], x  , y  , z-1 ),
                                      grad(ms_p[BA+1], x-1, y  , z-1 )),
                             lerp(u, grad(ms_p[AB+1], x  , y-1, z-1 ),
                                      grad(ms_p[BB+1], x-1, y-1, z-1 ))));
</pre>
<p><BR><br />
This will return a double value by linear interpolating between all the gradient values at this point in the lattice.</p>
<p>Before this will work, we just have three utility functions to define.  The first one is the fade curve, which weights the input fractions towards zero and one, to ease the transitions of interpolations across lattice cells:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
private static double fade(double t)
{
return (t * t * t * (t * (t * 6 - 15) + 10));
}
</pre>
<p><BR><br />
The _lerp function (linear interpolation) is pretty straight forward,and returns a double:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
private static double lerp(double t, double a, double b)
{
return (a + t * (b - a));
}
</pre>
<p><BR><br />
The last, and most important of the utility functions is the grad() function, which computes the gradient based on the hash value:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
private static double grad(int hash, double x, double y, double z)
{
int h = hash &amp; 15;
double u = h&lt;8 ? x : y;
double v = h&lt;4 ? y : h==12||h==14 ? x : z;

return ((h&amp;1) == 0 ? u : -u) + ((h&amp;2) == 0 ? v : -v);
}
</pre>
<p><BR><br />
And that is it, at least for the perlin noise part.  The above functions can now be used to return a pseudo-random value in the [-1, 1] range for any 3d input, such as terrain vertex positions etc.</p>
<p><BR><br />
<strong>Step 3 &#8211; Fractals for Interesting Noise:</strong></p>
<p>Okay, with the noise class defined above you may well be thinking that the battle&#8217;s almost over &#8211; well, not quite.  We could (if we hadn&#8217;t defined the noise function as private) just call the noise function above and pass in the input coordinates to define a texture of noise.  This would result in a texture based on just one octave of noise.  But in order to achieve nice results, or rather varied results for a wide variety of textures, we need to use multiple octaves of noise.</p>
<p>Each successive noise function you use for one point of input is known as an octave, and you can use as many or as little octaves as you like in the texture.  When we call multiple octaves of noise, we can specify an amplitude and frequency.  The amplitude is used to modify the output of the noise function while the frequency modifies the input values for each call to the noise function.  The frequency of an octave is usually double that of the previous octave.  For this reason, there becomes a point where the frequency of the octaves is too high to be displayed on the screen, so it makes sense to limit the use of octaves.</p>
<p>There is another property which can be used called persistence or lacunarity, which specifies the rate of change of the frequency (of the input) over octaves.</p>
<p>Now we&#8217;ll just run through some fractal functions which can be used to create more interesting noise, and which should explain these new terms a little better:</p>
<p>The first fractal function is fractal browian motion (fBm).  This is just the weighted sum of multiple scales of an arbiturary basis function (the basis function in our case is improved perlin noise &#8211; but the basis could be anything else such as simplex noise)</p>
<p><BR></p>
<pre name="code" class="c-sharp">
public static double fBm(double x, double y, double z, int octaves, float lacunarity, float gain)
{
    double frequency = 1.0f;
    double amplitude = 0.5f;
    double sum = 0.0f;

    for (int i = 0; i < octaves; i++)
    {
        sum += noise(x * frequency, y * frequency, z * frequency) * amplitude;
        frequency *= lacunarity;
        amplitude *= gain;
    }
    return sum;
}
</pre>
<p><BR><br />
You can see that the frequency used to modify the input values is doubled on each iteration of the octaves (I'm assuming here that the lacunarity is 2.0f), while the amplitude is modified based on the gain.  The frequency is multiplied with each input variable to the noise function.  This function produces textures similiar to:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/tutorials/?action=view&#038;current=fBmOutput.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/tutorials/fBmOutput.jpg" border="0" alt="Photobucket"></a></p>
<p>The next fractal function is Ridged multifractal.  It is generated in much the same way as fBm noise, except the output of each octave is modified by an absolute value function.  This function is very popular for creating terrain heightmaps, as it produces ridge like features at all scales.  The implementation is as follows:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
public static double RidgedMF(double x, double y, double z, int octaves, float lacunarity, float gain, float offset)
{
double sum = 0;
float amplitude = 0.5f;
float frequency = 1.0f;
double prev = 1.0f;

for (int i = 0; i &lt; octaves; i++)
{
double n = ridge(noise(x * frequency, y * frequency, z * frequency), offset);
sum += n * amplitude * prev;
prev = n;
frequency *= lacunarity;
amplitude *= gain;
}

return sum;
}

public static double ridge(double h, float offset)
{
h = Math.Abs(h);
h = offset - h;
h = h * h;
return h;
}
</pre>
<p><BR><br />
The RdgedMF in the source code I have provided produces the following texture:</p>
<p><BR><br />
<a href="http://s429.photobucket.com/albums/qq13/lintfordpickle/tutorials/?action=view&#038;current=RidgedMFoutput.jpg" target="_blank"><img src="http://i429.photobucket.com/albums/qq13/lintfordpickle/tutorials/RidgedMFoutput.jpg" border="0" alt="Photobucket"></a></p>
<p><BR><br />
<strong>4. Getting the Project setup to create and display the textures:</strong></p>
<p>We have covered a lot of ground so far, but there is still one thing left to do, and that is to actually create the textures!  If you want to go ahead then and open up the CreateTexture.cs file class in the solution explorer and we'll define the following function in there.  First of all setup the class as another static class like this:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
using System;
using Microsoft.Xna.Framework.Graphics;
using TextureGeneration.Noise;

namespace TextureGeneration
{
public static class CreateTexture
{

}
}
</pre>
<p><BR><br />
All the following functions should be created inside this class.  Now we'll  justlook at creating a texture which could be used to generate a heightmap from, like in Riemers tutorials (here).  Define the following function:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
public static Color[] CreatefBmHeightMap(int width, int height)
{
Color[] data = new Color[width * height];
float tempColor;

float x = 0, y = 0, z = 0;
</pre>
<p>As you may be able to guess, we'll be filling the Color[] array within the function and we'll pass it back out at the end.  This will later be used to fill a texture2D class instance.  The next step is too create a two for loops, one nested within the other.  This will enable us to produce a noise value for each texel of a texture (given the width and height):</p>
<pre name="code" class="c-sharp">
for (int v = 0; v &lt; width; v++)
{
x += 0.5f;
y = 0;
for (int u = 0; u &lt; height; u++)
{
tempColor = (float)c3DPerlinNoise.fBm(x, y, z, 8, 0.45f, 1.0f);
data[v * width + u] = new Color(tempColor, tempColor, tempColor, 1);

y += 0.5f;
}
}

return data;
}
</pre>
<p><BR><br />
There are a few things going on here which we need to take note of.  The first is that we do not use the integers created by the nested for loops input directly because if you remember, integer values produce 0 as output, so instead we use the x,y and z floats defined locally in the function, and manually increment them.  We then go on to use the result of the fBm function to fill all components of a Color struct, producing a black and white image.  This should be perfect for a heightmap.  The output of this function can be seen above (the fBm sample).</p>
<p><BR><br />
<strong>For the Sake of Completness:</strong></p>
<p>We'll quickly define some code to get the texture up on the screen in your application.  This is all pretty basic stuff, so I'm not going to linger on anything.  Go back into the Game1.cs class and define a Texture2d member:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
private Texture2D _HeightmapTexture;
</pre>
<p><BR><br />
This will contain the texture that we are to create.  In this tutorial we'll just set the texel data directly with the SetData function.</p>
<p>Now go into the LoadContent() method and add the following code:</p>
<p><BR></p>
<pre name="code" class="c-sharp">
_HeightmapTexture = new Texture2D(GraphicsDevice, 512, 512, 1, TextureUsage.None, SurfaceFormat.Color);
_HeightmapTexture.SetData
(CreateTexture.CreatefBmHeightMap(_HeightmapTexture.Width, _HeightmapTexture.Height));
</pre>
<p><BR><br />
This will create an instance of the Texture2D with the specified size and with a surface format of Color which has 8-bits for RGB and A.  The second line fills the texture data with the Color[] array which is created and returned from the CreateTexture.CreatefBmHeightMap() function.</p>
<p>Lastly, go to the draw method and add this line between the SpriteBatch.Begin() and SpriteBatch.End():</p>
<p><BR></p>
<pre name="code" class="c-sharp">
_SpriteBatch.Draw(_HeightMap, new Rectangle(10,10,512,512), Color.White);
</pre>
<p><BR><br />
And that's that!  Press F5 and you should see a fBm noise texture displayed on the screen.</p>
<p><BR><br />
That pretty much concludes the tutorial,  I hope you found it interesting!</p>
<p>Now as this was my first tutorial, I would greatly appreciate any comments or criticism about issues, things I may have forgot or any improvements.  I look forward to your feedback and I'll try and use it for my next tutorial (in a few weeks)</p>
<p>You can donwload the sample project <a href='http://www.filehosting.org/file/details/137582/PerlinNoiseSample.zip'>here</a></p>
<p><BR><br />
<a href='http://www.noisemachine.com/talk1/'>Making Noise</a></p>
<p>Thanks,</p>
<p>-John</p>
<p>References:</p>
<p><a href='http://mrl.nyu.edu/~perlin/noise/'>Perlin's Improved noise reference</a></p>
]]></content:encoded>
			<wfw:commentRss>http://britonia-game.com/?feed=rss2&amp;p=60</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
	</channel>
</rss>
