Archive for May, 2009

Fixed XBox 360 Controller Shoulder Button Images

If you’re using the stock XBox 360 controller button images provided by Microsoft, you may have noticed that they mislabelled the two shoulder buttons. I spent a few minutes fixing the labels in Paint.NET, and I’ve uploaded the corrected images here for others to use:

I’ve also provided both PNGs and the Paint.NET source images in a ZIP archive.

Please note that the original images were made available under the Microsoft Permissive License.

You may also want to consider using alternate button graphics, like those available in Jeff Jenkins’ Button Pack 1 and Button Pack 2.

Tags: ,

Bits and pieces week

Did work on various bits and pieces of the game this week. A rough overview:

  • Added the first piece of level geometry that deals damage on contact (spikes)
  • Overhauled my ComputeStandingY algorithm so that it takes an order of magnitude less time to run
  • Implemented a new animation for surface mantling that includes camera control
  • Moved jumping, ledge clinging and mantling from using tasks to using a combination of animation triggers and simple state machine logic

So, I guess I’ll give each bullet point a little detail.


Adding spikes was fairly straightforward. The largest challenges were getting the collision detection and rendering to work correctly. All the geometry I’ve added to levels before now has simple collision detection, in that the geometry remains relatively static and obstructs the player’s movement. Spikes, however, needed to allow the player to move through them but still detect collisions so that they could deal damage. Getting this to work meant some changes to my collision detection code, in order to correctly handle cases where a piece of geometry had no collision, and also meant that I had to add support for changing a piece of geometry’s collision on the fly – that way I could leave the spike with no collision by default, but assign it collision temporarily during each update so that I can perform a collision check to find the entities it’s touching.

            _CollisionList = _DrawList;
            this.FindObstructions(this.InflictDamage);
            _CollisionList = Game.NullCollisionList;

Rendering the spikes was a bit of a challenge as well – since they’re arbitrarily sized and can point in different directions, I had to do some work to figure out how to take an arbitrary texture and use SpriteBatch to align it with the spike’s geometry. After a lot of iteration, I ended up with something that properly scales, rotates, and aligns the sprite so that it lines up with the geometry – determining the proper inputs to a SpriteBatch.Draw call can be challenging when you’re rotating, scaling and translating all in one go, so it involved a lot of trial and error.


Some investigation of issues I was running into with standing on surfaces revealed that my current approach was getting too complicated and fragile – previously, I was scanning over all the objects under the player, and then choosing arbitrary points along their surface (left edge, middle, and right edge) and casting rays downward at those points to attempt to determine where the player should stand on the surface. This ended up not working well for complex surfaces, like the uneven edges of the stone outcroppings created by the stone potion, and being unnecessarily expensive for simple surfaces like flat rectangles (which really only need a single ray cast). Furthermore, it had a negative performance impact, since I was issuing hundreds of ray cast calls per frame in situations where I might have gotten away with only a dozen.

The solution to this ended up being simple: Where previously, I’d issue ComputeStandingY calls on each object that the player could be standing on, multiple times to cast individual rays, now I would issue a single call for each object, telling it the location of the player’s left and right edges. This way each object could have its own implementation for handling uneven surfaces – simple rectangles could just return the Y coordinate of their top edge, while complex geometry could sweep over its vertices and do the necessary math to compute the Y coordinate. In some cases, the new handlers got a bit complicated, but in most cases, they weren’t actually any harder to write than the old ones – a pleasant surprise. For example, the handler for pressure plates required a complete rewrite, since a pressure plate is represented by a rectangle (in the middle) with two triangles on the corners to give it a smooth slope:

        public override float? ComputeStandingY (float x1, float x2, float y) {
            var p = _CollisionList[0];
            if ((x2 >= p[1].X) && (x1 <= p[2].X))
                return Anchor.Y;
            else if (x2 < p[2].X)
                return RuntimeTriangle.ComputeStandingY(p[0], p[1], x1, x2, y);
            else
                return RuntimeTriangle.ComputeStandingY(p[2], p[3], x1, x2, y);
        }

While other handlers, like Triangle, required only minor changes to account for the addition of a second X coordinate:

        public static float ComputeStandingY (Vector2 slopeBegin, Vector2 slopeEnd, float x1, float x2, float y) {
            var minX = slopeBegin.X;
            var maxX = slopeEnd.X;

            if (x2 < minX)
                return slopeBegin.Y;
            else if (x1 > maxX)
                return slopeEnd.Y;

            var startY = slopeBegin.Y;
            var endY = slopeEnd.Y;
            var dX = maxX - minX;
            var dY = endY - startY;

            float x = (dY > 0) ? x1 : x2;

            var d = (x - minX) / dX;

            var result = startY + (dY * MathHelper.Clamp(d, 0.0f, 1.0f));

            return result;
        }

The end result is that ComputeStandingY went from around #10 on profiler results to well below #50 (always good to maintain a stable framerate), and a number of minor surface standing oddities went away. Future work involving complex surfaces should be much easier, as well, which will be important for some of the game content I have planned.


Earlier this week I got the art for one of the player characters’ surface mantling animations, so I decided to get it into the game. Doing this required throwing out most of the existing code for surface mantling, since I had previously animated it by actually moving the player character progressively from his old location to the new one. The new animation is simpler, in that the player switches instantly from the old location to the new one, but poses some interesting challenges: I have to realign the player such that his animation looks like it’s moving from his old location to the new one, without the jarring realignment of the camera that would normally accompany an instant relocation like that.

The end result looks pretty good. The basic approach looks like this:

        protected void BeginMantle (ICollidable mantleTarget, Vector2 targetPosition) {
            Jumping = false;
            JumpApex = false;
            LedgeClinging = false;
            Mantling = true;
            LockInput = true;

            var anim = PlayAnimation("Mantle");
            _MantleTarget = mantleTarget;
            _MantleStartPosition = Position;

            _LockCamera.Position = Position;
            _LockCamera.Weight = 1.0f;
            Game.CameraStack.Add(_LockCamera);

            Velocity = Vector2.Zero;
            Position = mantleTarget.Anchor + targetPosition;

            var rideable = mantleTarget as IRideable;
            if ((rideable != null) && (!_Riding.ContainsKey(rideable)))
                BeginRiding(rideable);
        }

        protected void EndMantle () {
            Mantling = false;
            LockInput = false;
            if (StandingOn != null)
                _RidingPosition = Position - StandingOn.Anchor;

            Game.CameraStack.Remove(_LockCamera);
            Game.CameraStack.Add(new LookAtCameraController(
                _MantleStartPosition, 0.0f, 0.0f, MantleCameraPanDuration
            ));
        }

A few things are going on here: When the player begins mantling onto a surface, I set some state flags in order to keep things sane, for example disabling the input, so that you can’t move left/right or jump while mantling is in progress. After that, I start the mantle animation and initialize some fields so that the player’s code can keep track of the surface it’s mantling onto and what the source and target positions are, for animation purposes. Next, I lock the camera on the player’s original position, so that it won’t move suddenly when I relocate the player to the new location. Finally, I move the player to his new position, reset his velocity, and if the surface being mantled onto is rideable, I set him as riding it.

The rest of the work mostly happens automatically: I tag the animation frames with markers so that the game knows what his origin is and where the top of his head is, so that his bounding box changes automatically along with the animation, and he appears to be climbing up onto the surface. When the animation finishes, it triggers a handler (EndMantle) to do the rest of the work – Cleaning up the state, and triggering a short camera pan from the old location to the new location so everything looks smooth. One final touch is that I play the ‘crouch to stand’ animation immediately after completing a mantle, so that the player appears to quickly stand back up after climbing onto a surface.

In practice, this solution actually looks smoother and more realistic than the old one, despite the fact that the animation is simpler and the collision detection approach is simpler.


And finally, this brings me to the task changes. As you might have noticed, previously I used tasks to structure ‘long-lived’ pieces of player state, like mantling onto a surface or gripping onto a ledge. This was convenient since tasks could easily take parameters and have local variables that would last for their entire duration, allowing me to track things like the source and destination positions for a mantle without needing to define fields for them. It also simplified the state machines necessary for handling player input and motion, since states like ‘is the player mantling’ could be represented entirely by the task responsible for them, and all the logic for updating during that task could be handled by the task itself, once per frame. Tasks also gave me an easy way to ensure that code ran at the beginning and end of a given animation, via the use of IDisposable, without having to manually track state and call Begin/End functions. Put together, all this was a huge timesaver initially, before the addition of my animation system and the simplification of my collision detection code – early prototypes contained some utterly terrifying state machines before I simplified things by switching to tasks.

The time had finally come to stop using tasks for this, though. The new animation system gave me a way to easily attach logic to onscreen animation, by responding to markers/triggers and to the beginning and end of an animation, and the conditional branching support in the animation format meant that the majority of my animation logic no longer needed to live in the code at all, alleviating most of the issues with huge state machines that I had before. So in the process of rigging up the new mantle animation, I converted jumping, mantling, and ledge clinging so that they used simple state machines and animations instead of tasks.

For the most part, the process was straightforward – I added boolean fields to track the player’s state where I previously used a task (so the player now has LedgeClinging and Mantling flags that he didn’t before), and created private fields for things that were previously stored in task locals (like the surface being mantled onto). Logic that needs to happen at the beginning or end now has its own handler (like the BeginMantle and EndMantle functions shown above), and in the event that I need to run some logic every frame during an animation, I write a simple function for it and insert it into the appropriate part of the state machine. Some of the code for handling player input is starting to get rather complicated, with chains of 5-6 if () else if () else if () else if () conditions, but it’s at least remaining relatively small and encapsulated.

        protected bool BeginLedgeCling (out ICollidable clingTarget) {
            if (!CanLedgeCling(out clingTarget)) {
                LedgeClinging = false;
                return false;
            }

            Velocity = Vector2.Zero;
            LedgeClinging = true;
            _ClingDirection = GetInputDirection();
            if (clingTarget != null)
                _ClingPosition = Position - clingTarget.Anchor;
            if (_ClingTarget is IRideable)
                BeginRiding(_ClingTarget as IRideable);

            return true;
        }

        protected void UpdateLedgeCling () {
            if (_ClingTarget == null)
                return;

            var delta = (_ClingTarget.Anchor + _ClingPosition) - Position;
            ApplyMotion(delta);
            AutoUpdateBounds();
        }

        protected void EndLedgeCling () {
            LedgeClinging = false;
            if (_ClingTarget is IRideable)
                StopRiding(_ClingTarget as IRideable);
            _ClingDirection = 0;
            _ClingTarget = null;
        }

During the process of moving things around, I actually found a few bugs in my implementation of ledge clinging, which made this refactoring quite worthwhile. Previously, I’d been depending on some bugs in my code in order to make the player remain stationary while clinging to a ledge, when I could have easily accomplished this with a single-line change in the right spot. I also discovered that rebounding off of a wall was actually intermittently broken before because the ledge clinging code had the ability to interfere by causing the player to begin clinging onto the ledge during the middle of a rebound. The new state machine approach made it much easier to address this problem by adding some appropriate checks, so that the player can’t even attempt to grip onto a ledge if he’s moving away from it.

All in all, a productive week!

Tags: , , , ,

Animation markers and triggers

One of the first things I did this week was implement support for scripted animation markers. Markers let me attach names to various parts of a sprite so that I can use them in animation and collision detection – for example, lining up a weapon with a character’s hand, or doing hit detection against a character’s hand instead of his entire hitbox.

Once I had some simple markers for the player’s feet added to his animation script, to test them out more thoroughly, I implemented support for attaching simple script triggers to a combination of a marker and a given animation frame, like this:

    <SpriteMarker typeId="2">
        <Name>Left Foot</Name>
        <Groups>
            ...
            <Group name="run">
                <Frames>
                    <Frame anchor="tl" x="80"  y="170" index="0" />
                    <Frame anchor="tl" x="61"  y="169" index="1" />
                    ...
                    <Frame anchor="tl" x="132" y="143" index="6" />
                    <Frame anchor="tl" x="99"  y="173" index="7" trigger="Footstep" />
                </Frames>
            </Group>
        </Groups>
    </SpriteMarker>

Using the combination of markers and triggers, I was able to write a simple bit of C# to go with the animation script and spawn small puffs of smoke every time the player’s feet land on the ground during his run animation:

    public void Footstep (string foot) {
        if (Jumping && !JumpLanded)
            return;

        var pos = ResolveMarker(foot);
        if (!pos.HasValue)
            return;
        Game.SpawnSmokePuff(Position + pos.Value - GetDrawOrigin(Animator.Frame), 10, 0.5f);
    }

The real motivation behind the marker system, however, was syncing animations with the game world – I wanted the player’s grappling hook to extend from his hand, have his melee attacks actually sync up with his animation frames, and have his collision detection change realistically while crouched.

Essentially, where before I used hard-coded coordinates and percentages, now I ‘resolve’ one of the player’s named markers. Resolving a marker either returns coordinates (relative to the top left of the frame) or null, which allows me to determine whether a given frame has a particular marker attached to it. Once I have coordinates for a marker, I compute the player’s origin (used for positioning his animation frames) and use that to compute the on-screen or in-world coordinates for the marker, based on the frame-relative coordinate I already have. Given that, I can sync up things like a grappling hook or a potion with the player’s hand:

    public Vector2 GrappleFrom {
        get {
            var handPos = ResolveMarker("Right Hand");
            return Position + handPos.GetValueOrDefault(
                new Vector2(0, Obstruction.Y * -0.5f)
            ) - GetDrawOrigin(Animator.Frame);
        }
    }

After using this technique to make the player’s bounding box change while crouching, I realized that by uncrouching, the player could become stuck in a ceiling. The solution to this ended up being a bit of a hack – before increasing the size of the player’s bounding box, do a quick collision check to see if the player’s current bounding box is able to move upward by that same amount. If the check fails, I now know exactly how far the player’s current bounding box would have been able to move, and I can constrain the growth of the bounding box to avoid making the player become stuck.

Once the player is out of a tight space, I can grow the bounding box to its full height, restoring sanity. It’s not perfect (and looks kind of stupid since it allows the player’s head to stick through ceilings), but it was relatively simple to implement. I suspect I’ll end up with a different solution in the final game – perhaps forcing the player to stay crouched if he can’t stand up in his current position.

During the process of rigging up the player’s animations, I spent a lot of time fine-tuning things and working out issues. To make things move quicker, I ended up adding a couple new features to my engine:

First, I added support for reloading sprites and tiles at runtime. My existing game code already was designed in such a way that this wasn’t too difficult, but I still had to do some work in order to get the rest of the way. One of the biggest changes was that I had to change entities to store a sprite’s Name instead of storing the sprite itself, so that I could replace a given sprite instance at runtime after reloading it from disk. As a result, where before I had:

    this.Sprite.Animations["Walk"].Run(this.SpriteContext);

Now, I have something like this:

    Game.Sprites[this.SpriteName].Animations["Walk"].Run(this.SpriteContext);

A bit more verbose, but easy to abstract out using properties and helper methods – such that actual game code can just use convenience methods, like so:

    this.PlayAnimation("Walk");

And everything happens behind the scenes.

The other change I made was to overhaul my rendering model in order to make it easier to add debugging overlays, user interface graphics, and special effects without having to change the Game’s Draw function. First, I changed the signature of most of my objects’ Draw methods, such that they now take an extra parameter:

    public override void Draw (DrawFlags flags) {

Then, the game code can pass a combination of flags to an object to specify which types of rendering to perform:

    if (ShowHUD) {
        var flags = DrawFlags.HUD | (GlobalDrawFlags & DrawFlags.DebugHUD);
        RenderGeometry(flags);
        RenderEntities(flags);
    }

As a result, I have the ability to easily toggle off sections of an individual object’s painting code, without having to directly hook the logic into the Game object itself. This also nicely simplifies a lot of the code in my editor, since I can now do editor-related painting (like drawing bounding boxes, selection highlights, etc) in the Draw method of the object in question, instead of having to add a special function to the editor that draws those things manually, or having to add an ‘EditorDraw’ method to the objects (like I had before in a few cases, unfortunately).

With the addition of a couple extension methods to simplify things, it wasn’t too hard to wire things up inside my game objects. For example, this is what SpriteEntity.Draw looks like:

    public override void Draw (DrawFlags flags) {
        ...
        var drawPos = GetDrawPosition();
        var origin = GetDrawOrigin(Animator.Frame);

        if (flags.Check(DrawFlags.Entities))
            Draw(drawPos, origin, Scale, Color);

        if (flags.Check(DrawFlags.DebugEntities)) {
            Game.SetupRenderState(true);
            Game.DrawBox(this.Bounds, Color.White);
            Game.CleanupRenderState();
        }

It simply checks for each of the draw flags it knows how to handle, and processes them accordingly, in a given order. This gives me the ability to do multiple draw passes at once, or do them individually if I want finer-grained control over draw order. A good example of this is the HUD pass – I want HUD elements to cover all the objects in the game world, so I draw them in a separate pass. But debugging overlays like entities’ bounding boxes don’t need to cover everything, so I draw them in the same pass as the entities themselves.

For the curious, the extension methods I ended up writing look like this:

    public static bool Check (this DrawFlags drawFlags, DrawFlags flag) {
        return (drawFlags & flag) == flag;
    }

    public static DrawFlags Toggle (this DrawFlags drawFlags, DrawFlags flag) {
        return ((drawFlags ^ DrawFlags.All) & flag) | (drawFlags & (flag ^ DrawFlags.All));
    }

They’re fairly simple, but having them tremendously simplifies the process of working with the DrawFlags enumeration. This is one thing that I wish C# had built-in support for, but it’s at least fairly easy to add with extension methods. Unfortunately, generic types and enums don’t get along, otherwise you could have generic forms of these functions instead of having to write them for each Flags enumeration in your game.

Tags: , , , , , , ,

Scripted animations and saved games

I spent some time this week building a new animation system to replace my old hard-coded player animations. Right now the player doesn’t look any different, but the new system is set up such that I can drop the animation frames my artist is working on directly into my Content folder and see them in action with minor XML changes, instead of having to adjust large parts of the Player class.

One of the main goals I had for the Player class was to separate the presentation-related aspects of the animations (number of frames, size, etc) from the logic-related ones. Previously, both were handled in the same C# function – to handle punching, I had an Animation_Punch function in the Player class that looked something like this:

        protected Anim Animation_Punch () {
            _AttackShape = new DrawablePolygon(
                new Vector2[4]
            );

            using (Finally.Do(() => { ActiveAttack = Attack.None; _AttackShape = null; }))
            using (var a = Animation_OneShot(AnimId_Punch, 40 * Time.MillisecondInTicks))
            while (a.MoveNext() && (ActiveAttack == Attack.Punch)) {
                float x = ObstructionWidth / 2.0f * Facing;
                float y = -ObstructionHeight + ArmTop;
                float w = ((Sprite[Animator.Group][Animator.Frame].Width * ScaleFactor) - ObstructionWidth) / 2.0f * Facing;
                float h = ArmHeight;

                _AttackShape.SetVertex(0, new Vector2(x, y));
                _AttackShape.SetVertex(1, new Vector2(x + w, y));
                _AttackShape.SetVertex(2, new Vector2(x + w, y + h));
                _AttackShape.SetVertex(3, new Vector2(x, y + h));

                yield return a.Current;
            }

            yield return new SetAnimation {
                Animation = (Jumping && !JumpLanded) ? Animation_Jump_Fall() : Animation_Stand()
            };
        }

As you can see, the presentation - Animation_OneShot(AnimId_Punch, 40 * Time.MillisecondInTicks) – and logic are mixed directly together. Also, it has hard-coded coordinates and sizes in it, in order to keep the collision detection in sync with the animation. My goal is to eliminate both such that the Animation_Punch function becomes pure logic and all of the presentation-related data lives in the animation file. The use of an animation file also eliminates annoyances like hard-coded animation IDs, replacing them with filenames.

The equivalent in the new animation file looks like this:

            <SpriteAnimation typeId="1">
                <Name>Punch</Name>
                <Group name="punch" />
                <Frames delay="40" />
                <NativeWrapper name="Animation_Punch" />
            </SpriteAnimation>

As you can see, it expresses the same information, though in some cases it is able to omit things that had to be explicit before. The Animation_Punch function still exists, but has a more clearly defined purpose:

        protected Anim Animation_Punch (Anim inner) {
            using (Finally.Do(() => { ActiveAttack = Attack.None; _AttackShape = null; }))
            using (inner) {
                ActiveAttack = Attack.Punch;
                _AttackShape = new DrawablePolygon(
                    new Vector2[4]
                );

                while (inner.MoveNext()) {
                    var group = (SpriteGroup)Animator.Group;
                    var frame = group[Animator.Frame];
                    float x = ObstructionWidth / 2.0f * Facing;
                    float y = -ObstructionHeight + ArmTop;
                    float w = ((frame.Width * ScaleFactor) - ObstructionWidth) / 2.0f * Facing;
                    float h = ArmHeight;

                    _AttackShape.SetVertex(0, new Vector2(x, y));
                    _AttackShape.SetVertex(1, new Vector2(x + w, y));
                    _AttackShape.SetVertex(2, new Vector2(x + w, y + h));
                    _AttackShape.SetVertex(3, new Vector2(x, y + h));

                    yield return inner.Current;
                }

                if (Jumping && !JumpLanded)
                    PlayAnimation("Jump_Falling");
                else
                    PlayAnimation("Stand");
            }
        }

Oddly enough, the function actually got larger. Future refactorings will enable me to shrink it, but for now, it at least has less presentation mixed in – the actual animation itself is passed in via a parameter (inner), and the function is called as a result of being referenced by the animation file, instead of the other way around. The logic for pulling out the current frame is also abstracted out, which is another small but important improvement.

One of the other requirements for my animation system is the ability to set up simple triggers that cause one animation to switch to another. The way I previously implemented this was by checking the triggers every frame, using a convenience function in my C#:

        protected Anim Animation_Stand () {
            return Animation_PingPong(AnimId_Stand, 50 * Time.MillisecondInTicks)
                .SwitchIf(Animation_Stand_to_Walk, () => Acceleration != 0)
                .SwitchIf(Animation_Grapple, () => Grappling);
        }

Now, the entire animation lives in the file, more or less unchanged:

        <SpriteAnimation typeId="1">
            <Name>Stand</Name>
            <Group name="stand" />
            <Frames delay="50" loop="PingPong" />
            <Branches>
                <Branch name="Stand_to_Walk" if="Acceleration != 0" />
                <Branch name="Grapple" if="Grappling" />
            </Branches>
        </SpriteAnimation>

One detail of note here is that this means I’ve moved the conditions from compiled code (C#) to interpreted code (they’re now handled using the same expression evaluator I already use for configuring levels). This has a performance impact, but is worth it since it means I’m free to reload animations without having to recompile the game – particularly important if I’m trying to quickly fine-tune animations, since it cuts out the entire ‘Save, Exit, Compile, Start, Load’ cycle.

Thanks to the fact that my animations were already represented as composited iterators (take an iterator that represents an animation, and then layer another iterator atop it that will play a second animation when the first one completes – and so on), the core animation code didn’t have to change at all, which was a big time saver – when I switched from the old C# animations to the new file-based ones, the animations all looked the same, so I didn’t have to spend any time hunting down minor differences.

One other advantage to this approach is that it’s now a reasonable idea for me to let my artist make changes to the game’s animations, instead of doing it all myself. Even fairly complex animations are understandable:

        <SpriteAnimation typeId="1">
            <Name>Jump_Falling</Name>
            <Group name="jump_fall" />
            <Frames delay="70" first="-2" last="-1" loop="Repeat" />
            <Branches>
                <Branch name="Jump_to_Walk" if="(Running) and (!Jumping)" />
                <Branch name="Jump_to_Stand" if="(!Jumping)" />
                <Branch name="Grapple" if="Grappling" />
            </Branches>
        </SpriteAnimation>

As long as you understand XML, most of it is fairly easy to interpret. The equivalent C# would have been much harder to understand, and easier to break if my artist had to edit it to make changes.

The next thing I did was spend some time getting saved games working properly again. The addition of two-character support broke some parts of my saved game implementation, and it seemed like it was about time to fix them. The core problem ended up being larger than I expected – properly loading a saved game without a lot of hacks meant that I had to rethink the way I structured some of my game code.

Originally, objects like entities and geometry had both design-time and run-time representations. For entities, these were the LevelEntity and Entity objects. You constructed a LevelEntity with basic configuration information on the entity, and then added it to a Level. At runtime, the game would load the Level, and construct a RuntimeLevel object from it. Every LevelEntity would become a corresponding Entity in the RuntimeLevel. The core problem here was that constructing an Entity took a reference to the Game object, not to the Level or RuntimeLevel. So if I wanted to construct a new version of an entity (like a monster, or a player), I had no way to tell it which Level to use – it had to guess.

The first step I took was to rename Entity to RuntimeEntity, because it was getting pretty confusing. :) After that, I bit the bullet and changed everything such that constructing a RuntimeEntity required a RuntimeLevel instead of a Game. This meant I had to shuffle lots of things around, and update some code, but in the end, the payoff was worth it – now, I could load a new level from disk, construct all the entities and geometry, and swap it in for the current level, without any glitches. This was an important requirement for being able to undo actions like destroying walls, killing monsters, etc when the player loaded a saved game.

This change also helps kill off some technical debt I’d accrued in the design – lots of code in various places was jumping through ridiculous hoops, doing things like this.Player.Game.RuntimeLevel.Level.Entities[...]… in order to get at objects, so I clearly needed to rethink my dependencies.

One of my next goals is to add a way to place named ‘markers’ inside my animations, so that the game logic can reference locations like the player’s left hand without having to do arithmetic every frame. Getting that working will go a long way towards shrinking the size of functions like Animation_Punch and allow me to add more detailed animations for things like footsteps and attacks.

Tags: , , , , ,

Throwing potions III

Most of my work this week focused around getting the stone potion working.

One of the first things I had to do was split some of my existing Entity code out into smaller pieces. All the entities I’d written previously were sprites, but the stone potion spawns geometric shapes. I ended up pulling the sprite-related code out into a SpriteEntity class, derived from Entity, so that I could customize entity rendering behavior without having to duplicate the code for mantling, collision detection, etc.

Once that was done, I was able to spawn stone outcroppings at the point of impact of a stone potion, based on the surrounding geometry. The player could walk across them and destroy them. This quickly revealed that there were some issues with my algorithm for walking on surfaces: previously, all the surfaces in the game were simple geometric shapes – rectangles, triangles, circles. The stone outcroppings are irregular surfaces, which meant that some of the assumptions I made previously no longer hold.

Previously, to determine where on a surface the player should stand, I checked the left and right edges of the player along with his center. In order to account for irregular surfaces, I now have to scan across the entire width of the player in small increments to account for variations in height. It’s a slight performance hit, but it ensures that the player can walk smoothly over irregular surfaces cobbled together from multiple stones.

I also discovered that I’d made a mistake when implementing my damage effect code – the code in the XNA framework for maintaining a smooth framerate introduced timing inconsistencies between frames, such that the points where I sampled a damage effect’s curve didn’t match the points I sampled initially when computing the total damage (as described in the previous post). The result was that sometimes a potion would do more or less damage depending on the timing of its impact and the game’s current framerate. The solution to this was to maintain an internal clock for each damage effect so that I could walk along the curve at the same points in time.

The next thing I noticed was that the player had difficulty grabbing onto stone outcroppings and mantling up onto them. It turned out that there were two problems there:

The first problem was that the algorithm for finding a point to mantle onto assumed square surfaces. As a result, the uneven, rounded shape of the stone outcroppings caused it to sometimes select points below or above the surface of the stone. I rewrote the algorithm to work in two stages: First, sweep upward to find an obstruction, starting at the player’s feet, and then sweep upward further to find the end of the obstruction and a new place for the player’s feet to occupy.

Tags: , , ,

Concurrency and generics

Most of my work this week was on making some improvements to some of my libraries. I did some work on the game too, but nothing worth writing about. :)

The main change I made was to one of the core classes I use for concurrency: Future. The future class is a container that can store a single value, and can only be written to once. You can attach one or more listeners to it that will get invoked once it has a value. The primary advantage of using this class is that it lets you easily perform asynchronous operations without having to deal with locking and most types of race conditions, due to the fact that it’s write-once.

Having a type like Future is extremely useful when dealing with things like disk IO or network operations. But it also turns out to be useful in games – you can use Futures to represent long-lived operations like getting a user’s selection from a menu, finding a path through a level, or loading a texture from disk. Future is also the foundation of the Task primitive in my cooperative multithreading library.

The original interface for the Future class didn’t make use of .NET generics. This meant that it was easy to write general code atop futures – you could write a simple function that would take a list of futures as inputs and return a single future as a result that would become completed once all the inputs were completed, for example. The downside is that you basically didn’t get any type safety, and values were always boxed – a future that contained an integer had to store it as an object, and any time you wanted to retrieve a value from a future, you had to cast it.

This week I decided to try and refactor my code such that Future could utilize .NET generics but still be usable with simple utility functions.

The solution was to create a baseline interface that all Futures implement, and write all the utility functions and libraries using that baseline interface, but expose fully typed generic Futures as return values from functions. Here’s a before and after example:

        public static Future WaitForAll (params Future[] futures) {
            return WaitForX(futures, 1);
        }

        public static Future RunInThread (Func<object> workItem) {
            var thunk = new FuncRunInThreadThunk {
                WorkItem = workItem,
            };
            ThreadPool.QueueUserWorkItem(FutureHelpers.RunInThreadHelper, thunk);
            return thunk.Future;
        }

As you can see, the original code lacks type information, so you have to infer it from usage and do casting everywhere. The upside is that it’s general, but you end up paying for it when you make mistakes about types and have to add explicit casts everywhere.

        public static IFuture WaitForAll (params IFuture[] futures) {
            return WaitForX(futures, 1);
        }

        public static Future<U> RunInThread<U> (Func<U> workItem) {
            var thunk = new FuncRunInThreadThunk<U> {
                WorkItem = workItem,
            };
            ThreadPool.QueueUserWorkItem(FutureHelpers.RunInThreadHelper, thunk);
            return thunk.Future;
        }

In the refactored code, the type information is preserved when going through a utility function like RunInThread – if the function being run in a thread returns a float, the resulting future will also contain a float. This eliminates casting but still preserves generality – since a Future<float> implements IFuture just like a Future<int>, you can use that underlying type when writing utility functions, like WaitForAll (though one downside is that WaitForAll is forced to return an IFuture instead of a future of a specific type, since there’s no easy way to guarantee that all the futures are of a given type.)

Performing this refactoring took lots of individual steps – first, I had to change various code to use IFuture instead of Future, and make minor tweaks in order to keep things functioning and keep tests passing. In some cases I still needed to use Future (one obvious example – you can’t construct an interface, so in that case the real type needed to be used). The largest chunk of work there was updating the handlers for futures – previously, a future listener looked like this:

var handler = (OnComplete) (future, result, error) => { Console.WriteLine("Future {0} completed with result {1}/error {2}", future, result, error); };

The three arguments were mostly an artifact from previous refactorings – originally the Future argument wasn’t there at all. The existence of the result argument was a problem, because it had to be the same type as the future – a Future<float> needed an OnComplete listener that took a float result, which made it difficult to construct generic listeners.

In order to make things simpler, I removed the result and error parameters. Including the future still made it possible to get at the result and error, but allowed the listener to be general by accepting an IFuture instead of a strictly-typed Future<T>. This was important for being able to wire futures up to each other (The WaitForAll function is a good example of this, in that it connects multiple futures to a single result future.)

Once I had updated all the existing listener code, the final step was to add a type argument to Future, and add type information to various library functions.

Here’s an example of the results – if you were writing a Task to do asynchronous reads from a socket or a file, one line at a time, the code to do the read might look like this:

Future f = input.ReadLine();
yield return f;
string line = (f.Result as string);

The ReadLine method of the input stream returns a Future, which will be completed with a string when a line has been successfully read from the stream. The Task yields on the Future to suspend execution until it’s been completed with a result. Once it’s completed, execution resumes, and we pull the resulting line out of the future. It’s obvious that there are some problems with this approach. With the new generic type, the cast is eliminated and ReadLine has a clear return type:

Future<string> f = input.ReadLine();
yield return f;
string line = f.Result;

And if you put C# 3.0′s language features to work, the end result is almost free of duplication:

var f = input.ReadLine();
yield return f;
var line = f.Result;

This is one example where having bidirectional iterators (like in Python) would be beneficial. Python’s yield expression has a result, so you can ‘send’ an input into an iterator every time you advance it. As a result, this code written using a library like imvu.task would look like so:

line = yield input.readLine()

The advantage is pretty obvious – the entire operation is in one line and the meaning is more clear.

Still, this solution is pretty good for C#. You get most of the advantages you could want: Simple code, type safety, thread safety, rock-solid error handling, and scalability. (One of the advantages of using the Future type is that it ensures that you always get either a result or an error. This means that any code that uses a Future to retrieve a result will have exceptions rethrown when an asynchronous operation fails – no need to manage error flags and add lots of try/catch blocks.)

While doing all this refactoring, my large set of unit tests came in handy – they caught a number of bugs I introduced early, and revealed an existing bug that was months old. As a result, I ended up with better error handling, better type safety, and a more robust set of unit tests. On the other hand, I still don’t have any unit tests for my platformer, so maybe I should take another shot at figuring out how to write some for it. (:

If you’re interested in seeing how Future and Task work, you can see the source code and some working examples here:

http://code.google.com/p/fracture/source/browse/#svn/trunk/Squared/TaskLib

I encourage you to check out the repository and try the MUD Server and Telnet Chat examples. They’re not real-world applications, but they’re easy to understand and demonstrate how using Futures and Tasks simplifies concurrency. The MUD even has gameplay! :)

Tags: , ,