gohan/component.go

59 lines
1.3 KiB
Go
Raw Normal View History

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