<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Nick Gravelyn's Blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/nicgrave/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/nicgrave/feed.xml</link>
    <description>on XNA Game Studio and game development</description>
    <lastBuildDate>Wed, 17 Apr 2019 03:27:12 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Change in UIElementRenderer behavior and update to UIElementRendererHelper</title>
      <link>https://docs.microsoft.com/archive/blogs/nicgrave/change-in-uielementrenderer-behavior-and-update-to-uielementrendererhelper</link>
      <pubDate>Mon, 26 Sep 2011 09:30:00 GMT</pubDate>
      <dc:creator><![CDATA[NickGravelyn]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nicgrave/2011/09/26/change-in-uielementrenderer-behavior-and-update-to-uielementrendererhelper/</guid>
      <description><![CDATA[A while I back I posted about a UIElementRendererHelper class I had made to simplify life when...]]></description>
      <content:encoded><![CDATA[<p>A while I back I posted about a UIElementRendererHelper class I had made to simplify life when mixing Silverlight and XNA Framework rendering in Windows Phone 7 Mango. Since then we've shipped an update or two to the tools and along with those has come a change in how UIElementRenderer works and as such an update to my own UIElementRendererHelper.<br /><br />When we shipped the first beta of XNA GS 4.0 Refresh along with the Windows Phone 7.1 SDK, you were able to call UIElementRenderer.Render() anywhere you wanted in your draw code. This was convenient as it allowed you to keep all your UIElementRenderer code in one location however it wasn't really safe or consistent enough for our liking. Under the hood, the Render method needs to do a render target swap to draw certain UI elements to the texture which meant that in some cases you'd lose your backbuffer and in others you wouldn't. This was a bit inconsistent since our default render targets discard the backbuffer when switching between them and it was also way too complicated to have developers have to track what elements do what in which conditions.<br /><br />In an effort to make the framework more consistent and safe for our developers, we updated the type to make sure that Render always discards the backbuffer to ensure developers don't get caught in weird situations. By making this consistent with our render target API, developers have to only learn one set of rules which apply both to custom render targets and the UIElementRenderer. I believe this is a big improvement, even if it means a change from our original beta behavior.<br /><br />As for UIElementRendererHelper this means that the existing code is likely to break real rendering scenarios because the call to Render is in the middle of the draw (the helper specifically hooks up after your page's draw code, calls Render, and then draws the UI). As such a change was required. I didn't like any of the more automated solutions such as creating and managing new timers, so instead I just made the helper a little less automatic. The original usage for construction still applies:<br /><br /><span style="font-family: 'courier new', courier;">// Make a field for the helper</span><br /><span style="font-family: 'courier new', courier;">UIElementRendererHelper uiRenderer;</span><br /><br /><span style="font-family: 'courier new', courier;">// Construct in OnNavigatedTo after enabling XNA rendering</span><br /><span style="font-family: 'courier new', courier;">uiRenderer = new UIElementRendererHelper(this);</span><br /><br /><span style="font-family: 'courier new', courier;">// Dispose in OnNavigatedFrom before turning off XNA rendering</span><br /><span style="font-family: 'courier new', courier;">uiRenderer.Dispose();</span><br /><br />However now you must do some manual method calls in OnDraw to make sure the UI can render into the texture before you've started drawing the scene:<br /><br /><span style="font-family: 'courier new', courier;">// PreRender handles rendering the Silverlight content to the render target</span><br /><span style="font-family: 'courier new', courier;">uiRenderer.PreRender();</span><br /><br /><span style="font-family: 'courier new', courier;">SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);</span><br /><br /><span style="font-family: 'courier new', courier;">// TODO: Add your drawing code here</span><br /><br /><span style="font-family: 'courier new', courier;">// Draw uses SpriteBatch to draw the Silverlight UI to the screen</span><br /><span style="font-family: 'courier new', courier;">uiRenderer.Draw();</span><br /><br />It's not quite as nice as the original, but the helper still handles a lot of things for you such as managing the size of the UIElementRenderer in case of page resizing (e.g. toggling the app bar, rotating the screen, etc). Additionally it still handles translating the UI drawing due to the on screen keyboard coming up for text boxes.<br /><br />Hopefully this information helps you in your own code and the helper can continue to be useful as you get your apps and games Mango ready.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/10/21/67/35/UIElementRendererHelperSample.zip" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-21-67-35/UIElementRendererHelperSample.zip">UIElementRendererHelperSample.zip</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Simplifying UIElementRenderer usage for full-page scenarios</title>
      <link>https://docs.microsoft.com/archive/blogs/nicgrave/simplifying-uielementrenderer-usage-for-full-page-scenarios</link>
      <pubDate>Tue, 24 May 2011 12:18:00 GMT</pubDate>
      <dc:creator><![CDATA[NickGravelyn]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nicgrave/2011/05/24/simplifying-uielementrenderer-usage-for-full-page-scenarios/</guid>
      <description><![CDATA[UPDATE: Please see this new post regarding UIElementRendererHelper as it includes a newer version of...]]></description>
      <content:encoded><![CDATA[<p><strong>UPDATE: Please see <a href="https://blogs.msdn.com/b/nicgrave/archive/2011/09/26/change-in-uielementrenderer-behavior-and-update-to-uielementrendererhelper.aspx">this new post</a> regarding UIElementRendererHelper as it includes a newer version of the code that is better suited for Windows Phone 7.1 SDK RTM.</strong></p>
<p>With the new Windows Phone Developer Tools 7.1 Beta you can combine Silverlight and XNA Framework in a single app for Windows Phone. This is super powerful for enabling rich UI for games or for rendering 3D content for your application (among an almost infinite list of other ideas I'm sure you'll all come up with). The feature is very powerful, but I wanted to make it even easier for developers.</p>
<p>Built into the framework is the new UIElementRenderer type. This new object takes a Silverlight UIElement and renders it to an XNA Framework Texture2D object. You then can draw that Texture2D to the screen using the XNA Framework APIs (like SpriteBatch) which gives you Silverlight UI integrated into your XNA Framework rendered content. However there are a couple interesting things we found during development:</p>
<ol>
<li>There is a lot of boiler plate code when you desire to render the whole Silverlight page, such as hooking the LayoutUpdated event, calling Render on the UIElementRenderer, and the SpriteBatch code to draw it to the screen.</li>
<li>Handling the TextBox control properly with the on screen keyboard is a bit of a chore, since you need to watch the page transform and adjust your rendering of the page directly.</li>
</ol>
<p>Given these two concerns I cooked up a class called the UIElementRendererHelper. What the helper does is allow you to add full page rendering with UIElementRenderer, and handle all the page transform stuff, in just three lines of code for your page. Here's the basic usage:</p>
<pre>// Make a field for the helper
UIElementRendererHelper uiRenderer;

// Construct after enabling XNA rendering in OnNavigatedTo
uiRenderer = new UIElementRendererHelper(this, timer); // timer is a GameTimer instance

// Dispose before turning off XNA rendering in OnNavigatedFrom
uiRenderer.Dispose();</pre>
<p>That's it. The constructor automatically hooks up all the proper events and even hooks the timer's Draw event so that it draws the scene for you. This does, of course, assume you've already hooked the Draw event for yourself, otherwise you'll have the Silverlight content rendering first. However if you put this into the default page template in the places described above, you'll be fine.</p>
<p><span style="text-decoration: line-through;">I've attached the sample to this post which contains the UIElementRendererHelper class and a very small sample app for its usage. This code is all licensed under the <a title="https://www.microsoft.com/opensource/licenses.mspx#Ms-PL" href="https://blogs.msdn.com/controlpanel/blogs/posteditor.aspx/Microsoft Public License">Microsoft Public License</a>, so have at it. :)&nbsp;</span><strong>UPDATE: Please see&nbsp;<a href="https://blogs.msdn.com/b/nicgrave/archive/2011/09/26/change-in-uielementrenderer-behavior-and-update-to-uielementrendererhelper.aspx">this new post</a>&nbsp;regarding UIElementRendererHelper as it includes a newer version of the code that is better suited for Windows Phone 7.1 SDK RTM.</strong></p>]]></content:encoded>
    </item>
    <item>
      <title>WPF Hosting for XNA Game Studio 4.0</title>
      <link>https://docs.microsoft.com/archive/blogs/nicgrave/wpf-hosting-for-xna-game-studio-4-0</link>
      <pubDate>Fri, 25 Mar 2011 10:30:00 GMT</pubDate>
      <dc:creator><![CDATA[NickGravelyn]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nicgrave/2011/03/25/wpf-hosting-for-xna-game-studio-4-0/</guid>
      <description><![CDATA[A while back I wrote up a method for rendering XNA Game Studio 4.0 content inside of a WPF window....]]></description>
      <content:encoded><![CDATA[<p>A while back I <a href="https://blogs.msdn.com/b/nicgrave/archive/2010/07/25/rendering-with-xna-framework-4-0-inside-of-a-wpf-application.aspx">wrote up a method</a> for rendering XNA Game Studio 4.0 content inside of a WPF window. My method involved using a render target and doing a CPU transfer of those bits into a WriteableBitmap. This method had some pros and cons:</p>
<p><strong>Pros:</strong></p>
<ol>
<li>Extremely simple in concept and in actual implementation.</li>
<li>Enabled high level of composition with native WPF elements.</li>
<li>Allowed app to leverage WPF input events.</li>
</ol>
<p><strong>Cons:</strong></p>
<ol>
<li>Not the most efficient process, given a full CPU swap of the pixels each frame. (The R/B swap I did on the CPU could be moved to a pixel shader prior to getting the data which would reduce a good bit of the work, but you're still moving a lot of data from the GPU into the WriteableBitmap every frame).</li>
<li>Limits the app from using render targets without more plumbing work as switching away from the main render target prevents the content from making it to the screen.</li>
</ol>
<p>These limits may be acceptable for some people. I built a real-time shader editing tool using this system and it worked great for my needs. However since some people have asked for more ways to do this integration that provide more performance and don't require the render targets, I went back to the drawing board a bit. After talking with a coworker for a bit (i.e. taking his core idea and running with it ;-) ), I have come up a new solution for this integration using WPF's HwndHost base type.</p>
<p>The idea of the new solution is simple: create a control subclasses WPF's HwndHost to create a child window to which the XNA Framework will render graphics. I leveraged the GraphicsDeviceService from the <a href="https://create.msdn.com/en-US/education/catalog/sample/winforms_series_1">WinForms sample</a> (with some modifications) to handle GraphicsDevice management and used the CompositionTarget.Rendering event to drive my draw loop. I also used some concepts from the GraphicsDeviceControl in the WinForms sample so that each of my controls will present to the correct window handle, thus enabling apps to have multiple controls running at the same time and sharing the same GraphicsDevice.</p>
<p>This solution, however, is not without its own set of trade offs. Essentially we're flipping the pro/con list from above:</p>
<p><strong>Pros:</strong></p>
<ol>
<li>Rendering requires no CPU copies as we Present directly to the child window where we want our content. This means we get some great performance even with large windows.</li>
<li>Since we're presenting directly to the window, we no longer use render targets which allows the app itself to use them for any purpose.</li>
</ol>
<p><strong>Cons:</strong></p>
<ol>
<li>Due to the nature of hosting a child window, you cannot composite WPF controls on top of the GraphicsDeviceControl (the exception being other child window content such as menus or dialogs).</li>
<li>Because the control is really a child window, mouse input is directed to that window's WndProc which means input handling requires a bit more work and causes some duplication of events. My sample does implement enough of this work to be useful, however there may be some things you want that I didn't tackle.</li>
<li>This solution requires a few native method calls and an implementation of a WndProc which means the implementation is quite a bit more complex than my previous solution. The usage is still relatively straight forward, however.</li>
</ol>
<p>What it comes down to is that these two solutions are both useful in different ways and therefore I recommend you look at them both to see which will meet your needs. </p>
<p>At a high level, use of this new sample is very simple. Add a GraphicsDeviceControl into your XAML layout where you want to render XNA graphics. The GraphicsDeviceControl has a LoadContent event that will fire when the GraphicsDevice has been created and a RenderXna event that fires each frame for you to draw your content. Additionally there are a number of "Hwnd*" events for various aspects of mouse input since I couldn't route it through the normal UIElement mouse events. The control also has methods to capture/release the mouse which makes the cursor invisible and forces the cursor position to reset, which is great for tools where you want to rotate an object and not worry about the mouse leaving the view. </p>
<p>The sample application shows how to leverage these various actions in an app with two GraphicsDeviceControls. The top control draws a constantly spinning cube whose color is based on the sliders in the left panel. The bottom control draws a cube in one of three colors than can be changed with the buttons next to the control (or using the 'R', 'G', or 'B' keyboard keys which are set up as hotkeys for those buttons). Additionally you can use the right mouse button and drag to rotate the bottom cube without capturing the mouse or the left mouse button and drag to rotate the cube with capturing the mouse.</p>
<p>Hopefully this proves useful to some of you. Feel free to leave questions or comments below, but to make this point clear: the implementation of this solution is pretty complex and I cannot provide much support as I simply don't have the time. I encourage everyone to play with it, but if you run into issues please start by checking out MSDN documentation or ask on the <a href="https://forums.create.msdn.com/forums">App Hub forums</a> so that the community can work with you to solve the issue.</p>
<p><i>Disclaimer: This code was written by a colleague and myself and is <strong>not</strong> an official solution for mixing XNA Game Studio and WPF. Use of this sample is at your own risk and I make no guarantees as to the quality or usability of the code. I do not guarantee any level of support for users of this sample. The code in the downloadable sample is licensed under the Microsoft Public License, the terms of which can be found here:&nbsp;</i><a href="https://www.microsoft.com/opensource/licenses.mspx#Ms-PL">https://www.microsoft.com/opensource/licenses.mspx#Ms-PL</a></p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/10/14/39/89/WpfHostedXna.zip" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-14-39-89/WpfHostedXna.zip">WpfHostedXna.zip</a></p>]]></content:encoded>
    </item>
    <item>
      <title>MediaPlayer changes in XNA Game Studio 4.0 for Windows Phone</title>
      <link>https://docs.microsoft.com/archive/blogs/nicgrave/mediaplayer-changes-in-xna-game-studio-4-0-for-windows-phone</link>
      <pubDate>Fri, 18 Mar 2011 09:48:00 GMT</pubDate>
      <dc:creator><![CDATA[NickGravelyn]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nicgrave/2011/03/18/mediaplayer-changes-in-xna-game-studio-4-0-for-windows-phone/</guid>
      <description><![CDATA[MediaPlayer, the interface for playing music on Windows Phone, is seeing some small tweaks that can...]]></description>
      <content:encoded><![CDATA[<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;">MediaPlayer, the interface for playing music on Windows Phone, is seeing some small tweaks that can affect applications. These changes are visible in the emulator that comes with the January update to the Windows Phone Developer Tools and will become more visible when the next update for Windows Phones rolls out through Zune.</span></span></p>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;"><br /></span></span>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;">The short is that you are no longer allowed to set the Volume or IsMuted properties when the active media source is the Zune media library and any time you switch between library music and title music, you must reset any properties on MediaPlayer you care about. These changes were made to ensure applications didn&rsquo;t alter the user&rsquo;s music playback experience in a way that the native Zune media player cannot reverse (there is no UI in the Zune media player for music-specific volume or a mute control).</span></span></p>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;"><br /></span></span>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;">You can see this change today in the emulator. If you were to run the following code you would see that the Volume and IsMuted are ignored while media from the user&rsquo;s library is playing:</span></span></p>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;"><br /></span></span>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9.5pt">MediaPlayer</span><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt">.Play(<span style="COLOR: blue">new</span> <span style="COLOR: #2b91af">MediaLibrary</span>().Songs);<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9.5pt">MediaPlayer</span><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt">.Volume = .5f;<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9.5pt">MediaPlayer</span><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt">.IsMuted = <span style="COLOR: blue">true</span>;<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9.5pt">Debug</span><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt">.WriteLine(<span style="COLOR: #a31515">"Volume: {0}, IsMuted: {1}"</span>, <span style="COLOR: #2b91af">MediaPlayer</span>.Volume, <span style="COLOR: #2b91af">MediaPlayer</span>.IsMuted);<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt"><o:p>&nbsp;</o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt">Output:<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt">Volume: 1, IsMuted: False<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><o:p>&nbsp;</o:p></span></p>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;">While the change does affect certain applications attempting to replace the default Zune media player, for some apps and games that play their own music there is a side effect that may cause issues. Because the user may be listening to music on their device when your game starts, if you are setting the Volume or IsMuted properties for your own title music those properties may be ignored.</span></span></p>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;"><br /></span></span>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;">For example, a common pattern with music playback was something like this where the code would load the song, set the properties accordingly, and then start song playback:</span></span></p>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;"><br /></span></span>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9.5pt">Song</span><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt"> song = Content.Load&lt;<span style="COLOR: #2b91af">Song</span>&gt;(<span style="COLOR: #a31515">"BackgroundMusic"</span>);<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9.5pt">MediaPlayer</span><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt">.Volume = 0.5f;<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9.5pt">MediaPlayer</span><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt">.Play(song);<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt"><o:p>&nbsp;</o:p></span></p>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;">This worked in RTM because we didn&rsquo;t care what the active media source was; we would set those properties for whatever was playing. With our change this can have issues if the user is listening to music when you try to set the volume. </span></span></p>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;"><br /></span></span>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;">Moving forward <strong>we always recommend playing your music before setting any of the MediaPlayer properties</strong> to ensure they are applied to your game&rsquo;s music:</span></span></p>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;"><br /></span></span>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9.5pt">Song</span><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt"> song = Content.Load&lt;<span style="COLOR: #2b91af">Song</span>&gt;(<span style="COLOR: #a31515">"BackgroundMusic"</span>);<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9.5pt">MediaPlayer</span><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt">.Play(song);<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; COLOR: #2b91af; FONT-SIZE: 9.5pt">MediaPlayer</span><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt">.Volume = 0.5f;<o:p></o:p></span></p>
<p class="MsoNormal"><span style="FONT-FAMILY: Consolas; FONT-SIZE: 9.5pt"><o:p>&nbsp;</o:p></span></p>
<p class="MsoNormal"><span style="font-size: small;"><span style="font-family: Calibri;">If you follow this new pattern, it will ensure your title will continue to work as expected when the update rolls out to users. The good part is that you can title update your game today and it will work on the RTM version of Windows Phone as well as the upcoming update. <o:p></o:p></span></span></p>
</p>
<p><o:p></o:p></p>
</p>
<p><o:p></o:p></p>
</p>
<p><o:p></o:p></p>
</p>
<p><span style="LINE-HEIGHT: 115%; FONT-FAMILY: Consolas; FONT-SIZE: 9pt"><o:p></o:p></span></p>
</p>
<p><o:p></o:p></p>
</p>
<p><o:p></o:p></p>
</p>]]></content:encoded>
    </item>
    <item>
      <title>‘using’ IDisposable objects</title>
      <link>https://docs.microsoft.com/archive/blogs/nicgrave/using-idisposable-objects</link>
      <pubDate>Tue, 28 Dec 2010 13:46:32 GMT</pubDate>
      <dc:creator><![CDATA[NickGravelyn]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nicgrave/2010/12/28/using-idisposable-objects/</guid>
      <description><![CDATA[This isn’t fully game related, but I see so many people posting code on forums that looks like this:...]]></description>
      <content:encoded><![CDATA[<p>This isn’t fully game related, but I see so many people posting code on forums that looks like this:</p>  <pre class="code"><span style="color: #2b91af">Stream </span>stream = storageContainer.CreateFile(<span style="color: #a31515">&quot;MyFile.txt&quot;</span>);
<span style="color: #2b91af">StreamWriter </span>writer = <span style="color: blue">new </span><span style="color: #2b91af">StreamWriter</span>(stream);
writer.Write(<span style="color: #a31515">&quot;Stuff&quot;</span>);
writer.Close();
stream.Close();</pre>

<p>I cringe at this sight. </p>

<p>IDisposable is an interface that objects leveraging native handles or resources will almost always implement to ensure the native resources are released properly and deterministically. If any of the code in there were to cause an exception, you’d risk not releasing those resources at that point. At best you’d see them released when a garbage collection occurred and at worst they wouldn’t get cleaned up at all.</p>

<p>Now, most people will respond with “but there’s so little going on there, what would throw an exception?” and that’s valid for this example, but a lot of games do a lot more in there. Things like serializing (or deserializing) objects, parsing strings into numbers, and so on. There are lots of places where file IO, state saving/loading, and other Stream manipulation can throw, so it’s always better to be on the side of safety rather than stubbornness.</p>

<p>Anytime a type implements IDisposable, that should be your hint to leverage the <a href="https://msdn.microsoft.com/en-us/library/yh598w02.aspx">‘using’ statement</a>. In an unfortunate case, the ‘using’ keyword is not only used for including namespaces but also for scoping IDisposable objects so that they are guaranteed to be disposed. To reuse the example above, here’s the correct way to write that:</p>

<pre class="code"><span style="color: blue">using </span>(<span style="color: #2b91af">Stream </span>stream = storageContainer.CreateFile(<span style="color: #a31515">&quot;MyFile.txt&quot;</span>))
{
    <span style="color: blue">using </span>(<span style="color: #2b91af">StreamWriter </span>writer = <span style="color: blue">new </span><span style="color: #2b91af">StreamWriter</span>(stream))
    {
        writer.Write(<span style="color: #a31515">&quot;Stuff&quot;</span>);
    }
}</pre>

<p>Not only does this help scope your objects to prevent using either the stream or writer objects outside of their respective blocks, but it means that even if the code in the middle of the ‘using’ block throws an exception, the objects created in the ‘using’ statements are guaranteed to be disposed. Basically the compiler takes the above code and turns it into this:</p>

<pre class="code">{
    <span style="color: #2b91af">Stream </span>stream = storageContainer.CreateFile(<span style="color: #a31515">&quot;MyFile.txt&quot;</span>);
    <span style="color: blue">try
    </span>{
        <span style="color: #2b91af">StreamWriter </span>writer = <span style="color: blue">new </span><span style="color: #2b91af">StreamWriter</span>(stream);

        <span style="color: blue">try
        </span>{
            writer.Write(<span style="color: #a31515">&quot;Stuff&quot;</span>);
        }
        <span style="color: blue">finally
        </span>{
            <span style="color: blue">if </span>(writer != <span style="color: blue">null</span>)
                ((<span style="color: #2b91af">IDisposable</span>)writer).Dispose();
        }
    }
    <span style="color: blue">finally
    </span>{
        <span style="color: blue">if </span>(stream != <span style="color: blue">null</span>)
            ((<span style="color: #2b91af">IDisposable</span>)stream).Dispose();
    }
}</pre>

<p>(And yes, those extra curly braces are intended; they are used to scope the ‘stream’ object so it cannot be used outside of the ‘using’ block.)</p>

<p>As you can see this is much safer code than the first snippet because it removes the possibility of not disposing those objects and thus ensures that native resources will be properly released when you expect rather than when the next GC occurs or when your app shuts down.</p>

<p>So please, if you find yourself writing code similar to the first snippet, please stop doing that and start ‘using’ IDisposable objects properly. <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/34/41/metablogapi/6330.wlEmoticon-winkingsmile_0A3C92E8.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-34-41-metablogapi/6330.wlEmoticon_2D00_winkingsmile_5F00_0A3C92E8.png" /></p>]]></content:encoded>
    </item>
    <item>
      <title>Build-time content pipeline usage in Windows games</title>
      <link>https://docs.microsoft.com/archive/blogs/nicgrave/build-time-content-pipeline-usage-in-windows-games</link>
      <pubDate>Wed, 24 Nov 2010 13:36:07 GMT</pubDate>
      <dc:creator><![CDATA[NickGravelyn]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nicgrave/2010/11/24/build-time-content-pipeline-usage-in-windows-games/</guid>
      <description><![CDATA[One of the problems that some folks have hit in XNA Game Studio 4.0 is not being able to use the...]]></description>
      <content:encoded><![CDATA[<p>One of the problems that some folks have hit in XNA Game Studio 4.0 is not being able to use the build-time content pipeline assemblies in their Windows games. Generally this is desired when developers are trying to save out an object using the IntermediateSerializer so they can use the resulting XML as a template to create more of those files as content in their project.</p>  <p>One of the gotchas with this is that XNA Game Studio 4.0 Windows games default to using the <em>.NET Framework 4.0 Client Profile. </em>The Client Profile is a slimmed down set of the .NET Framework that contains most of the functionality a shipping product would need. This profile was created so that .NET applications can use a smaller .NET Redistributable and therefore be a smaller total package size for users. However the Client Profile does not contain a lot of the build-time features of the .NET Framework such as MSBuild.</p>  <p>In order to use the build-time content pipeline assemblies and functionality, you must switch your game to use the full .NET Framework. This is a pretty easy set of steps to fix up:</p>  <ol>   <li>Right click the game project and select <em>Properties.</em></li>    <li>Find the <em>Target Framework</em> drop down menu which should say <em>.NET Framework 4.0 Client Profile</em> and change that to just <em>.NET Framework 4.0.</em></li>    <li>Save the properties (which will cause a project reload) and your game now targets the full .NET Framework.</li> </ol>  <p>Once you’ve switched the target framework, you should find all of the build-time assemblies of .NET Framework show up in the Add References dialog including the build-time content pipeline assemblies. </p>  <p>Do keep in mind that this doesn’t change anything in terms of the EULA or what you are permitted to redistribute with your Windows game; you should read the EULA for XNA Game Studio before distributing your Windows game to ensure that you are following all of the rules. But for simply finding out how to format your XML or for using the build-time components for some other reason, this should help you get up and running.</p>]]></content:encoded>
    </item>
    <item>
      <title>What storage is right for me?</title>
      <link>https://docs.microsoft.com/archive/blogs/nicgrave/what-storage-is-right-for-me</link>
      <pubDate>Wed, 10 Nov 2010 15:30:00 GMT</pubDate>
      <dc:creator><![CDATA[NickGravelyn]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nicgrave/2010/11/10/what-storage-is-right-for-me/</guid>
      <description><![CDATA[Developers moving across all three of the platforms supported by XNA Game Studio might find...]]></description>
      <content:encoded><![CDATA[<p>Developers moving across all three of the platforms supported by XNA Game Studio might find themselves working with their storage code to create a single codebase that works across all three. One of the main confusions can be the issue of what actually works on each of the platforms. Here’s a small table that quickly sums up what you have on each platform:</p>  <table border="0" cellspacing="0" cellpadding="2" width="500"><tbody>     <tr>       <td valign="top" width="131">&#160;</td>        <td valign="top" width="216">         <p style="margin-right: 0px" dir="ltr"><strong>StorageDevice/StorageContainer</strong></p>       </td>        <td valign="top" width="151"><strong>IsolatedStorage</strong></td>     </tr>      <tr>       <td valign="top" width="131"><strong>Windows</strong></td>        <td valign="top" width="216">Yes</td>        <td valign="top" width="151">Yes</td>     </tr>      <tr>       <td valign="top" width="131"><strong>Windows Phone 7</strong></td>        <td valign="top" width="216">No</td>        <td valign="top" width="151">Yes</td>     </tr>      <tr>       <td valign="top" width="131"><strong>Xbox 360</strong></td>        <td valign="top" width="216">Yes</td>        <td valign="top" width="151">Yes</td>     </tr>   </tbody></table>  <p>Allow me now to elaborate on the Xbox 360 implementation of isolated storage as that is likely the most interesting part of this post. A few high level points can be made to give some details about how isolated storage works on Xbox 360:</p>  <ul>   <li>IsolatedStorageFile is analogous to the StorageContainer API. This means you can only have one open at a time and you need to dispose of it in order to commit the changes. </li>    <li>IsolatedStorageFile is a non-player specific container, so it cannot be used for player specific save files. </li>    <li>IsolatedStorageFile’s underlying container appears in the Xbox UI as “Storage for [Game Title]”; there is no way to customize this as there is with StorageContainers. </li>    <li>Given that GetUserStoreForApplication() isn’t as asynchronous method, IsolatedStorageFile will not prompt the user for a storage device. It will always attempt to create the container on the same device as the game. This has a few notable results:      <ul>       <li>No UI popups; your game simply has access to the data. </li>        <li>Your user cannot choose the device on which their data is saved. </li>        <li>If the device holding the game is full or close to it, you may not be able to save enough data or even create the container. </li>        <li>If the game is moved from one device to another after the container is created, the game will not see the old container unless it is also moved. </li>     </ul>   </li> </ul>  <p>So as the title says, “what storage is right for me?” </p>  <p>Generally speaking the recommendation for games on Xbox 360 is to use the StorageDevice/StorageContainer APIs. These are what professional titles for XBLA and retail will use (or the native equivalents) and will therefore make your game feel more at home in the ecosystem. Isolated storage is there if it fits your needs and your desired experience, but be mindful of the limitations that come with that API as you work on your game.</p>]]></content:encoded>
    </item>
    <item>
      <title>Encoding and decoding images in XNA Game Studio 4.0</title>
      <link>https://docs.microsoft.com/archive/blogs/nicgrave/encoding-and-decoding-images-in-xna-game-studio-4-0</link>
      <pubDate>Sun, 03 Oct 2010 23:17:53 GMT</pubDate>
      <dc:creator><![CDATA[NickGravelyn]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nicgrave/2010/10/03/encoding-and-decoding-images-in-xna-game-studio-4-0/</guid>
      <description><![CDATA[In previous releases of XNA Game Studio, there were the Texture2D.Save and Texture2D.FromFile...]]></description>
      <content:encoded><![CDATA[<p>In previous releases of XNA Game Studio, there were the Texture2D.Save and Texture2D.FromFile methods for encoding and decoding images, but they only worked on Windows. In XNA GS 4.0, we introduced a few new methods: Texture2D.SaveAsPng, Texture2D.SaveAsJpeg, and Texture2D.FromStream. These methods replace the old Save and FromFile methods and are available across all three of our platforms.</p>  <p>SaveAsPng and SaveAsJpeg both do as they say. You pass in the Stream to which the data should be written along with the size you want to save the image (useful for saving thumbnails of images by passing in values smaller than the actual texture).</p>  <p>Texture2D.FromStream supports decoding PNG, JPEG, and GIF data from a Stream object. There are two overloads of this method:</p>  <p><font face="Consolas">Texture2D.FromStream(GraphicsDevice graphicsDevice, Stream stream)</font><font face="Consolas">      <br /></font><font face="Consolas">     <br />Texture2D.FromStream(</font><font face="Consolas">GraphicsDevice graphicsDevice, Stream stream,      <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; </font><font face="Consolas">int width, int height, bool zoom)</font></p>  <p>The first overload should be pretty easy to understand as it simply decodes the image data from the stream and gives you back a Texture2D object. </p>  <p>The second overload takes in a maximum size along with a “zoom” value. If zoom is false, the resulting image will be scaled along its longer dimension to fit in the width and height. If zoom is true, the resulting image is scaled along its shorter dimension to fit in the width and height, cropping as necessary.</p>  <p>As an example, here’s the classic image of <a href="https://blogs.msdn.com/b/shawnhar/archive/2007/03/07/return-of-the-son-of-programmer-art.aspx">Shawn’s cat</a>, found in many of our samples:</p>  <p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Shawn&#39;s cat" border="0" alt="Shawn&#39;s cat" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/34/41/metablogapi/7558.cat_2118B124.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-34-41-metablogapi/7558.cat_5F00_2118B124.png" width="150" height="242" /></p>  <p>This image is 153x248. If we load the image in with Texture2D.FromStream passing in 100 for both the width and height and false for the zoom parameter, this is the resulting texture:</p>  <p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="No zoom" border="0" alt="No zoom" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/34/41/metablogapi/4747.cat1_19210EC2.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-34-41-metablogapi/4747.cat1_5F00_19210EC2.png" width="63" height="102" /></p>  <p>This texture is 61x100. The longest dimension (the height) was scaled to our maximum height and aspect ratio was maintained.</p>  <p>Here’s what we see if we pass in true for the zoom parameter:</p>  <p><img style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="With zoom" border="0" alt="With zoom" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/34/41/metablogapi/1526.cat2_06D84800.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-34-41-metablogapi/1526.cat2_5F00_06D84800.png" width="102" height="102" /></p>  <p>This texture is 100x100. The shortest dimension (the width) was scaled to our maximum width and the image was cropped to fit in our 100x100 requested size.</p>  <p>A couple notes about Texture2D.FromStream:</p>  <ul>   <li>The Texture2D you receive is always using SurfaceFormat.Color </li>    <li>The method does not handle color keys, premultiplied alpha, DXT compression, or mipmaps. </li> </ul>  <p>Texture2D.FromStream is useful for games that want to decode gamer pictures (which are now a Stream property instead of a Texture2D), album art (on Windows Phone), or user library pictures (on Windows Phone). It’s also nice to pair with the SaveAs* methods for saving and loading screenshots for games on any platform.</p>  <p><em>Tiny fun fact: the images you see above weren’t generated by me using a paint program; I actually loaded the texture with FromStream and saved out the images with SaveAsPng. So these are really the results you’d get. :)</em></p>]]></content:encoded>
    </item>
    <item>
      <title>Don’t build more than what you need</title>
      <link>https://docs.microsoft.com/archive/blogs/nicgrave/dont-build-more-than-what-you-need</link>
      <pubDate>Wed, 29 Sep 2010 15:53:31 GMT</pubDate>
      <dc:creator><![CDATA[NickGravelyn]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nicgrave/2010/09/29/dont-build-more-than-what-you-need/</guid>
      <description><![CDATA[One of the more abstract lessons I learned through making my AppWeek game was to build for the...]]></description>
      <content:encoded><![CDATA[<p>One of the more abstract lessons I learned through making my <a href="https://blogs.msdn.com/b/nicgrave/archive/2010/09/29/my-appweek-2010.aspx">AppWeek game</a> was to build for the current project. I am, in my spare time, trying to build what one could call a 3D game engine. I’ve been (very) slowly building up code in various areas that will hopefully enable me to efficiently build game ideas when I have them. At this point it’s little more than a class library full of <em>stuff</em>.</p>  <p>One aspect of this “engine” was an entity system I was building. The idea was the composition pattern that many people have moved to for game development. At its core it means that an object in my game is nothing more than a container that is then stuffed with a bunch of components that actually build it up. The idea is that you can make building blocks (components) that you then combine to make more interesting objects. It’s a great theory but I’ve never really used a component system for a full game.</p>  <p>The first week was well underway, but I didn’t feel like I was moving fast enough to actually finish what I wanted. Eventually it hit me that the entity system (or at least my mindset) was causing friction between me and productivity. I was spending too much time managing component classes and interfacing between them, and not enough time progressing on the actual gameplay. </p>  <p>Towards the end of the first week, I decided to make a radical move and scrap the entire entity system for a “traditional” class hierarchy approach. Boy was that a good decision! It took me no time at all to build back to where I was and then it was much easier for me to continue to build upon my objects to finish off the game. I’m certain if I had kept fighting the component system, I never would have reached the point I did. </p>  <p>What it boils down to is that if you’re familiar with one paradigm or have a piece of code that works for your needs, stop trying to improve upon it until you have downtime or a real reason to improve it. Your customers won’t care if you used an entity system or class hierarchy, but if you spend all your time obsessing over details like that you might never get to the point of having customers.</p>]]></content:encoded>
    </item>
    <item>
      <title>Don’t reinvent those wheels</title>
      <link>https://docs.microsoft.com/archive/blogs/nicgrave/dont-reinvent-those-wheels</link>
      <pubDate>Wed, 29 Sep 2010 15:22:26 GMT</pubDate>
      <dc:creator><![CDATA[NickGravelyn]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/nicgrave/2010/09/29/dont-reinvent-those-wheels/</guid>
      <description><![CDATA[Still continuing on about my AppWeek game, another bit that really helped me out was leveraging...]]></description>
      <content:encoded><![CDATA[<p>Still continuing on about my <a href="https://blogs.msdn.com/b/nicgrave/archive/2010/09/29/my-appweek-2010.aspx">AppWeek game</a>, another bit that really helped me out was leveraging existing code for pieces of the game I didn’t really know how to make in a short time. While I do have a decent amount of generic code I’ve accumulated over the years, there are some pieces that I pulled together to make some aspects of the game easier.</p>  <p>The first piece of code was to grab my <a href="https://easyconfig.codeplex.com/">EasyConfig</a> library, which is a simple three-class library for parsing INI files. I used these INI files to define how each gun behaved, what it looked like, and what sounds it made. The files contained things like damage done, rounds per clip, max ammo, and, for the grenade, the damage falloff exponent so the damage decreased over time. While this code is code I’ve written, I mention it here because it is publicly available to anyone that wants to quickly drop in support for INI files.</p>  <p>The next piece I grabbed was the BoxCollider library from Fabio Policarpo’s FPS demo (available as a download on this page: <a title="https://fabio.policarpo.nom.br/Demos.html" href="https://fabio.policarpo.nom.br/Demos.html">https://fabio.policarpo.nom.br/Demos.html</a>). BoxCollider is a great little library for handling collisions between boxes, rays, and triangulated meshes. I used the library for the character movement collision as well as to handle raycasting for the guns and the collision portion of my grenade physics (I handled the dynamics myself and just did bouncing; the grenades actually never rotate or roll). I did do a few passes over the code base to optimize some of the methods and remove a few parts that created garbage, but it’s still a very valuable library without those changes.</p>  <p>I also needed to make my <a href="https://www.youtube.com/watch?v=0bXK06UKuY8">grenades go boom</a>, so I snagged the <a href="https://creators.xna.com/en-us/sample/particle3d">Particle 3D sample</a> and dropped that in. With minor changes just to the size of the particles, the built in explosion effect quickly became the look for my grenades. Is it realistic? No, but then again a giant fireball is way cooler to watch than a bunch of tiny pieces of metal flying around.</p>  <p>What’s the moral here? If you’re trying to actually finish a game, I recommend taking a bit to search around for pieces of code you can leverage to make your development quicker and smoother.</p>]]></content:encoded>
    </item>
  </channel>
</rss>