gohan/entity.go

61 lines
1.4 KiB
Go
Raw Normal View History

2021-11-19 04:13:28 +00:00
package gohan
import (
"sync"
"time"
)
// Entity is an entity identifier.
type Entity int
2021-11-19 04:13:28 +00:00
var maxEntityID Entity
2021-11-19 04:13:28 +00:00
var entityMutex sync.Mutex
// NewEntity returns a new (or previously removed and cleared) Entity. Because
// Gohan reuses removed Entity IDs, a previously removed ID may be returned.
func NewEntity() Entity {
entityMutex.Lock()
defer entityMutex.Unlock()
if len(availableEntityIDs) > 0 {
id := availableEntityIDs[0]
availableEntityIDs = availableEntityIDs[1:]
allEntities = append(allEntities, id)
return id
}
maxEntityID++
allEntities = append(allEntities, maxEntityID)
gameComponents = append(gameComponents, make([]interface{}, maxComponentID+1))
return maxEntityID
}
// Remove removes the provided Entity's components, causing it to no longer be
// handled by any system. Because Gohan reuses removed EntityIDs, applications
// must also remove any internal references to the removed Entity.
func (entity Entity) Remove() {
entityMutex.Lock()
defer entityMutex.Unlock()
for i, e := range allEntities {
if e == entity {
allEntities = append(allEntities[:i], allEntities[i+1:]...)
removedEntities = append(removedEntities, e)
return
}
}
}
var numEntities int
var numEntitiesT time.Time
// ActiveEntities returns the number of currently active entities.
func ActiveEntities() int {
if time.Since(numEntitiesT) >= time.Second {
numEntities = len(allEntities)
numEntitiesT = time.Now()
}
return numEntities
2021-11-19 04:13:28 +00:00
}