XNA Community Games are Amazing

Posted 10/30/2008 @ 07:01:39 AM by Joseph Molnar
Filed under: Games , Xbox 360 , XNA

Tonight I was in San Francisco at the XNA Community Games Party. I had a great time meeting various folks including games developers and designers, the media, and the team who made XNA Game Studio happen within Microsoft.

One of the people I spoke with was Nathan Fouts, the developer behind Dream Build Play 2008 3rd place winner Weapon of Choice. Nathan used to work for Insomniac Games. You can see why he was a good fit within Insomniac when you see the weapon designs in his XNA game. While I jokingly called him a defector (from Sony), it was clear he was impressed with what Microsoft built, and happy that XNA gave him an easy way to start his own gaming company.

While I didn't get to play all of the games, my two favourites were CarnyVale: Showtime and Battle Tennis. I wasn't surprised to hear these were the 1st and 2nd place winners respectively in Dream Build Play 2008. In fact CarnyVale was a game I saw XNA team members having trouble putting down.

What is abundantly clear is XNA GS is an amazing tool that allows developers to build games that rival and surpass games on Xbox Live Arcade. Congratulations and thank you to the XNA team for bringing this to the public and congratulations to the game developers for building some amazing games. November 19th (the release date of the new Xbox 360 User Interface and XNA Community Games) cannot come soon enough.

Tales Framework for XNA: Tech Preview 1 Limitations

Posted 10/26/2008 @ 06:00:00 PM by Joseph Molnar
Filed under: Programming , Tales Framework , Xbox 360 , XNA

I'll be releasing the framework soon so I wanted to share the preview's limitations. The items outlined below are essentially items on my improvement/to-do list. The high/med/low indicator is a priority rating; things marked high will be worked on first.

  • Layout and Rendering
    • (high) Poor use/sharing of SpriteBatches in controls .
    • (med) Use of Vector2d for size and position information. Vector2d uses floats so coordinate calculations that result in non-integer values can cause fonts to look blurred.
    • (low) No support for clipping.
    • (low) Labels do not support wrapping or multiple font types (developers can use the framework to create this ability).
    • (low) None of the layout handlers support control wrapping (developers can use the framework to create this ability).
    • (low) No support for table layout (developers can use the framework to create this ability).
  • Events, Callbacks and Input:
    • (high) Consistency between event types, delegates and input handling needs improvement.
    • (high) Spinners do not report the direction of a value change. Without this, sophisticated data validation isn’t possible.
    • (med) Only InputBinding events report the player that caused the event. Indirect events, such as MenuItem.Selected, do not report who caused the event.
    • (low) Keyboard input is currently bound to player 1 because in XNA 2.0 the USB keyboard reports its key presses across all gamepad keyboards.
    • (low) If a child is in focus, the parent isn’t considered in focus.
  • SystemDefaults:
    • (high) VisualDefaults presumes there are fonts called “Fonts/title”, “Fonts/normal”, “Fonts/small”, “Fonts/menu”.
    • (high) No support for overriding the various defaults.
  • Screen support:
    • (high) No generic support for a Screen with focusable elements; current implementation forces the use of Menus and MenuItems.
    • (high) The ScreenManager uses a push/pop mechanism for active Screens. I want to have better support for closing and not favouring pre-created Screens.
    • (med) Need additional Screen types (e.g. full-screen screens, dialogs/pop-ups).
    • (med) ScreenManager only supports a single Screen across all gamepads, instead of allowing one active Screen per gamepad.
  • Networking
    • (high) GameSession is largely a wrapper around NetworkSession and is missing some of the later's abilities. Need to reconsider what to do with this class.

Getting my Lips out for American Thanksgiving

Posted 10/25/2008 @ 06:00:00 PM by Joseph Molnar
Filed under: Food and Drink , Games , Music , Xbox 360

So looks like Thanksgiving is going to be great this year. I now have confirmation that we will have two couples from Toronto, a family of four from San Jose and a friend from Seattle joining us; that makes 12 total.

I must say, I prefer American Thanksgiving to Canadian Thanksgiving. Maybe it is because it starts a four day weekend so more people are able to get together, or maybe it is because it starts the Holiday season (Canadian Thanksgiving is in early October) ... either way, I love American Thanksgiving. We have been doing these Thanksgiving get togethers for 8 years and I think this will be the largest one.

With that many people and no room for Rock Band or Guitar Hero, I decided to pre-order Lips. It is a singing and quasi-dancing game (has motion sensitive microphones) that allows you to use your own music. The game is actually for my daughter (who loves to sing and dance) and I. I just decided to use a people-filled, party-game wanting Thanksgiving as a good excuse to get the game before Christmas.

I want to thank Dan and linda, and Paulo and Gill for taking the time-off to fly down and of course Pete for flying down too. Better get those singing voices and performance moves in place before heading here.

Tales Framework for XNA: Network Helper

Posted 10/24/2008 @ 07:01:01 AM by Joseph Molnar
Filed under: Programming , Tales Framework , Xbox 360 , XNA

The past two Tales Framework posts discussed UI elements. In this post we will move to networking. In particular I’m going to concentrate on the class I built to aid the finding, creating and joining of network sessions.

XNA GS’s built-in networking functions provide a great consistent way to handle both local networked and Internet networked games while allowing you to choose either synchronous or asynchronous mechanisms to find, create and join sessions. What I did was create a helper class to alleviate one of the remaining tricky parts in getting a networked session going ... providing a responsive and thread-safe UI.

The menuing system of a game should be as responsive as possible, so you definitely do not want to use XNA's synchronous network find, create and join methods in direct response to user input. Even if you put the find, create and join calls in a separate thread or you use the asynchronous calls (which use separate threads when calling your callbacks) you still need to synchronize access to any data you share with the UI thread and manage and ensure you never try to create a NetworkSession and AvailableNetworkSessionCollection at the same time.

The GameSessionHelper class handles these tricky parts for you. For example, users can start a find operation and then immediately start a create operation and not have to wait between these two steps.

If you are going to use the GameSessionHelper class, these are the important steps:

  1. Subscribe to the GameSession.Helper.XXXFinished and GameSession.Helper.XXXErrored events.
  2. Call the GameSession.Helper.XXXStart methods to start an operation.
  3. In the menu’s Update or Draw method, call the GameSession.Helper.Update method. If new network data is available the call to GameSession.Helper.Update will cause either the XXXFinished or XXXErrored events to fire.
  4. When you close the menu call the GameSession.Helper.Clear method.

Here are the complete details of what happens when following the above example  and steps:

  1. User Action: User goes to the 'find network game' menu and starts looking for a network game.
    • Game Code: When the menu is created you should register for the GameSession.Helper.FindFinished and GameSession.Helper.FindErrored events. When they start looking for a network game you call GameSession.Helper.StartFind. The menu's Update method should continually call the GameSession.Helper.Update method.
    • Tales Code: The helper class asks XNA to perform a find operation.
  2. User Action: Use goes back, closing the menu before the GameSession.Helper.FindFinished or GameSession.Helper.FindErrored events fire.
    • Game Code: When the menu closes you should call GameSession.Helper.Clear. You should continue to call the GameSession.Helper.Update method.
    • Tales Code: The helper is still waiting to hear back from XNA libraries so it queues the request to clear the data.
  3. User Action: User goes to the 'create game' menu and creates a network game.
    • Game Code: When the menu is created you should register for the GameSession.Helper.CreateFinished and GameSession.Helper.CreateErrored events. When the user creates the network game call the GameSession.Helper.StartCreate. In the menu's Update method you should continually call the GameSession.Helper.Update method.
    • Tales Code: The helper has not yet heard back from the XNA framework on the initial find call so it queues up the request to do a create.
  4. User Action: User waits for the create game to start.
    • Game Code: Continue to call the GameSession.Helper.Update method.
    • Tales Code: The helper will eventually hear back from the XNA framework for the initial find request. The helper clears out the data, in this case the AvailableNetworkSessionCollection. Then the helper starts the game session create operation. Once the session is created the CreateFinished event will fire.

The above shows the user only waited during moments when they initiated a network request. The UI was fully responsive; to the user it felt like they were canceling or starting a new operation when in fact the old operation was completing in the background.

 

This is a pretty detailed look at the GameSessionHelper class. Too much code is required to provide an example in this post but the sample I'll be providing with the framework should provide a good amount of reference code.

Tales Framework for XNA: Input and Focus

Posted 10/18/2008 @ 10:00:00 PM by Joseph Molnar
Filed under: Programming , Tales Framework , Xbox 360 , XNA

In my last post I talked about controls and the control structure within the Tales Framework. In this post I will go over the input handling. The two most important ideas to understand are a) input gestures, which represent things like button presses, and b) how focus impacts input handling.

Input Gestures

When building a GameControl that takes input you need to bind a method to one or more input gestures that implement the IInputGesture interface.

The IInputGesture interface looks like this:

public interface IInputGesture {
    /// <summary>
    /// This method is used to check if we have input in a particular state.
    /// </summary>
    /// <param name="thePlayerIndex">The index of player that we are 
    /// checking input for.</param>
    /// <param name="theGameTime">The GameTime for the input update.</param>
    /// <returns>True if the expected input occurred.</returns>
    bool MatchGesture( PlayerIndex thePlayerIndex, GameTime theGameTime );
}

A gesture’s MatchGesture method simply checks some state, like a pressed button, for the specified player and if the state is true the method returns true.

For example, this is a simple gesture that detects if a button was literally just pressed:

public class ButtonDownGesture : IInputGesture {
    private readonly Buttons _buttons;

    /// <summary>
    /// Constructor taking the buttons in question.
    /// </summary>
    /// <param name="theButtons">The buttons to check to see if they
    /// were pressed.</param>
    public ButtonDownGesture( Buttons theButtons ) {
        _buttons = theButtons;
    }

    /// <summary>
    /// The buttons to check.
    /// </summary>
    public Buttons Buttons {
        get {
            return _buttons;
        }
    }

    /// <summary>
    /// This method checks to see if the configured buttons were
    /// just pressed.
    /// </summary>
    /// <param name="thePlayerIndex">The player index being checked.</param>
    /// <param name="theGameTime">The GameTime for the checking.</param>
    /// <returns>Returns true if the buttons were just pressed.</returns>
    public bool MatchGesture( 
        PlayerIndex thePlayerIndex, 
        GameTime theGameTime ) {
        
        bool returnValue = false;
        int index = ( int )thePlayerIndex;

        if( InputManager.CurrentGamePadStates[ index ].IsButtonDown( _buttons ) &&
            InputManager.PreviousGamePadStates[ index ].IsButtonUp( _buttons ) ) {
            returnValue = true;
        }

        return returnValue;
    }
}

The MatchGesture method uses the InputManager. The InputManager stores the current and previous states for gamepads and keyboards.

Developers can create their own gestures but the framework includes the critical gestures. There are simple gestures for detecting that a gamepad button or key was just pressed or just released, and there is support for more complicated gestures that only return true periodically while a user holds a button or key down.

Binding Gestures

So how do you use gestures in your controls or menus? GameControl has a protected method called BindGestures that takes a delegate and set of IInputGestures. By default the framework will automatically call the MatchGesture methods on the bound gestures and if one of the gestures indicates a match the delegate is called. Advanced framework users can also manually check gestures by using the InputManager.

This snippet of code from a sample spinner control shows the binding of gestures.

public class SampleSpinner : MenuItem {
    // <snip> 

    /// <summary>
    /// Initializes the left/right analog stick/d-pad 
    /// as the mechanism to select next/prev option.
    /// </summary>
    protected override void InitializeInput( ) {
        //base.InitializeInput( );
        BindInputGestures(
            this.HandlePrevValue,
            new IInputGesture[] {
                new ButtonDownGesture( Buttons.DPadLeft ),
                new ButtonDownGesture( Buttons.LeftThumbstickLeft )
            } );

        BindInputGestures(
            this.HandleNextValue,
            new IInputGesture[] {
                new ButtonDownGesture( Buttons.DPadRight ),
                new ButtonDownGesture( Buttons.LeftThumbstickRight )
            } );
    }   

    /// <summary>
    /// Handler for requesting the next option.
    /// </summary>
    protected void HandleNextValue( 
        GameControl theControl, 
        PlayerIndex thePlayer, 
        IInputGesture theGesture ) {
        // <snip> 
        // make it go to the next value
        // <snip> 
    }

    /// <summary>
    /// Handler for requesting the previous option.
    /// </summary>
    protected void HandlePrevValue( 
        GameControl theControl, 
        PlayerIndex thePlayer, 
        IInputGesture theGesture ) {
        // <snip> 
        // make it go to the previous value
        // <snip> 
    }
 
    // <snip> 
}

Input and Focus

Another important aspect of input, and making sure that your registered delegates are called, is understanding focus. The framework doesn’t call every single registered gesture for every single control, instead it checks the gestures for the controls that are in focus, and if a gesture isn’t matched it will traverse up through parent controls checking the registered gestures.

I said ‘checks the gestures for the controls that are in focus’. This implies more than one control can be in focus. This is true, however only one control can be in focus for each player. More details on this are discussed below in Advanced Focus.

To put a control in focus, you simply need to set its Focused property to true. Some of the high-level controls will automatically set the focus. For example, the ScreenManager will set the focus on Menus as they are made active while Menus will set the focus of MenuItems as a user moves between the menu options.

Advanced Focus

One of the advanced features for focus and input is the notion of FocusScope. While the default FocusScope will accept input from all players, you can create FocusScopes that control which players’ input will be accepted and processed. This means not only must a control be in focus, but a FocusScope must exist that allows input from the player. This is best explained with the following example.

It is common during game play that if a player hits the Start button the game will load a pause menu that pauses the game and only that same player can hit the Back button to close the pause menu. Input from other players is ignored.

This advanced ability can also be used to bind certain controls of a HUD to particular players in local multi-player games. If you want to use this ability I recommend you have a look at the FocusManager.

The above hopefully has given a good overview of input and focus handling. Additional posts regarding the framework will be coming soon.

Tales Framework for XNA: Controls

Posted 10/06/2008 @ 10:34:40 PM by Joseph Molnar
Filed under: Programming , Tales Framework , Xbox 360 , XNA

I’m finally putting together a post on the Tales Framework, the XNA library I am developing. While I haven’t had much time to work on the framework, I did complete the framework code that was holding back the preview. I’ll post the tech preview once I clean-up the sample. Until then I’ll post some details.

I thought I would start on the UI side, in particular, the idea of controls. I’m sure many first time XNA developers have experience with .NET Windows Forms, Windows Presentation Foundation (WPF) or ASP.NET development. All three use the idea of controls as the base item that represents what you see and what you interact with.

XNA doesn’t have such a concept. While XNA supports sophisticated 3D rendering and low-level 2D sprite handling, the idea of a control framework is quite useful for everything from building menu screens, to HUDs (Heads-Up-Displays), to managing UI state.

So in my attempt to dig deep into XNA I created a control structure that feels similar to Windows Forms and WPF while attempting to recognize the useful and practical differences that XNA brings.

The base class for UI controls is GameControl, which inherits from DrawableGameComponent. I have kept intact the use of Draw and Update but added a fair number of abilities:

  • Controls are hierarchical meaning they have a parent and can have children. This eases things like animation; moving a control automatically moves the children.
  • There are properties, logic and classes related to layout. This includes specifying how a control docks within the parent’s client space, how a control fills the parent’s client space, padding and layout handlers for managing how children are placed within the control’s client space.
  • There are InputBindings which map input events such as button and key presses to callback methods.
  • There are events and properties for handling focus. Ultimately, focus is managed through a FocusManager, which ties into how input is handled.

In addition to this base class, a variety of subclasses exist as starting points to ease the creation of menus and HUDs. The subclasses include:

  • Panel – Commonly used base class for controls that have children. GameControl can have children too, but Panel has logic for handling things like analyzing children locations to get the preferred size of the panel.
  • Screen – Commonly used base class for display screens, such as menus or the main game screen.
  • MenuScreen – Commonly used base class for menu screens. This class primarily adds logic on how to cycle between menu options.
  • MenuItem – Common class used as a menu. This class adds logic and events for selection handling.
  • Label – Simple control that represents text.
  • ImageBox – Simple control that represents an image.
  • NumberSpinnerControl – A control that manages the logic for creating a control that can increment/decrement numbers.
  • OptionSpinnerControl – A control that manages the logic for spinning through a set of non-numeric options.

Generally speaking the controls do not specify how they look but instead contain logic and members that manage how they are used. To manage what they look like you need to subclass. For example, the following code shows a sample number spinner. In this case the control indicates how it wants to look both when the control is in focus and not in focus:

/// <summary>
/// Sample number spinner that has a label containing text 
/// that indicates what the number represents, and another 
/// label that represents the current number.
/// </summary>
public class SampleNumberSpinnerControl : NumberSpinnerControl {
    private Label _valueLabel;
    private string _nameText;
    private Texture2D _background;
    private Color _focusBackgroundColour = new Color( 0xFF, 0xFF, 0xFF, 0x33 );

    /// <summary>
    /// Constructor taking the parameters needed for the numeric spinner.
    /// </summary>
    /// <param name="theText">User text describing the control.</param>
    /// <param name="theMinimumValue">The minimum numeric value.</param>
    /// <param name="theMaximumValue">The maximum numeric value.</param>
    /// <param name="theParent">The parent control.</param>
    public SampleNumberSpinnerControl( 
        string theText, 
        int theMinimumValue, 
        int theMaximumValue, 
        int theCurrentValue, 
        DrawableGameComponent theParent )
        : base( 
            theMinimumValue, 
            theMaximumValue, 
            theCurrentValue, 
            theParent ) {
        _nameText = theText;
    }

    /// <summary>
    /// Called to load any needed content, this implementation 
    /// creates a background texture used when the control is in focus.
    /// </summary>
    protected override void LoadContent( ) {
        base.LoadContent( );
        _background = new Texture2D( 
            this.GraphicsDevice, 
            1, 1, 1, 
            TextureUsage.None, 
            SurfaceFormat.Color );
        _background.SetData<Color>( new Color[ ] { Color.White } );
    }

    /// <summary>
    /// Called to unload loaded content, this implementation
    /// frees the background texture.
    /// </summary>
    protected override void UnloadContent( ) {
        base.UnloadContent( );
        _background.Dispose( );
    }

    /// <summary>
    /// Called to setup the control. This implementation
    /// indicates how we want the control to look..
    /// </summary>
    public override void Initialize( ) {
        base.Initialize( );

        // use horizontal flow layout where children align in the middle vertically
        HorizontalFlowLayout layout = new HorizontalFlowLayout( 
VerticalAlignment.Middle );
        // 6 pixels of padding on left and right, 2 on top and bottom.
        this.Padding = new Padding( 6, 2 );
        // indicate the control fills the parent's horizontal space
        this.Fill = new Vector2( 1.0f, 0 ); 
        this.LayoutHandler = layout;
    }

    /// <summary>
    /// Called to create children controls.
    /// </summary>
    protected override void InitializeControls( ) {
        base.InitializeControls( );

        SpriteBatch batch = new SpriteBatch( this.Parent.Game.GraphicsDevice );
        Label label = new Label( this );

        // first setup the user description label
        label.Fill = new Vector2( 0.4f, 0f );
        label.Font = SystemDefaults.VisualDefaults.MenuFont;
        label.Text = _nameText;
        label.SpriteBatch = batch;
        this.Controls.Add( label );

        // create a panel that holds arrows/label showing the numeric value
        Panel valuePanel = new Panel( this );

        valuePanel.Fill = new Vector2( 0.6f, 0f );
        this.Controls.Add( valuePanel );

        // first, left aligned, label ... a simple arrow to 
        // indicate you can press left to lower the value
        label = new Label( valuePanel );
        label.Padding = new Padding( 5, 0, 5, 0 );
        label.HorizontalDock = HorizontalAlignment.Left;
        label.Font = SystemDefaults.VisualDefaults.MenuFont;
        label.Text = "<";
        label.SpriteBatch = batch;
        valuePanel.Controls.Add( label );

        // now setup the center aligned label that holds the numeric text
        _valueLabel = new Label( valuePanel );
        _valueLabel.HorizontalDock = HorizontalAlignment.Center;
        _valueLabel.Font = SystemDefaults.VisualDefaults.MenuFont;
        _valueLabel.SpriteBatch = batch;
        _valueLabel.Color = SystemDefaults.VisualDefaults.NormalTextColor;
        _valueLabel.Text = GetValueString( );
        valuePanel.Controls.Add( _valueLabel );

        // now setup the final, right aligned, label ... a simple arrow
        // to indicate you can press right to increase the value
        label = new Label( valuePanel );
        label.Padding = new Padding( 5, 0, 5, 0 );
        label.HorizontalDock = HorizontalAlignment.Right;
        label.Font = SystemDefaults.VisualDefaults.MenuFont;
        label.Text = ">";
        label.SpriteBatch = batch;
        valuePanel.Controls.Add( label );
    }

    /// <summary>
    /// This overridden Draw paints a background if the control
    /// is in focus.
    /// </summary>
    public override void Draw( GameTime gameTime ) {
        if( this.Focused ) {
            _valueLabel.SpriteBatch.Begin( SpriteBlendMode.AlphaBlend );
            _valueLabel.SpriteBatch.Draw( 
                _background, 
                new Rectangle( 
                    ( int )this.PhysicalPosition.X, 
                    ( int )this.PhysicalPosition.Y, 
                    ( int )this.Size.X, 
                    ( int )this.Size.Y ), 
                    this._focusBackgroundColour );
            _valueLabel.SpriteBatch.End( );
        }

        base.Draw( gameTime );
    }
    
    /// <summary>
    /// OnFocusChanged is called when the focus changes. This 
    /// implementation changes the label that shows the current
    /// numeric value to use a different colour when it is in 
    /// focus than when it is not in focus.
    /// </summary>
    protected override void OnFocusedChanged( ) {
        base.OnFocusedChanged( );
        if( this.Focused ) {
            _valueLabel.Color = SystemDefaults.VisualDefaults.FocusTextColor;
        } else {
            _valueLabel.Color = SystemDefaults.VisualDefaults.NormalTextColor;
        }
    }

    /// <summary>
    /// This method is called when the numeric value has
    /// changed. This implementation sets the value 
    /// label to the value the user has changed it to.
    /// </summary>
    protected override void OnValueChanged( ) {
        _valueLabel.Text = GetValueString( );
        base.OnValueChanged( );
    }

    /// <summary>
    /// Simple method used to get the string value
    /// of the current chosen number. 
    /// </summary>
    protected string GetValueString( ) {
        return this.Value.ToString( );
    }
}

In the screenshot below you can see the sample numeric spinner in action. In fact you can see three. Two of spinners are not in focus, but the middle one is. You can see the description text aligned to left, beside it is a panel that contains the arrows (aligned to the left and right of the panel) and the numeric value (centered in the panel). The spinner that has focus has a lighter grey background and the value text is dark blue.

NumericSpinnerExample

Hopefully this has given you a good first look at the control structure for the Tales Framework. In future posts I’ll look at how input and focus work, as well as how network session handling works.

Side Notes:

  1. Some of the items outlined here are going to change prior to my 1.0 release. I’ll be outlining the items I plan on changing when I release the preview.
  2. Until the release of XNA Game Studio 3.0, the Tales Framework is built for XNA GS 2.0.
  3. If you use Windows Live Writer to write your blog entries and want something to do syntax highlighting like you see above, please contact me. Last year I wrote a configurable Live Writer plug-in that can handle most languages.