/
universe.go
105 lines (89 loc) · 2.06 KB
/
universe.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package ospokemon
import (
"time"
"github.com/cznic/mathutil"
"github.com/ospokemon/ospokemon/space"
"taylz.io/types"
)
type Universe struct {
Id uint
*Space
Entities map[uint]*Entity
Spawners []*Spawner
Private bool
// internals
bodyIdGen *mathutil.FC32
FullFrame types.Dict
}
type Space struct {
Dimension space.Vector
Division *space.Line
Sub *[2]*Space
Entities Entities
}
func MakeUniverse(universeid uint) *Universe {
bodyIdGen, _ := mathutil.NewFC32(0, 999999, true)
return &Universe{
Id: universeid,
Space: &Space{
Dimension: space.Vector{},
Division: nil,
Sub: nil,
Entities: Entities{},
},
Entities: make(map[uint]*Entity),
bodyIdGen: bodyIdGen,
FullFrame: nil,
}
}
func (u *Universe) GenerateId() uint {
return uint(u.bodyIdGen.Next())
}
func (u *Universe) Update(d time.Duration) {
frame := types.Dict{}
for entityId, entity := range u.Entities {
if entity == nil {
continue
}
entity.Update(u, d)
frame[types.StringUint(entityId)] = entity.Json()
}
u.FullFrame = frame
for _, spawner := range u.Spawners {
spawner.Update(u, d)
}
}
func (u *Universe) Add(entities ...*Entity) {
entitieslog := make([]uint, len(entities))
for i, e := range entities {
e.Id = u.GenerateId()
u.Entities[e.Id] = e
entitieslog[i] = e.Id
}
log.Add("Universe", u.Id).Add("Entity", entitieslog).Debug("ospokemon.Universe.Add")
}
func (u *Universe) AddSpawner(spawner *Spawner) {
u.Spawners = append(u.Spawners, spawner)
}
func (u *Universe) Remove(e *Entity) {
log.Add("Universe", u.Id).Add("Entity", e.Id).Debug("ospokemon.Universe.Remove")
delete(u.Entities, e.Id)
e.Id = 0
}
func GetUniverse(id uint) (u *Universe, err error) {
if u = Universes.Cache[id]; u == nil {
if u, err = Universes.Select(id); err == nil {
Universes.Cache[id] = u
} else {
log.With(types.Dict{
"Universe": id,
"Error": err.Error(),
}).Error("ospokemon.GetUniverse: create")
}
}
return
}
var Universes = struct {
Cache map[uint]*Universe
Select func(uint) (*Universe, error)
}{make(map[uint]*Universe), nil}