Sunday, May 26, 2013

Component Entity System

When I started my current project, I was in much of a "hardcode things" mindset. I imagined that the project would be relatively small, so it wouldn't be too bad to write a C++ class for each object in the game. I started out with a fairly standard object-oriented approach. I had Actors, which were general purpose objects that were updated once per frame. Derived from that, I had GameActors, which had a few extra features, such as being able to access the game's state more easily. From that was derived NetworkActor (which, as the name implies, was an actor synced on the network). DynamicPhysicsActor was derived from that, and then came more more specific classes, such as Player, Enemy (from which things like BatEnemy would be derived), etc.

Like many others, as I tried to maintain this system, I discovered that even with just a few actor types, it very quickly started to become messy, unmanageable, and worst of all, restrictive. For example, what if I wanted an enemy that didn't have a standard physical component? I shouldn't derive it from Enemy, since Enemy derives from DynamicPhysicsActor! I'd have to derive it from NetworkActor and rewrite the base Enemy code. Or maybe I'd make an option to disable physics in DynamicPhysicsActor, but that's equally nasty. What if I wanted to use a different networking model for an object? NetworkActor is up pretty high in the hierarchy, so in order to not use it I'd have to make a completely new hierarchy.

In addition to these issues, I was getting tired of hardcoding resource names into my classes and having to update a ton of references every time I added or changed a resource. Clearly I needed an alternative to the mess that I had coded myself into.
It was at this point that I remembered the "component-entity-system" design pattern. I started doing some research and realized that this design would be much better suited to my requirements. There isn't any one "right way" to implement a component-entity-system design, so I made a list of features I wanted and designed the system to fit. These features include:

  • No hardcoding entities in C++: entities should be loaded from a file at startup, and each entity consists of a list of components (components are "hardcoded" in the engine).
  • Dynamically adding/removing components from entities is not required.
  • Components should be able to communicate in some "generic" way. E.g. a PositionComponent and a DynamicPhysicsComponent should both be able to provide a Vector3 position value.

I'll now describe the solution I came up with to meet these requirements.

Components:

Each component consists of a C++ class derived from the Component base class. Unlike many implementations, logic is implemented in the components themselves, as opposed to just storing data. Each class derived from Component must contain the following:

  • A nested class called Settings, which has a constructor that reads the settings for a component from part of a file.
  • A static method getDescription() which returns a ComponentDescription, described below.

At startup, all components are registered with the ComponentEntityManager class. This is done using a templated method registerComponent <T>(). This component calls the getDescription() method on T to obtain a ComponentDescription containing the following:

  • A string representing the name of the component
  • The size/alignment requrements of the component
  • A list of message handlers for the component, described below (side note: actually two lists, one for the client and one for the server)
  • The network state table variables for the component. I won't go into detail about this here, but I've implemented a system similar to Valve's.
  • A few more "thunky" functions for constructing and destroying the component

Message Handlers:

Components communicate using a messaging system. Messages are sent to entities and are forwarded to a message handler for each interested component. The message handler should return a bool value: true indicates that the message has been "consumed" and should not be forwarded to the remaining components. Messages consist of structures of the following form:

 struct SomeMessage {
static const uint ID = 100;
int pieceOfData;
float moreData;
};

Note the ID field: each message type must have a unique value. Each component of type T registers a number of message handlers. A message handler consists of an integer "priority", used to determine the order in which components receive a message, and a function pointer to handle the message, of the form: bool T::someMessageHandler( SomeMessage * message )

Using the power of templates, when registering message handlers, all we need to do is provide a pointer to the message handling function and the message ID value will be determined from the message type argument in the handler. This means we never have to deal with the IDs once we've declared them, just the message types. Message handlers are encapsulated using the following implementation (which uses boost and fastdelegate):

 struct MessageHandlerDescription {
uint messageId;
int priority;
fastdelegate::FastDelegate2 <Component*, void*, bool> handler;
// slightly ugly - space for the member function pointer to the message handler
char handlerPointer[16];

// another option that would simplify this would be to convert the "handler" argument to a template argument
// unfortunately, the downside is that ComponentType and MessageType can't be deduced that way
template <typename ComponentType, typename MessageType>
ComponentDescription::MessageHandlerDescription ComponentDescription::MessageHandlerDescription::create( bool (ComponentType::*handler)( MessageType* ), int priority ) {
BOOST_STATIC_ASSERT( (boost::is_base_of <Component, ComponentType>::value) );

// thunk to call the message handler
struct Thunk {
// pointerToHandlerPointer is a pointer to a buffer containing the handler function pointer
static bool thunk( Component * ptr, void * pointerToHandlerPointer, void * message ) {
// cast pointer to correct type
ComponentType * tPtr = (ComponentType*)ptr;
// cast handler function pointer to correct type
typedef bool (ComponentType::*THandler)( MessageType* );
THandler tHandler = *((THandler*)pointerToHandlerPointer);
return (tPtr->*tHandler)( (MessageType*)message );
}
};

MessageHandlerDescription desc;
desc.messageId = MessageType::ID;
desc.priority = priority;
desc.handler = &Thunk::thunk;
// copy the handler function pointer to the buffer
BOOST_STATIC_ASSERT( sizeof( handler ) <= sizeof( desc.handlerPointer ) );
memset( desc.handlerPointer, 0, sizeof( desc.handlerPointer ) );
memcpy( desc.handlerPointer, &handler, sizeof( handler ) );
return desc;
}
}

Entities:

Finally, we have entities, which bring order to the components and message handlers. Entities are loaded from the entity description file, entities.txt. Each entity type E provides a list of components, and each component C listed contains a list of settings. This is where the Component::Settings object receives its data from. So each instance of C within entities of type E gets those settings applied.

Since entities contain only a static list of components, we can do a lot of preprocessing when first loading the entities file. Similar to components, we store this preprocessed data in the EntityDescription struct. Components are constructed in-place in an array for each entity, so we determine the layout of each component within that array using using the size and alignment data determined in ComponentDescription.

Each component contains a hash table mapping message IDs to a list of component message handlers sorted by the message handler priorities previously provided. This means that when sending a message to an entity, we only need to forward that message to the list of components that actually care about it. Message handlers are where the component logic lies. For example, there are PreUpdate and PostUpdate messages which are sent to all entities each frame.

The implementation for receiveMessage() is once again templated to avoid explicit use of message IDs and is as follows:

 template <typename M> bool Entity::receiveMessage( M * message ) {
// check if there are handler(s) registered
EntityDescription::MessageHandlerList list;
if (entityDescription.messageHandlerMap.get( messageId, list )) {
// pass the message to each handler
// if any of them return true, then the message has been "consumed", so we return
for (size_t i = 0; i < list.count; ++i) {
const EntityDescription::ComponentMessageHandler & cmh =
entityDescription.messageHandlers[list.start + i];
Component * component = getComponent( cmh.componentIndex );
if (cmh.messageHandler( component, data ))
// if returned true, message consumed, so return true immediately
return true;
}
}
return false;
}

We also use the network state tables in each ComponentDescription to construct a single network state table for the entity.

Friday, January 25, 2013

UDP message dependency graph continued

In my last post I talked about some issues that come with using UDP and some approaches to dealing with them. In this post I'm going to describe my solution, a message dependency graph.

On the sending side, each guaranteed message has a sequence number associated with it. The sequence number is incremented each time a message is sent. When a message is sent, its sequence number is stored in a reference to a user-provided MessageDependency object. This way, when sending future messages, you call addDependency() and pass in the MessageDependency instance. You might wonder why I have a MessageDependency object instead of just using the sequence number directly. There is a good reason, which will be important later on.

Included in each message's header is the sequence number of that message as well as a list of dependencies. In my implementation, sequence numbers are 2 bytes unsigned integers in the range [0,32767] which wrap around when advancing past their maximum value. The reason I didn't use the full range is because the first bit is used as a "list termination" flag - if the first bit is 0, it signals the end of the list.

The following algorithm is used on the receiving side. When a new message arrives, a node in the graph is added for that message (if it doesn't already exist), and the node is initially flagged as "not executed". Next, the message nodes for each dependency are examined (if a dependency node doesn't yet exist, it is added and flagged as "not executed"). A directed edge is added pointing from each not-yet-executed dependency to the new message node. If the dependency has already been executed, then we don't add an edge between the two nodes.

Once the node has been added to the graph, we attempt to recursively execute any ready nodes. The algorithm for this is: start at node N. If N has any incoming edges, terminate, as this means it still has pending dependencies. Otherwise, if it has no incoming edges, execute it and flag it as "executed". Then, remove all outgoing edges from that node so that its successors know that it's been executed. Then recursively perform this algorithm on each successor.

Here is some pseudocode:

 void addMessage( seqNumber, dependencies[] )
n = getNode( seqNumber )
if n == null
n = addNode( seqNumber )
n.executed = false

// don't do anything if we've already executed the message
if n.executed
return

// add each dependency node
for depSeqNumber in dependencies
d = getNode( depSeqNumber )
if n == null
d = addNode( depSeqNumber )
d.executed = false
if !d.executed
addEdge( d, n )

void tryExecuteMessage( seqNumber )
// check to see if all dependencies have been completed
n = getNode( seqNumber )

// if there are no dependencies, this message is ready to be executed
if n.predecessorList is empty
// execute the message
executeMessage( n )
m.executed = true

// try executing all messages dependent on this one
for depSequenceNumber in n.successorList
d = getNode( depSequenceNumber )
removeEdge( n, d )
tryExecuteMessage( depSequenceNumber )

One detail is that you should remove nodes from the graph eventually. Not only does this prevent a memory leak, but it's also required because sequence numbers wrap around. If you don't remove nodes, then after a while ("after a while", the mark of a bug full of pain and suffering!) you'll start dropping messages when the wrap occurs because the graph thinks they've already been executed. I choose to start removing nodes after they've been around for the connection timeout limit plus a second of padding. I also made it so that if an unexecuted node reaches this removal timeout, a connection error is signaled.

So far the implementation is pretty good. But there are still two major issues with it. The first issue is subtle, but fundamental. The problem is "old dependencies". Here's an example: suppose you send a message to spawn an enemy, and the message has sequence number 10. Then the player leaves the area, so the enemy goes idle. After an hour, the player returns and kills the enemy. The "kill enemy" message has a dependency on the "spawn enemy" message. But since it's been an hour, the sequence numbers have wrapped around, and "10" now refers to a completely different message. In fact, mostly likely, "10" wouldn't refer to any message at all, since the node containing message 10 has most likely been removed from the graph. Clearly this will not work at all.

The second issue is something that all network game programmers should be concerned about: bandwidth. Each guaranteed message with n dependencies is an additional 2+2n bytes. Using the plain old ordered channels method, each guaranteed message will cost only an additional 2 bytes. We need to find a way to cut down on all the extra dependency data.

Fortunately, there's something we can do that can sovle both of these problems at once! The idea is to determine, on the sending side, when a message must have been executed on the receiving side. Once we've determined that a message has been executed, we can simply remove any dependencies on that message. Remember that the reason we have dependencies in the first place, such as "B depends on A", is to ensure that A gets executed before B. And if we've determined that A has already been executed, we've already met that requirement!

To do this, we keep a local copy of the message dependency graph on the sending side in addition to the one on the receiving side. In the local graph, a node is added whenever a message is sent, but that node is initially marked as "not executed" (since when we first send it, it hasn't been executed on the receiving side yet). When we send a packet containing guaranteed messages, we keep a list of the sequence numbers of messages in that packet. Then, when we receive an ACK for that packet, we call the tryExecuteMessage() function for each guaranteed message that was previously sent. This will cause the local dependency graph to be evaluated just as it is on the receiving side.

Locally, when evaluating messages in the dependency graph, we don't want to actually evaluate the data sent along with the message as we would on the receiver. Instead, whenever a message is executed, we want to remove future dependencies on it. (Implement executeMessage() as a function pointer to be able to easily interchange this functionality). Remember how above I talked about using a MessageDependency object instead of passing around the raw sequence numbers? This now becomes important.

First of all, take a look at my endMessage() method's signature:

 bool endMessage( MessageDependency * dependency = NULL );

The important thing to note is that rather than returning a dependency object, I pass in an existing one to be filled out (or optionally none). Internally, when the function is called, a pointer to the dependency object passed in is stored along with the message. This is because the MessageDependency contains not only the message sequence number, but also an "executed" flag. Whenever a message is executed in the local graph, the corresponding dependency object's "executed" flag is set, so that next the object is passed into a call to addDependency(), it is simply ignored. Everything is completely transparent to the user!

(The implementation of this takes a bit of care; for example, the MessageDependency class should not be copyable, and its destructor needs to make sure to clear the external reference to it.)

Let's reexamine each of the above issues with this new local graph solution. The first issue was "old dependencies". E.g. message A is "spawn enemy", message B is "kill enemy". Message B is dependent on message A but occurs a long time after. With the local graph solution, an ACK for message A will be quickly received (usually in the connection round trip time), and A's dependency object will be marked as "executed". When message B is sent a long time later, the dependency won't even be added. First problem solved.

The second issue was bandwidth. Since we're quickly removing dependencies, the 2n term in the number of additional bytes needed per message will rapidly disappear, and we'll just be left with 2 bytes for the sequence number, which is just as good as having an ordered channel. Of course, this won't be the case when rapidly sending a ton of guaranteed messages with many interdependencies, but I can't imagine very many scenarios where this would occur, so I think it's safe to call the bandwidth issue "solved".

So far my implementation has been working great. I'd be interested in hearing your thoughts on the idea, or results if anyone has used something like it before.

Thursday, January 24, 2013

UDP message dependency graph

Many multiplayer games with realtime requirements, such as first person shooters, use UDP for networking (huh, it just dawned on me that saying "UDP protocol" is like saying "ATM machine"). The advantage of using UDP rather than TCP is that if a packet is lost, the connection doesn't have to wait until that packet is recovered before processing newer packets. Of course, the downside is the fact that you acutally have to deal with lost packets (and that you don't even have a connection).

Glenn Fiedler has a great series of articles called Networking for Game Programmers which talks about TCP and UDP in more detail, and then goes on to describe how to implement a virtual connection on top of UDP and how to deal with packet loss. I won't go into detail here, as I've linked the articles, but in summary the implementation works by having the side receiving a packet send an ACK (acknowledgement) back to the sender to alert them that the packet has been received. This way, when sending a packet, you can know for sure when it gets through, and if an ACK is missed, you can decide how to proceed (whether or not to resend data). In this post I'm going to talk about my approach to making this decision.

In my project, "DR", packets are made up of a series of messages. Each message represents a command like "spawn object of type ENEMY at (x,y,z)" or "update object with ID 5 to position (x,y,z)". Some of these messages are important - if a packet with a "spawn enemy" message is dropped, you definitely want to resend that packet, since if you don't, the player would have an invisible enemy draining its health, and that wouldn't be very fun. Well, maybe it would be, but it's certainly not the intent. Other messages, like the "update object" message, aren't as important - if a packet with an "update object" message is dropped, the player might see a a very brief moment of lag (or maybe not even that, if extrapolation/prediction is used), but another "update object" message would be sent immediately after, and the mistake would quickly be fixed.

The first choice I made was to have two message types: guaranteed messages and non-guaranteed messages. When sending guaranteed messages, the content of the message is copied in a buffer, and once the ACK for the packet containing that message is received, the message is removed from the buffer. However, if the ACK for that packet is missed, the message is automatically sent along with the next packet. This process keeps occurring until an ACK for a packet containing that message is received. For non-guaranteed messages, none of this happens - you just send out the message and forget about it.

So that solves the issue of guaranteed messages. But there's another issue with UDP: packets don't necessarily arrive in order. I made the decision to simply drop packets which are older that the most recently received packet, but messages can still arrive out of order. For example, consider the following sequence of events:

Server sends packet 1 containing message A

Server sends packet 2 containing message B

Client receives packet 2 (packet 1 was lost) containing message B and sends back an ACK

Server realizes packet 1 was lost and resends message A in packet 3

Client receives packet 3 containing message A

The server sent A, then B, but the client received B, then A. This could cause some bad situations. For example, suppose message A contains "spawn ENEMY with ID 1", and message B contains "kill ENEMY with ID 1". Those messages need to be correctly ordered. A common solution is to implement a small part of TCP to allow for ordered messages. Each guaranteed message has a sequence number which is incremented, and a message with sequence number N is only executed once all messages with sequence numbers from 0 to N-1 have been executed. So when an out-of-order message is received, it is stored and then recalled to be executed once the messages that should come before it are received.

Of course, implementing TCP on top of UDP brings the same problems that we wanted to avoid with TCP! Messages can get delayed if other messages are dropped. For example, suppose you want chat messages to be guaranteed, as well as "spawn enemy" messages. If a player says something over chat and that packet is dropped, no "spawn enemy" messages can get through until the chat message is recovered. This contraint is obviously pointless and undesirable. One way to fix this is to have several guaranteed message "channels", such as one for critical game events and one for chat messages. Each channel would have its own sequence number counter, so messages from the "chat" channel wouldn't delay messages from the "critical game events" channel. This is better, but still not ideal. If you're spawning 10 enemies and the message to spawn the first enemy gets dropped, it would be nice if the other 9 weren't held up.

I was thinking about this when I came to the realization that message ordering "channels" are simply a special case of a more general data structure - a directed acyclic graph. In the message channel model, each message has a single dependency: the message that came directly before it. (Terminology: if B depends on A, then B is a successor of A and A is a predecessor of B). If you had 3 different message channels, the graph representation would look like 3 separate chains of nodes. If you remove the channel restriction and just allow for arbitrary dependencies (without cycles of course), all the issues I talked about above are solved. For example, a chat message would have a single dependency to the previous chat message, a "spawn enemy" message would have no dependencies, and a "kill enemy" message would have a single dependency to its corresponding "spawn enemy" message. Another example: suppose you have the server send info about each of the N players to each player, and then a "start game" message. The "start game" message could have N dependencies on the N "player info" messages. This way, the game wouldn't start until all player info was received.

I'm going to end this post, as it's getting late, but next I'll talk about my implementation of the UDP message dependency graph.

Friday, January 18, 2013

Realtime binaural audio

If you haven't heard of binaural recording, put on a good pair of stereo headphones and watch this video (or rather, listen to it). Pretty striking difference in terms of immersion from the audio we're used to hearing in games and movies. The idea behind it is to record using two microphones, one placed at each ear (perhaps even in ear-shaped molds to mimic precisely how sound travels through the ear canal), and when playing back the sound, play the left ear recording through the left stereo channel and the right ear recording through the right channel.

Part of the reason binaural recordings sound so much more realistic than standard stereo is that they capture the slight difference between time the sound takes to travel to each ear. For example, if a sound is coming from your right, it probably won't sound much louder in your right ear, but it will arrive at your right ear a tiny bit sooner. This slight difference is how your brain determines where the sound is coming from.

I decided to take a stab at implementing this effect in software. (I wonder if there will ever be "programmable audio shaders".) I started by playing a (looping) mono sound. I'll call the array of samples input, and the stream of samples I ultimately send to the sound card will be called left and right. If t is our time, in terms of the sample rate, then the regular way to play the sound would be

 left[t] = right[t] = input[t]

In order to get the binaural effect, we want to offset each output channel based on the distance that "ear" is from the source. This is because each ear is hearing the sound slightly "in the past". So how much do we offset by? To figure that out, we need to know a few things, such as the position of the source, the position of each ear, and the speed of sound, which is 340.29 meters/sec. So to figure out how long the sound took to travel from the source to the ear, we compute

 offset_seconds = distance(ear_position, source_position) / 340.29

To convert this into number of samples, we just multiply by the sample rate:

 offset_samples = offset_seconds * samples_per_second

So our code would look something like

 left_offset = (distance(left_ear_position, source_position / 340.29) * samples_per_second  

right_offset = (distance(right_ear_position, source_position / 340.29) * samples_per_second

left[t] = input[t - left_offset]

right[t] = input[t - right_offset]

Example: if the source is directly to your right and the ears are 15cm apart, left_offset would be 0.15 / 340.29 = 0.00044 seconds larger than right_offset. At 44.1kHz, left_offset is behind right_offset by about 19.5 samples.

Of course, there are a lot of other details I left out (which I don't know much about) such as interpolation between samples and interpolation of distances, but this is the basic idea. And as a bonus, you get the doppler effect for free, since as you move around, the offsets are changing, causing pitch shifts.

Here's my implementation. Controls are ASDW and move mouse to look around (quit with Alt-F4, since the mouse sticks in the center). I put in basic linear interpolation for samples and distance changes, which sounds absolutely awful, but it's a lot better than no interpolation.

It looks like there's been some research on this in the last few years. This video is pretty impressive... sounding!

Blog!

I figure I might as well do the standard "intro post" to get started. So, welcome to my humble ablog! The topic: game and graphics programming, and probably some other various topics from time to time. I'll be posting ideas, implementation challenges, and project progress updates.

I'm currently working on an indie game project (which I will refer to as "DR") which I am planning to release on tablet platforms. Unfortunately since I'm the only programmer, progress can be a bit slow at times, but I'll try to keep reasonably regular updates. I'm writing DR in C++ and OpenGL, using the engine I spent the last year building, which I've named "Crunch Game Engine". If you want to take a look, you can browse or download the repository on bitbucket.

Anyway, enough introductions, time to get onto some real posts.