Spriter implementation for FlatRedBall

For over the past year, I have been working on an API and plugin to use in the FlatRedBall engine that makes it dead simple to load, play, and manipulate Spriter animations in your FlatRedBall games. The implementation is written as an extension to the FlatRedBall engine, so you get all the goodness that comes from using first-class objects that the engine understands.

A few features that other Spriter implementations may not have:

  • Positioning in 3D space
  • Scaling the entire animation
  • Setting animation speed
  • Reversing animation playback (negative speed)
  • Rotating an animation on any axis (X/Y/Z)
  • Cloning animations
  • Playing every entity in an animation file simultaneously via SpriterObjectCollection
    • Every one of the features above works on SpriterObjectCollection as well

This is just a subset of the features in my Spriter implementation. If you are interested, install the FlatRedBall development kit, and head over to the releases section to get the latest release of my plugin. It’s a simple installation process into the Glue tool you get in FRBDK. Follow the tutorials, and you’ll be creating and using Spriter animations in a real game in no time!

Test Driven Development (TDD) vs. Traditional Testing

TDD can get you pretty far, but integration testing is necessary.

The subject of this post is a bit of a misnomer, because the two are not mutually exclusive. That is to say, test driven development is not a replacement for testing. In fact, test driven development has less to do about testing than it does about design. TDD should drive your class design in such a way that makes it easier to get to the real testing phase. There are certain cases that are not going to be apparent during the initial class design, so when developing any application, testing should begin as soon as possible. TDD Can get you there faster, because a lot of the pieces of the application can be faked since the design is testable!

Anything that gets mocked in a unit test can be faked in a built and deployed application, so business users, UX specialists, and designers will get a chance to play with the app to tweak requirements very early in the process! This early change is a lot less risky than late change when an application is “done” because the whole system is less complex.

Take for example my most recent project for which I am using TDD. It is a gesture library for desktop games using XNA (not windows 8 store games). I created a GestureProvider object which relied on an ITouchEventProvider interface to receive raw TouchEvent objects and return GestureSample objects. Using just four conceived objects, I wrote some simple tests that would prove Tap, Drag, and Pinch gestures could be detected given the proper touch events.

The tap test went something like…

[TestMethod]  
public void single_tap_registers_from_one_touch()  
{  
    // Given a mock ITouchEventProvider that returns the following
    _container  
        .Arrange<ITouchEventProvider>(p => p.Events)  
        .Returns(new List  
        {  
            new TouchEvent  //    touch down at 0,0
            {  
                Id = 1,  
                Position = Vector2.Zero,  
                Action = TouchEvent.TouchEventAction.Down,  
                TimeStamp = DateTime.Now  
            },   
            new TouchEvent  //    touch up at 0,0
            {  
                Id = 1,  
                Position = Vector2.Zero,  
                Action = TouchEvent.TouchEventAction.Up,  
                TimeStamp = DateTime.Now.AddMilliseconds(200.0)  
            }  
        });  

    var gestureProvider = _container.Instance;  

    // Get gestures from the real GestureProvider object (system under test or SUT)
    var samples = gestureProvider.GetSamples();  

    // Assert that there is one GestureSample object for a Tap at 0,0 
    var gestureSamples = samples.ToList();  
    Assert.AreEqual(1, gestureSamples.Count);  

    var tap = gestureSamples[0];  
    Assert.AreEqual(Vector2.Zero, tap.Delta);  
    Assert.AreEqual(Vector2.Zero, tap.Delta2);  
    Assert.AreEqual(Vector2.Zero, tap.Position);  
}

I did that test, and another for Drag and Pinch. Everything seemed to be going so well that I wanted to test them out, because I had a sneaking suspicion that I was missing something. I wrote up a quick test for a real ITouchEventProvider implementation that would use an interop library to listen for events, and provide them to the GestureProvider. I fired up a real game and added the necessary code to use the GestureProvider. I noticed one thing right away: Tap was not registering as a tap, but instead it was a drag. I double checked my tests, and it all looked ok, so I had to debug a bit. Eventually I found that my assumption about what events would fire for a tap was flawed. There could be any number of “move” events between “down” and “up”. I made the quick fix to add one move event to the test arrangement and fixed the GestureProvider so that the test passed, and then it worked. This proves that integration testing is a very important step in any system.

My unit test alone did not make the whole system work, but via TDD, I had a designed the classes such that there was a clear path to fix the test so that it satisfied the real-world scenario instead of the erroneous assumption I made. Chalk up another TDD win!

Multi touch and gesture input in Windows with DPI scaling

I mentioned in a previous post that I am working on a new project related to gesture input. That very day, I hit a wall regarding desktop scaling, and last night I broke through it! Perhaps a topic for another post: with some applications, TDD can get you to a certain point, but integration testing is a must pretty early on.

The FRBTouch project is no exception! There are a few different problems to solve with this project:

  • Touch event capturing
  • Gesture detection
    • Taking touch events and making gestures
    • e.g. One touch event down then up is a tap
  • Coordinate translation
    • Taking window coordinates and translating them in an application (e.g. a FlatRedBall game)

The first two bullet points turned out to be the easiest, because they were mockable. For instance:

        public void single_tap_registers_from_one_touch()
        {
            // Arrange
            _container
                .Arrange<ITouchEventProvider>(p => p.Events)
                .Returns(new List<TouchEvent>
                {
                    new TouchEvent
                    {
                        Id = 1,
                        Position = Vector2.Zero,
                        Action = TouchEvent.TouchEventAction.Down,
                        TimeStamp = DateTime.Now
                    },
                    new TouchEvent
                    {
                      Id = 1,
                      Position = Vector2.Zero,
                      Action = TouchEvent.TouchEventAction.Move,
                      TimeStamp = DateTime.Now.AddMilliseconds(10)
                    },
                    new TouchEvent
                    {
                        Id = 1,
                        Position = Vector2.Zero,
                        Action = TouchEvent.TouchEventAction.Up,
                        TimeStamp = DateTime.Now.AddMilliseconds(200.0)
                    }
                });
            var gestureProvider = _container.Instance;

            // Act
            var samples = gestureProvider.GetSamples();

            // Assert
            var gestureSamples = samples.ToList();
            Assert.AreEqual(1, gestureSamples.Count);

            var tap = gestureSamples[0];
            Assert.AreEqual(Vector2.Zero, tap.Delta);
            Assert.AreEqual(Vector2.Zero, tap.Delta2);
            Assert.AreEqual(Vector2.Zero, tap.Position);
        }

That’s the test that proves a tap gesture is detectable given how the touch events are provided. It was easy to setup a mock scenario for drag and pinch as well, and just assert the required gesture return values. The TouchEvent object maps pretty closely to the events that User32.dll provides, also, so there wasn’t that much to test for actually capturing events.

The major problems came when attempting to translate coordinates from touching an XNA game window into world coordinates. I use a surface pro for all development, and it is pretty much a necessity to have 150% scaling on at all times, because the size of the screen is small. Windows scales all windows up, but in doing so it breaks the coordinate system for touch input. This is not something you can see or solve with test driven development (at least not traditional unit tests), because it requires a live scaled window and graphics object to operate.

To solve the problem, one simply has to disable the auto scaling, and tell Windows that the application will handle understanding the DPI settings. You have to make your application DPI Aware. (More info). The window will then not auto-scale, and the coordinate system will not be broken, so normal translation routines will work.

King Randall’s Party by Jesse Crafts-Finch

A friend and fellow indie developer who is trying to make it on his own has launched a Kickstarter campaign for his game, King Randall’s Party. King Randall’s Party is a mash-up between a Minecraft and tower defense. I love the concept, and I backed his game.

He has been working on the game for a while now, and he’s using the FlatRedBall engine, while using some of the tile map technology that I developed. King Randall’s Party actually drove some of the requirements for what I wrote, so he helped me as well.

Please back his project for whatever you can. I know this blog is not high traffic or anything, but I hope it reaches some people at least!

Unit testing with mocks

Recently I have really gotten into Test Driven Development (TDD). My first real try at TDD was for a library that I have yet to complete for integrating spriter animations into FlatRedBall. Now I am working on something work related, so I can’t give any specific details as it is proprietary information. I can, however, come up with some contrived examples that may be beneficial to the community regarding Mocking.

There are several different mocking frameworks out there, and I started using Moq first, but I have changed to using Telerik JustMock because it has a less verbose syntax. I may post a “differences between Moq and JustMock” some day, but others have already covered that on the web, so it really isn’t necessary.

I also find great value in dependency injection, so IoC containers are invaluable in my production code; however, something I have also recently learned is that they can be just as invaluable in a unit test. Implementing the dependency injection pattern enables techniques such as inversion of control (IoC), which allow specifying concrete dependencies at runtime for abstract dependencies. That is to say, if class A relies on interface I, and B implements I, class C associates A with B at runtime without either class knowing of the other. Example:

public class Foo
{
    private IWorker _iworker;
    public Foo(IWorker iworker)
    {
        _iworker = iworker;
    }

    public string DoWork()
    {
        return _iworker.DoWork();
    }
}

public interface IWorker
{
    string DoWork();
}

public class Bar : IWorker
{
    public string DoWork()
    {
        return "Bar";
    }
}

We have two classes. Foo which has a dependency on an abstraction (interface IWorker). You can see that Foo doesn’t have any reference to class Bar in this example, and the reverse is true. Bar doesn’t know anything about Foo.

One might use this class in the following manner:

// Manually injecting the dependency through a constructor
var foo = new Foo(new Bar());

// or by Automatically injecting the dependency by setting up an IoC container
var container = new UnityContainer();
container.RegisterType<IWorker, Bar>();

// Typically the below step is done by a dependency resolver which depends on a
// container of some sort, but for a concise example:
Foo foo = container.Resolve<Foo>();

I’ll let the comments explain the code. Suffice it to say that the second pattern is much nicer, because a third class is responsible for coupling all of your dependencies. In MVC, this is typically a BootStrapper static class, but it can be anything that sets the MVC configuration’s global DependencyResolver object.

Why should you use this pattern in your class design? Unit tests! Unit tests! Unit tests!

Example:

[TestMethod]
public void a_dowork_returns_dowork_from_IWorker()
{
    // Arrange
    var container = new MockingContainer(); 
    container.Arrange(i => i.DoWork()).Returns("test");

    // Act 
    Foo foo = container.Instance;
    var result = foo.DoWork();

    // Assert
    Assert.AreEqual("test", result);
}

Mind blown? There’s a lot going on here, but essentially:

Arrange:
The unit test takes advantage of the dependency injection pattern and injects a proxy implementation of the IWorker interface into the Foo object it maintains inside the MockingContainer. The call to Arrange is saying that this proxy object should return “test” for any calls to its DoWork function. So we have an object that implements IWorker (it has nothing to do with class Bar), and we inject that into the instance of Foo automatically with the container.

Act:
We then call DoWork on the instance of Foo that the container provides us (which has the dependency injected already)

Assert:
We assert that the result returned from foo.DoWork() matches what the proxy DoWork was returning.

This is a simple contrived example, but it illustrates how IoC containers work in tandem with mocking very well. I hope someone finds this useful!

Separation of responsibilities: Ability, AbilityEffect, and EffectManager

After talking with @Sunflash93 on twitter (find their blog here), I got to thinking I should post about how I designed the ability system in my game Z-Com. See my previous blog post for more info about the game.

In my coding adventures, I like to attempt to stick to the SOLID principles of OOD as outlined here. Namely, my favorite and arguably the easiest of the principles to smell is the Single Responsibility Principle. In short, A class should have one, and only one, reason to change. This can and should be applied to all facets of OO programming, including game development.

When first trying to flesh out the details of how I would do abilities, I knew I wanted a few things:

  • Single target abilities
  • AOE/Multi target abilities
  • Friendly abilities (heals)
  • Damage/Healing over time abilities
  • Constant effects (increases your speed by x for y seconds)

Starting with single target abilities, I thought perhaps I would just do it all in one class (Ability). A TacticalEntity (my movable player and zombie object) would get a list of abilities that one could fire at will (zombies through their AI, and players through some GUI). What is so wrong with this approach? For starters, it would would fine for a single target or aoe instant ability,  but how would a single method on a single instance of an ability apply a damage over time effect (e.g. Does 10 damage per second for 4 seconds)? You have to apply something to an entity and have it stick: AbilityEffect.

That was the biggest revelation for me: separate the responsibility of applying effects and the actual damage/healing effect to a different object altogether. Ok great… now I can just put a collection of effects on a TacticalEntity and an ability can apply effects to the entity! Wait… who is responsible for removing the effects once they expire? For that matter, who is responsible for keeping track of all the effects?

Of course the effect could probably have handled all of this, and the entity itself could have removed effects from itself when they expire, but that’s not the responsibility of the TacticalEntity. It already has a lot of code and does enough. That is where EffectManager comes along. It’s a static class that has an Activity() method that gets called every frame, and it gets the honor of keeping track of a Dictionary<TacticalEntity, List> which holds all effects that are applied to all TacticalEntities.

In both of the examples above, adhering to the Single Responsibility Principle drove me to make decisions which keep my code more concise and maintainable. Any time you hear yourself saying you can use a single class to do multiple different things, you should ask yourself if it would work better split into separate responsibilities.

I haven’t done an AOE ability yet, but that is all about targetting and figuring out which entities to apply effects to outside of the whole ability/effect/manager classes as described above. Without rambling any further, here is the code as it stands right now:

BasicAbility.cs:

    public class BasicAbility : IAbility
    {
        public BasicAbility(List effects)
        {
            Effects = effects;
        }

        public void execute(TacticalEntity source, List destination)
        {
            foreach (TacticalEntity entity in destination)
            {
                execute(source, entity);
            }
        }

        public void execute(TacticalEntity source, TacticalEntity destination)
        {
            Projectile projectile = Factories.ProjectileFactory.CreateNew();
            projectile.Position = source.Position;
            projectile.SourceEntity = source;
            projectile.TargetEntity = destination;
            projectile.SpriteAnimate = true;
            projectile.Ability = this;
        }

        public List Effects
        {
            get;
            private set;
        }
    }

AbilityEffect.cs:

    public class AbilityEffect : IAbilityEffect
    {
        private bool ConstantEffectsApplied = false;

        public AbilityEffect()
        {
            ConstantEffectsApplied = false;
        }

        public AbilityEffect(bool tickImmediately, int healthPerTick, int speedEffect, int defenseEffect, float aggroRadiusEffect, int strengthEffect, int totalticks, string name)
        {
            TickImmediately = tickImmediately;
            HealthEffectPerTick = healthPerTick;
            SpeedEffectWhileActive = speedEffect;
            DefenseEffectWhileActive = defenseEffect;
            AggroRadiusEffectWhileActive = aggroRadiusEffect;
            StrengthEffectWhileActive = strengthEffect;
            TotalTicks = totalticks;
            Name = name;
            ConstantEffectsApplied = false;
        }

        public AbilityEffect(TacticalEntity source, TacticalEntity affectedEntity, IAbilityEffect that)
            : this(that.TickImmediately, that.HealthEffectPerTick, that.SpeedEffectWhileActive, that.DefenseEffectWhileActive, that.AggroRadiusEffectWhileActive, that.StrengthEffectWhileActive, that.TotalTicks, that.Name)
        {
            AffectedEntity = affectedEntity;
            SourceEntity = source;
        }

        public int HealthEffectPerTick
        {
            set;
            get;
        }

        public int SpeedEffectWhileActive
        {
            set;
            get;
        }

        public int DefenseEffectWhileActive
        {
            set;
            get;
        }

        public float AggroRadiusEffectWhileActive
        {
            set;
            get;
        }

        public int StrengthEffectWhileActive
        {
            set;
            get;
        }

        private int _TotalTicks;
        public int TotalTicks
        {
            get
            {
                return _TotalTicks;
            }
            private set
            {
                _TotalTicks = value;
                TicksRemaining = value;
            }
        }

        public int TicksRemaining
        {
            get;
            private set;
        }

        public string Name
        {
            get;
            set;
        }

        public bool Active
        {
            get
            {
                return TicksRemaining > 0;
            }
        }

        public TacticalEntity AffectedEntity
        {
            get;
            set;
        }

        public void ApplyConstantEffects()
        {
            AffectedEntity.strengthEffects += StrengthEffectWhileActive;
            AffectedEntity.defenseEffects += DefenseEffectWhileActive;
            AffectedEntity.speedEffects += SpeedEffectWhileActive;
            AffectedEntity.aggroCircleRadiusEffects += AggroRadiusEffectWhileActive;
        }

        public void RemoveConstantEffects()
        {
            AffectedEntity.strengthEffects -= StrengthEffectWhileActive;
            AffectedEntity.defenseEffects -= DefenseEffectWhileActive;
            AffectedEntity.speedEffects -= SpeedEffectWhileActive;
            AffectedEntity.aggroCircleRadiusEffects -= AggroRadiusEffectWhileActive;
        }

        public void ApplyEffectTick()
        {
            if (!ConstantEffectsApplied)
            {
                ApplyConstantEffects();
                ConstantEffectsApplied = true;
            }
            if (Active)
            {
                AffectedEntity.health += HealthEffectPerTick;
                --TicksRemaining;
            }
        }

        public IAbilityEffect Clone(TacticalEntity source, TacticalEntity entity)
        {
            return new AbilityEffect(SourceEntity, entity, this);
        }

        public TacticalEntity SourceEntity
        {
            get;
            private set;
        }

        public bool TickImmediately { get; set; }
    }

EffectManager.cs:

    public static class EffectManager
    {
        private static Dictionary<TacticalEntity, List> entityEffects = new Dictionary<TacticalEntity, List>(20);
        private static double lasttick = TimeManager.CurrentTime;

        public static void AddEffectsToEntity(TacticalEntity source, TacticalEntity entity, List effects)
        {
            if (!entityEffects.ContainsKey(entity))
            {
                entityEffects.Add(entity, new List(effects.Count));
            }
            foreach (IAbilityEffect effect in effects)
            {
                AddEffectToEntity(source, entity, effect);
            }
        }

        public static void AddEffectToEntity(TacticalEntity source, TacticalEntity entity, IAbilityEffect effect)
        {
            IAbilityEffect newEffect = effect.Clone(source, entity);
            List effects;
            if (!entityEffects.ContainsKey(entity))
            {
                effects = new List(1);
                entityEffects.Add(entity, effects);
            }
            else
            {
                effects = entityEffects[entity];
            }
            effects.Add(newEffect);

            if (newEffect.Active && newEffect.TickImmediately)
            {
                newEffect.ApplyEffectTick();
            }
        }

        public static void Activity()
        {
            if ((TimeManager.CurrentTime - lasttick) > 1.0)
            {
                lasttick = TimeManager.CurrentTime;
                foreach (KeyValuePair<TacticalEntity, List> pair in entityEffects)
                {
                    TickAndRemoveInactiveEffects(pair);
                }
            }
        }

        private static void TickAndRemoveInactiveEffects(KeyValuePair<TacticalEntity, List> pair)
        {
            foreach (IAbilityEffect effect in pair.Value)
            {
                effect.ApplyEffectTick();
            }

            for (int x = pair.Value.Count - 1; x >= 0; --x)
            {
                if (!pair.Value[x].Active)
                {
                    pair.Value[x].RemoveConstantEffects();
                    pair.Value.RemoveAt(x);
                }
            }
        }
    }

And the call to attack another entity:

        public virtual void attack(TacticalEntity attackableEntity)
        {
            if (this.currentAbility != null &&
                this.attackCircle.CollideAgainst(attackableEntity.hitCircle))
            {
                this.currentAbility.execute(this, attackableEntity);                
            }
        }

Manic coder on a mission: FlatRedBall game engine, Tiled Map Editor, and you.

I’ve been busy. Like a manic coder on a mission busy, and I love it. I haven’t been this driven about anything in a long time, and I am loving every second of it.

About a month ago, Joel Martinez introduced me to FlatRedBall. I posted a quick blog post about it, but I did not do justice to this amazing engine. Not only is the engine the best thing since sliced bread (I will never do game development without it ever again), but the people there are AMAZING.

Let’s talk for a second about Victor Chelaru. Where do I begin? He created FlatRedBall on a philosphy. Basically, he was touched by the thorough, selfless help of a random stranger on the gamedev.net forums named Teej, and he uses that experience to drive development efforts at FRB. I am seriously impressed with his work ethic and desire to help others. That’s enough about Vic and FRB, though. As I said, I have been busy.

I have been working on an X-Com type game for a few months now, mostly prior to finding out about FRB. I had an extremely simple prototype that was unbelievably complex under the covers when I wrote it straight up with XNA. FlatRedBall nearly trivializes the work I did there, but that is a good thing. With the FRB engine at my disposal, I can just whip up an isometric tile map, slap a NodeNetwork on it, and have a sprite pathfinding to its heart’s content in 2.5d. Well, now I can, but there was a major piece missing when I arrived to all the FRB goodness.

So I filled the gap. I wrote a Tiled Map Editor to FlatRedBall toolkit which I am now calling TMXGlue.

Basically what this tool does is plug right into Glue (I will write about glue eventually I’m sure) and allow you to add tiled maps directly to your game and have them displaying immediately. Not only is there support for orthogonal and isometric maps and tilesets, but both types work with object layers in TMX for collision and node network generation, generating NodeNetwork and ShapeCollection which you can use in game for A* pathfinding and collisions however you want.

I am constantly working to improve this system, so please leave comments here if you have anything you would like to contribute, see added, or if you find anything completely broken. You can also drop me a note on twitter if you prefer to.

FlatRedBall game engine

In speaking with Joel Martinez about my most recent game project, we got to the point of talking about finishing a game, and he mentioned something about animation. A friend of mine had developed part of a game engine I had always planned to use which had a pretty intuitive and well laid out library. When I mentioned that to him, he pointed me toward FlatRedBall.com.

I was blown away.

This game engine / framework has it all:

At first I was feeling a bit like using this type of thing would mean that I was giving up something, like I had lost that “cool” factor or some form of virtual street cred. Developing with flatredball would be nothing more than using some tool where you drag and drop a bunch of things and make a game and claim you’re an indie dev; however, I’ve been reading the wiki a little bit here and there today, and I have to say I am over that hump… Joel said it best:

… I felt exactly like that in 2010 … then I got over it and released 3 games last year 🙂

Ok… I’m sold. now to start playing, or finding the time to play!

Update: I’m having a bit of trouble creating a project with “Glue” at the moment, so we’ll see how it pans out.