forked from zllangct/ecs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchunk.go
138 lines (121 loc) · 2.5 KB
/
chunk.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package ecs
const (
ChunkSize uintptr = 1024 * 16
//ChunkSize int64 = 512
EntitySize uintptr = 8
)
const (
ChunkAddCodeSuccess int = iota
ChunkAddCodeFull
ChunkAddCodeInvalidElement
)
type Chunk[T ComponentObject] struct {
data []T
ids map[int64]int64
idx2id map[int64]int64
len int64
max int64
eleSize uintptr
pend uintptr
pre *Chunk[T]
next *Chunk[T]
}
func NewChunk[T ComponentObject]() *Chunk[T] {
size := TypeOf[T]().Size()
max := ChunkSize / size
c := &Chunk[T]{
data: make([]T, max, max),
eleSize: size,
max: int64(max),
ids: make(map[int64]int64),
idx2id: make(map[int64]int64),
}
return c
}
func (c *Chunk[T]) Add(element *T, id int64) (*T, int) {
if uintptr(len(c.data)) >= c.pend+c.eleSize {
c.data[c.pend+1] = *element
} else {
return nil, ChunkAddCodeFull
}
idx := c.len
c.ids[id] = idx
c.idx2id[idx] = id
real := &(c.data[c.pend])
c.len++
c.pend += c.eleSize
return real, ChunkAddCodeSuccess
}
func (c *Chunk[T]) Remove(id int64) {
if id < 0 {
return
}
idx, ok := c.ids[id]
if !ok {
return
}
lastIdx := c.len - 1
lastId := c.idx2id[lastIdx]
c.ids[lastId] = idx
c.idx2id[idx] = lastId
delete(c.idx2id, lastIdx)
delete(c.ids, id)
c.data[idx], c.data[lastIdx] = c.data[lastIdx], c.data[idx]
c.len--
}
func (c *Chunk[T]) RemoveAndReturn(id int64) *T {
if id < 0 {
return nil
}
idx, ok := c.ids[id]
if !ok {
return nil
}
lastIdx := c.len - 1
lastId := c.idx2id[lastIdx]
c.ids[lastId] = idx
c.idx2id[idx] = lastId
delete(c.idx2id, lastIdx)
delete(c.ids, id)
c.data[idx], c.data[lastIdx] = c.data[lastIdx], c.data[idx]
r := &(c.data[lastIdx])
c.len--
c.pend -= c.eleSize
return r
}
func (c *Chunk[T]) MoveTo(target *Chunk[T]) []int64 {
moveSize := uintptr(0)
if c.len < c.max {
moveSize = uintptr(c.len)
} else {
moveSize = uintptr(c.max)
}
copy(target.data[target.pend:target.pend+moveSize], c.data[c.pend-moveSize:c.pend])
var moved []int64
for i := int64(0); i < int64(moveSize); i++ {
idx := c.len - int64(moveSize) + i
id := c.idx2id[idx]
moved = append(moved, id)
}
target.pend += moveSize * c.eleSize
c.pend -= moveSize * c.eleSize
target.len += int64(moveSize)
c.len -= int64(moveSize)
return moved
}
func (c *Chunk[T]) Get(id int64) *T {
idx, ok := c.ids[id]
if !ok {
return nil
}
return &(c.data[idx])
}
func (c *Chunk[T]) GetByIndex(idx int64) *T {
if idx < 0 || idx >= c.len {
return nil
}
return &(c.data[idx])
}
func (c *Chunk[T]) Len() int64 {
return c.len
}