-
Notifications
You must be signed in to change notification settings - Fork 0
/
entityLoader.go
59 lines (46 loc) · 1.14 KB
/
entityLoader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package ecs
import (
"encoding/json"
"errors"
"log"
"github.com/co0p/tankism/lib/ecs"
)
type EntityLoader struct {
registry map[ecs.ComponentType]LoadableComponent
}
type LoadableComponent interface {
Type() ecs.ComponentType
Load([]byte) LoadableComponent
}
func NewEntityLoader() EntityLoader {
el := EntityLoader{
registry: make(map[ecs.ComponentType]LoadableComponent),
}
return el
}
func (e *EntityLoader) Register(cs ...LoadableComponent) {
for _, v := range cs {
e.registry[v.Type()] = v
}
}
// Load returns a new entity from given by adding json unmarshalled components
func (el *EntityLoader) Load(e *ecs.Entity, data []byte) error {
cs := []ecs.Component{}
var componentMap map[ecs.ComponentType]any
err := json.Unmarshal(data, &componentMap)
if err != nil {
return errors.New("failed to load entity: " + err.Error())
}
for k, v := range componentMap {
t, ok := el.registry[k]
if !ok {
log.Fatalf("could not find type %T in registry\n", t)
}
v1 := v.(map[string]interface{})
jjsss, _ := json.Marshal(v1)
component := t.Load(jjsss)
cs = append(cs, component)
}
e.AddComponents(cs...)
return err
}