mirror of
https://github.com/bloeys/nmage.git
synced 2025-12-29 05:18:21 +00:00
Starting entities, components, and levels
This commit is contained in:
43
entity/entity.go
Executable file
43
entity/entity.go
Executable file
@ -0,0 +1,43 @@
|
||||
package entity
|
||||
|
||||
type Entity struct {
|
||||
|
||||
// Byte 1: Generation; Byte 2: Flags; Bytes 3-8: Index
|
||||
ID uint64
|
||||
Comps []Comp
|
||||
}
|
||||
|
||||
type Comp interface {
|
||||
Name() string
|
||||
}
|
||||
|
||||
func AddComp(e *Entity, c Comp) {
|
||||
e.Comps = append(e.Comps, c)
|
||||
}
|
||||
|
||||
func GetComp[T Comp](e *Entity) (out T) {
|
||||
|
||||
for i := 0; i < len(e.Comps); i++ {
|
||||
|
||||
comp, ok := e.Comps[i].(T)
|
||||
if ok {
|
||||
return comp
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func GetAllCompOfType[T Comp](e *Entity) (out []T) {
|
||||
|
||||
out = []T{}
|
||||
for i := 0; i < len(e.Comps); i++ {
|
||||
|
||||
comp, ok := e.Comps[i].(T)
|
||||
if ok {
|
||||
out = append(out, comp)
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
35
entity/registry.go
Executable file
35
entity/registry.go
Executable file
@ -0,0 +1,35 @@
|
||||
package entity
|
||||
|
||||
import "github.com/bloeys/nmage/assert"
|
||||
|
||||
type Registry struct {
|
||||
EntityCount uint64
|
||||
Entities []Entity
|
||||
}
|
||||
|
||||
func (r *Registry) NewEntity() *Entity {
|
||||
|
||||
assert.T(r.EntityCount < uint64(len(r.Entities)), "Can not add more entities to registry because it is full")
|
||||
|
||||
for i := 0; i < len(r.Entities); i++ {
|
||||
|
||||
// @TODO: Implement generational indices
|
||||
e := &r.Entities[i]
|
||||
if e.ID == 0 {
|
||||
r.EntityCount++
|
||||
e.ID = uint64(i) + 1
|
||||
|
||||
assert.T(e.ID != 0, "Entity ID must not be zero")
|
||||
return e
|
||||
}
|
||||
}
|
||||
|
||||
panic("failed to create new entity because we did not find a free spot in the registry. Why did the assert not go off?")
|
||||
}
|
||||
|
||||
func NewRegistry(size uint32) *Registry {
|
||||
assert.T(size > 0, "Registry size must be more than zero")
|
||||
return &Registry{
|
||||
Entities: make([]Entity, size),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user