Developer Diary: XNA Extension Framework

Posted 07/21/2008 @ 12:30:08 AM by Joseph Molnar
Filed under: Developer Diary , Programming , Tales Framework , XNA

Since the 4th of July weekend I've been coding in XNA in my spare time. As is typical with me I've been putting together an extension framework. The goal of the framework is to provide some basic needs when writing XNA games. I'll release, as Microsoft calls them, a Community Technical Preview (CTP) soon.

While not exhaustive, here is what I've been doing:

  • A UI control, screen state and input management system. It is largely meant to handle things like menuing systems and heads-up displays. General features:
    • Hierarchical control structure similar to WinForms or WPF.
    • Controller-bound screen state management system.
    • Layout handling including control docking, automatic sizing and layout managers.
    • Focus manager that, unlike most UI systems, supports more than one control in focus at a time; it supports one control in focus per controller.
    • Input-mechanism that supports binding 'gestures' similar to WPF. 
    • Includes a few helpful controls, though nothing implies how a control should look; a developer has full control.
    • Developers can extend anything (e.g. they can add input gestures, layout managers, controls, etc).
  • A GameSession that replaces NetworkSession. General features:
    • Abstracted the notion of sessions so it supports both pure local or network games where the participants can be local users, network users or even bots.
    • Includes controls and screens that do not make assumptions on how something looks, but manage the lobby process. This means developers generally do not need to write the game session logic, but concentrate on how the lobby should look.

I'll post more details, including samples, once I release the CTP.

Developer Diary: XNA Threading - Locks

Posted 04/17/2007 @ 10:30:01 PM by Joseph Molnar
Filed under: Developer Diary , Programming , XNA

In my previous Developer Diary I discussed the problems that can arise from threaded development particularly as outlined in the example. In this post I discuss locks, what they are and how they can fix the problems with the example.

What are Locks?

The lock is one of the primary synchronization primitives in .NET. Locks are largely used to control access to a particular part of code (commonly called a critical section).

When a thread owns a lock no other thread is able to use the lock and execute the code protected by the lock. This results in the other threads waiting for the first thread to release its ownership. Once the first thread releases ownership one of the waiting threads will then own the lock and continue executing.

The basic way to create and use a lock is as follows:

class SomeClass {
    private object syncLock = new object( ); // create the lock in the class

   public void SomeMethod( ) {
        lock( syncLock ) { // request ownership of the lock
            // protected code here
        }                  // release ownership of lock
    }
}

The variable syncLock can actually be of any reference type. This means primitive and value types (such as int, float, Vector3, etc) cannot be used.

Updating Our Example

So how do locks help given our example? First let's update the code from the example in the previous Developer Diary (Note: the fully updated source is at the end of this post).

First we need our class-level shared lock.

        private object enemyDataLock = new object( );

After that we need to update the code in EnemyAIThreadMethod to lock just the area that updates the data that is used in the Draw method. You want to lock as little as possible otherwise you may slow down other threads who are also trying to use the lock. For example, if the Thread.Sleep( 10 ); statement was in the lock block then we would make it more difficult for the Draw method to maintain a high frame rate.

        private void EnemyAIThreadMethod( ) {
            while( !isStopping ) {
                // lock to make sure data is updated
                // correctly and Draw doesn't get 
                // partial results
                lock( enemyDataLock ) {
                    // NOTE: this is just filler code.
                    // Real code would analyze user location and if multiple
                    // enemies perform flocking, or other behaviours.
                    enemyRotation -= 0.01f;
                    enemyVelocity += new Vector3( 1, 0, 1 );
                    enemyPosition += enemyVelocity;
                }
                // sleeping will probably be in order, but outside 
                // of the lock so we have Draw a chance
                Thread.Sleep( 10 );
            }
        }

Finally we update the Draw method. At first glance you may consider simply putting a lock around the entire foreach block to ensure that we use the same values for enemyRotation and enemyPosition for each mesh in the model. The Draw method would look like this:

        public override void Draw( GameTime gameTime ) {
            // ... draw other aspects of the scene....

            // Copy any parent transforms.
            Matrix[ ] transforms = new Matrix[ enemyModel.Bones.Count ];
            enemyModel.CopyAbsoluteBoneTransformsTo( transforms );

            // make sure we have consistent data
            lock( enemyDataLock ) {
                // draw the enemy model
                foreach( ModelMesh mesh in enemyModel.Meshes ) {
                    foreach( BasicEffect effect in mesh.Effects ) {
                        effect.EnableDefaultLighting( );
                        // ... but ensure we draw it at the right location 
                        effect.World = transforms[ mesh.ParentBone.Index ]
                            * Matrix.CreateRotationY( enemyRotation )
                            * Matrix.CreateTranslation( enemyPosition );
                        effect.View = Matrix.CreateLookAt(
                            cameraPosition,
                            Vector3.Zero,
                            Vector3.Up );
                        effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                            MathHelper.ToRadians( 45.0f ),
                            aspectRatio,
                            1.0f,
                            10000.0f );
                    }
                    mesh.Draw( );
                }
            }

            // ... draw other aspects of the scene....
            
            base.Draw( gameTime );
        }

That is a lot of code to lock. Remember you want to lock as little as possible. A better approach is to create local copies of the data and only lock the point where the data is copied. Our new Draw method looks as follows:

        public override void Draw( GameTime gameTime ) {
            // ... draw other aspects of the scene....

            // Copy any parent transforms.
            Matrix[ ] transforms = new Matrix[ enemyModel.Bones.Count ];
            enemyModel.CopyAbsoluteBoneTransformsTo( transforms );

            // local copies of the class data
            Vector3 enemyPositionCopy;
            float enemyRotationCopy;

            // make sure we have consistent data
            lock( enemyDataLock ) { 
                enemyPositionCopy = enemyPosition;
                enemyRotationCopy = enemyRotation;
            }
            
            // draw the enemy model
            foreach( ModelMesh mesh in enemyModel.Meshes ) {
                foreach( BasicEffect effect in mesh.Effects ) {
                    effect.EnableDefaultLighting( );
                    // ... but ensure we draw it at the right location 
                    effect.World = transforms[ mesh.ParentBone.Index ]
                        * Matrix.CreateRotationY( enemyRotationCopy )
                        * Matrix.CreateTranslation( enemyPositionCopy );
                    effect.View = Matrix.CreateLookAt(
                        cameraPosition,
                        Vector3.Zero,
                        Vector3.Up );
                    effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                        MathHelper.ToRadians( 45.0f ),
                        aspectRatio,
                        1.0f,
                        10000.0f );
                }
                mesh.Draw( );
            }

            // ... draw other aspects of the scene....

            base.Draw( gameTime );
        }
    }

This seriously cuts down on the amount of code locked allowing both threads to run more quickly. As a note, the Vector3 type is a value type (struct), instead of a reference type (class). This means the line enemyPositionCopy = enemyPosition; isn't simply assigning a reference, but making a field by field copy of the Vector3 members. This is an important distinction. If we had reference types then other code would need to be considered. I'll cover that in my next article.

Why Does It Work?

I mentioned in the previous article that our example needed updating to cover two problems.

The first problem was uncontrolled access to the data. This is fixed by the lock statements. The use of a lock prevents the Draw thread from using the enemy data while the data is being updated in the EnemyAIMethod thread and conversely the EnemyAIMethod can't update the values while the Draw method is copying them.

The second problem was getting around .NET's memory and synchronization model. The reason this isn't an issue is due to how locks work. I'll attempt a simple explanation since it is much more complicated than I'm describing. Locks explicitly indicate to .NET that there is threaded code so that certain optimizations will not occur. Some optimizations, such as the caching of data in processor and system caches, aren't an issue because a lock ensures that modified data makes it in and out of main memory.

As you may have guessed using locks incurs a performance penalty. However, it can be a small price to pay for correctness. More advanced options are available, but they are harder to code for. I'll outline one such approach in my next post.

In Summary

Locks are an important part of threading in .NET but, as with all things, they have their advantages and disadvantages.

Advantages of locks:

Disadvantages of locks:

  • Is fairly expensive to execute
  • Easier to create deadlock situations
What is a Deadlock?

It is best to discuss deadlocks when you have an example. Fortunately the XNA example code we have been using isn't subject to deadlocks, but the following piece of code is:

private object syncLockA = new object( );
private object syncLockB = new object( );

// thread one is running here
private void ThreadMethodOne( ) {
    while( !isStopping ) {
        lock( syncLockA ) {
            // do some work
            lock( syncLockB ) {
                // do some more work
            }
        }
    }
}

// thread two is running here
private void ThreadMethodTwo( ) {
    while( !isStopping ) {
        lock( syncLockB ) {
            // do some work
            lock( syncLockA ) {
                // do some more work
            }
        }
    }
}

The potential for deadlocks occur when two or more threads have two or more locks they are sharing. In the above code a deadlock can occur if we have a thread executing in ThreadMethodOne that is currently trying to acquire syncLockB after having acquired syncLockA, and we have another thread executing in ThreadMethodTwo trying to acquire syncLockA after having acquired syncLockB. These threads are now stuck forever since they are waiting for the other thread to release the additional lock needed.

That's a deadlock. Once you have multiple threads and multiple locks you need to be extra careful with your code.

Follow-on Posts

I hope this post gave you a good overview of how to use locks in .NET. In my next post I'll talk about another mechanism that can be used to handle our example, as well as some pointers for additional .NET threading details and recommendations.

 

Complete Updated Example Source Code

using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;

namespace SampleThreading {
    public class ThreadedEnemyComponent : DrawableGameComponent {
        // general members
        private ContentManager content;
        Vector3 cameraPosition = new Vector3( 0.0f, 50.0f, -5000.0f );
        float aspectRatio = 640.0f / 480.0f;

        // thread members
        private Thread enemyAIThread = null;
        private volatile bool isStopping = false;
        private object enemyDataLock = new object( );

        // enemy specific data (model, velocity, position rotation, etc).
        private Model enemyModel;
        private Vector3 enemyVelocity = Vector3.Zero;
        private Vector3 enemyPosition = Vector3.Zero;
        private float enemyRotation = 0.0f;

        /// <summary>
        /// Basic constructor taking the game the component is to be a part of.
        /// </summary>
        /// <param name="theGame">The game the component will belong to.</param>
        public ThreadedEnemyComponent( Game theGame )
            : base( theGame ) {
            content = new ContentManager( this.Game.Services );
        }

        /// <summary>
        /// Override Initialize to start our separate AI thread.
        /// </summary>
        public override void Initialize( ) {
            base.Initialize( );

            enemyAIThread = new Thread( EnemyAIThreadMethod );
            enemyAIThread.Start( );
        }

        /// <summary>
        /// Override dispose to ensure our thread is shutdown.
        /// </summary>
        /// <param name="disposing">
        /// Set to true to release manage and unmanaged resources.
        /// Set to false to release unmanaged resources.
        /// </param>
        protected override void Dispose( bool disposing ) {
            try {
                isStopping = true;
                if( disposing ) {
                    // let's shutdown our thread if it hasn't
                    // shutdown already
                    if( enemyAIThread != null ) {
                        enemyAIThread.Join( ); // wait for the to shutdown
                        enemyAIThread = null;
                    }
                }
            } finally {
                base.Dispose( disposing );
            }
        }

        protected override void LoadGraphicsContent( bool loadAllContent ) {
            if( loadAllContent ) {
                // load our enemy model
                enemyModel = this.content.Load<Model>( @"Content\Models\
enemyModel" );
            }
        }

        protected override void UnloadGraphicsContent( bool unloadAllContent ) {
            if( unloadAllContent == true ) {
                content.Unload( );
            }
        }

        /// <summary>
        /// The thread that runs the enemy AI
        /// </summary>
        private void EnemyAIThreadMethod( ) {
            while( !isStopping ) {
                // lock to make sure data is updated
                // correctly and Draw doesn't get 
                // partial results
                lock( enemyDataLock ) {
                    // NOTE: this is just filler code.
                    // Real code would analyze user location and if multiple
                    // enemies perform flocking, or other behaviours.
                    enemyRotation -= 0.01f;
                    enemyVelocity += new Vector3( 1, 0, 1 );
                    enemyPosition += enemyVelocity;
                }
                // sleeping will probably be in order, but outside 
                // of the lock so we have Draw a chance
                Thread.Sleep( 10 );
            }
        }

        /// <summary>
        /// The thread that does the drawing from frames
        /// </summary>
        public override void Draw( GameTime gameTime ) {
            // ... draw other aspects of the scene....

            // Copy any parent transforms.
            Matrix[ ] transforms = new Matrix[ enemyModel.Bones.Count ];
            enemyModel.CopyAbsoluteBoneTransformsTo( transforms );

            // local copies of the class data
            Vector3 enemyPositionCopy;
            float enemyRotationCopy;

            // make sure we have consistent data
            lock( enemyDataLock ) {
                enemyPositionCopy = enemyPosition;
                enemyRotationCopy = enemyRotation;
            }
            
            // draw the enemy model
            foreach( ModelMesh mesh in enemyModel.Meshes ) {
                foreach( BasicEffect effect in mesh.Effects ) {
                    effect.EnableDefaultLighting( );
                    // ... but ensure we draw it at the right location 
                    effect.World = transforms[ mesh.ParentBone.Index ]
                        * Matrix.CreateRotationY( enemyRotationCopy )
                        * Matrix.CreateTranslation( enemyPositionCopy );
                    effect.View = Matrix.CreateLookAt(
                        cameraPosition,
                        Vector3.Zero,
                        Vector3.Up );
                    effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                        MathHelper.ToRadians( 45.0f ),
                        aspectRatio,
                        1.0f,
                        10000.0f );
                }
                mesh.Draw( );
            }

            // ... draw other aspects of the scene....

            base.Draw( gameTime );
        }
    }
}

Developer Diary: XNA Threading - The Problems

Posted 04/15/2007 @ 10:30:36 AM by Joseph Molnar
Filed under: Developer Diary , Programming , XNA

As an extension to my previous Developer Diary I thought it made sense to give some more background information on threading in .NET and how it may apply to XNA development. In part this is intended to provide some insight into the difficulties of threaded development. This will be a three post backgrounder.

This first post will introduce the example and discuss the problems with it. This example will be the point of reference for all three posts.

The Example

The premise of the example is that you want to put your enemy AI code in a separate thread so that Update and Draw will have as much time as possible to execute. The below example code is derived from a Microsoft example on how to draw models. I have modified the example to do AI calculations in a separate thread (there is no real AI code, just filler).

using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;

namespace SampleThreading {
    public class ThreadedEnemyComponent : DrawableGameComponent {
        // general members
        private ContentManager content;
        Vector3 cameraPosition = new Vector3( 0.0f, 50.0f, -5000.0f );
        float aspectRatio = 640.0f / 480.0f;

        // thread members
        private Thread enemyAIThread = null;
        private bool isStopping = false;

        // enemy specific data (model, velocity, position rotation, etc).
        private Model enemyModel;
        private Vector3 enemyVelocity = Vector3.Zero;
        Vector3 enemyPosition = Vector3.Zero;
        float enemyRotation = 0.0f;

        /// <summary>
        /// Basic constructor taking the game the component is to be a part of.
        /// </summary>
        /// <param name="theGame">The game the component will belong to.</param>
        public ThreadedEnemyComponent( Game theGame )
            : base( theGame ) {
            content = new ContentManager( this.Game.Services );
        }

        /// <summary>
        /// Override Initialize to start our separate AI thread.
        /// </summary>
        public override void Initialize( ) {
            base.Initialize( );

            enemyAIThread = new Thread( EnemyAIThreadMethod );
            enemyAIThread.Start( );
        }

        /// <summary>
        /// Override dispose to ensure our thread is shutdown.
        /// </summary>
        /// <param name="disposing">
        /// Set to true to release manage and unmanaged resources.
        /// Set to false to release unmanaged resources.
        /// </param>
        protected override void Dispose( bool disposing ) {
            try {
                isStopping = true;
                if( disposing ) {
                    // let's shutdown our thread if it hasn't
                    // shutdown already
                    if( enemyAIThread != null ) {
                        enemyAIThread.Join( ); // wait for the to shutdown
                        enemyAIThread = null;
                    }
                }
            } finally {
                base.Dispose( disposing );
            }
        }

        protected override void LoadGraphicsContent( bool loadAllContent ) {
            if( loadAllContent ) {
                // load our enemy model
                enemyModel = this.content.Load<Model>( @"Content\Models\
enemyModel" );
            }
        }

        protected override void UnloadGraphicsContent( bool unloadAllContent ) {
            if( unloadAllContent == true ) {
                content.Unload( );
            }
        }

        /// <summary>
        /// The thread that runs the enemy AI
        /// </summary>
        private void EnemyAIThreadMethod( ) {
            while( !isStopping ) {
                // NOTE: this is just filler code.
                // Real code would analyze user location and if multiple
                // enemies perform flocking, or other behaviours.
                enemyRotation -= 0.01f;
                enemyVelocity += new Vector3( 1, 0, 1 );
                enemyPosition += enemyVelocity;
                // sleeping will probably be in order.
                Thread.Sleep( 10 );
            }
        }

        /// <summary>
        /// The thread that does the drawing from frames
        /// </summary>
        public override void Draw( GameTime gameTime ) {
            // ... draw other aspects of the scene....

            // Copy any parent transforms.
            Matrix[ ] transforms = new Matrix[ enemyModel.Bones.Count ];
            enemyModel.CopyAbsoluteBoneTransformsTo( transforms );

            // draw the enemy model
            foreach( ModelMesh mesh in enemyModel.Meshes ) {
                foreach( BasicEffect effect in mesh.Effects ) {
                    effect.EnableDefaultLighting( );
                    // ... but ensure we draw it at the right location 
                    effect.World = transforms[ mesh.ParentBone.Index ] 
                        * Matrix.CreateRotationY( enemyRotation )
                        * Matrix.CreateTranslation( enemyPosition );
                    effect.View = Matrix.CreateLookAt( 
                        cameraPosition, 
                        Vector3.Zero, 
                        Vector3.Up );
                    effect.Projection = Matrix.CreatePerspectiveFieldOfView( 
                        MathHelper.ToRadians( 45.0f ),
                        aspectRatio, 
                        1.0f, 
                        10000.0f );
                }
                mesh.Draw( );
            }

            // ... draw other aspects of the scene....
            
            base.Draw( gameTime );
        }
    }
}

The Problems with the Sample

The thread method EnemyAIThreadMethod does a slew of calculations while the Draw method uses the results of the calculations to display the model. If you didn't know otherwise the above code looks perfectly fine.

In fact when you run it, more often than not it will behave as you would expect. However, it won't always be right and I don't mean per running of the application. On a frame-by-frame basis you may see things behave in an unexpected fashion, such as an odd warping of the model. There are two main reasons for this.

Uncontrolled Access to Data

Since there are two separate threads using the data, in this case one reading (Draw) and one writing (EnemyAIThreadMethod), it is possible that the Draw thread will use values for enemyPosition, enemyRotation, etc, while they are changing. In other words, in a single frame for a single model some of the meshes in the model could use old values while other meshes for the same model could use newer values. This will result in some rather interesting looking (as in bad) models.

.NET Memory and Synchronization Model

Another reason for odd behaviour is related to how .NET works. .NET is essentially defined such that if nothing in a method or in a member declaration indicates there are multiple threads then .NET assumes it is single threaded code. The simple declaring and starting of a thread, as done in the above sample, isn't sufficient. Your code needs to indicate its awareness of threads.

Why? .NET attempts to optimize the code through a variety of techniques. A common optimization is to cache data in processor or system caches. For example, enemyRotation could be cached separately in the EnemyAIThreadMethod thread and the Draw thread. This means that when you change enemyRotation in the EnemyAIThreadMethod thread the Draw thread may not see the change until something triggers the caches to flush back to main memory. The reason for caching is speed; accessing a cache is much faster than accessing main memory.

Follow-on Posts

This post was just meant to introduce the typical problems encountered with threading. The follow-on posts, which I'll post over the next couple days, will cover ways to correct the problems outlined here.

Developer Diary: XNA Game Loop and Threading

Posted 04/10/2007 @ 06:30:35 AM by Joseph Molnar
Filed under: Developer Diary , Programming , Xbox 360 , XNA

In my previous Developer Diary I talk about the tools and tutorials I used to get some background on XNA. After playing with the tutorials I decided to start digging into the mechanics of what makes an XNA game. The big defining elements are the two main Game methods, Draw and Update. In the process of looking at these method I thought I would give you some insight into .NET threading.

Note: Most of my sample code will be implemented as DrawableGameComponents instead of actual Games. I found this the most convenient way to bring code into an existing project.

Main Game Loops and Threading

Draw, which is intended for drawing frames, and Update, which is intended to run game logic, are called automatically by the XNA framework. When I saw these methods I had assumed they were called via different threads. After all, game developers typically try to achieve 60 frames per second (fps) and therefore try to remove any potential contention.

I was wrong. In .NET you typically get the current thread id using Thread.CurrentThread.GetManagedThreadId. For example, in the following code I retrieve the current thread id in both the Draw and Update methods.

/// <summary>
/// Sample class for checking thread id.
/// </summary>
public class CheckThreadIdClass : DrawableGameComponent {
    /// <summary>
    /// Constructor required for the game component.
    /// </summary>
    /// <param name="theGame">The Game this component will be used by.</param>
    public CheckThreadIdClass( Game theGame )
        : base( theGame ) {
    }

    /// <summary>
    /// The method used to draw frames.
    /// </summary>
    /// <param name="gameTime">GameTime since last call.</param>
    public override void Draw( GameTime gameTime ) {
        base.Draw( gameTime );
        // get the thread that is being called by this thread.
        int currentThreadId = Thread.CurrentThread.ManagedThreadId;
    }

    /// <summary>
    /// The method used to update game location.
    /// </summary>
    /// <param name="gameTime">GameTime since last call.</param>
    public override void Update( GameTime gameTime ) {
        base.Update( gameTime );
        // get the thread that is being called by this thread.
        int currentThreadId = Thread.CurrentThread.ManagedThreadId;
    }
}

Under Windows you will get the same thread id value in both Draw and Update (probably 1). Under the 360 both methods also report the same value, but it is a large negative value, -117440492 (not sure what this value means). From here I added some code to create a new thread to see what its thread id is.

/// <summary>
/// Sample class for creating a thread.
/// </summary>
public class CreateThreadClass : DrawableGameComponent {
    private Thread extraThread = null;
    private volatile bool isStopping = false;

    /// <summary>
    /// Constructor required for the game component.
    /// </summary>
    /// <param name="theGame">The Game this component will be used by.</param>
    public CreateThreadClass( Game theGame )
        : base( theGame ) {
    }

    public override void Initialize( ) {
        base.Initialize( );
        // create and start thread
        extraThread = new Thread( ThreadMethod );
        extraThread.Start( );
    }

    /// <summary>
    /// The method used to draw frames.
    /// </summary>
    /// <param name="gameTime">GameTime since last call.</param>
    public override void Draw( GameTime gameTime ) {
        base.Draw( gameTime );
        // get the thread that is being called by this thread.
        int currentThreadId = Thread.CurrentThread.ManagedThreadId;
    }

    /// <summary>
    /// The method used to update game location.
    /// </summary>
    /// <param name="gameTime">GameTime since last call.</param>
    public override void Update( GameTime gameTime ) {
        base.Update( gameTime );
        if( GamePad.GetState( PlayerIndex.One ).Buttons.Back == ButtonState.
Pressed ) {
            ShutDown( );
        } else {
            // get the thread that is being called by this thread.
            int currentThreadId = Thread.CurrentThread.ManagedThreadId;
        }
    }

    /// <summary>
    /// Method called when we are to shutdown the game.
    /// </summary>
    private void ShutDown( ) {
        isStopping = true;
        // wait for the thread to die
        if( this.extraThread != null ) {
            this.extraThread.Join( );
            this.extraThread = null;
        }
        // now exit
        this.Game.Exit( );
    }

    /// <summary>
    /// Sample thread method.
    /// </summary>
    private void ThreadMethod( ) {
        // get the thread that is being called by this thread.
        int currentThreadId = Thread.CurrentThread.ManagedThreadId;

        while( !isStopping ) {
        }
    }
}

On the Xbox 360 the new Thread's thread id returned a similar large negative value, -117440472. At this point I recalled that Microsoft added a special method, Thread.SetProcessorAffinity, for the 360 that allows you to associate a software thread to hardware thread (one of the six the 360 has). So I changed the ThreadMethod method to use a particular hardware thread.

Note: Thread.SetProcessorAffinity must be called within the thread that wishes to run on particular hardware threads.

/// <summary>
/// Sample thread method.
/// </summary>
private void ThreadMethod( ) {
    // get the thread that is being called by this thread.
    int currentThreadId = Thread.CurrentThread.ManagedThreadId;
#if XBOX360
    // set the processor threads to run on
    Thread.CurrentThread.SetProcessorAffinity( new int[ ] { 3 } );
    // re-get the thread id
    currentThreadId = Thread.CurrentThread.ManagedThreadId;
#endif
    while( !isStopping ) {
    }
}

The Xbox 360 returned the same negative value, -117440472. Needless to say, it is a safe assumption that Draw and Update are in the same thread.

The reason for this is simple. Having Draw and Update in the same thread is easier for novices. Writing threaded code when sharing data between threads, as would be the case if Draw and Update were in separate threads, is trickier than it may seem.

Some Threading Notes of Interest

The MSDN Library description for Thread.SetProcessorAffinity has a description of the 360's threading (see the remarks section). Of interest is how many threads are actually listed as either being reserved or partially used by the 360's system software and Dashboard. It seems there is more overhead than I recall from blogs and podcasts on this subject. Perhaps this breakdown is specific to XNA on the 360?

From a tool standpoint, there is one other item of interest. It appears that Visual C# Express does not support the thread debug window, which allows you to view, switch and freeze threads. While some may consider this a mild annoyance there are certain circumstances, like deadlock debugging, that will be difficult to debug without this feature; I would love for Microsoft to allow XNA to be installed into non-Express editions of Visual Studio 2005. Microsoft has stated this may come in a future update to the XNA tools, though most likely not in the update coming this month.

Follow-on Post

I'll continue my discussion on threading, delving into implementation options and difficulties over the next few post:

Recent Developer Diary Articles

Developer Diary: Getting Started on XNA

Posted 03/15/2007 @ 06:30:00 AM by Joseph Molnar
Filed under: Developer Diary , Homebrew , Programming , XNA

Each week I like to set aside a few hours to explore software development technologies I haven't tried. This past weekend I started to take a deeper look at XNA.

I'll be documenting my XNA investigation with periodic updates as a Developer Diary. Today's Developer Diary is simple, I documented what I did to get a base understanding of XNA.

The quick summary, I downloaded a variety of tools, read a variety of blogs/tutorials and created some code derived from the tutorials. So this entry is largely a collection of links that will ensure a solid start.

As a note, while I'm new to XNA and 3D programming, I'm extremely familiar with C# and .NET (background here) so I'll be assuming readers know C#.

The Base Tools

Before you can really do anything (except read) you need to install the tools, Visual C# Express and XNA Game Studio Express.

Since I'm on Vista I followed David Weller's guide to installing the base tools on Vista. Even if you aren't on Vista it is a good general description of getting the tools in place.

As a note, Dave's blog post pre-dates Microsoft's release of the Visual Studio 2005 SP1 Update for Windows Vista, so make sure you get the new update.

Also, an updated version of XNA Game Studio Express is coming this April.

Auxiliary Tools

With the base tools in place I found and installed some tools to aid my XNA experimentation.

  • Paint.NET: If you aren't a graphic artist or designer but need something to help with creating textures from photos this free tool should do the trick.
  • FX Composer: A free environment from nVidia that allows you to create shaders. Definitely a great tool for experimentation; wish they had more samples.
  • Turbo Squid: This site contains free and inexpensive 3D models that can be used with the XNA framework. I recommend experimenting with some free models.
  • Blender: Blender is a free open source 3D modeling and animation tool. It can export to .X files (one of two model formats that XNA readily supports). I find 3D modeling packages a bit daunting but this tutorial was helpful. I haven't played a ton yet, but it works on Vista (I tried SOFTIMAGE's free tool, but it wouldn't work consistently).

Tutorials and Samples

With all my tools in place, I used the sites below to get myself familiar with XNA development.

  • First place I visited was the MSDN XNA site (the same information is included as a help file with XNA Game Studio Express).
  • Next, I found Riemers XNA Tutorials. These are the most comprehensive set of easy to follow 3D tutorials I found. They progress nicely from beginner to advanced.
  • Once you have gotten the basics the XNA Creator's site samples are not a bad place to go next. While some overlap with Riemers, the samples are great for experimentation.
  • The blog Ramblings of a Hazy Mind also has a series of tutorial articles. As a slight warning, the tutorials are really guiding the creation of an XNA-based 3D graphics framework and the posts started in the betas so I don't believe the early code will work on the release version of XNA.

With the tutorials done you should be in a pretty good spot to write something more original by experimenting with the tutorial samples. I also recommend getting familiar with the growing XNA community. Here are some of the XNA related sites I regularly read.

My Bookmarked or RSS Subscribed Sites

Developer blogs that caught my attention:

  • Manders vs Machine: A Microsoft employee providing some interesting insights into various XNA problems and techniques.
  • Shawn Hargreaves: Shawn is also a Microsoft employee. His blog contains various code snippets and background information on the XNA framework.
  • abi.exdream.com: Benjamin Nitchke's blog commonly lists advanced technique's and details about his XNA work. Benjamin is definitely someone to watch.
  • Aliens of Extraordinary Ability: This blog tends to have interesting shaders being used or explored. Side-note: I'm assuming his blog's name is a reference to a special form of US Immigration Visa ... as a Canadian in the US, you become quite familiar with Visas.

Community sites:

  • Ziggyware: Contains tutorials and information about XNA built games.
  • Mykres Space: Gathers updates from the XNA community and commonly has code snippets to share.
  • The ZBuffer: Tracks the general pulse of the XNA universe.
  • XBOX 360 Homebrew: Contains information on XNA games, forums for developers, etc.
  • Let's Kill Dave: Personal blog of David Weller, Microsoft's Game Developer Community Manager.

Official Microsoft Sites:

  • XNA Creators Club Online: The official Microsoft site for XNA developers.
  • MSDN XNA Site: The Microsoft Developer Network site for XNA. Unclear if this will continue now that XNA Creators Club Online is, um, online.

Follow-on blog posts ...

My next post will describe my initial reactions to XNA, things to consider, and some questions I'm hoping to eventually find answers to.