Skip to content

Archive

Category: Game Programming

Earlier, I described how to integrate Blender 2.4x assets with XCode build rules. Let’s jump into the present and do the same with Blender 2.6x.

Fundamentally, the solution is the same (see here). I added a new build rule with the described parameters:

Matching rule

*2.5x/assets/*.blend

So, all 2.5x / 2.6x files go under a ###/2.5x/### folder (depending on the file version, I run either Blender 2.49b or Blender 2.6x ). This rule matches a fragment of the path, so it will still work with multiple projects, e.g. :

  • …/foobar/2.5x/assets/foo.blend,
  • …/superfungame/2.5x/assets/funasset.blend
  • (…)

Script invocation

/Applications/blender-2.6x/blender.app/Contents/MacOS/blender -b “${INPUT_FILE_PATH}” -P /Users/xxx/svn/blender-scripts/ox3ich/ox3ich_main.py — “$INPUT_FILE_DIR/../../build/$INPUT_FILE_BASE.blz”

ox3ich_main.py is the script used to export assets, so maybe you’ll invoke a COLLADA export script or such.

Output:

${INPUT_FILE_DIR}/../../build/${INPUT_FILE_BASE}.blz

This just matches the output (in script invocation, specified after “–”, note this is a custom script rule, Blender lets you pass custom parameters after “–” )

Caveats

While testing remember XCode may not re-run the script unless the input file has changed (even if the previous invocation failed).

Blender 2.5x/2.6x has a somewhat complex script registration mechanism. When integrating with XCode, however, what tends to happen is… …nothing. So typically you have a script FOO.py, which is designed to run as a registered blender script; then you should pass a bootstrap script BAR.py to drive FOO when running Blender from cd. This is more or less what I did.

One more thought on this is that, all considered, if the main use of your script is exporting via cd, you don’t need to learn about script registration, you just write your export script and feed it to Blender via the command line.

Note: With a little trickery you can write scripts that will run on both blender 2.5x and 2.63 and later; I’ll cover the changes later. Or you can read the NGons and tesselated faces gotcha (from blender.org).

Since we’re already using blender as a level editor, I got a little curious about BGE and decided to check it out.

What is it?

The blender game engine (BGE) is part of Blender, it allows creating games using Blender. Games can run as standalone executables on a PC or Mac. I think there may be a plugin to run this in browsers as well.

I’m not sure whether there is an iOS compatible engine that supports BGE or not. You could look into SiO2 or GameKit.
If you made your own engine (whether 2D or 3D), exporting BGE graphs should be a big piece of cake (somewhat time consuming, but not difficult).

How it works

You can read the comprehensive introduction (see older links, below), I’m not very used to (this approach to) visual programming so this is how I explained it to myself.

The blender game engine uses sensors, controllers and actuators. Soberly, this is an event driven architecture. For each object you define trigger conditions causing events to be generated, then link the conditions to scripts affecting the stage of game objects.

  • sensor: sensors generate events, for example dedicated sensors detect keyboard or collision events.
  • actuator: actuators change the state of the world, for example make an object move or play an animation.
  • controller: read on.
In Blender’s logic editor, each object has a tab for sensors, actuators and controllers, so BGE is also object oriented. In practice we attach behavior to a game object by creating a graph, so a basic linked graph will look like this in the blender UI:
.
[sensor] => [controller] => [actuator]
example:
[right arrow key] => [AND] => [motion actuator]  
.
So we could make a game actor move to the right by linking a keyboard sensor (right arrow key) to a motion actuator, right? So what’s this AND controller in the middle?
Controllers provide a way to integrate inputs from several sensors. For example if we have sensors A and B and we want actuator X to apply only when both A and B are firing, we can use a simple AND controller. Yes, basic controllers are ‘logic gates’. Naturally this scales up – you can write your own logic expressions, or use scripts if you need more elbow room.

Links

2.5x/2.6x

  • Tutorials (Blender Noob To Pro on wikibooks – search ‘Game engine’)
  • Where to start BGE Python (blenderArtists.org)
  • 2.6x API docs
  • 2.6x GameObjectSettings  - These APIs aren’t used to access game objects while a BGE game is running, instead they can be used to inspect/modify game properties (including actuators/sensors/controllers).
    Blender 2.5x and later stores this under an object’s game property; 2.6x added APIs to inspect linkages between sensors, controllers and actuators.
    Situations where this gets useful:
    • You want to setup game objects programmatically
    • You want to export logic bricks using a py script.

Older links (but still useful to understand how stuff works)

In this post I summarize four principles of real-time interaction. Shoot.

1. State Driven Control

Event driven control is inductive – it relies on assumptions about the state of the world. Unfortunately, as often as not, these assumptions are incorrect.

State Driven Control is deductive – it relies on evaluating the current state of the world before deciding how an entity should be updated.

2. Conflictual Ownership

By default, game objects tend to be modeled as commons. This, quite naturally, leads to the disaster of commons.

Ownership: an interaction cannot take control of a resource without acquiring this resource.

Conflictual: explicit resource conflicts. By default, fail fast. Whenever necessary, define resolution clauses.

3. The Rule of Return

Never register any callback that may never return. Conversely (and more usefully), do not provide registration methods unless you can warrant that the associate callback will fire. At runtime, validate the callback by asserting return conditions.

4. Pedantic Command

In debug mode, do not allow overly concise control – to the contrary, require control to be somewhat declarative as it allows asserting its integrity. Three examples may illuminate this idea:

Compare this…

  • glPush() / glPop() - unsafe
  • [foo retain] / [foo release] – unsafe
  • startAnimation(“dodge”) / stopAnimation() - unsafe
…with:
  • glPush(myToken) / glEnd(myToken) - safe
  • [foo retain:fromBar] / [foo release:fromBar] - safe
    (but avoid back references using hash values)
  • startAnimation(“dodge”) / stopAnimation(“dodge”) - safe

Timeout

I’m not especially in the mood to elaborate on this today; questions, however, are not unwelcome.

Just collected a few useful resources. I was mainly looking for explanations and sample code about matrix calculus:

When the motion of game actors is driven by a physics engine, we need a reliable method to control their motion. A governor uses negative feedback to adjust forces given a target velocity.

Principle

When a body of mass M is at rest, applying a force F will result in a speed S = F / m.

This formula can be used to write a simple governor – given the current velocity V0 and a target velocity V1, we have:

F = ( V1 – V0 ) * M

Units:

  • F – force applied (Newtons)
  • V1, V0 – velocity (meters per second)
  • M – mass (kilograms)

Given the above we can write a very simple function that will calculate the force F required to update the velocity of an actor at every frame.

It may be working better than you’d expect – notably, given motion conservation, even a trivial governor (based on the above principle) will quickly achieve target velocity.

Scaling the output

The above formula can be modified by introducing a scale parameter:

F = ( V1 – V0 ) * M * S

The scale parameter may have uses – for example you can use it to increase the governor’s output when friction/air resistance become significant.

Note that scaling the output in this way may break time invariance – the simulation will behave somewhat differently depending on the size of time steps.

Implementation notes

Impulses vs continuous forces

A simple way to implement the above consists in delivering the governor’s output as impulses. An impulse is a discrete force applied to a physical body. A priori it may appear that continuous forces would be a better choice. However, depending on the way continuous forces are implemented by the physics engine, an impulse governor may be preferable:

  • When applying a continuous force, the force is usually given in newtons per second. Therefore additional calculations are needed to precisely determine the total force delivered by the governor.
  • With impulses applied at every frame, the ‘stop and start’ effect that one should expect is not visible.
Beware that using impulses doesn’t mean that we can fully ignore the size of time steps (see ‘scaling the output’, above).
Ground units
When driving the motion of ground units, there are many situations where the slope of the terrain isn’t known a priori. So the primary input to the governor is a velocity vector parallel to the horizontal plane.
However, applying horizontal forces to a ground unit may cause artifacts.
Why should we expect artifacts? The governor adjusts velocity towards a specified target – so if the terrain has a slope, velocity includes a vertical component. Unless this vertical component is included into the target velocity, the governor will ‘resist’ climbing and falling.
For a ground unit, it is meaningful to disable the governor’s output when a ground unit is airborne.

Issues

Sharp changes in orientation

In some games, sharp changes in orientation are not a problem, especially when the actor need to be responsive (e.g. controlled by the player). For large actors and some other games however, sharp changes in orientation look ugly. A low value for S ( ~0.1 or less ) will reduce artifacts but this solution is not ideal.

A simple way to solve this problem is to interpolate between the current orientation and the target velocity before passing the target velocity to the governor.

Note: I removed the ‘motion aliasing’ section referred here previously; the artifacts I observed in my simulations were not related to the governor itself.

Going further: adaptive governors

Compared to the solution described above an adaptive governor can handle various situations by automatically correcting the scale factor S. This is done by measuring the bias between the expected output (target velocity at frame t0) and the actual output (real velocity at frame t1 = t0+1).

It is wiser to start with a simple governor - whether adaptive or not, the governor needs to be initialized with a base value for S; additionally when encountering obstructions, adaptive governors tend to ‘overheat’ – increasing S to a very high value. While it is possible to clamp the scale factor to a specific range, this is probably just the first in a series of adjustments – adaptive governors are smarter, they are also harder to design.

This post is password protected. To view it please enter your password below:


Don’t retain anything unless you must

Regarding reference counting, this is the idea I’d like a developer to at least consider. For several reasons.

  • A dangling pointer / weak reference needn’t be evil. During development hitting a dangling pointer is better than preventing an object to deallocate when it should. An object that exceeds it’s intended lifetime can behave in undesirable, unpredictable ways. All it takes to detect an invalid object is turning NSZombieEnabled on.
  • Everything retained needs to be released. Retain less = less work.
  • If the sums don’t add up (over-released/over-retained object) it’s easier to work out what’s wrong when the number of objects involved is small (e.g. 1, 2 or 3)
  • Potentially any object that retains a target will increase the target’s lifetime; this a priori translates into increased memory usage.
  • Whenever retaining an object we risk creating a cyclic reference. Of course ‘we know what we’re doing’ (and cyclic dependencies can be removed) but isn’t it just easier to avoid getting too many of these.

Unwanted objects that remain inside the runtime after they should have deallocated will harm you. The more your system is dynamic (e.g. game, simulation) the more these objects are likely to generate functional bugs that are hard to figure.

I read a little about automated reference counting (ARC) which we are getting in iOS5. If I understand correctly (reading here) the central idea of this article will translate to ‘don’t abuse strong references’. Now that I more or less get it I look forward to using ARC but I guess I’ll be waiting for another 6 months or so, being a happy laggard.

A quick introduction

Reference counting approaches memory management indirectly, using concurrent ownership:

  • Take ownership of an object by retaining it
  • Relinquish ownership by releasing the object.
  • When all owners of an object have released it, the object is deallocated.

indirect : we don’t explicitly deallocate the object.
concurrent: several objects can simultaneously retain the same target.

The basic rules are covered in many places, like here and here and from the horse’s mouth, here.

Reference counting is efficient, error prone and occasionally awkward.

More efficient than garbage collection: objects get deallocated as soon as their reference count reaches zero, whereas GC is heuristic and may cause your program to slow down unexpectedly while it’s doing its thing.

Error prone – programmers need to pair release/retain statements (either directly or indirectly). Mismatched statements cause a program to leak or crash. Additionally reference counting is hackable; it is easy to traffic the sums (either accidentally or by design) and obtain a valid program that handles memory correctly, while violating reference counting rules.

Awkward, notably when we know beforehand that we would like to deallocate a well defined subset of the runtime graph. A typical example is when you start a kind of ‘session’, allocate any number of objects in the course of the session and wish to deallocate all the objects at the end of the session. In such cases opting out may be somewhat short sighted yet remains attractive.

A design idea

There is a principle which I find rather productive: instead of thinking about whether an object should retain X or not, consider X then try to think about an object ‘up the runtime graph’ that should own X. Often there is an object Y such that, if Y deallocates, X should also deallocate. It could be the parent of X or maybe another object up the chain.

Now, if there is only one such object Y, then you don’t need to retain X anywhere else. You can even assert the retain count to ensure that X is unambiguously managed by Y.

Anti-patterns?

There are little recipes around (e.g. here and here) that you can use to ‘ease the pain of memory management’.  From the point of ownership these recipes work the same way GC does: easy way out of memory management issues, hard into functional bugs with all the enticing prospects of a muddle-through approach.

One point these approaches have in common is ‘if in doubt, retain’. I’m OK with that as long as I know (beyond reasonable doubt) that keeping the target alive won’t generate unwanted behavior. If the target is an observer that receives and processes notifications… …then if in doubt, don’t retain. A clean, happy crash will provide the decision point where you can say:

  • ‘Yea, this object should still be alive at this point’ (in which case maybe something else should have retained it) or…
  • ‘No, this object is dead and well dead, we should have sent a death note’

Additionally these approaches look incomplete. You need to use class extensions if you want to declare everything as a property without exposing all your ivars.

Weak references

An unretained field is a ‘weak reference’. At least in a first approach, the use of weak references is encouraged in a number of situations:

  • Backward references from a child to a parent
  • Listener sets. See a straightforward application here.
  • Same type objects cross-referencing each other.
  • Any situation where you feel unsure whether to claim ownership (retain) or not.

Implementation details

Maybe for historical reasons there are two approaches to enforcing reference counting in objective C:

  • The non intrusive approach revolves around tagging using properties and indirect access using self.x = . Although this approach looks theoretically better and safer there are practical details of how it is done in Objective C which I often find off-putting. For one I like to not declare properties until I want to expose public state, and I’m not used to class extensions, thus find myself unwilling to add class extensions to my .m files.
  • An older approach revolves around the [release] and [retain] statements. The advantage (easier reviewing/debugging) and inconvenience (intrusive approach leading to somewhat cluttered code) are the explicit way in which things are done. This leads to a weird situation because it makes it more likely that bugs are introduced while making the same bugs easier to fix.

Note about [autorelease]

[autorelease] is very convenient and helps avoid errors in many situations. Sadly enough when an error does occur and [autorelease] is the lucky guy that causes a target to deallocate, we get very little debugging information because [autorelease] doesn’t take effect until we exit the frame.

So I try to limit its usage to where it’s unavoidable.

What is covered elsewhere (or should be)

  • Cocoa collections (NSArray, NSSet, NSDictionary) retain all their elements. This can be a hindrance in some cases, but you can configure the underlying, toll-free bridged counterparts, as demonstrated here.
  • There are various approaches to notifying stakeholders when an object gets deallocated. I will try to write a quick article about an approach I find useful when implementing observer schemes.

What a great title. I’m having issues fixing up a physical model for my game character. Since this has been dragging on for a while I decided to review the situation.

The problem given

Game character:

  • Walk, run, jump
  • Can get hit by heavy projectiles (when hit, we want a ‘physical reaction’)
  • Can fall

The terrain:

  • Arbitrary shape including slopes (in the worst case scenario, modeled as a mesh)
  • Walls and other obstructions
  • steps – probably not staircases but a variety of things that look like steps, including non static models (e.g. planks)

Animation system:

  • Traditional animation cycles (no physics in here)

What I’ve done

I tried two distinct physical models

  • Capsule. A single capsule is used to represent the actor
  • Balls. One ball is used to represent the actor’s feet, another represents the head.

I have also written a servo to control walking and running. A ballistic simulation (running in a sandbox) is used to prepare jumps.

What doesn’t work, or doesn’t work well

A ground ball isn’t great

Up to a point, rolling a ball on the ground (aka ‘ground ball’) to represent walking is OK, and I can also add impulses to make it jump. But this isn’t perfect:

  • If we really let the ball roll, we can’t attach anything to it. This means that we need a constraint to maintain the relative position of the feet with another ball representing the head/upper body.
  • If the character is thin, the feet can’t skip stairs or climb over obstacles unless we add a vertical impulse. Or we have to make the ground ball larger.
  • Balls don’t respond very well to friction. This means that the actor tend to drift especially when stopping on inclined surfaces.

Capsules aren’t perfect

Using a capsule brings a different set of problems:

  • In my previous tests I’ve seen a kind of stop and start effect which is probably the result of sliding the capsule on the ground using my servo. This might be because friction plays a very different part when sliding versus rolling.
  • I can’t really lock the capsule’s rotation. locking a body’s rotation is a one liner which makes sense in some cases. Let’s take a simple case where it doesn’t work: I have a heavy block falling on a game actor – then locking the capsule’s rotation is plain wrong.

Common issues

Handling climbing gracefully is a chore. So far I found it difficult to tune my servo to get seamless climbing – in other words, slope transitions generate a kind of noise while the servo is adjusting.

Sudden altitude changes (e.g climbing on top of a plank) are also difficult to handle correctly. If the servo is too loose, velocity tends to get out of control. If the servo is too tight the actor will stop, or even backtrack a little when an obstacle is encountered.

All the above problems are made more visible (a) by the use of a traditional animation system and (b) by the fact that I’m animating a human character. Human (or animals for all that matters) negotiate obstacles with grace and can adjust their motor functions in a smart way.

I’m reluctant to use a rag-doll (actually model limbs and joints). In theory it’s the best solution. In practice it might bring enough problems to keep me busy for a month (or three?)

Then… what?

Here’s my guess:

  1. Use a capsule (or even a box). Using a ground ball doesn’t solve half of my problems and forces a clumsy model for the upper body.
  2. Add a soft constraint to maintain posture (in other words, ‘lock rotation’ ). The constraint should do ‘enough of a decent job’ that the actor won’t tilt more than 5-10 degrees while walking or running. When a heavy object hit the actor the constraint should saturate, and we also want to adjust the same constraint dynamically (e.g, when an actor is KO or badly stunned they can’t stand, so we relax the constraint)
  3. Test the feet’s line of sight (eyes in your toes?) to detect obstacles. We’d rather never do that because it’s expensive but we don’t need to do it at every frame ‘just sometimes’.
  4. Consider using fixed settings instead of a servo (or write a better servo) to handle slopes and other continuous changes.

Alternatively, I could try using a very simple rag-doll (e.g 3 to 5 bodies for the legs and trunk). But most problems will remain integer and even a simple rag-doll may be a lot more work.

[to be continued]

This article is somewhat personal… It illustrates the kind of problem you might run into if you try to enforce integer separation ‘between view and model’. In this case, ‘integer separation’ means that I can run my game without popping an Open GL rendering surface or a UI. Getting this to work has been some work. Getting to work without it being in the way of even the simplest things may require more work.

Yesterday I added basic support for playing image sequences to my StageComponent. StageComponent seemed a good choice because it is a high level controller owning the stage (model), the stage view (3D canvas) and the stage UI.

Cut scenes are often triggered by simple events – defeating an enemy, entering a new area. So it made sense to call my stage component from a trigger handler. I unexpectedly bumped into an idiotic problem: according to the framework *I* wrote, I’m not supposed to call StageComponent from game code (at least, not directly). Heck, why is that and what am I supposed to do about it?

So I dug a little and run into my StageManager. StageManager is readily accessible to game code. It doesn’t know about the stage component or the UI, and the intent became clear: to run my game without graphics (for test), I’m hiding dependencies on OpenGL and the UI toolkit.

Now I also remember another design goal: hot switching. The idea of that is to allow seamlessly switching the scene or the UI without breaking behavior.

Looks nice, but it can’t be really nice if it makes me feel like a pedantic ass when I’m just trying to play a slideshow.

A route

A found a way to call the stage component, however the result isn’t very satisfying. It looks like this:

  • StageManager playCutScene:(tag)name
    • <UADelegate> playCutScene:(tag)name
      TestUADelegate playCutScene:(tag)name (skip the cut scene)
      VisualUADelegate playCutScene:(tag)name (call StageComponent)

      • StageComponent playCutScene:(tag)name

Maybe you can see where this is coming from:

  • StageManager may be more adequately named ‘GameSessionManager’. It is a top level game controller that gives indirect access to the game UI.
  • User Agent (UA) delegates are classes that can either emulate or wrap the game UI.
  • The stage component looks like an MVC controller. When running without graphics, I still instantiate a stage (typically from a data file) but I don’t instantiate a stage component.

So why is it bad (setting pedantry aside)?

Part of the problem is simply that I’m not used working this way.

Another part of the problem is that I couldn’t find a route to bridge these classes using game code. All the above classes are framework level.

Finally, I think part of the problem is that visual and non visual agents are defined as an alternative. This disposition looks fragile. I’m guessing a more durable disposition would be to have all interactions processed by a non visual agent, and have visual agents (the UI) call into that.

This post is password protected. To view it please enter your password below: