C comes after E?

On the surface components are fairly simple. In ECS, a component, is basically a set of properties that an entity has. So if the entity is located somewhere, it might have a Location component with x and y coordinates. In fact, even though I’m add a protocol for Component, there’s nothing in it.

protocol Component {
}

I added it just in case I ever do need anything on the base component and to add a bit of clarity to the purpose of anything that’s used as a component.

ComponentContainer

The slightly more complicated part of components is how they’re stored and associated to an entity.

protocol ComponentContainer : EntityContainer {
	associatedtype ComponentType where ComponentType : Component
	func get(entity: Entity) -> ComponentType?
	func update(entity: Entity, component: ComponentType)
	var entities: AnySequence<(Entity, ComponentType)> {get}
}

At first I tried to allow the component container able to be a struct, but it ended up really not working well for reasons that’ll be covered later.

Right now I think there are 2 types of component containers:

  • Dense where the majority of entities have the component
  • Sparse where only a few entities have the component

The dense container will internally use an array to store components and the sparse container will use a dictionary instead. While the implementations are pretty short, I’ll leave them out for now for reasons below.

Next up

I’ve come to realize that talking about ECS in isolation doesn’t really work well. I’ve been implementing it while working on a game which drives what I need it to do, but that isn’t really shown in these posts.

To fix that, I’ll write a simple game to go along with it. It won’t be anywhere near complicated enough to really justify using an ECS (I’m thinking Breakout), but hopefully it’ll be enough to illustrate how it’s used.

Once I have enough of it in place, I’ll add a github repository with the ECS implementation and the sample game.

History

All posts about the development of SwiftECS can be found here

:computer:

Updated: