<?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; Code</title>
	<atom:link href="https://www.horsedrawngames.com/category/code/feed/" rel="self" type="application/rss+xml" />
	<link>https://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>Hdg Remote Debug &#8211; Released!</title>
		<link>https://www.horsedrawngames.com/hdg-remote-debug-released/</link>
		<comments>https://www.horsedrawngames.com/hdg-remote-debug-released/#comments</comments>
		<pubDate>Fri, 13 May 2016 09:00:42 +0000</pubDate>
		<dc:creator><![CDATA[Geoff]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Remote Debug Tool]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=230</guid>
		<description><![CDATA[You can now get the Remote Debug tool on the asset store! Editing live on the device has never been easier, for fast iteration time and the ultimate in &#8220;what you see is what you get&#8221;.  For more info check out this video, the forum thread or just read some of the other entries on this...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/hdg-remote-debug-released/" title="ReadHdg Remote Debug &#8211; Released!">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>You can now get the Remote Debug tool on the <a title="asset store" href="https://www.assetstore.unity3d.com/en/#!/content/61863">asset store</a>!</p>
<p>Editing live on the device has never been easier, for fast iteration time and the ultimate in &#8220;what you see is what you get&#8221;.  For more info check out this <a title="video" href="https://www.youtube.com/watch?v=3Oigkg-8rWQ">video</a>, the <a title="forum thread" href="http://forum.unity3d.com/threads/hdg-remote-debug-live-update-inspector-for-your-phone.399096/">forum thread</a> or just read some of the other entries on this blog!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/hdg-remote-debug-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hdg Remote Debug &#8211; How It Works</title>
		<link>https://www.horsedrawngames.com/hdg-remote-debug-more-info/</link>
		<comments>https://www.horsedrawngames.com/hdg-remote-debug-more-info/#comments</comments>
		<pubDate>Tue, 03 May 2016 01:06:49 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Remote Debug Tool]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[remote]]></category>
		<category><![CDATA[unity3d]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=220</guid>
		<description><![CDATA[Hdg Remote Debug works using .NET&#8217;s reflection features; it doesn&#8217;t use any sort of built-in Unity serialisation. Every second it gathers all GameObjects that are currently active, finds all Components on them, and for each component, uses reflection to find all serialised and public fields. This data is sent back to the client running in...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/hdg-remote-debug-more-info/" title="ReadHdg Remote Debug &#8211; How It Works">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>Hdg Remote Debug works using .NET&#8217;s reflection features; it doesn&#8217;t use any sort of built-in Unity serialisation. Every second it gathers all <code>GameObjects</code> that are currently active, finds all <code>Components</code> on them, and for each component, uses reflection to find all serialised and public fields. This data is sent back to the client running in the editor over a network connection, where the data is displayed in custom hierarchy and inspector windows.</p>
<p>This means it doesn&#8217;t use the built-in Unity inspectors or any custom inspectors you may have created, so when you click on, say, a <code>Camera</code> object you see the public and serialised fields of the <code>Camera</code> type rather than what Unity&#8217;s built-in <code>CameraEditor</code> inspector would have shown.</p>
<p>I would like to fix this and use the built-in inspectors and I have actually prototyped it extensively but it turns out there are several problems. To use the built-in inspectors we require a proxy <code>GameObject</code> that represents the selected object on the server. The idea is that whenever we receive a message from the server, we create a new proxy <code>GameObject</code>, dynamically add all components to it, and for each component, create an <code>Editor</code> instance with <code>Editor.CreateEditor(component)</code>. When drawing the UI for the components, we just call <code>Editor.OnInspectorGUI</code> for each one and use <code>BeginChangeCheck/EndChangeCheck</code> to determine if anything changed. If fields have changed we send a message to the server to update it.</p>
<p>There are a couple of problems with this approach. The built-in inspectors cause undo events to be added to the system, but those undo events are undesirable; the <code>GameObject</code> is a temporary proxy object for which we don&#8217;t want to track undo events. In fact the object is not visible in the scene, so the undo events seem spurious to the user. It&#8217;s not a good user experience to generate all these undo events that go nowhere.</p>
<p>Another problem is that <code>EndChangeCheck</code> doesn&#8217;t detect that changes have happened when certain fields are changed. One such field that I found was the camera mask property. It seems to be something to do with the <code>EditorGUI.PropertyField</code>, which doesn&#8217;t seem to set <code>GUI.changed</code> to true.</p>
<p>The last major problem is with the proxy <code>GameObject</code>. We create a new proxy every time we receive a message from the server, but destroying the previous one seems to cause the <code>Editor</code> objects that we created to throw <code>NullReferenceExceptions</code> when you hit play or when Unity reloads assemblies, when it tries to reinitialise its <code>serializedObject</code> field. I think I need to find a way to clear the reference on the <code>Editor</code> when destroying the <code>GameObject</code>, but it wasn&#8217;t possible when I last investigated. I can&#8217;t just leave the proxy object; that&#8217;s a memory leak!</p>
<p>I have a Trello <a href="https://trello.com/b/TSDsEbrA/hdg-remote-debug-roadmap" target="_blank">roadmap board</a> with some features I&#8217;d like to add. Some are wishlist features which may not really be possible without digging into the Unity source (e.g. hotswapping prefabs, or the aforementioned built-in inspectors). One feature I would like to add is an extensible console system, where you can hook in your own commands to control the game remotely. That way you can add debug features to the game that you can then control from Unity.</p>
<p>Get in touch if you have any questions or feature requests for Hdg Remote Debug!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/hdg-remote-debug-more-info/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Remote debug / live update of Unity builds on device</title>
		<link>https://www.horsedrawngames.com/remote-debug-live-update-of-unity-builds-on-device/</link>
		<comments>https://www.horsedrawngames.com/remote-debug-live-update-of-unity-builds-on-device/#comments</comments>
		<pubDate>Sat, 30 Apr 2016 12:09:43 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Remote Debug Tool]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[remote]]></category>
		<category><![CDATA[unity3d]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=214</guid>
		<description><![CDATA[Unity has a feature called the Unity Remote which is an app that you run on an Android or iOS device. The editor talks to this app via USB and sends the render output of the game as it is running in the editor to the device. The touch inputs from the device along with...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/remote-debug-live-update-of-unity-builds-on-device/" title="ReadRemote debug / live update of Unity builds on device">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>Unity has a feature called the <a title="Unity Remote" href="http://docs.unity3d.com/Manual/UnityRemote4.html" target="_blank">Unity Remote</a> which is an app that you run on an Android or iOS device. The editor talks to this app via USB and sends the render output of the game as it is running in the editor to the device. The touch inputs from the device along with other device-specific data such as GPS and accelerometer are also sent back to the editor. This gives you an idea of how your game looks on a device and also lets you test touch controls and other device hardware without having to constantly do full builds.</p>
<p>That&#8217;s the theory, anyway. A lot of people have complaints about the Unity Remote, saying that it doesn&#8217;t work very well or at all.</p>
<p>I&#8217;ve always felt that Unity should have a live debug view of the game running on the device that shows you all the GameObjects and their components and serialised fields. I imagined it would look like the regular built-in hierarchy and inspector windows, except it would be pulling the data via a network connection from the live build. A lot of AAA engines have a live update feature like this but Unity has nothing.</p>
<p>In 2014 I started work on a tool to do just this. I built an initial prototype with plans to sell it on the asset store. But then contracting jobs got in the way, and I put the project on hold. Late last year my contract work dried up, and I decided it was time to get back to it and finish it off, so I&#8217;ve spent the last four months working on it. It&#8217;s now working pretty well:</p>
<p>&nbsp;</p>
<p>You can sit in Unity, bring up the Remote Debug window, connect to your device, and see what&#8217;s happening on it, just as though you were looking at a build running in the editor. It&#8217;s really easy to iterate on things on the device, and I&#8217;ve found it especially useful for tweaking touch controls.</p>
<p>Currently it requires Unity 5.3.2f1 or better because I&#8217;m using the new <a href="https://docs.unity3d.com/ScriptReference/SceneManagement.Scene.GetRootGameObjects.html" target="_blank"><code>Scene.GetRootGameObjects</code></a> API that was added. I can make it work in previous versions of Unity but with some unfortunate side effects depending on what API I use. If I use <code>Object.FindObjectsOfType</code> I can&#8217;t get inactive objects. There is also <code>Resources.FindObjectsOfType</code> but it returns all objects including resources that were manually loaded from the Resources directory. I think I can filter these out, but it just means the server is a bit more costly in terms of memory and CPU. This is something I want to do though because it would be great to provide versions of the tool for Unity 5.x across the board.</p>
<p>I&#8217;ve made a thread on the <a href="http://forum.unity3d.com/threads/hdg-remote-debug-live-update-inspector-for-your-phone.399096/" target="_blank">Unity forums</a> about Hdg Remote Debug. If you want more information feel free to post there or email us here at Horse Drawn HQ. The tool should be going live on the asset store in the next couple of weeks.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/remote-debug-live-update-of-unity-builds-on-device/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Visual Studio shader syntax highlighting part 2</title>
		<link>https://www.horsedrawngames.com/shader-syntax-highlighting/</link>
		<comments>https://www.horsedrawngames.com/shader-syntax-highlighting/#comments</comments>
		<pubDate>Tue, 23 Feb 2016 05:11:53 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[cg]]></category>
		<category><![CDATA[glsl]]></category>
		<category><![CDATA[hlsl]]></category>
		<category><![CDATA[shaders]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=191</guid>
		<description><![CDATA[I have updated the NShader syntax highlighter to allow adding extra extensions dynamically via the Visual Studio settings. This is one of the most requested features, and it really is a feature that makes sense. The plugin was previously hard-coded to specific file extensions. The reason for this is because that&#8217;s just the way you...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/shader-syntax-highlighting/" title="ReadVisual Studio shader syntax highlighting part 2">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>I have updated the NShader syntax highlighter to allow adding extra extensions dynamically via the Visual Studio settings. This is one of the most requested features, and it really is a feature that makes sense. The plugin was previously hard-coded to specific file extensions. The reason for this is because that&#8217;s just the way you define what file extensions your language service is for in a Visual Studio plugin; you add a bunch of attributes to your <code>Package</code> implementation.</p>
<p>However if you implement the <code>IVsEditorFactory</code> interface, you can get an entry to show up in the VS settings page! You don&#8217;t even have to implement the full interface yourself because there is a built-in implementation that does most of the hard work called <code><a href="https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.package.editorfactory.aspx">EditorFactory</a></code>.</p>
<p>To use this updated version, in Tools->Options->Text Editor->File Extension, add a file extension, select &#8220;NShader Editor&#8221; in the dropdown, and click &#8220;Add&#8221;. Then when you open a file with any of those extensions they will use the NShader syntax highlighter. Files will default to using the HLSL highlighter, so if you want to force them to use GLSL, CG, or Unity, you can use the <code>shadertype</code> tag I mentioned in my <a href="http://www.horsedrawngames.com/shader-syntax-highlighting-in-visual-studio-2013/" title="previous">previous</a> post.</p>
<p>Note that all the file extensions that NShader previously recognised are still recognised, so if you are using any of those file types you don&#8217;t have to do anything extra.</p>
<p>It seems that there is a bug in at least Visual Studio 2013 and possibly earlier versions where the setting can be forgotten and when you open a file in the list the syntax highlighting is not applied. However, the extension still appears in the list. To work around this you must remove and re-add the extension to the list. Also in Visual Studio 2015 if you load a file from the &#8220;recently used&#8221; list it doesn&#8217;t seem to use the syntax highlighter, but if you load it from elsewhere (e.g. File->Open or the Solution Explorer) it will work. This seems like a bug in Visual Studio, because it worked in 2013.</p>
<p>If you add a file extension or use the <code>shadertype</code> tag you will need to close and re-open any currently open files to reflect the changes.</p>
<p>An installer for NShader can be downloaded <a href="https://github.com/samizzo/nshader/releases/download/2.0/NShader.vsix">here</a>. The installer can be used to install into both Visual Studio 2013 and 2015.</p>
<p>The source code is available on github <a href="https://github.com/samizzo/nshader">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/shader-syntax-highlighting/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Ring buffers / circular buffers</title>
		<link>https://www.horsedrawngames.com/ring-buffers-circular-buffers/</link>
		<comments>https://www.horsedrawngames.com/ring-buffers-circular-buffers/#comments</comments>
		<pubDate>Mon, 08 Feb 2016 00:59:33 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=118</guid>
		<description><![CDATA[A ring buffer, also known as a circular buffer or cyclic buffer, is a very useful data structure for certain situations, and worth having around in your programmer&#8217;s toolchest. It&#8217;s a fixed-size buffer but treated as though it&#8217;s connected end to end (that is, the end is connected to the start) and data is written...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/ring-buffers-circular-buffers/" title="ReadRing buffers / circular buffers">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>A <a title="ring buffer" href="https://en.wikipedia.org/wiki/Circular_buffer">ring buffer</a>, also known as a circular buffer or cyclic buffer, is a very useful data structure for certain situations, and worth having around in your programmer&#8217;s toolchest. It&#8217;s a fixed-size buffer but treated as though it&#8217;s connected end to end (that is, the end is connected to the start) and data is written and read in a FIFO (first-in first-out) way. Usually this is all hidden behind an API to make it easy to read and write to it.</p>
<p>They are often used when there is a need to read and write data in a streaming manner, for example, streaming audio to a sound card, I/O buffering for a UART in an embedded device, and in fact any I/O buffer situation (e.g. a network device or a disk). Because the buffer is fixed in size you know what the memory footprint will be up front and this makes it ideal for use in embedded systems or on consoles where memory is constrained and you don&#8217;t want to dynamically allocate memory.</p>
<h2>Overview</h2>
<p>You can imagine a ring buffer as a circular block of memory that cycles around like this (the numbers represent the indices into the block of memory, which is treated as an array of bytes):</p>
<p style="text-align: center;"><img class="size-full wp-image-122 aligncenter" alt="ringbuffer1" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer1.png" width="256" height="256" /></p>
<h6 style="text-align: center;">Fig. 1 &#8211; Imaginary ring buffer</h6>
<p>But of course in reality the memory is really laid out like this:</p>
<p style="text-align: center;"><img class="size-full wp-image-129 aligncenter" alt="ringbuffer2" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer2.png" width="512" height="81" /></p>
<h6 style="text-align: center;">Fig. 2 &#8211; Actual memory layout</h6>
<p>The current read and write locations in the buffer are tracked, and the ring buffer operation is as follows:</p>
<ul>
<li><span style="line-height: 1.5em;">When writing, we copy new data into the buffer starting at the write location, and if the new data goes off the end of the buffer, we wrap around and write the remaining data starting at the start of the buffer, until we have written all data or we run out of space.</span></li>
<li><span style="line-height: 1.5em;">When reading, we copy data out of the buffer starting at the read location until we have read some specified amount of data, or we reach the write location, wrapping around the end of the buffer as above.</span></li>
</ul>
<p>We know we&#8217;ve run out of space for writing when we reach the read location, and we know we have no more data to read when we reach the write location. In those cases we can just stop and return the amount of data actually written or read.</p>
<h2>Implementation</h2>
<p>Phew! That seems complicated! Let&#8217;s break this down and look at how we might implement it. We need to keep track of a few things:</p>
<ul>
<li>A pointer to the start of the memory for the buffer.</li>
<li>The size of the buffer in bytes.</li>
<li>The current read index in the buffer.</li>
<li>The current write index in the buffer.</li>
</ul>
<p>The read and write indices represent where the current read and write location is in the buffer (these could instead be kept as pointers if we wanted).</p>
<p>In my implementation I also choose to track:</p>
<ul>
<li>The number of bytes available for reading.</li>
<li>The number of bytes available for writing.</li>
</ul>
<p>We can actually avoid tracking these two if we want, but it makes everything a bit clearer and doesn&#8217;t cost us much more.</p>
<p>We also want to be able to read and write to the buffer. Let&#8217;s sketch out a class for what we have so far:</p>
<pre class="brush: cpp; title: ; notranslate">
class RingBuffer
{
    public:
        RingBuffer(int sizeBytes);
        ~RingBuffer();

        // Copies 'length' bytes from 'source' to the ring buffer.
        // Returns the number of bytes actually written, which may be less than 'length'
        // if there was insufficient space to write into the ring buffer.
        int Write(const void* source, int length);

        // Reads 'length' bytes from the ring buffer into 'dest'.
        // Returns the number of bytes actually read, which may be less than 'length'
        // if there was insufficient data in the ring buffer.
        int Read(void* dest, int length);

    private:
        char* m_buffer;
        int m_sizeBytes;
        int m_readIndex;
        int m_writeIndex;
        int m_readBytesAvailable;
        int m_writeBytesAvailable;
}
</pre>
<p>For our write function we&#8217;ll clamp the length to the amount of space available for writing, and for our read function we&#8217;ll clamp it to the amount of data available in the buffer for reading.</p>
<h2>Reading and Writing</h2>
<p>We have two possible situations we need to handle when implementing reading and writing. The case where the current write index is greater than the current read index:</p>
<p style="text-align: center;"><img class="size-full wp-image-132 aligncenter" alt="ringbuffer3" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer3.png" width="512" height="128" /></p>
<h6 style="text-align: center;">Fig. 3 &#8211; Write index greater than read index</h6>
<p>And the case where the current write index is less than the current read index:</p>
<p style="text-align: center;"><img class="size-full wp-image-143 aligncenter" alt="ringbuffer4" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer4.png" width="512" height="128" /></p>
<h6 style="text-align: center;">Fig. 4 &#8211; Write index less than read index</h6>
<p>For writing in figure 3, we need to split the write up into two regions. The first region is from the current write index to the end of the buffer (index 11 to 15 inclusive), and the second region is from the start of the buffer to just before the current read index (index 0 to 3 inclusive):</p>
<p style="text-align: center;"><a href="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer5.png"><img class="size-full wp-image-160 aligncenter" alt="ringbuffer5" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer5.png" width="512" height="128" /></a></p>
<h6 style="text-align: center;">Fig. 5 &#8211; Two regions for writing</h6>
<p>For the figure 4 case, we have just one region, from the current write index to just before the current read index (index 1 to 8 inclusive):</p>
<p style="text-align: center;"><a href="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer6.png"><img class="aligncenter size-full wp-image-161" alt="ringbuffer6" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer6.png" width="512" height="128" /></a></p>
<h6 style="text-align: center;">Fig. 6 &#8211; One region for writing</h6>
<p>Reading is pretty much the same, but opposite! For reading in the figure 3 case, we just read from the current read index to just before the current write index (index 4 to 10 inclusive). For the figure 4 case we need to split the read up into two regions. The first region is from the current read index to the end of the buffer (index 9 to 15 inclusive), and the second region is from the start of the buffer to just before the current write index (index 0 only).</p>
<p>When there are two regions, it&#8217;s possible that the length of data we want to write or read isn&#8217;t enough to take us into the second region! So we may only end up requiring one region. Clamping the length makes it easy to determine this without a whole lot of nested if statements, because we can compare the clamped length to the remaining bytes in the buffer from the current read or write index. I think this is easier to explain in code, so putting this all together, we can come up with a write function like this:</p>
<pre class="brush: cpp; title: ; notranslate">
int RingBuffer::Write(const void* source, int length)
{
    assert(m_buffer);
    assert(source);
    assert(length &gt;= 0);
    assert(m_writeBytesAvailable &gt;= 0);

    // If there is no space or nothing to write then don't do anything.
    if (m_writeBytesAvailable == 0 || length == 0)
        return 0;

    // Clamp the length to the number of bytes available for writing.
    if (length &gt; m_writeBytesAvailable)
        length = m_writeBytesAvailable;

    int remainingWriteBytes = m_sizeBytes - m_writeIndex;
    if (length &gt; remainingWriteBytes)
    {
        // If the number of bytes to write is bigger than the remaining bytes
        // in the buffer, we have to wrap around and write into two regions.
        memcpy(m_buffer + m_writeIndex, source, remainingWriteBytes);
        memcpy(m_buffer, (char*)source + remainingWriteBytes, length - remainingWriteBytes);
    }
    else
    {
        // No wrapping, only one region to write to, which starts from the write index.
        memcpy(m_buffer + m_writeIndex, source, length);
    }

    // Increment the write index and wrap around at the end.
    m_writeIndex = (m_writeIndex + length) % m_sizeBytes;

    // Update the read and write sizes.
    m_writeBytesAvailable -= length;
    m_readBytesAvailable += length;

    return length;
}
</pre>
<p>Our read function will look pretty similar:</p>
<pre class="brush: cpp; title: ; notranslate">
int RingBuffer::Read(void* dest, int length)
{
    assert(m_buffer);
    assert(dest);
    assert(length &gt;= 0);
    assert(m_readBytesAvailable &gt;= 0);

    // If there is no data in the buffer or nothing to read then don't do anything.
    if (IsEmpty() || length == 0)
        return 0;

    // Clamp the length to the maximum number of bytes available for reading.
    if (length &gt; m_readBytesAvailable)
        length = m_readBytesAvailable;

    int remainingReadBytes = m_sizeBytes - m_readIndex;
    if (length &gt; remainingReadBytes)
    {
        // If the number of bytes to read is bigger than the remaining bytes
        // in the buffer, we have to wrap around and read from two regions.
        memcpy(dest, m_buffer + m_readIndex, remainingReadBytes);
        memcpy((char*)dest + remainingReadBytes, m_buffer, length - remainingReadBytes);
    }
    else
    {
        // No wrapping, only one region to read from, which starts from the read index.
        memcpy(dest, m_buffer + m_readIndex, length);
    }

    // Increment the read index and wrap around at the end.
    m_readIndex = (m_readIndex + length) % m_sizeBytes;

    // Update the read and write sizes.
    m_writeBytesAvailable += length;
    m_readBytesAvailable -= length;

    return length;
}
</pre>
<p>And that&#8217;s it! There is a full implementation available <a href="https://github.com/samizzo/ring-buffer" title="here">here</a>. Note that it makes no attempt to be thread safe! You should lock as appropriate if you use this in a multi-threaded environment.</p>
<p>Next time we&#8217;ll look at using this class to dynamically generate a continuous audio stream!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/ring-buffers-circular-buffers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The case of the continually checked out prefabs</title>
		<link>https://www.horsedrawngames.com/the-case-of-the-continually-checked-out-prefabs/</link>
		<comments>https://www.horsedrawngames.com/the-case-of-the-continually-checked-out-prefabs/#comments</comments>
		<pubDate>Wed, 17 Jun 2015 07:49:33 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[unity]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=109</guid>
		<description><![CDATA[I&#8217;ve been helping out my friends over at Three Phase Interactive on their game Defect: Spaceship Destruction Kit a little bit. The game is being developed in Unity, and they&#8217;re using Perforce for source control. We&#8217;re using different combinations of the built-in Unity Perforce support and the P4Connect plugin. We&#8217;ve had a strange issue in Unity for...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/the-case-of-the-continually-checked-out-prefabs/" title="ReadThe case of the continually checked out prefabs">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been helping out my friends over at <a href="http://threephaseinteractive.com/">Three Phase Interactive</a> on their game <a href="http://sdkgame.com/">Defect: Spaceship Destruction Kit</a> a little bit. The game is being developed in Unity, and they&#8217;re using Perforce for source control. We&#8217;re using different combinations of the built-in Unity Perforce support and the <a href="https://www.assetstore.unity3d.com/en/#!/content/25523">P4Connect</a> plugin. We&#8217;ve had a strange issue in Unity for a while now where it would try to check out two specific prefabs seemingly randomly. There seemed to be no reason why, as the prefabs weren&#8217;t directly being changed!</p>
<p>After much searching around and digging, I was able to discover the reason for this. If you have a prefab in your project with a <code>MonoBehaviour</code> which implements the <code>OnValidate</code> function, Unity will at times execute the <code>OnValidate</code> on prefabs that aren&#8217;t in the current scene and are not even selected in the project tab.</p>
<p>In the <code>OnValidate</code>, if you assign any values to certain members, Unity then flags the prefab as dirty, and thus when you save the project it decides that it needs to be checked out of source control. In our case the values weren&#8217;t actually changing; they were being set to the same as their initial values, so the prefabs would be checked out but then there wouldn&#8217;t be any changes in the file.</p>
<p>The most common times when Unity runs <code>OnValidate</code> appear to be when entering play mode, and when Unity rebuilds after code has changed.</p>
<p>I was able to reproduce this behaviour in a small test project, but only when modifying properties of the <code>GameObject</code>&#8216;s transform (e.g. setting <code>transform.rotation</code> to identity). Setting serialised class members didn&#8217;t seem to trigger this issue, so it seems that it only happens if you set built-in Unity properties (maybe it hooks into the property setter).</p>
<p>In SDK the way I solved this was to add this code to the top of the <code>OnValidate</code> methods:</p>
<pre class="brush: csharp; title: ; notranslate">
#if UNITY_EDITOR
   if (gameObject.hideFlags == HideFlags.HideInHierarchy)
      return;
#endif
</pre>
<p>However in my test project, that didn&#8217;t work, and I had to instead do this:</p>
<pre class="brush: csharp; title: ; notranslate">
if (transform.rotation != Quaternion.identity)
   transform.rotation = Quaternion.identity;
</pre>
<p>I suspect that only changing the values if they are different is the more reliable method; in SDK prefabs seemed to be set to <code>HideInHierarchy</code> but that wasn&#8217;t the case in my test project. I&#8217;m not sure why as I couldn&#8217;t see anywhere where it was changing the hide flags, so I may have to go back and change it in SDK.</p>
<p>It took a while to figure this out, but it was thanks to a post over on the NGUI forums <a href="http://www.tasharen.com/forum/index.php?topic=6766.5;wap2">here</a> and a post on Unity answers <a href="http://answers.unity3d.com/questions/623461/prefabs-in-git.html">here</a> that I was able to track this down!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/the-case-of-the-continually-checked-out-prefabs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Shader syntax highlighting in Visual Studio 2013</title>
		<link>https://www.horsedrawngames.com/shader-syntax-highlighting-in-visual-studio-2013/</link>
		<comments>https://www.horsedrawngames.com/shader-syntax-highlighting-in-visual-studio-2013/#comments</comments>
		<pubDate>Mon, 15 Jun 2015 04:10:17 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[cg]]></category>
		<category><![CDATA[glsl]]></category>
		<category><![CDATA[hlsl]]></category>
		<category><![CDATA[shaders]]></category>
		<category><![CDATA[visual studio 2013]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=95</guid>
		<description><![CDATA[If you edit shader code in Visual Studio 2013, you might like to use NShader to get syntax highlighting. NShader was originally written by Alexandre Mutel. His version is available here but it only supports VS2008, VS2010, and VS2012. Issam Khalil had forked it and added VS2013 support, as well as Unity shader highlighting. I&#8217;ve...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/shader-syntax-highlighting-in-visual-studio-2013/" title="ReadShader syntax highlighting in Visual Studio 2013">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>If you edit shader code in Visual Studio 2013, you might like to use NShader to get syntax highlighting. NShader was originally written by Alexandre Mutel. His version is <a href="https://nshader.codeplex.com/">available here</a> but it only supports VS2008, VS2010, and VS2012. Issam Khalil had <a href="https://nshader.codeplex.com/SourceControl/network/forks/IssamK/VS2013andUnityShaders">forked</a> it and added VS2013 support, as well as Unity shader highlighting.</p>
<p>I&#8217;ve <a href="https://github.com/samizzo/nshader">forked</a> Issam&#8217;s code and added a couple of features. The installer for the extension can be downloaded <a href="https://github.com/samizzo/nshader/releases/download/2.0/NShader.vsix">here</a>. This installer can be used to install into both Visual Studio 2013 and 2015.</p>
<p>You can now override the file type detection by specifying, on the first line of a shader file, a comment like so:</p>
<p><code>// shadertype=&lt;type&gt;</code></p>
<p>where <code>&lt;type&gt;</code> is one of:</p>
<blockquote><p>hlsl<br />
glsl<br />
cg<br />
unity
</p></blockquote>
<p>This will force the file to use the specified syntax highlighter. This is case sensitive and must appear exactly as above. Otherwise if the <code>shadertype</code> tag is not present, the file extension will be used to decide what type of highlighting to use. The following extensions are recognised:</p>
<blockquote><p>
HLSL syntax highlighter &#8211; .fx, .fxh, .hlsl, .vsh, .psh, .fsh<br />
GLSL syntax highlighter &#8211; .glsl, .frag, .vert, .fp, .vp, .geom, .xsh<br />
CG syntax highlighter &#8211; .cg, .cgfx<br />
Unity syntax highlighter &#8211; .shader, .cginc, .compute
</p></blockquote>
<p>The keyword mapping files that can be placed in <code>%APPDATA%\NShader</code> now override the built-in mappings. For example, if <code>float</code> is mapped as a <code>keyword</code> in the built-in mapping for GLSL, it can be changed to a <code>type</code> by adding the following line to <code>%APPDATA%\NShader\GLSLKeywords.map</code>:</p>
<blockquote><p>TYPE=float</p></blockquote>
<p>Multiple words can be specified on a single line by separating them with spaces or tabs. The zip file contains the built-in keyword mapping files as examples.</p>
<p>I&#8217;ve also added a separate colour setting for anything that is defined as a <code>type</code>. This should appear in Tools &gt; Options &gt; Environment &gt; Fonts and Colors in the display items list for the text editor colours. Scroll down to &#8216;n&#8217; and you should see all the NShader colour settings. The new setting is &#8216;NShader &#8211; Type&#8217;.</p>
<p>If you are having troubles with files not highlighting, try uninstalling NShader first via Tools &gt; Extensions and Updates. Also make sure you restart Visual Studio after installing NShader!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/shader-syntax-highlighting-in-visual-studio-2013/feed/</wfw:commentRss>
		<slash:comments>52</slash:comments>
		</item>
		<item>
		<title>BinaryFormatter on iOS</title>
		<link>https://www.horsedrawngames.com/binaryformatter-on-ios/</link>
		<comments>https://www.horsedrawngames.com/binaryformatter-on-ios/#comments</comments>
		<pubDate>Tue, 06 May 2014 15:28:12 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[unity]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=88</guid>
		<description><![CDATA[If you&#8217;re trying to use a BinaryFormatter under iOS you may discover that it doesn&#8217;t work. You may get exceptions like &#8220;ExecutionEngineException: Attempting to JIT compile method ..&#8221;. This is because by default the mono BinaryFormatter uses runtime generated class serializers. This won&#8217;t work on iOS because JIT compilation is not permitted. To get around...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/binaryformatter-on-ios/" title="ReadBinaryFormatter on iOS">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;re trying to use a BinaryFormatter under iOS you may discover that it doesn&#8217;t work. You may get exceptions like &#8220;ExecutionEngineException: Attempting to JIT compile method ..&#8221;. This is because by default the mono BinaryFormatter uses runtime generated class serializers. This won&#8217;t work on iOS because JIT compilation is not permitted. To get around this, you can force mono to use reflection to perform the serialization instead. You can do this by inserting this line:</p>
<pre class="brush: csharp; title: ; notranslate">
Environment.SetEnvironmentVariable(&quot;MONO_REFLECTION_SERIALIZER&quot;, &quot;yes&quot;);
</pre>
<p>somewhere in your project (e.g. in the Awake() method of the MonoBehaviour that needs to use serialization).</p>
<p>You could also instead use <a href="https://code.google.com/p/protobuf-net/">protobuf-net</a>, which is a serializer for .NET that uses Google&#8217;s <a href="https://code.google.com/p/protobuf/">Protocol Buffers</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/binaryformatter-on-ios/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>EditorWindow and play mode</title>
		<link>https://www.horsedrawngames.com/editorwindow-and-play-mode/</link>
		<comments>https://www.horsedrawngames.com/editorwindow-and-play-mode/#comments</comments>
		<pubDate>Sun, 27 Apr 2014 09:30:20 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[unity]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=84</guid>
		<description><![CDATA[If you&#8217;re trying to write custom editors in Unity you may run into a snag. I just spent several hours hitting my head against a wall trying to solve this issue. When you enter play mode, Unity will reload all mono assemblies. This means that your EditorWindow object is recreated, and you will need to...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/editorwindow-and-play-mode/" title="ReadEditorWindow and play mode">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;re trying to write custom editors in Unity you may run into a snag. I just spent several hours hitting my head against a wall trying to solve this issue.</p>
<p>When you enter play mode, Unity will reload all mono assemblies. This means that your EditorWindow object is recreated, and you will need to explicitly handle serialising and deserialising any settings that you want to persist between edit mode and play mode. This is detailed on the <a href="http://blogs.unity3d.com/2012/10/25/unity-serialization/">Unity blog</a> but unfortunately is not really covered in the documentation.</p>
<p>This is all well and good but Texture2D instances don&#8217;t seem to be serialised, even if you use the Serializable attribute. In my case, I am using small 1&#215;1 instances of Texture2D when drawing a horizontal group of controls in order to draw highlighted selections. These textures are initialised in my EditorWindow&#8217;s constructor every time. However, when entering play mode, although the constructor and OnEnable are called, at the next OnGUI call the textures are again null!</p>
<p>I am not sure if this is by design, but it certainly isn&#8217;t documented except in various <a href="http://forum.unity3d.com/threads/63555-Editor-Extension-Persistent-Data">forum</a> <a href="http://answers.unity3d.com/questions/430579/editor-serialization.html">posts</a>. My workaround for this is to re-create the textures in OnGUI if they are null. It&#8217;s ugly but it works!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/editorwindow-and-play-mode/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unity performance and empty functions</title>
		<link>https://www.horsedrawngames.com/unity-performance-and-empty-functions/</link>
		<comments>https://www.horsedrawngames.com/unity-performance-and-empty-functions/#comments</comments>
		<pubDate>Thu, 20 Feb 2014 03:00:17 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[unity]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=73</guid>
		<description><![CDATA[We&#8217;re busy here at Horse Drawn HQ working on our first mobile and tablet game. We&#8217;ve still got a bit of a way to go, but I thought I&#8217;d do some profiling of our game on my iPhone 4 using Unity&#8217;s built-in profiler to see where we were at. I was surprised to see an...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/unity-performance-and-empty-functions/" title="ReadUnity performance and empty functions">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>We&#8217;re busy here at Horse Drawn HQ working on our first mobile and tablet game. We&#8217;ve still got a bit of a way to go, but I thought I&#8217;d do some profiling of our game on my iPhone 4 using Unity&#8217;s built-in profiler to see where we were at. I was surprised to see an update function showing up for each of the main playable game objects and taking anywhere from 4ms to 9ms! This was the function:</p>
<pre class="brush: csharp; title: ; notranslate">
void Update()
{
    Vector4 campos = Camera.main.transform.position;
    campos = renderer.worldToLocalMatrix.MultiplyPoint(campos);
    renderer.material.SetVector(&quot;_modelSpaceCameraPos&quot;, campos);
}
</pre>
<p>This code transforms the camera position into model space and then sets the result as a shader constant. Okay, so maybe it&#8217;s just that slow &#8211; it&#8217;s being done for up to 125 objects every frame. I&#8217;m not too worried about it at the moment though, because that shader constant is only used by a particular material which we&#8217;re currently not planning on shipping with. However, we want to be able to switch materials, so I changed the code to the following:</p>
<pre class="brush: csharp; title: ; notranslate">
void Update()
{
    if (m_updateCamPos)
    {
        Vector4 campos = Camera.main.transform.position;
        campos = renderer.worldToLocalMatrix.MultiplyPoint(campos);
        renderer.material.SetVector(&quot;_modelSpaceCameraPos&quot;, campos);
    }
}
</pre>
<p><code>m_updateCamPos</code> is usually false, and true only when we use the material that needs it. At the moment the game isn&#8217;t using those materials so this is always false. This helped a lot; the function still shows up but now only at around 0.1ms or 0.2ms. Unfortunately it still spikes at 2ms or 3ms (once even at 33ms)! This still isn&#8217;t good enough. I don&#8217;t want an empty function to show up at all (note that it is possible that the empty function will be optimised out in a final build, but you can&#8217;t profile a final build in Unity).</p>
<p>It turns out that Unity actually calls the MonoBehaviour methods that you &#8216;override&#8217; using reflection; Update, Start, et al are not actually virtual methods. You can tell because you never have to use the &#8216;override&#8217; or &#8216;new&#8217; keywords when defining those functions, which C# requires if you are introducing a new implementation of an inherited method, and also Start and Awake can have a return type of void OR IEnumerator but C# doesn&#8217;t support covariant return types. To be a bit more concrete about it, if we bust open MonoBehaviour in Visual Studio or ILDasm we see this (note: attributes and comments removed for brevity):</p>
<pre class="brush: csharp; title: ; notranslate">
namespace UnityEngine
{
    public class MonoBehaviour : Behaviour
    {
        public MonoBehaviour();
        public bool useGUILayout { get; set; }
        public void CancelInvoke();
        public void CancelInvoke(string methodName);
        public void Invoke(string methodName, float time);
        public void InvokeRepeating(string methodName, float time, float repeatRate);
        public bool IsInvoking();
        public bool IsInvoking(string methodName);
        public static void print(object message);
        public Coroutine StartCoroutine(IEnumerator routine);
        public Coroutine StartCoroutine(string methodName);
        public Coroutine StartCoroutine(string methodName, object value);
        public Coroutine StartCoroutine_Auto(IEnumerator routine);
        public void StopAllCoroutines();
        public void StopCoroutine(string methodName);
    }
}
</pre>
<p>If you dig deeper down the inheritance hierarchy (MonoBehaviour -> Behaviour -> Component -> Object) you can see that there are no virtual functions at all. So Unity is using reflection to call these functions, and reflection is <a href="https://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx" title="not cheap" target="_blank">not cheap</a>! I would imagine that Unity are doing things like caching the MethodInfo objects, or even converting to delegates which are apparently faster. But I think the best thing to do is to write your code in such a way that empty update functions don&#8217;t exist. This is commonly mentioned in relation to the OnGUI function but it seems that it applies to all the common MonoBehaviour functions. In our case, I will be removing the method entirely for now, but if and when we need this functionality I will create a derived class that implements update, so that the common case is not penalised.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/unity-performance-and-empty-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
