gohan/component.go

57 lines
1.3 KiB
Go

package gohan
import (
"sync"
)
var componentMutex sync.Mutex
// ComponentID is a component identifier. Each Component is assigned a unique ID
// via World.NewComponentID, and implements a ComponentID method returning its ID.
type ComponentID int
// Component represents data for an entity, and how it interacts with the world.
type Component interface {
ComponentID() ComponentID
}
// NewComponentID returns the next available ComponentID.
func (w *World) NewComponentID() ComponentID {
entityMutex.Lock()
defer entityMutex.Unlock()
componentMutex.Lock()
defer componentMutex.Unlock()
w.maxComponentID++
for i := Entity(1); i <= w.maxEntityID; i++ {
w.components[i] = append(w.components[i], nil)
}
return w.maxComponentID
}
// AddComponent adds a Component to an Entity.
func (w *World) AddComponent(entity Entity, component Component) {
componentMutex.Lock()
defer componentMutex.Unlock()
componentID := component.ComponentID()
w.components[entity][componentID] = component
entityMutex.Lock()
defer entityMutex.Unlock()
w.modifiedEntities = append(w.modifiedEntities, entity)
}
// Component gets a Component of an Entity.
func (w *World) Component(entity Entity, componentID ComponentID) interface{} {
components := w.components[entity]
if components == nil {
return nil
}
return components[componentID]
}