Creating your first ECS
ECS stands for Entity-Component-System. It is a design pattern commonly used in game development to manage game objects and their behaviour. In an ECS architecture:
- Entities are unique identifiers that represent objects in the game world.
- Components are data containers that hold the properties of entities.
- Systems contain the logic that operates on entities with specific components.
Castrum uses this pattern to efficiently manage game objects and their interactions. Traditional game engines often couple data and behaviour together. This is also a good architecture. ECS trades some of this coupling for flexibility and performance by separating data from logic.
In simple terms, ECS separates the "what" (data) from the "how" (logic). Entities and components define the "what", while systems define the "how".
Entities and Components
An entity is a handle with a unique ID. It holds no component data itself; components store the object's data.
Let's create an entity called box in the starter project from the previous guide. In main.go, add:
// add this in the import block:
// github.com/Leonard-Atorough/castrum/core
// add this before the runner execution
_, err := g.World().NewEntity()
if err != nil {
panic(err)
}
Great... but this on its own won't do much. An entity without any components is like a key to an empty chest. To make it useful, we need to add components that define its properties and behaviour.
Components are data containers. In Castrum, a component is a Go struct that can optionally implement Validatable. Castrum validates components when they are added through the world or entity APIs. Queries, which we will come to, do not run validation.
Castrum comes with a set of built-in components. One of the most important ones is the Transform component. The Transform component controls the position and rotation of entities in the game world, with rotation expressed in radians. It also handles scaling and offset, allowing for flexible manipulation of entity transforms.
We can now update our earlier call to create an entity and add the component directly in the call. This is one of the main ways you'll create an entity with components in Castrum.
_, err = g.World().NewEntity(core.Transform{})
Now we have an entity handle with a component that holds some data. We just need something that can act. That's where systems come in.
Systems
A system is a function that matches the system function signature. Systems are executed in Phases. A Phase defines a stage in the engine's execution lifecycle and will be covered in more detail in a future guide.
Define a system by writing a function that conforms to the system function signature. Add the following system to your project:
func Rotate(ctx *core.Context) error {
// logic implemented here
return nil
}
We'll add some logic to this system in the next section. In the meantime, register the system in the game like this:
if err := g.AddSystem(core.PhaseFrame, "box-rotation", Rotate); err != nil {
panic(err)
}
Note the phase. The PhaseFrame phase means the system runs at the framerate, not on a fixed tick. When we do something in this phase like rotate the box, we will have to smooth the action out by multiplying by the DeltaTime
Now that a system is registered and our entity has a component, we're ready to rotate it. To do this we'll need to learn how to query for entities with specific components and update their data within a system.
Querying and Updating Components
Castrum supports typed and untyped queries. Queries are used to find entities based on their components by using query filter methods. In general typed queries are the preferred option; they are faster than untyped queries and provide a quick way to work with data. In this tutorial we'll cover typed queries.
To create a query, you specify the component types you are interested in using the query builder and then execute it to retrieve matching entities. So that we can more easily locate the box entity let's add one more component to it; a marker component called boxTag:
// declare outside of the main func
type boxTag struct {}
_, err = g.World().NewEntity(core.Transform{}, boxTag{})
In the rotate system we wrote earlier, we want to find all entities that have a Transform and boxTag component.
Declare the following variable outside of the main function:
var transformQuery *core.Query2[core.Transform, boxTag]
Since the camera also has a Transform, we'll narrow the query to the box. Then add the following line after the entity:
transformQuery = core.NewQuery2[core.Transform, boxTag](g.World())
Now that we have the query, we can iterate over it by calling the Execute method. This method returns a Go iterator that allows us to loop through all matching entities.
Add the following loop to iterate over the query results in the Rotate system function:
for _, comps := range transformQuery.Execute() {
// we'll add
}
A typed query returns two values: The first value is the Entity handle and the second value is a Typed struct matching the number of types requested, keyed from A to H, in query order. In this case A is the Transform and B is the boxTag
To make the box spin we update the Rotation field of the A component which is our Transform:
for _, comps := range transformQuery.Execute() {
comps.A.Rotation += ctx.DeltaTime.Seconds() * 2
}
return nil
With this, every entity that has a Transform and boxTag component will rotate at 2 radians per second.
Finishing Up
We now have almost everything we need. At this stage if we run the game using go run . from the root of the project directory, our window will appear and we'll see a black screen with nothing. This is because while our update on the transform is happening, we have nothing to visualise. To fix this, we'll use another engine component, Primitive.
Update your entity that we created earlier to this:
// add the following to the import block:
// "image/color"
// github.com/Leonard-Atorough/castrum/sprite
// github.com/Leonard-Atorough/castrum/geom
_, err = g.World().NewEntity(
core.Transform{},
boxTag{},
sprite.Primitive{
Shape: sprite.ShapeRect,
Rect: geom.Vector2{X: 64, Y: 64},
Style: sprite.Style{
Color: &color.RGBA{G: 255, A: 255},
},
},
)
That's it! The entity now has both a Transform and a Primitive component, so it will be visible and will rotate according to the system we defined earlier. Run the game using go run . and you should see a rotating green square on the screen.
You can find a complete, runnable version of this example in examples/your-first-ecs.