package ecs
import (
"fmt"
"math"
"reflect"
)
type registry struct {
Used bitMask
Types []reflect .Type
IDs []uint8
Components map [reflect .Type ]uint8
}
func newRegistry() registry {
return registry {
Components : map [reflect .Type ]uint8 {},
Types : make ([]reflect .Type , maskTotalBits ),
Used : bitMask {},
IDs : []uint8 {},
}
}
func (r *registry ) ComponentID (tp reflect .Type ) (uint8 , bool ) {
if id , ok := r .Components [tp ]; ok {
return id , false
}
return r .registerComponent (tp , maskTotalBits ), true
}
func (r *registry ) ComponentType (id uint8 ) (reflect .Type , bool ) {
return r .Types [id ], r .Used .Get (id )
}
func (r *registry ) Count () int {
return len (r .Components )
}
func (r *registry ) registerComponent (tp reflect .Type , totalBits int ) uint8 {
val := len (r .Components )
if val >= totalBits {
panic (fmt .Sprintf ("exceeded the maximum of %d component types or resource types" , totalBits ))
}
newID := uint8 (val )
id := id (val )
r .Components [tp ], r .Types [newID ] = newID , tp
r .Used .Set (id .id )
r .IDs = append (r .IDs , newID )
return newID
}
func (r *registry ) unregisterLastComponent () {
newID := uint8 (len (r .Components ) - 1 )
id := id8 (newID )
tp , _ := r .ComponentType (newID )
delete (r .Components , tp )
r .Types [newID ] = nil
r .Used .Clear (id .id )
r .IDs = r .IDs [:len (r .IDs )-1 ]
}
type componentRegistry struct {
registry
IsRelation []bool
IsTrivial []bool
Archetypes []int
version uint32
}
func newComponentRegistry() componentRegistry {
return componentRegistry {
registry : newRegistry (),
IsRelation : make ([]bool , maskTotalBits ),
IsTrivial : make ([]bool , maskTotalBits ),
Archetypes : make ([]int , maskTotalBits ),
version : 1 ,
}
}
func (r *componentRegistry ) ComponentID (tp reflect .Type ) (uint8 , bool ) {
if id , ok := r .Components [tp ]; ok {
return id , false
}
return r .registerComponent (tp , maskTotalBits ), true
}
func (r *componentRegistry ) registerComponent (tp reflect .Type , totalBits int ) uint8 {
newID := r .registry .registerComponent (tp , totalBits )
r .IsRelation [newID ] = isRelation (tp )
r .IsTrivial [newID ] = isTrivial (tp )
return newID
}
func (r *componentRegistry ) unregisterLastComponent () {
newID := uint8 (len (r .Components ) - 1 )
r .registry .unregisterLastComponent ()
r .IsRelation [newID ] = false
}
func (r *componentRegistry ) addArchetype (id uint8 ) {
r .Archetypes [id ]++
r .version ++
}
func (r *componentRegistry ) rareComponent (ids []ID ) ID {
minCount := math .MaxInt
var rareID ID
for _ , id := range ids {
count := r .Archetypes [id .id ]
if count < minCount {
minCount = count
rareID = id
}
}
return rareID
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .