Entity-Component-System (ECS) is a distributed and compositional architectural design pattern that is mostly used in game development. It enables flexible decoupling of domain-specific behaviour, which overcomes many of the drawbacks of traditional object-oriented inheritance.
Elixir is a dynamic, functional language built on top of the Erlang VM designed for building scalable and maintainable applications.
In this article, discover how we can use both ECS and Elixir in a novel approach to structure our programs beyond the class based inheritance paradigm.
Drawbacks of class-based inheritance
The traditional way to build game worlds is to have an object-oriented hierarchy of game objects that model the world. However, even simple objects can end up with a large set of unused functionality. Consider the example below:
We’re building a game engine, and we find ourselves with the below class hierarchy:
We have a base
GameObject, which is subclassed by
Animal is subclassed by
Whale, each with its own special behaviour
swim() respectively. We also have a
Killer Whale, which is a subclass of
Whale than can
Let’s try to introduce a new animal to our world:
Killer Bunnyto be able to
kill(), but which class should
Killer Bunnyinherit from?
For languages / platforms with only single inheritance, we’re out of luck. We’d have to move both
kill() to some superclass such as
Killer Bunny can then inherit. However, all other subclasses of
Animal will inherit things they don’t need.
kill(). Over time,
Animal will become a god object with a massive set of behaviours.
Multiple inheritance doesn’t do it either. Suppose
Killer Bunny inherits from both
Killer Bunny will inherit
swim(), which is unneeded functionality.
We face a number of other issues:
Rigid functionality: Only
Killer Whale can
kill(). We can’t change our mind later and make other animals
kill() very easily. Behaviour is only available to classes that were specifically coded to support that behaviour. As the number of game entities grow, we face greater difficulty in finding a spot in the hierarchy to place new entities under.
The Diamond Problem: The “diamond problem” (sometimes referred to as the “deadly diamond of death”) is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?
The Blob antipattern: With inheritance, games end up with a huge single root class or some other leaf node with a large amount of functionality. Subclasses become overburdened with unneeded functionality.
The difficulties mentioned above has plagued game developers for a long time, and Entity Component Systems attempts to remedy these annoyances. We’ll learn about ECS in the next section.
Entity Component Systems
There are three key abstractions in ECS:
We’ll examine each in detail, starting from
The qualities or aspects of an entity.
Components are minimal, reusable data objects that are plugged into entities to support some behaviour. A Component tags an entity with a single quality. A Component itself has no behaviour. Typically, it’s implemented as a struct or dictionary.
Imagine we have a
Bunny entity in our world:
We can define bunnies as nothing more than an aggregation / collection of independent components. In the example above, a Bunny is ‘composed’ of components such as
Each component support some behaviour. To illustrate,
Seeing has attributes
sight_radius to support a sight behaviour. Note however, that a Component themselves have no behaviour. Each component is simply a minimal data object.
An aggregation or container of components.
Entities are solely the sum of its components. Entities are implemented as a globally unique IDs associated to a collection of Components. Note that Entities themselves have no actual data or behaviour. Each Component gives an Entity data to support some behaviour.
Let’s look at our
See the dashed box around our components? That’s the
Bunny entity - nothing more than a container of components. We can define entities as an aggregation of any subset of components, like this
An entity is little more than a collection of components.
Some ECS implementations allow you to modify an entity’s components collection at runtime. This allows you to “mutate” entities on the fly. For example, we could have a
Poisonedcomponent that makes entities tagged with this component to lose health over time. We can add and remove this component dynamically to inflict and cure poison. You might also have a ‘blind’ status effect that removes the
Seeingcomponent of entities it hits.
Up until this point, we haven’t touched on any logic or behaviour. Entities are just an aggregation of components; Components are just data objects. Where does behaviour in ECS come from? They come from Systems.
Systems brings entities and components to life.
Systems enumerate over Components or groups of Components, updating their state according to an internal rule or external event. A way to think of Behaviour is as a change from one state to another. Let’s see an example:
Behaviour: “A bunny on a tree falls due to gravity.”
How do we implement the above behaviour? We can make it so that
Placeable Components with a
z value more than 0 to decrease over time to 0.
Behaviour: “Living beings age.”
How do we implement the above behaviour? We can make it so that
Living Components has its
age value increase over time.
We create a dedicated System for each behaviour we wish to support. A
GravitySystem enumerates over all
Placeable Components; a
TimeSystem enumarates over all
Living components. Bear in mind that Systems operate on Components, not Entities.
Data Flow in Entity-Component-System
To further cement your understanding of the pattern, let’s see a typical data flow in this architecture:
Each System listens to some event stream such as time or player input, and updates the states of its Components in response to that event and some internal rules. These continuously changing state is available for access by the Entities it is a part of, and thus result in behaviour.
Another example: Suppose the player presses the “move left” key. PlayerInputSystem executes and detects the keypress, updating the Motion component. MotionSystem executes and “sees” the Motion for the entity is to the left, applying a Physics force to the left. The RenderSystem executes and reads the current position of the entity, and draws it according to the Spatial definition (which may include texture region / animation information).
The spreadsheet analogy
Another way to think of ECS is as a relational table, like a spreadsheet:
An Entity Component System can be visualized as a table with columns of components and rows of entities. To operate on a single component, we select its column and look at each cell. To operate on an entity, we selects its row and look at each cell.
Advantages Of ECS
Now that we have a better understanding of the Entity-Component-System architecture, let’s think about how this approach compares to class-based inheritance.
Good decoupling, single responsibility principle: each behaviour or domain is decoupled from each other in independent components and/or systems. Unlike our monolithic god object in class based inheritance, we can extract any subset of functionality and assemble it in any combination. ECS also encourages small interfaces.
Composability and runtime object definition: Any type of game object can be created by adding the correct components to an entity. This can also allow the developer to easily add features of one type of object to another, without any dependency issues. For example, we can do
Entity.build([FlyingComponent, SeeingComponent]) at runtime.
Testable: Each component and system is a unit by definition. We can also substitute components with mocked or demo components for testing.
Parallelizable: In many real-world ECS implementations such as MMOs, a System is implemented as a distributed system or a worker pool that can distribute the work amongst themselves. This lets us horizontally scale the size of our simulations by increasing the number of system workers in our pool.
Separation of data and behaviour: components hold data, systems hold behaviour. There is no intermingling of the two. This property lets you plug-and-play different behaviour to apply on the same data.
Challenges Of ECS
Despite the flexibility this gives us, ECS introduces a number of non-trivial challenges:
ECS is a relatively unknown pattern: Since this design pattern has been mostly limited to game development, discussing how to use ECS for domains outside of it such as for building web apps can be challenging. There are few resources available for applying this pattern to other domains, if any.
Handling interprocess communication: How do we handle the communication between systems and components? We need some kind of message bus or publish-subscribe system to enable parts of our ECS to talk to each other. Depending on the language or platform the ECS is implemented in, this could introduce a spike in complexity. The cost of iterating through components and entities may also result in a drop in performance.
Inter-component communication: What happens when a system needs to access and modify data in multiple components? Components might need to share state with other components and communicate with each other prior to communicating with systems. For example, say we have a
Sound component in an entity. We could have a
PositionalSoundSystem that needs to communicate with both components. We may need a separate channel for inter-component communication to support this use case.
Inter-system communication: What happens when two systems need to access and modify the same component? Say we have two systems: one multiplies attribute
-1, the other adds
10. Depending on the order of application of the two systems, the end result will be different. Unless the operations are associative, we may need to introduce a way to ensure that the order of the systems are correct.
Not as concretely define as other design patterns such as MVC: There are a multitude of ways to implement ECS. Each language or platform will have different abstractions available, which result in different flavours of ECS.
ECS in the Real world
Aside from being a popular architecture for video games, current applications of ECS are for large-scale distributed simulations. This includes real-time city traffic, internet telecommunications network, and physics simulations. It’s also used for building massively multiplayer backends for video games with staggering numbers of entities.
One startup in particular, is building an ECS-as-a-service called SpatialOS.
An ECS implementation in Elixir
In this section, we’ll take a look at one possible implementation of Entity-Component-System in Elixir. I’ll start by briefly mentioning why Elixir (also Erlang) and its concurrency primitives is a good fit for the ECS pattern.
From here on out, since Elixir compiles to Erlang bytecode, when I say Elixir I also mean Erlang.
The Actor Model
One of the key abstractions of Elixir are processes - these are akin to actors of the actor model. Actors are computations entities that can:
- Send messages
- Receive messages
- Spawn new actors
In the diagram above, Actor
A sends messages
2 to Actor
C, which it receives. In response to these messages, Actor C can do send new messages, or spawn new actors and wait to receive messages from those actors.
Elixir also has higher-level abstractions for building actors called
Consider how you might implement ECS with the help of actors.
Here’s what our implementation would look like in use:
My ECS implementation in Elixir is open source on Github. You can clone and run it via
iex -S mix from the root folder. You must have Elixir installed on your machine.
An entity is a struct with a randoms string
id and a list of components. We can create entities and extend it by adding components. Both can be done at runtime.
Below is an actual entity, the
The above code introduces the idea of a ‘prefab’, which are convenient factories for entities with a common set of components. Using the prefab saves you from typing too much, and acts as a facade.
Component.Agent modules provide facilities to get and set state. Each Component is backed by an Actor (an Agent - a kind of GenServer.) Components such as
TimeComponent implement the
Component behaviour (interface.)
Below is an actual component, the
TimeComponent, which implements the
System and Registry
Systems enumerates over all components of its type.
A few things to notice:
dispatchtakes in an external action, evaluates it based on an internal rule, and returns a new state. This part was inspired largely by my experiences with Redux reducers and Elm’s
componentsmethod returns the set of components that this System will enumerate. Whenever a Component is instantiated, it registers its agent to the
Registrywhich keeps track of all active components. The Registry is itself an actor, shown below:
And that’s it!
This particular ECS implementation may be a bit rough around the edges. There are many flavours of ECS, and this is most certainly not the only way to make ECS work. Your feedback is most welcome!
ECS is an overlooked architectural pattern that overcomes some of the drawbacks of OOP-style inheritance, and is a great fit for distributed systems.
Branching out into unfamiliar domains (such as game development) is a fruitful source of new ideas and patterns to write better software.
Thanks for reading! I hope you found this article useful or otherwise interesting. Let me know your thoughts via the comments below!
Get notified of my latest articles by providing your email below.