<?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>Horse Drawn Games &#187; Uncategorized</title>
	<atom:link href="http://www.horsedrawngames.com/category/uncategorized/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.horsedrawngames.com</link>
	<description>Horse Drawn Games</description>
	<lastBuildDate>Sun, 10 Jun 2018 09:50:52 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	
	<item>
		<title>Type-safe object pool for Unity</title>
		<link>http://www.horsedrawngames.com/type-safe-object-pool-for-unity/</link>
		<comments>http://www.horsedrawngames.com/type-safe-object-pool-for-unity/#comments</comments>
		<pubDate>Sat, 09 Jun 2018 11:37:13 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=278</guid>
		<description><![CDATA[Managing memory usage can be crucial for decent performance in game development, especially on memory-constrained devices like mobile phones or consoles. It&#8217;s usually best to allocate what you need up-front at startup or on level load rather than mid-game during a frame, because the default memory allocators can be slow at finding free memory blocks....  <a class="excerpt-read-more" href="http://www.horsedrawngames.com/type-safe-object-pool-for-unity/" title="ReadType-safe object pool for Unity">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>Managing memory usage can be crucial for decent performance in game development, especially on memory-constrained devices like mobile phones or consoles. It&#8217;s usually best to allocate what you need up-front at startup or on level load rather than mid-game during a frame, because the default memory allocators can be slow at finding free memory blocks. Constructing objects can also be time consuming depending on the complexity of your classes.</p>
<p>In a garbage collected, managed language like C# you still have to worry about this. You don&#8217;t know when the garbage collector is going to clean up objects that are no longer referenced in order to reclaim unused memory. If you allocate objects regularly every frame that quickly become unused and unreferenced, you&#8217;ll probably cause regular hitches in your framerate. Also in Unity the <code>Instantiate</code> function call can take quite a bit of CPU time.</p>
<p>One technique we can use to avoid these issues is called &#8220;object pooling&#8221;. Let&#8217;s say you want to spawn a firework particle effect:</p>
<a href="http://www.horsedrawngames.com/2014/wp-content/uploads/2018/06/fx.gif"><img class="alignnone size-full wp-image-285 aligncenter" alt="fx" src="http://www.horsedrawngames.com/2014/wp-content/uploads/2018/06/fx.gif" width="218" height="200" /></a>
<p>Instead of instantiating the prefab whenever you need it, you could pre-instantiate a list of them and disable them. Then when you need to spawn a new firework, go through the list, find one that isn&#8217;t enabled, enable it, configure its position, and play it. When it finishes, disable it. This way you re-use firework effects instead of continually creating new objects and destroying them later.</p>
<h2>A First Attempt</h2>
<p>A first pass on a system like this might look as follows:</p>
<pre class="brush: cpp; title: ; notranslate">
using UnityEngine;
using System.Collections.Generic;

public class BasicObjectPool : MonoBehaviour
{
    // Prefab for this object pool
    public GameObject m_prefab;

    // Size of this object pool
    public int m_size;

    public void Awake()
    {
        // Instantiate the pooled objects and disable them.
        for (var i = 0; i &lt; m_size; i++)
        {
            var pooledObject = Instantiate(m_prefab, transform);
            pooledObject.gameObject.SetActive(false);
        }
    }

    // Returns an object from the pool. Returns null if there are no more
    // objects free in the pool.
    public GameObject Get()
    {
        if (transform.childCount == 0)
            return null;

        return transform.GetChild(0).gameObject;
    }

    // Returns an object to the pool.
    public void ReturnObject(GameObject pooledObject)
    {
        // Reparent the pooled object to us and disable it.
        var pooledObjectTransform = pooledObject.transform;
        pooledObjectTransform.parent = transform;
        pooledObjectTransform.localPosition = Vector3.zero;
        pooledObject.gameObject.SetActive(false);
    }
}
</pre>
<p>Note that our <code>Get</code> method returns null if there are no more objects in the pool. We could also dynamically increase the size of the pool here, but that defeats the purpose of pre-allocating the objects. It&#8217;s up to the code calling <code>Get</code> to check if no object is available and handle that situation. In practice you would pick a pool size that adequately covers the maximum number of objects you would like to have available at any one time. It&#8217;s not feasible to just keep spawning objects &#8211; you&#8217;ll run out of memory if you do!</p>
<p>This solution isn&#8217;t bad, but I have one big problem with it. The pool doesn&#8217;t know what type of component you&#8217;re pooling! This means that you have to do a <code>GetComponent</code> call every time you get an object out of the pool. It also means that there are no guarantees that the pool even HAS the component type you&#8217;re expecting; you can&#8217;t enforce it, so someone could mis-configure it in a prefab or a scene.</p>
<p>Can we do better? Yes! With generics!</p>
<h2>Generics</h2>
<p>Generics are a feature of the C# language. They let you design a class or write a method with a placeholder type, which means you can write classes or methods that work with any data type, and still remain type safe. Unity makes use of them, and in fact if you use Unity&#8217;s <code>GetComponent&lt;..&gt;()</code> methods you, are already using them yourself.</p>
<p>This line:</p>
<pre class="brush: cpp; title: ; notranslate">fooGameObject.GetComponent&lt;FooComponent&gt;()</pre>
<p>gets the MonoBehaviour of type <code>FooComponent</code> which is on <code>fooGameObject</code>. How can this work? The Unity developers don&#8217;t know anything about your <code>FooComponent</code>. This syntax with the angled brackets indicates that the <code>GetComponent</code> method is a generic method which can work with any type (actually, specifically any MonoBehaviour type). When you call the method and put your type in the angled brackets, you tell the compiler to automatically generate a version of <code>GetComponent</code> that knows specifically about your type.</p>
<p>For more detailed information about generics, check out this <a href="https://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx" target="_blank">introduction</a> from Microsoft.</p>
<h2>Improved Implementation</h2>
<p>Let&#8217;s implement our object pool class using generics. First we need to define a generic version of the class that accepts a type name. We want to pool Unity components, so we&#8217;ll also add a constraint on the type which says that it <strong>must</strong> be a MonoBehaviour:</p>
<pre class="brush: cpp; title: ; notranslate">public class ObjectPool&lt;T&gt; : MonoBehaviour where T : MonoBehaviour</pre>
<p>The <code>where</code> keyword defines the constraint. There are several different <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters" target="_blank">types</a> of constraints we can specify. In our case we want the constraint that says &#8220;the type MUST derive from MonoBehaviour&#8221;.</p>
<p>Now that we have the class defined like this, we can use the generic type placeholder <code>T</code> anywhere that we want to refer to the type that the pool was created with:</p>
<pre class="brush: cpp; title: ; notranslate">
public class ObjectPool&lt;T&gt; : MonoBehaviour where T : MonoBehaviour
{
    // Prefab for this pool. The prefab must have a component of type T on it.
    public T m_prefab;

    // Size of this object pool
    public int m_size;

    // The list of free and used objects for tracking.
    // We use the generic collections so we can give them our type T.
    private List m_freeList;
    private List m_usedList;

    public void Awake()
    {
        m_freeList = new List(m_size);
        m_usedList = new List(m_size);

        // Instantiate the pooled objects and disable them.
        for (var i = 0; i &lt; m_size; i++)
        {
            var pooledObject = Instantiate(m_prefab, transform);
            pooledObject.gameObject.SetActive(false);
            m_freeList.Add(pooledObject);
        }
    }
}
</pre>
<p>Let&#8217;s now add two methods: one to get an object out of the pool and one to return an object back to the pool. Previously we passed GameObjects around because we didn&#8217;t know what type we would be dealing with. Now that we are using generics, we can use our placeholder <code>T</code>:</p>
<pre class="brush: cpp; title: ; notranslate">
public T Get()
{
    var numFree = m_freeList.Count;
    if (numFree == 0)
        return null;

    // Pull an object from the end of the free list.
    var pooledObject = m_freeList[numFree - 1];
    m_freeList.RemoveAt(numFree - 1);
    m_usedList.Add(pooledObject);
    return pooledObject;
}

// Returns an object to the pool. The object must have been created
// by this ObjectPool.
public void ReturnObject(T pooledObject)
{
    Debug.Assert(m_usedList.Contains(pooledObject));

    // Put the pooled object back in the free list.
    m_usedList.Remove(pooledObject);
    m_freeList.Add(pooledObject);

    // Reparent the pooled object to us, and disable it.
    var pooledObjectTransform = pooledObject.transform;
    pooledObjectTransform.parent = transform;
    pooledObjectTransform.localPosition = Vector3.zero;
    pooledObject.gameObject.SetActive(false);
}
</pre>
<p>And we&#8217;re done! You can see the <a href="https://github.com/samizzo/TypeSafeObjectPool/blob/master/Assets/Scripts/ObjectPool.cs" target="_blank">full class</a> over on github. Now, we can&#8217;t actually add this class to a GameObject yet. As it stands, the class is just a kind of template. It doesn&#8217;t really exist as any concrete code until we declare it somewhere with a concrete type.</p>
<p>Let&#8217;s assume that we have an <code>Explosion</code> MonoBehaviour which is on a prefab:</p>
<pre class="brush: cpp; title: ; notranslate">
public class Explosion : MonoBehaviour
{
    private ParticleSystem m_particleSystem;

    public bool IsAlive { get { return m_particleSystem.IsAlive(); } }

    public void Awake()
    {
        m_particleSystem = GetComponent&lt;ParticleSystem&gt;();
    }

    public void Spawn(Vector3 position)
    {
        gameObject.SetActive(true);
        gameObject.transform.position = position;
        m_particleSystem.Play();
    }
}
</pre>
<p>We want to create a pool of <code>Explosion</code> objects. To do this, we must define a new class which derives from <code>ObjectPool</code> with the <code>Explosion</code> as our type parameter:</p>
<pre class="brush: cpp; title: ; notranslate">
public class ExplosionPool : ObjectPool&lt;Explosion&gt;
{
}
</pre>
<p>And that&#8217;s it! You can now add <code>ExplosionPool</code> to a GameObject, and assign a prefab to it. The <code>ObjectPool</code>&#8216;s <code>m_prefab</code> field will appear in the inspector, and it will only allow you to drop an <code>Explosion</code> component on it. It&#8217;s strongly typed!</p>
<a href="http://www.horsedrawngames.com/2014/wp-content/uploads/2018/06/objectpool.png"><img class="aligncenter size-full wp-image-333" style="border: 1px solid black;" alt="objectpool" src="http://www.horsedrawngames.com/2014/wp-content/uploads/2018/06/objectpool.png" width="448" height="215" /></a>
<p>Now to spawn an explosion, you can do this:</p>
<pre class="brush: cpp; title: ; notranslate">
public void SpawnExplosion(Vector3 position)
{
    var explosion = m_explosionPool.Get();
    if (explosion == null)
    {
        // The pool is empty, so we can't spawn any more at the moment.
        return;
    }

    explosion.Spawn(position);
    m_activeExplosions.Add(explosion);
}
</pre>
<p>In the above example we also keep track of the active explosions so we can return them to the pool when they are finished:</p>
<pre class="brush: cpp; title: ; notranslate">
public void Update()
{
    for (var i = 0; i &lt; m_activeExplosions.Count - 1; i &gt;= 0; i--)
    {
        var explosion = m_activeExplosions[i];
        if (!explosion.IsAlive)
        {
            m_activeExplosions.RemoveAt(i);
            m_explosionPool.ReturnObject(explosion);
        }
    }
}
</pre>
<p>Over on github I have a <a href="https://github.com/samizzo/TypeSafeObjectPool" target="_blank">sample Unity project</a> that demonstrates both the non-type-safe and type-safe methods. It&#8217;s a simple project that fires some particles from a pool when you click in the game window.</p>
<p>Feel free to hit me up on <a href="https://twitter.com/BananaboySam" target="_blank">Twitter</a> if you have any questions, or leave a comment below!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.horsedrawngames.com/type-safe-object-pool-for-unity/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Decoding iOS crash call stacks</title>
		<link>http://www.horsedrawngames.com/decoding-ios-crash-call-stacks/</link>
		<comments>http://www.horsedrawngames.com/decoding-ios-crash-call-stacks/#comments</comments>
		<pubDate>Wed, 05 Apr 2017 13:58:34 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=237</guid>
		<description><![CDATA[Wow it&#8217;s been a while since I updated the blog! I think we&#8217;re due for a web site refresh too. But first let&#8217;s talk about call stacks! Let&#8217;s say your iOS game crashes outside of the debugger. Assuming your device is plugged into your mac, you can get the device log from Xcode by bringing...  <a class="excerpt-read-more" href="http://www.horsedrawngames.com/decoding-ios-crash-call-stacks/" title="ReadDecoding iOS crash call stacks">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>Wow it&#8217;s been a while since I updated the blog! I think we&#8217;re due for a web site refresh too. But first let&#8217;s talk about call stacks!</p>
<p>Let&#8217;s say your iOS game crashes outside of the debugger. Assuming your device is plugged into your mac, you can get the device log from Xcode by bringing up the &#8220;Devices&#8221; window via Window -> Devices. You should see a live updated log and you might be able to find your crash details in among the spammy output. But even better &#8211; if you click on &#8220;View Device Logs&#8221; you&#8217;ll see a list of apps that have crashed.</p>
<a href="https://www.horsedrawngames.com/2014/wp-content/uploads/2017/04/Screen-Shot-2017-04-05-at-10.53.50-PM.png"><img src="https://www.horsedrawngames.com/2014/wp-content/uploads/2017/04/Screen-Shot-2017-04-05-at-10.53.50-PM.png" alt="Screen Shot 2017-04-05 at 10.53.50 PM" width="1238" height="838" class="alignnone size-full wp-image-257" /></a>
<p>In this example, <a href="https://www.polyphoniclp.com/resynth" title="Resynth" target="_blank">Resynth</a> (a game I&#8217;ve been working on for my new company <a href="https://www.polyphoniclp.com" title="Polyphonic LP" target="_blank">Polyphonic LP</a>) has crashed a couple of times, and I&#8217;ve selected one of the crashes.</p>
<p>Why did it crash? Luckily we have the full call stack. A call stack is simply a list of functions that are currently being executed by the CPU. In this case, the call stack looks like this:</p>
<pre class="brush: cpp; title: ; notranslate">
Thread 0 Crashed:
0   libobjc.A.dylib               	0x000000018749ef68 objc_msgSend + 8
1   Foundation                    	0x0000000189548ba4 _NS_os_log_callback + 68
2   libsystem_trace.dylib         	0x0000000187b0f954 _NSCF2data + 112
3   libsystem_trace.dylib         	0x0000000187b0f564 _os_log_encode_arg + 736
4   libsystem_trace.dylib         	0x0000000187b0ffb8 _os_log_encode + 1036
5   libsystem_trace.dylib         	0x0000000187b13200 os_log_with_args + 892
6   libsystem_trace.dylib         	0x0000000187b1349c os_log_shim_with_CFString + 172
7   CoreFoundation                	0x0000000188a38de4 _CFLogvEx3 + 152
8   Foundation                    	0x0000000189549cb0 _NSLogv + 132
9   resynth                       	0x000000010056ac28 0x10004c000 + 5368872
10  resynth                       	0x000000010056b654 0x10004c000 + 5371476
11  resynth                       	0x000000010056bdd4 0x10004c000 + 5373396
12  resynth                       	0x00000001000b13f4 0x10004c000 + 414708
13  resynth                       	0x0000000100081c94 0x10004c000 + 220308
14  resynth                       	0x00000001000816f4 0x10004c000 + 218868
15  resynth                       	0x000000010053a33c 0x10004c000 + 5169980
16  resynth                       	0x0000000100e23404 0x10004c000 + 14513156
17  resynth                       	0x0000000100714b54 0x10004c000 + 7113556
18  resynth                       	0x0000000100714f24 0x10004c000 + 7114532
19  resynth                       	0x0000000100708054 0x10004c000 + 7061588
20  resynth                       	0x0000000100709db4 0x10004c000 + 7069108
21  resynth                       	0x000000010070a0a8 0x10004c000 + 7069864
</pre>
<p>There isn&#8217;t much symbol information; the only thing we can really see is that the <code>NSLog</code> function was running. But what called <code>NSLog</code> and what caused it to crash?</p>
<p>Fortunately there are several tools we can use to decode this. I&#8217;m going to cover one of them today: <code>atos</code>. <code>atos</code> converts memory addresses to symbol names, and it comes with macOS and lives in <code>/usr/bin</code> so it should already be in your path. It takes a couple of parameters:</p>
<p><code>atos -arch &lt;architecture&gt; -l &lt;load address&gt; -o &lt;path to debug binary&gt; &lt;addresses&gt;</code></p>
<p>We need to supply the architecture of our binary, the load address (the base address in memory where the executable was loaded), the path to a version of our binary with full debug information present, and the list of call stack addresses that we wish to translate into symbols.</p>
<p>If you have archived your game from Xcode, the full debug executable can be found inside the archive, in <code>dSYMs/resynth.app.dSYM/Contents/Resources/DWARF</code>.</p>
<p>Our architecture is <code>arm64</code> (unless you&#8217;re running <code>arm7</code> which is unlikely these days).</p>
<p>For this crash our load address is <code>0x10004c000</code>. The load address could be anything and won&#8217;t always be the same. Sometimes the load address might not be present, and the call stack lines might look something like this:</p>
<pre class="brush: cpp; title: ; notranslate">9   resynth                       	0x000000010056ac28 resynth + 5368872</pre>
<p>This can happen if you get your crash information from the device log view in Xcode instead of from the specific application crash view.</p>
<p>Here <code>0x000000010056ac28</code> is the real memory address where this particular function was loaded, and <code>5368872</code> is the offset of the function from the load address. We can therefore easily calculate the load address; it&#8217;s just <code>0x000000010056ac28 - 5368872</code> which is <code>0x10004C000</code>.</p>
<p>Now we have everything we need, so let&#8217;s run this!</p>
<pre class="brush: cpp; title: ; notranslate">
$ atos -arch arm64 -l 0x10004c000 -o resynth-debug 0x000000010056ac28 0x000000010056b654 0x000000010056bdd4
CM_NSLog(NSString*, ...) (in resynth-debug) (CloudManager.mm:17)
-[CloudManager getLongLong:] (in resynth-debug) (CloudManager.mm:171)
getLongLong (in resynth-debug) (CloudManager.mm:225)
</pre>
<p>In the interests of brevity I&#8217;ve used only the three top most addresses. This is usually enough to figure out the problem anyway!</p>
<p>In this case the culprit turns out to be the <code>getLongLong</code> Objective-C method:</p>
<pre class="brush: cpp; title: ; notranslate">
- (long long) getLongLong:(NSString *)key
{
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    long long value = [[userDefaults objectForKey:key] longLongValue];
    DEBUG(@&quot;CloudManager: getLongLong key=%@ value=%@&quot;, key, value);
    return value;
}
</pre>
<p>On line 5 we specify a string with the <code>%@</code> format specifier, which means we should be passing in an <code>NSObject</code>-derived object. However, we are instead passing a <code>long long</code> value which causes a crash.</p>
<p>The fix is simple. We just convert the <code>long long</code> to an <code>NSObject</code>:</p>
<pre class="brush: cpp; title: ; notranslate">DEBUG(@&quot;CloudManager: getLongLong key=%@ value=%@&quot;, key, @(value));</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.horsedrawngames.com/decoding-ios-crash-call-stacks/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Merry Christmas!</title>
		<link>http://www.horsedrawngames.com/merry-christmas-2/</link>
		<comments>http://www.horsedrawngames.com/merry-christmas-2/#comments</comments>
		<pubDate>Wed, 25 Dec 2013 08:35:39 +0000</pubDate>
		<dc:creator><![CDATA[hdg]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/2014/?p=62</guid>
		<description><![CDATA[Merry Christmas from Horse Drawn Games! We’re a new team of indie game developers in Australia and are doing a soft launch of our new studio. Exciting things are happening, including our first project and a new website. We can’t wait to show you but in the meanwhile, we’ve baked you a delicious Christmas treat! We...  <a class="excerpt-read-more" href="http://www.horsedrawngames.com/merry-christmas-2/" title="ReadMerry Christmas!">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>Merry Christmas from Horse Drawn Games! We’re a new team of indie game developers in Australia and are doing a soft launch of our new studio. Exciting things are happening, including our first project and a new website. We can’t wait to show you but in the meanwhile, we’ve baked you a delicious <a href="http://www.horsedrawngames.com/xmas">Christmas treat</a>!</p>
<p>We also had some fun recently making a little <a href="http://www.horsedrawngames.com/nye">New Year&#8217;s Eve</a> greeting!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.horsedrawngames.com/merry-christmas-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
