<?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>Nick Gravelyn &#187; Uncategorized</title>
	<atom:link href="http://blog.nickgravelyn.com/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.nickgravelyn.com</link>
	<description></description>
	<lastBuildDate>Tue, 27 Jul 2010 22:43:16 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>This blog is retiring</title>
		<link>http://blog.nickgravelyn.com/2010/06/this-blog-is-retiring/</link>
		<comments>http://blog.nickgravelyn.com/2010/06/this-blog-is-retiring/#comments</comments>
		<pubDate>Sun, 20 Jun 2010 05:06:30 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.nickgravelyn.com/?p=1539</guid>
		<description><![CDATA[I have to admit that over the last few months I haven&#8217;t been feeling the blog. I&#8217;ve redone my homepage and moved this blog to a subdomain to keep it around, but try to shove it out of the limelight of my existence. That said, I am hoping to start blogging a little bit more [...]]]></description>
			<content:encoded><![CDATA[<p>I have to admit that over the last few months I haven&#8217;t been feeling the blog. I&#8217;ve redone <a href="http://nickgravelyn.com">my homepage</a> and moved this blog to a subdomain to keep it around, but try to shove it out of the limelight of my existence. That said, I am hoping to start blogging a little bit more and more, though it&#8217;ll likely be less frequently moving forward. I&#8217;ve also decided that for various reasons I&#8217;m going to start blogging on my <a href="http://blogs.msdn.com/b/nicgrave/">MSDN blog</a>. You&#8217;ll want to head over there and subscribe for future posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nickgravelyn.com/2010/06/this-blog-is-retiring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>TiledLib now on CodePlex</title>
		<link>http://blog.nickgravelyn.com/2010/03/tiledlib-now-on-codeplex/</link>
		<comments>http://blog.nickgravelyn.com/2010/03/tiledlib-now-on-codeplex/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 03:57:19 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.nickgravelyn.com/?p=1524</guid>
		<description><![CDATA[With the help of Jesse Chounard, I&#8217;ve made a lot of great changes to the library and put the whole thing up on CodePlex for everyone to enjoy: http://tiledlib.codeplex.com/. Enjoy.
]]></description>
			<content:encoded><![CDATA[<p>With the help of <a href="http://thirdpartyninjas.com">Jesse Chounard</a>, I&#8217;ve made a lot of great changes to the library and put the whole thing up on CodePlex for everyone to enjoy: <a href="http://tiledlib.codeplex.com/">http://tiledlib.codeplex.com/</a>. Enjoy.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nickgravelyn.com/2010/03/tiledlib-now-on-codeplex/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Know when to be lazy</title>
		<link>http://blog.nickgravelyn.com/2010/03/know-when-to-be-lazy/</link>
		<comments>http://blog.nickgravelyn.com/2010/03/know-when-to-be-lazy/#comments</comments>
		<pubDate>Sat, 06 Mar 2010 21:04:11 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.nickgravelyn.com/?p=1511</guid>
		<description><![CDATA[There are times when making a game that you absolutely can&#8217;t be lazy. You need to focus and get things done if you ever want to ship. But there are times when being lazy is the best way to solve a problem. Today was one of those times for me.
I&#8217;ve started working on a new [...]]]></description>
			<content:encoded><![CDATA[<p>There are times when making a game that you absolutely can&#8217;t be lazy. You need to focus and get things done if you ever want to ship. But there are times when being lazy is the best way to solve a problem. Today was one of those times for me.</p>
<p>I&#8217;ve started working on a new ninja game that was going to use largely tile based maps. I first started down the <a href="/2009/09/pixel-man-post-mortem-2/">same road</a> of Pixel Man, using Paint.NET for my level editor. I quickly realized that the increased complexity meant a confusing palette which made life too hard. It also ruled out things like cutscenes or any other interesting level markers. So I started working on my own editor. My method for <a href="/2010/03/resizing-2d-arrays/">resizing 2D arrays</a> was so I could support the editor as I went. I never got very far into making an editor because, frankly, it&#8217;s a lot of work.</p>
<p>So I started feeling burnt out. I want to make this game but I was stuck from the get-go without having any means to create my levels. I could have gone ahead and hard coded a few maps but I find that&#8217;s not a workflow I tend to like. I prefer to solve the content problem first that way I know what data I will be able to code around. Today I came up with a solution for all of this. I would simply be lazy and find a tile editor someone else had made, thus saving me time.</p>
<p>During some random searches, I found a nice tile editor called <a href="http://mapeditor.org/">Tiled</a>. Tiled is a near perfect editor for tile maps. You can attach metadata to pretty much everything and you can make layers that just hold arbitrary rectangles of metadata. It&#8217;s really quite nice. Here&#8217;s one of my test levels in Tiled:</p>
<p><center><a href="/wp-content/uploads/2010/03/demolevel.png"><img src="http://blog.nickgravelyn.com/wp-content/uploads/2010/03/demolevel-300x164.png" alt="Test Level in Tiled" title="Test Level in Tiled" width="300" height="164" class="alignnone size-medium wp-image-1512" /></a></center></p>
<p>You can see I dedicated a rectangle for a spawn point and two for cutscenes which I could use to display some text about the game or whatever (this is a test level so none of those really mean anything).</p>
<p>So this editor is great. It does pretty much everything I need out of an editor, but how can I use the levels? Thankfully all levels are saved as XML files which means it&#8217;s not a whole lot of work to parse them and use them.  Since I was on a streak of using other people&#8217;s work, I went out in search of XNA GS code to use the level files.</p>
<p>My search started at the <a href="http://sourceforge.net/apps/mediawiki/tiled/index.php?title=Main_Page">Tiled wiki</a> which lead me to Kevin Gadd&#8217;s <a href="http://www.luminance.org/code/2009/06/17/tiled-map-loader-for-xna">excellent website</a> which pointed me to Stephen Belanger&#8217;s <a href="http://www.stephenbelanger.com/2009/07/14/tiled-maps-for-xna-full-support-for-the-tiled-map-xml-specification/">blog post</a> expanding on Kevin&#8217;s code. I took a look at the code in excitement and was a bit let down. All of the XML parsing was done at runtime into very mutable objects with some design choices I didn&#8217;t quite agree with. So I decided that this is something to take into my own hands.</p>
<p>Starting at around 7:30 this morning (and ending just a few minutes ago), I feverishly wrote up a custom content pipeline extension project for parsing and processing the TMX files produced by Tiled and turning them into an easy to use, largely immutable structure. Why immutable? I&#8217;m personally a fan of closed systems until you need them open. Why would you make the width of the map mutable? What happens if I accidentally change that? So in my code, most variables are read only to stop me from shooting myself in the foot. Using C#&#8217;s &#8216;internal&#8217; keyword, I&#8217;ve made it so most objects are only internally constructable with a lot of private members. This keeps all the data out of the hands of those meddling games (or people like me who accidentally change something and break it all).</p>
<p>The extensions are nice and minimal in what they require of you. Just drop a TMX file into your content project and you&#8217;re basically done. You will also need any tile sheets used by the map. You can place them anywhere in the content folder directory and you don&#8217;t need to add them to the content project; the map will build anything it needs and it also handles loading those in for you. The only parameter on the TMX processor is the directory where those sheets can be found, relative to the content project. In my project, I have a Maps directory in my content library with my TMX file and then a TileSets directory next to that with the sheets. Therefore my TMX files need to set their TileSet Directory values to &#8220;TileSets&#8221;.</p>
<p>Since I spent a good five hours creating this (which is likely orders of magnitude less than it would take for me to write something on par with Tiled), I decided to share with the community. I&#8217;m sure there are others out there who would want to use Tiled for their level editor and now you can have a great base on which to build up your own library for using those maps. The code is all MS-Pl so feel free to do with it what you will. I, of course, take no responsibility if the code manifests itself into the end of the world, a black hole, or your ex-girlfriend so use at your own risk. However I&#8217;ve yet to see any of those three things, so I think we&#8217;re good.</p>
<p>Enough blabbing. Links:</p>
<p><a href="http://opensource.org/licenses/ms-pl.html">License</a><br />
<a href='http://blog.nickgravelyn.com/wp-content/uploads/2010/03/TiledDemo.zip'>Libraries and Demo Project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nickgravelyn.com/2010/03/know-when-to-be-lazy/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Further extending C# arrays</title>
		<link>http://blog.nickgravelyn.com/2010/03/further-extending-c-arrays/</link>
		<comments>http://blog.nickgravelyn.com/2010/03/further-extending-c-arrays/#comments</comments>
		<pubDate>Sat, 06 Mar 2010 00:44:33 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.nickgravelyn.com/?p=1508</guid>
		<description><![CDATA[In my last post, I showed an extension method for resizing arrays. Today I decided to come up with some more extension methods that I find handy. First up: Fill.
Fill is an extension method I wrote because I&#8217;m sick of iterating over arrays to fill them in or alter values. Fill looks like this:
public static [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="/2010/03/resizing-2d-arrays/">last post</a>, I showed an extension method for resizing arrays. Today I decided to come up with some more extension methods that I find handy. First up: Fill.</p>
<p>Fill is an extension method I wrote because I&#8217;m sick of iterating over arrays to fill them in or alter values. Fill looks like this:</p>
<pre class="brush: csharp;">public static void Fill&lt;T&gt;(this T[,] array, Func&lt;int, int, T, T&gt; fill)
{
	int width = array.GetLength(0);
	int height = array.GetLength(1);

	for (int x = 0; x &lt; width; x++)
	{
		for (int y = 0; y &lt; height; y++)
		{
			array[x, y] = fill(x, y, array[x, y]);
		}
	}
}</pre>
<p>You can see that it uses a Func to generate the new values. The Func takes in the x and y indices as well as the existing value at that location in the array, then returns the new value. This can be useful for a number of things. Let&#8217;s say I have an array of objects and I just used my Resize method to expand the array. I now have a bunch of null objects in there. I can easily use Fill to fix this:</p>
<pre class="brush: csharp;">myArray.Fill((x, y, existing) =&gt; existing ?? new MyObject());</pre>
<p>How&#8217;s that for succinct? It&#8217;s also useful for new arrays that you want to populate:</p>
<pre class="brush: csharp;">int[,] myArray = new int[10, 10];
myArray.Fill((x, y, existing) =&gt; x * y);</pre>
<p>So you can easily ignore the existing value and simply return a value to replace the current one.</p>
<p>I have a blast making extension methods even if they aren&#8217;t revolutionizing how I write code. I find it gives me a chance to just think up a problem and try to solve it in a clean and simple way. Anyone else find themselves doing this? What extension methods are you writing?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nickgravelyn.com/2010/03/further-extending-c-arrays/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Resizing 2D arrays</title>
		<link>http://blog.nickgravelyn.com/2010/03/resizing-2d-arrays/</link>
		<comments>http://blog.nickgravelyn.com/2010/03/resizing-2d-arrays/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 15:39:56 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.nickgravelyn.com/?p=1497</guid>
		<description><![CDATA[I started working on a new tile system and editor for my ninja game and realized I&#8217;m going to want the ability to change level sizes. I store my tile layouts in a basic 2D array which means that my resizing will have to do a bit of moving things around. After a little bit [...]]]></description>
			<content:encoded><![CDATA[<p>I started working on a new tile system and editor for my ninja game and realized I&#8217;m going to want the ability to change level sizes. I store my tile layouts in a basic 2D array which means that my resizing will have to do a bit of moving things around. After a little bit of work, I came up with a fairly decent (i.e. it works for my few little test cases) extension method for resizing any 2D array, including choosing where you clamp to get the same effect as Paint.NET or Photoshop when you change canvas size but get to choose where the existing data will be in relationship to the resizing.</p>
<p><center><img src="http://blog.nickgravelyn.com/wp-content/uploads/2010/03/anchor.png" alt="Paint.NET Anchor Selection" title="Paint.NET Anchor Selection" width="378" height="541" class="alignnone size-full wp-image-1500" /></center></p>
<p>Anyway, here&#8217;s the method. Hope this can save someone else some time. Also if you spot anything wrong about this let me know.</p>
<pre class="brush: csharp;">public enum HorizontalClamp
{
	Left,
	Right,
	Center
}

public enum VerticalClamp
{
	Top,
	Bottom,
	Center
}

public static class ArrayExtensions
{
	public static T[,] Resize&lt;T&gt;(
		this T[,] array,
		int newWidth,
		int newHeight,
		HorizontalClamp xClamp,
		VerticalClamp yClamp)
	{
		// get the current width and height of the array
		int width = array.GetLength(0);
		int height = array.GetLength(1);

		// start/end from the old array
		int xStart = 0, xEnd = Math.Min(width, newWidth);
		int yStart = 0, yEnd = Math.Min(height, newHeight);

		// start/end for new array
		int targetX = 0;
		int targetY = 0;

		// figure out start, end, and target coordinates.
		// no check for left or top; those are defaults.

		if (xClamp == HorizontalClamp.Right)
		{
			xStart = Math.Max(width - newWidth, 0);
			xEnd = xStart + Math.Min(width, newWidth);
			targetX = newWidth - (width - xStart);
		}
		else if (xClamp == HorizontalClamp.Center)
		{
			xStart = Math.Max(width / 2 - newWidth / 2, 0);
			xEnd = xStart + Math.Min(width, newWidth);
			targetX = Math.Max(newWidth / 2 - width / 2, 0);
		}

		if (yClamp == VerticalClamp.Bottom)
		{
			yStart = Math.Max(height - newHeight, 0);
			yEnd = yStart + Math.Min(height, newHeight);
			targetY = newHeight - (height - yStart);
		}
		else if (yClamp == VerticalClamp.Center)
		{
			yStart = Math.Max(height / 2 - newHeight / 2, 0);
			yEnd = xStart + Math.Min(height, newHeight);
			targetY = Math.Max(newHeight / 2 - height / 2, 0);
		}

		// create our return value
		T[,] newArray = new T[newWidth, newHeight];

		// copy over the values from the old array to the new array
		for (int x1 = targetX, x2 = xStart; x2 &lt; xEnd; x1++, x2++)
		{
			for (int y1 = targetY, y2 = yStart; y2 &lt; yEnd; y1++, y2++)
			{
				newArray[x1, y1] = array[x2, y2];
			}
		}

		return newArray;
	}
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.nickgravelyn.com/2010/03/resizing-2d-arrays/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>sspack your images</title>
		<link>http://blog.nickgravelyn.com/2010/02/sspack-your-images/</link>
		<comments>http://blog.nickgravelyn.com/2010/02/sspack-your-images/#comments</comments>
		<pubDate>Sat, 27 Feb 2010 20:14:32 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.nickgravelyn.com/?p=1442</guid>
		<description><![CDATA[Today I checked in the first update to Sprite Sheet Packer in a few months. Inspired by a discussion post I somehow didn&#8217;t see for a few months and my own realization of the usefulness, I extracted the build process of the tool into a command line application and made the UI tool simply a [...]]]></description>
			<content:encoded><![CDATA[<p>Today I checked in the first update to <a href="http://spritesheetpacker.codeplex.com/">Sprite Sheet Packer</a> in a few months. Inspired by a discussion post I somehow didn&#8217;t see for a few months and my own realization of the usefulness, I extracted the build process of the tool into a command line application and made the UI tool simply a wrapper around it. This enables many more scenarios for integration.</p>
<p>First let&#8217;s do the techie thing and just look at the arguments of the tool:</p>
<pre class="brush: plain;">C:\Users\Nick\Desktop&gt;sspack
Missing required argument '/image'.
Missing required argument '/map'.
/image:&lt;string&gt;  Output file name for the image.
/map:&lt;string&gt;    Output file name for the map.
/mw:&lt;int&gt;        Maximum ouput width. Default:'4096'
/mh:&lt;int&gt;        Maximum ouput height. Default:'4096'
/pad:&lt;int&gt;       Padding between images. Default:'1'
/pow2            Ensures output dimensions are powers of two.
/sqr             Ensures output is square.
/r               Searches subdirectories of any input directories.
/il:&lt;string&gt;     Path(s) to file(s) listing the images to build.
&lt;input&gt;          Images to pack.</pre>
<p>Those first two lines are unfortunately a bit misleading but the library I used for parsing command line arguments didn&#8217;t have complex logic. You technically are required to have image and map but you also must have something for either il or the input images. Most of the arguments make sense but the last few may trip people up. First the /r. If you have that flag, your searches for input will be recursive. So you could invoke this:</p>
<pre class="brush: plain;">sspack /image:test.png /map:test.txt C:\Users\Nick\Desktop\MyImages\*.png</pre>
<p>And it would find all PNG images in the MyImages folder. Note that the wildcard is really primitive and likely to break if you try to do anything with it in the middle of the word; it&#8217;s mainly there for finding a bunch of images in one folder. Anyway, if you were to add in the /r flag, it would find any PNG image in the MyImages folder and any subdirectories. That&#8217;s it.</p>
<p>Next the il flag. Since you may want to pack lots and lots of images (like the tool requires), you can make a file like this:</p>
<pre class="brush: plain;">C:\Users\Nick\Desktop\MyImages\1.png
C:\Users\Nick\Desktop\MyImages\2.png
C:\Users\Nick\Desktop\MyImages\3.png
C:\Users\Nick\Desktop\MyImages\4.png</pre>
<p>And invoke sspack with that file which it uses to find the files:</p>
<pre class="brush: plain;">sspack /image:test.png /map:test.txt C:\Users\Nick\Desktop\ImagesToPack.txt</pre>
<p>This is really nice because you could make any other tool to generate that file and kick off the build. This is actually all that the UI tool does. It simply builds up that list (which it saves in %AppData%\Sprite Sheet Packer) and uses all the UI to simply build up the command to launch a Process to run sspack. Now you can make your own UI tool or integrate sprite sheet packing into your build.</p>
<p>If you have any suggestions, feel free to let me know, but no promises. As you can see, I don&#8217;t really do rapid development on this project. Also feel free to submit patches on CodePlex if you have fixes for bugs or enhancements. That really helps since I can do a quick code review and put it up for everyone else to use.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nickgravelyn.com/2010/02/sspack-your-images/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Naming your content</title>
		<link>http://blog.nickgravelyn.com/2010/02/naming-your-content/</link>
		<comments>http://blog.nickgravelyn.com/2010/02/naming-your-content/#comments</comments>
		<pubDate>Sat, 27 Feb 2010 15:35:58 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.nickgravelyn.com/?p=1439</guid>
		<description><![CDATA[A number of the built in types you load through ContentManager in XNA have a Name property. Most (all?) don&#8217;t actually set this at any point; it&#8217;s just there for you to use. I like to use these names for various things and I&#8217;m sick of setting them all manually. So I started out to [...]]]></description>
			<content:encoded><![CDATA[<p>A number of the built in types you load through ContentManager in XNA have a Name property. Most (all?) don&#8217;t actually set this at any point; it&#8217;s just there for you to use. I like to use these names for various things and I&#8217;m sick of setting them all manually. So I started out to make my own ContentManager that does this for me.</p>
<p>It started off with something like this:</p>
<pre class="brush: csharp;">public class MyContentManager : ContentManager
{
	public MyContentManager(IServiceProvider services)
		: base(services, &quot;Content&quot;)
	{
	}

	public override T Load&lt;T&gt;(string assetName)
	{
		T content = base.Load&lt;T&gt;(assetName);

		if (content is GraphicsResource)
		{
			(content as GraphicsResource).Name = assetName;
		}
		else if (content is SoundEffect)
		{
			(content as SoundEffect).Name = assetName;
		}

		return content;
	}
}</pre>
<p>And that works. But what if I miss some content? What if I add my own custom type with a Name property? On my second go I decided to use a reflection based approach by just seeing if the object has a settable Name property:</p>
<pre class="brush: csharp;">public class MyContentManager : ContentManager
{
	public MyContentManager(IServiceProvider services)
		: base(services, &quot;Content&quot;)
	{
	}

	public override T Load&lt;T&gt;(string assetName)
	{
		T content = base.Load&lt;T&gt;(assetName);

		PropertyInfo nameProperty = typeof(T).GetProperty(&quot;Name&quot;, typeof(string));
		if (nameProperty != null &amp;&amp; nameProperty.CanWrite)
		{
			nameProperty.SetValue(content, assetName, null);
		}

		return content;
	}
}</pre>
<p>And now any content that I load that has a Name property with a setter will get its name set. But I&#8217;m not quite done yet. Reflection isn&#8217;t the quickest thing in the world and I do like to use the ContentManager as a cache. This implementation will set the Name property each time the content is pulled from the ContentManager. While this is a good thing if you plan to change the name other places, it can be a performance hit. So I decided to add a dictionary to track what content has already been named and avoid naming things twice:</p>
<pre class="brush: csharp;">public class MyContentManager : ContentManager
{
	private readonly Dictionary&lt;string, bool&gt; namedContent = new Dictionary&lt;string, bool&gt;();

	public MyContentManager(IServiceProvider services)
		: base(services, &quot;Content&quot;)
	{
	}

	public override T Load&lt;T&gt;(string assetName)
	{
		T content = base.Load&lt;T&gt;(assetName);

		bool named = false;
		if (!namedContent.TryGetValue(assetName, out named) || !named)
		{
			PropertyInfo nameProperty = typeof(T).GetProperty(&quot;Name&quot;, typeof(string));
			if (nameProperty != null &amp;&amp; nameProperty.CanWrite)
			{
				nameProperty.SetValue(content, assetName, null);
			}
			namedContent.Add(assetName, true);
		}

		return content;
	}
}</pre>
<p>And that&#8217;s where I&#8217;m at now. I fully realize that reflection is not going to be as fast as doing those casts, but since I&#8217;m also doing this caching of what items have been named, I&#8217;m only going to see that performance hit the first time I load an object and generally loading the object takes enough time that the extra cost of the reflection isn&#8217;t likely to be noticeable or an issue.</p>
<p>I&#8217;d be interested in hearing what others are doing to extend this class. Anyone else using a custom ContentManager for anything?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nickgravelyn.com/2010/02/naming-your-content/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using GamerServicesDispatcher to fix up exception handling</title>
		<link>http://blog.nickgravelyn.com/2010/02/using-gamerservicesdispatcher-to-fix-up-exception-handling/</link>
		<comments>http://blog.nickgravelyn.com/2010/02/using-gamerservicesdispatcher-to-fix-up-exception-handling/#comments</comments>
		<pubDate>Sun, 21 Feb 2010 17:22:25 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.nickgravelyn.com/?p=1417</guid>
		<description><![CDATA[Since my last update to my exception handling code that showed how to handle using GamerServices in the exception game after the first game uses it, I&#8217;ve found out a much, much better way to handle this scenario. The key here: don&#8217;t use the GamerServicesComponent.
The GamerServicesComponent is a very minimal wrapper on top of the [...]]]></description>
			<content:encoded><![CDATA[<p>Since <a href="/2009/11/exception-handling-and-gamerservicescomponent/">my last update</a> to my <a href="/2009/07/a-more-robust-exception-system/">exception handling code</a> that showed how to handle using GamerServices in the exception game after the first game uses it, I&#8217;ve found out a much, much better way to handle this scenario. The key here: don&#8217;t use the GamerServicesComponent.</p>
<p>The GamerServicesComponent is a very minimal wrapper on top of the GamerServicesDispatcher. If we avoid using the GamerServicesComponent in both games, we&#8217;ll be fine. I&#8217;m personally moving away from using the component entirely, but you can keep using it in the real game and just use the dispatcher directly in the second.</p>
<p>Basically what you&#8217;ll do in your exception game is simply initialize the dispatcher directly if it needs to by calling Initialize and setting the window handle.</p>
<pre class="brush: csharp;">protected override void Initialize()
{
	if (!GamerServicesDispatcher.IsInitialized)
	{
		GamerServicesDispatcher.Initialize(Services);
	}
	GamerServicesDispatcher.WindowHandle = Window.Handle;
	base.Initialize();
}</pre>
<p>And then just remember to Update the dispatcher each frame:</p>
<pre class="brush: csharp;">protected override void Update(GameTime gameTime)
{
	GamerServicesDispatcher.Update();
	// update other stuff
	base.Update(gameTime);
}</pre>
<p>And there you go. No more need to make your GamerServicesComponent a static property or rely on that bug in the Game class. Much better.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nickgravelyn.com/2010/02/using-gamerservicesdispatcher-to-fix-up-exception-handling/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Scaling retro sprites at build time</title>
		<link>http://blog.nickgravelyn.com/2010/02/scaling-retro-sprites-at-build-time/</link>
		<comments>http://blog.nickgravelyn.com/2010/02/scaling-retro-sprites-at-build-time/#comments</comments>
		<pubDate>Sun, 21 Feb 2010 03:54:58 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.nickgravelyn.com/?p=1409</guid>
		<description><![CDATA[For my new game, I still am sticking with a retro feel of blowing up sprites 4x their original size to give them that blocky look. However, unlike Pixel Man where I did this as a &#8220;post process&#8221; by rendering the whole game tiny and scaling that up, I want to scale up each sprite [...]]]></description>
			<content:encoded><![CDATA[<p>For my new game, I still am sticking with a retro feel of blowing up sprites 4x their original size to give them that blocky look. However, unlike Pixel Man where I did this as a &#8220;post process&#8221; by rendering the whole game tiny and scaling that up, I want to scale up each sprite individually in order to have smoother motion as things move around. I therefore had a few options:</p>
<p>1) Scale each sprite individually when drawing. Pros: easy initially. Cons: adds a lot of redundant code since the scale will likely not change during runtime.<br />
2) Scale each sprite during editing. Pros: easy to do. Cons: have to remember to scale each sprite for the game, but keep a low-res copy for any other editing.<br />
3) Scale during build time. Pros: awesome. Cons: none? <img src='http://blog.nickgravelyn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>As you can guess by the title of the post, I went with #3. I figured this would let me still draw and save each sprite as tiny little images (tiles are currently 10&#215;10 and the ninja just slightly larger) and still have them nice and large in the game. I&#8217;ll now share some code with you in case this is something you&#8217;d want to do.</p>
<p>First I created a new content pipeline extension project and added a reference in my game&#8217;s content project. Next I added a basic class that will define any constants I might need as time moves on. For now, it&#8217;s just one:</p>
<pre class="brush: csharp;">public static class Constants
{
	public const int Scale = 4;
}</pre>
<p>Currently I&#8217;m scaling everything up 4x, but this lets me change one number and instantly get the game at a new scale.</p>
<p>Next I wrote up a quick and dirty texture importer. Since I didn&#8217;t feel like dealing with initializing D3D like the standard XNA TextureImporter class, I added a reference to System.Drawing and just used those APIs instead. Ultimately this is a pretty basic class. We load a bitmap and then copy over the pixels into a new PixelBitmapContent object which we then use as the first item in the mipmap chain.</p>
<pre class="brush: csharp;">[ContentImporter(DisplayName = &quot;Texture - Ninja!&quot;)]
public class NinjaTextureImporter : ContentImporter&lt;TextureContent&gt;
{
	public override TextureContent Import(string filename, ContentImporterContext context)
	{
		Bitmap bitmap = Bitmap.FromFile(filename) as Bitmap;

		// XColor is an alias for Microsoft.Xna.Framework.Graphics.Color
		PixelBitmapContent&lt;XColor&gt; bitmapContent = new PixelBitmapContent&lt;XColor&gt;(
			bitmap.Width * Constants.Scale,
			bitmap.Height * Constants.Scale);

		for (int x = 0; x &lt; bitmap.Width; x++)
		{
			for (int y = 0; y &lt; bitmap.Height; y++)
			{
				// DColor is an alias for System.Drawing.Color
				DColor pixel = bitmap.GetPixel(x, y);
				XColor xPixel = new XColor(pixel.R, pixel.G, pixel.B, pixel.A);

				for (int x2 = x * Constants.Scale; x2 &lt; (x + 1) * Constants.Scale; x2++)
				{
					for (int y2 = y * Constants.Scale; y2 &lt; (y + 1) * Constants.Scale; y2++)
					{
						bitmapContent.SetPixel(x2, y2, xPixel);
					}
				}
			}
		}

		Texture2DContent texture = new Texture2DContent();
		texture.Faces[0] = new MipmapChain { bitmapContent };
		return texture;
	}
}</pre>
<p>And there you go. Head back to the game content, choose this importer for my sprites, and like magic all of my sprites are scaled up for me. And since I&#8217;m handling the scaling, it&#8217;s all done with no interpolation so my pixels are nice and crisp.</p>
<p>The nice corollary to this experiment is that now I (and you for reading this post) know how to make a texture importer, meaning that the possibilities are endless. You could start loading in any image format supported by System.Drawing or use any other imaging system. As long as you can pack those into the PixelBitmapContent, you&#8217;re good to go.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nickgravelyn.com/2010/02/scaling-retro-sprites-at-build-time/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The magic of yield</title>
		<link>http://blog.nickgravelyn.com/2010/02/the-magic-of-yield/</link>
		<comments>http://blog.nickgravelyn.com/2010/02/the-magic-of-yield/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 06:56:01 +0000</pubDate>
		<dc:creator>Nick</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.nickgravelyn.com/?p=1396</guid>
		<description><![CDATA[C# has this &#8216;yield&#8217; keyword for all sorts of crazy voodoo. Maybe I&#8217;m just late to the party, but it seems like this is one of those tricks you learn from really smart people (as I did) and realize that there is so much you don&#8217;t know about a language. You might want to start [...]]]></description>
			<content:encoded><![CDATA[<p>C# has this &#8216;yield&#8217; keyword for all sorts of crazy voodoo. Maybe I&#8217;m just late to the party, but it seems like this is one of those tricks you learn from really smart people (as I did) and realize that there is so much you don&#8217;t know about a language. You might want to start off by reading up some of the MSDN articles and other links found from this conveniently linked <a href="http://www.bing.com/search?q=C%23+yield">Bing search</a>.</p>
<p>Now that you have at least a basic idea of how this works, let&#8217;s talk about how we can use this to do fun things. First let&#8217;s talk about using it for scripting. A common scenario for scripts are to be able to execute, pause a bit, and continue executing. For instance, your characters says something, pauses, and then says something more. Traditionally you&#8217;d use some sort of state management to track this process and handle all the updates. With &#8216;yield&#8217;, we can actually create an interesting array of ways to implement scripting into our game in a way that, visually, looks like exactly how we&#8217;d want to write scripts.</p>
<p>First we define a delegate for our scripts:</p>
<pre class="brush: csharp;">public delegate IEnumerator&lt;float&gt; Script();</pre>
<p>Next we create a ScriptEngine class to handle all the logic of update a script, sleeping, and so forth. I&#8217;ll just toss in my script engine (with comments) so you can see how I implemented things:</p>
<pre class="brush: csharp;">// handles a set of scripts
public class ScriptEngine : GameComponent
{
	// the currently executing scripts
	private readonly List&lt;ScriptState&gt; scripts = new List&lt;ScriptState&gt;();

	public ScriptEngine(Game game)
		: base(game)
	{
	}

	public void ExecuteScript(Script script)
	{
		// wrap the script in our state
		ScriptState scriptState = new ScriptState(script);

		// the script may complete in one go
		scriptState.Execute(null);

		// if not, add it to our list
		if (!scriptState.IsComplete)
		{
			scripts.Add(scriptState);
		}
	}

	public override void Update(GameTime gameTime)
	{
		// execute all of our scripts
		foreach (var scriptState in scripts)
		{
			scriptState.Execute(gameTime);
		}

		// remove any completed scripts
		scripts.RemoveAll(s =&gt; s.IsComplete);
	}

	// a wrapper over the Script delegate to manage sleeping and the enumerator
	private class ScriptState
	{
		private float sleepLength;
		private Script script;
		private IEnumerator&lt;float&gt; scriptEnumerator;

		// the script is complete when we null out our script
		public bool IsComplete { get { return script == null; } }

		public ScriptState(Script script)
		{
			if (script == null)
				throw new ArgumentNullException(&quot;script&quot;);

			this.script = script;
		}

		// executes the script until the next sleep time.
		public void Execute(GameTime gameTime)
		{
			// the first run needs to get the script enumerator and first sleepLength (if any)
			if (scriptEnumerator == null)
			{
				scriptEnumerator = script();
				sleepLength = scriptEnumerator.Current;
			}

			// if we are sleeping, subtract the time from our timer
			if (sleepLength &gt; 0 &amp;&amp; gameTime != null)
			{
				sleepLength -= (float)gameTime.ElapsedGameTime.TotalSeconds;
			}

			// if the sleep timer is done...
			if (sleepLength &lt;= 0)
			{
				bool unfinished = false;
				do
				{
					// MoveNext continues execution of our script until the end or until
					// the next yield return. MoveNext returns true if a yield return is
					// hit or false if the method is complete.
					unfinished = scriptEnumerator.MoveNext();
					sleepLength = scriptEnumerator.Current;

					// as soon as we are finished or we need to sleep, we exit our loop
				} while (sleepLength &lt;= 0 &amp;&amp; unfinished);

				// if the script is not unfinished (i.e. is complete), we null out our
				// script and enumerator which flags the script as IsComplete and lets
				// the engine clean it up.
				if (!unfinished)
				{
					script = null;
					scriptEnumerator = null;
				}
			}
		}
	}
}</pre>
<p>You can see that I implemented my engine as a game component to make life a little easier. I also wrap each script into a nice little state object that tracks sleeping and the enumerator.</p>
<p>Now let&#8217;s see a little test game:</p>
<pre class="brush: csharp;">public class Game1 : Game
{
	ScriptEngine engine;

	public Game1()
	{
		new GraphicsDeviceManager(this);
		Content.RootDirectory = &quot;Content&quot;;
		Components.Add(engine = new ScriptEngine(this));
	}

	protected override void LoadContent()
	{
		engine.ExecuteScript(TestScript);
	}

	private IEnumerator&lt;float&gt; TestScript()
	{
		Console.WriteLine(&quot;Hello... (wait for it)&quot;);
		yield return 3f;
		Console.WriteLine(&quot;World!&quot;);
	}

	protected override void Draw(GameTime gameTime)
	{
		GraphicsDevice.Clear(Color.CornflowerBlue);
		base.Draw(gameTime);
	}
}</pre>
<p>When run you&#8217;ll see &#8220;Hello&#8230; (wait for it)&#8221; printed to the debug and then, three seconds later, &#8220;World!&#8221; is printed out. The yield return does the magic of handling our enumerator for us because the compiler really is building a whole state machine type class over that TestScript method. Then our ScriptEngine and ScriptState classes use an IEnumerator<float> to track the enumerator. To get the enumerator, we call the delegate like normal. From there, we simply call MoveNext on the IEnumerator<float> which will start execution at the last yield return statement.</p>
<p>I know this is a bit complex (especially if you dig in to the details of the compiler plumbing that makes it all work), but it&#8217;s still something you can play with. I find it nice because our TestScript method looks, for the most part, like what we&#8217;d want to script. Once we have this engine, we can tuck it away and not deal with it, making our life much easier for making scripts in our game. We could, of course, extend the scripting to not just return a float value. You could return any type you wanted to get information back to the engine. Maybe a custom type that has a sleep amount, other scripts to invoke before continuing, or any number of things. It&#8217;s really quite powerful.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.nickgravelyn.com/2010/02/the-magic-of-yield/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
