ecs

package module
v0.3.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 1, 2024 License: MIT Imports: 0 Imported by: 6

README

ECS - Entity Component System

License Releases Go Report Card Codacy Grade Badge Codacy Coverage Badge Maintainability

Build your own Game-Engine based on the Entity Component System concept in Golang.

Features

  • Provide an easy-to-use framework to build a game engine from scratch.
  • No dependencies to other modules or specific game libraries - Feel free to use what fits your needs.
  • Minimum overhead - use only what is really needed.
Example engine

See engine-example for a basic implementation using raylib.

Walkthrough

Project layout

At first we create a basic project layout:

mkdir ecs-example
cd ecs-example
go mod init example
mkdir components systems

Next we create a main.go with the following content:

package main

import (
    "github.com/andygeiss/ecs"
)

func main() {
    em := ecs.NewEntityManager()
    sm := ecs.NewSystemManager()
    de := ecs.NewDefaultEngine(em, sm)
    de.Setup()
    defer de.Teardown()
    de.Run()
}

The execution of the program leads to an endless loop, as our engine is not yet able to react to user input.

The movement system

A system needs to implement the methods defined by the interface System. So we create a new file locally at systems/movement.go:

package systems

import (
    "github.com/andygeiss/ecs"
)

type movementSystem struct{}

func (a *movementSystem) Process(em ecs.EntityManager) (state int) {
    // This state simply tells the engine to stop after the first call.
    return ecs.StateEngineStop
}

func (a *movementSystem) Setup() {}

func (a *movementSystem) Teardown() {}

func NewMovementSystem() ecs.System {
    return &movementSystem{}
}

Now we can add the following lines to main.go:

sm := ecs.NewSystemManager()
sm.Add(systems.NewMovementSystem()) // <--
de := ecs.NewDefaultEngine(em, sm)

If we start our program now, it returns immediately without looping forever.

The player entity

A game engine usually processes different types of components that represent information about the game world itself. A component only represents the data, and the systems are there to implement the behavior or game logic and change these components. Entities are simply a composition of components that provide a scalable data-oriented architecture.

A component needs to implement the methods defined by the interface Component. Let's define our Player components by first creating a mask at components/components.go:

package components

const (
    MaskPosition = uint64(1 << 0)
    MaskVelocity = uint64(1 << 1)
)

Then create a component for Position and Velocity by creating corresponding files such as components/position.go:

package components

type Position struct {
    X  float32 `json:"x"`
    Y  float32 `json:"y"`
}

func (a *Position) Mask() uint64 {
    return MaskPosition
}

func (a *Position) WithX(x float32) *Position {
    a.X = x
    return a
}

func (a *Position) WithY(y float32) *Position {
    a.Y = y
    return a
}

func NewPosition() *Position {
    return &Position{}
}

Now we can add the following lines to main.go:

em := ecs.NewEntityManager()
em.Add(ecs.NewEntity("player", []ecs.Component{ // <--
components.NewPosition().
    WithX(10).
    WithY(10),
components.NewVelocity().
    WithX(100).
    WithY(100),
})) // -->
Extend the movement system

Our final step is to add behavior to our movement system:

func (a *movementSystem) Process(em ecs.EntityManager) (state int) {
    for _, e := range em.FilterByMask(components.MaskPosition | components.MaskVelocity) {
        position := e.Get(components.MaskPosition).(*components.Position)
        velocity := e.Get(components.MaskVelocity).(*components.Velocity)
        position.X += velocity.X * rl.GetFrameTime()
        position.Y += velocity.Y * rl.GetFrameTime()
    }
    return ecs.StateEngineStop
}

The movement system now moves every entity which has a position and velocity component.

We can replace ecs.StateEngineStop with ecs.StateEngineContinue later if we add another system to handle user input.

A rendering system is also essential for a game, so you can use game libraries such as raylib or SDL. This system could look like this with raylib:

// ...
func (a *renderingSystem) Setup() {
    rl.InitWindow(a.width, a.height, a.title)
}

func (a *renderingSystem) Process(em core.EntityManager) (state int) {
    // First check if app should stop.
    if rl.WindowShouldClose() {
        return core.StateEngineStop
    }
    // Clear the screen
    if rl.IsWindowReady() {
        rl.BeginDrawing()
        rl.ClearBackground(rl.Black)
        rl.DrawFPS(10, 10)
        rl.EndDrawing()
    }
    return core.StateEngineContinue
}

func (a *renderingSystem) Teardown() {
    rl.CloseWindow()
}

Documentation

Index

Constants

View Source
const (
	StateEngineContinue = 0
	StateEngineStop     = 1
)

Variables

This section is empty.

Functions

func NewEntityManager

func NewEntityManager() *defaultEntityManager

NewEntityManager creates a new defaultEntityManager and returns its address.

Types

type Component

type Component interface {
	Mask() uint64
}

Component contains only the data (no behaviour at all).

type ComponentWithName added in v0.0.71

type ComponentWithName interface {
	Component
	Name() string
}

ComponentWithName is used by FilterByNames to enable more than 64 Components (if needed).

type Engine added in v0.1.1

type Engine interface {
	// Run calls the Process() method for each System
	// until ShouldEngineStop is set to true.
	Run()
	// Setup calls the Setup() method for each System
	// and initializes ShouldEngineStop and ShouldEnginePause with false.
	Setup()
	// Teardown calls the Teardown() method for each System.
	Teardown()
	// Tick calls the Process() method for each System exactly once
	Tick()
}

Engine handles the stages Setup(), Run() and Teardown() for all the systems.

func NewDefaultEngine added in v0.1.1

func NewDefaultEngine(entityManager EntityManager, systemManager SystemManager) Engine

NewDefaultEngine creates a new Engine and returns its address.

type Entity

type Entity struct {
	Components []Component `json:"components"`
	Id         string      `json:"id"`
	Masked     uint64      `json:"masked"`
}

Entity is simply a composition of one or more Components with an Id.

func NewEntity added in v0.0.54

func NewEntity(id string, components []Component) *Entity

NewEntity creates a new entity and pre-calculates the component maskSlice.

func (*Entity) Add added in v0.0.55

func (e *Entity) Add(cn ...Component)

Add a component.

func (*Entity) Get added in v0.0.6

func (e *Entity) Get(mask uint64) Component

Get a component by its bitmask.

func (*Entity) Mask added in v0.0.54

func (e *Entity) Mask() uint64

Mask returns a pre-calculated maskSlice to identify the Components.

func (*Entity) Remove added in v0.0.55

func (e *Entity) Remove(mask uint64)

Remove a component by using its maskSlice.

type EntityManager

type EntityManager interface {
	// Add entries to the manager.
	Add(entities ...*Entity)
	// Entities returns all the entities.
	Entities() (entities []*Entity)
	// FilterByMask returns the mapped entities, which Components mask matched.
	FilterByMask(mask uint64) (entities []*Entity)
	// FilterByNames returns the mapped entities, which Components names matched.
	FilterByNames(names ...string) (entities []*Entity)
	// Get a specific entity by Id.
	Get(id string) (entity *Entity)
	// Remove a specific entity.
	Remove(entity *Entity)
}

EntityManager handles the access to each entity.

type System

type System interface {
	// Setup is called once before the first call to Process.
	// It is used to initialize the state of the system.
	Setup()
	// Process is called for each entity in the system.
	// It is used to modify the state of the entity.
	Process(entityManager EntityManager) (state int)
	// Teardown is called once after the last call to Process.
	// It is used to clean up the state of the system.
	Teardown()
}

System implements the behaviour of an entity by modifying the state, which is stored in each component of the entity.

type SystemManager added in v0.0.2

type SystemManager interface {
	// Add systems to the this SystemManager.
	Add(systems ...System)
	// Systems returns internally stored systems.
	Systems() []System
}

SystemManager handles the access to each system.

func NewSystemManager added in v0.0.2

func NewSystemManager() SystemManager

NewSystemManager creates a new defaultSystemManager and returns its address.

Directories

Path Synopsis
_examples module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL