• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mlange-42 / ark / 14191219880

01 Apr 2025 08:44AM CUT coverage: 99.832%. Remained the same
14191219880

push

github

web-flow
Add awesome-go badge (#229)

8298 of 8312 relevant lines covered (99.83%)

20284.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.21
/ecs/storage.go
1
package ecs
2

3
import (
4
        "fmt"
5
        "unsafe"
6
)
7

8
type storage struct {
9
        entities           []entityIndex
10
        isTarget           []bool
11
        graph              graph
12
        archetypes         []archetype
13
        relationArchetypes []archetypeID
14
        tables             []table
15
        components         []componentStorage
16
        cache              cache
17
        entityPool         entityPool
18
        registry           componentRegistry
19
        config             config
20
}
21

22
type componentStorage struct {
23
        columns []*column
24
}
25

26
func newStorage(capacity ...int) storage {
252✔
27
        config := newConfig(capacity...)
252✔
28

252✔
29
        reg := newComponentRegistry()
252✔
30
        entities := make([]entityIndex, reservedEntities, config.initialCapacity+reservedEntities)
252✔
31
        isTarget := make([]bool, reservedEntities, config.initialCapacity+reservedEntities)
252✔
32
        // Reserved zero and wildcard entities
252✔
33
        for i := range reservedEntities {
756✔
34
                entities[i] = entityIndex{table: maxTableID, row: 0}
504✔
35
        }
504✔
36
        componentsMap := make([]int16, maskTotalBits)
252✔
37
        for i := range maskTotalBits {
64,764✔
38
                componentsMap[i] = -1
64,512✔
39
        }
64,512✔
40

41
        archetypes := make([]archetype, 0, 128)
252✔
42
        archetypes = append(archetypes, newArchetype(0, 0, &bitMask{}, []ID{}, []tableID{0}, &reg))
252✔
43
        tables := make([]table, 0, 128)
252✔
44
        tables = append(tables, newTable(0, &archetypes[0], uint32(config.initialCapacity), &reg, []Entity{}, []RelationID{}))
252✔
45
        return storage{
252✔
46
                config:     config,
252✔
47
                registry:   reg,
252✔
48
                cache:      newCache(),
252✔
49
                entities:   entities,
252✔
50
                isTarget:   isTarget,
252✔
51
                entityPool: newEntityPool(uint32(config.initialCapacity), reservedEntities),
252✔
52
                graph:      newGraph(),
252✔
53
                archetypes: archetypes,
252✔
54
                tables:     tables,
252✔
55
                components: make([]componentStorage, 0, maskTotalBits),
252✔
56
        }
252✔
57
}
58

59
func (s *storage) findOrCreateTable(oldTable *table, add []ID, remove []ID, relations []RelationID, outMask *bitMask) *table {
495,715✔
60
        startNode := s.archetypes[oldTable.archetype].node
495,715✔
61

495,715✔
62
        node := s.graph.Find(startNode, add, remove, outMask)
495,715✔
63
        var arch *archetype
495,715✔
64
        if archID, ok := node.GetArchetype(); ok {
990,951✔
65
                arch = &s.archetypes[archID]
495,236✔
66
        } else {
495,715✔
67
                arch = s.createArchetype(node)
479✔
68
                node.archetype = arch.id
479✔
69
        }
479✔
70

71
        var allRelations []RelationID
495,715✔
72
        if len(relations) > 0 {
496,400✔
73
                allRelations = appendNew(oldTable.relationIDs, relations...)
685✔
74
        } else {
495,715✔
75
                allRelations = oldTable.relationIDs
495,030✔
76
        }
495,030✔
77
        table, ok := arch.GetTable(s, allRelations)
495,715✔
78
        if !ok {
496,258✔
79
                table = s.createTable(arch, allRelations)
543✔
80
        }
543✔
81
        return table
495,714✔
82
}
83

84
func (s *storage) AddComponent(id uint8) {
1,323✔
85
        if len(s.components) != int(id) {
1,324✔
86
                panic("components can only be added to a storage sequentially")
1✔
87
        }
88
        s.components = append(s.components, componentStorage{columns: make([]*column, len(s.tables))})
1,322✔
89
}
90

91
// RemoveEntity removes the given entity from the world.
92
func (s *storage) RemoveEntity(entity Entity) {
493,252✔
93
        if !s.entityPool.Alive(entity) {
493,253✔
94
                panic("can't remove a dead entity")
1✔
95
        }
96
        index := &s.entities[entity.id]
493,251✔
97
        table := &s.tables[index.table]
493,251✔
98

493,251✔
99
        swapped := table.Remove(index.row)
493,251✔
100

493,251✔
101
        s.entityPool.Recycle(entity)
493,251✔
102

493,251✔
103
        if swapped {
984,978✔
104
                swapEntity := table.GetEntity(uintptr(index.row))
491,727✔
105
                s.entities[swapEntity.id].row = index.row
491,727✔
106
        }
491,727✔
107
        index.table = maxTableID
493,251✔
108

493,251✔
109
        if s.isTarget[entity.id] {
493,254✔
110
                s.cleanupArchetypes(entity)
3✔
111
                s.isTarget[entity.id] = false
3✔
112
        }
3✔
113
}
114

115
func (s *storage) Reset() {
1✔
116
        s.entities = s.entities[:reservedEntities]
1✔
117
        s.entityPool.Reset()
1✔
118
        s.isTarget = s.isTarget[:reservedEntities]
1✔
119
        s.cache.Reset()
1✔
120

1✔
121
        for i := range s.archetypes {
5✔
122
                s.archetypes[i].Reset(s)
4✔
123
        }
4✔
124
}
125

126
func (s *storage) get(entity Entity, component ID) unsafe.Pointer {
5✔
127
        if !s.entityPool.Alive(entity) {
6✔
128
                panic("can't get component of a dead entity")
1✔
129
        }
130
        return s.getUnchecked(entity, component)
4✔
131
}
132

133
func (s *storage) getUnchecked(entity Entity, component ID) unsafe.Pointer {
5✔
134
        s.checkHasComponent(entity, component)
5✔
135
        index := s.entities[entity.id]
5✔
136
        return s.tables[index.table].Get(component, uintptr(index.row))
5✔
137
}
5✔
138

139
func (s *storage) has(entity Entity, component ID) bool {
17✔
140
        if !s.entityPool.Alive(entity) {
18✔
141
                panic("can't get component of a dead entity")
1✔
142
        }
143
        return s.hasUnchecked(entity, component)
16✔
144
}
145

146
func (s *storage) hasUnchecked(entity Entity, component ID) bool {
18✔
147
        index := s.entities[entity.id]
18✔
148
        return s.tables[index.table].Has(component)
18✔
149
}
18✔
150

151
func (s *storage) getRelation(entity Entity, comp ID) Entity {
457✔
152
        if !s.entityPool.Alive(entity) {
458✔
153
                panic("can't get relation for a dead entity")
1✔
154
        }
155
        return s.getRelationUnchecked(entity, comp)
456✔
156
}
157

158
func (s *storage) getRelationUnchecked(entity Entity, comp ID) Entity {
461✔
159
        s.checkHasComponent(entity, comp)
461✔
160
        return s.tables[s.entities[entity.id].table].GetRelation(comp)
461✔
161
}
461✔
162

163
func (s *storage) registerTargets(relations []RelationID) {
495,777✔
164
        for _, rel := range relations {
496,582✔
165
                s.isTarget[rel.target.id] = true
805✔
166
        }
805✔
167
}
168

169
func (s *storage) registerFilter(filter *filter, relations []RelationID) cacheID {
34✔
170
        return s.cache.register(s, filter, relations)
34✔
171
}
34✔
172

173
func (s *storage) unregisterFilter(entry cacheID) {
29✔
174
        s.cache.unregister(entry)
29✔
175
}
29✔
176

177
func (s *storage) getRegisteredFilter(id cacheID) *cacheEntry {
30✔
178
        return s.cache.getEntry(id)
30✔
179
}
30✔
180

181
func (s *storage) createEntity(table tableID) (Entity, uint32) {
495,031✔
182
        entity := s.entityPool.Get()
495,031✔
183

495,031✔
184
        idx := s.tables[table].Add(entity)
495,031✔
185
        len := len(s.entities)
495,031✔
186
        if int(entity.id) == len {
499,682✔
187
                s.entities = append(s.entities, entityIndex{table: table, row: idx})
4,651✔
188
                s.isTarget = append(s.isTarget, false)
4,651✔
189
        } else {
495,031✔
190
                s.entities[entity.id] = entityIndex{table: table, row: idx}
490,380✔
191
        }
490,380✔
192
        return entity, idx
495,031✔
193
}
194

195
func (s *storage) createEntities(table *table, count int) {
195✔
196
        startIdx := table.Len()
195✔
197
        table.Alloc(uint32(count))
195✔
198

195✔
199
        len := len(s.entities)
195✔
200
        for i := range count {
3,846✔
201
                index := uint32(startIdx + i)
3,651✔
202
                entity := s.entityPool.Get()
3,651✔
203
                table.SetEntity(index, entity)
3,651✔
204

3,651✔
205
                if int(entity.id) == len {
7,076✔
206
                        s.entities = append(s.entities, entityIndex{table: table.id, row: index})
3,425✔
207
                        s.isTarget = append(s.isTarget, false)
3,425✔
208
                        len++
3,425✔
209
                } else {
3,651✔
210
                        s.entities[entity.id] = entityIndex{table: table.id, row: index}
226✔
211
                }
226✔
212
        }
213
}
214

215
func (s *storage) createArchetype(node *node) *archetype {
479✔
216
        comps := node.mask.toTypes(&s.registry.registry)
479✔
217
        index := len(s.archetypes)
479✔
218
        s.archetypes = append(s.archetypes, newArchetype(archetypeID(index), node.id, &node.mask, comps, nil, &s.registry))
479✔
219
        archetype := &s.archetypes[index]
479✔
220
        if archetype.HasRelations() {
537✔
221
                s.relationArchetypes = append(s.relationArchetypes, archetype.id)
58✔
222
        }
58✔
223
        return archetype
479✔
224
}
225

226
func (s *storage) createTable(archetype *archetype, relations []RelationID) *table {
574✔
227
        // TODO: maybe use a pool of slices?
574✔
228
        targets := make([]Entity, len(archetype.components))
574✔
229

574✔
230
        if uint8(len(relations)) < archetype.numRelations {
574✔
231
                // TODO: is there way to trigger this?
×
232
                panic("relation targets must be fully specified")
×
233
        }
234
        for _, rel := range relations {
741✔
235
                idx := archetype.componentsMap[rel.component.id]
167✔
236
                targets[idx] = rel.target
167✔
237
        }
167✔
238
        for i := range relations {
741✔
239
                rel := &relations[i]
167✔
240
                s.checkRelationComponent(rel.component)
167✔
241
                s.checkRelationTarget(rel.target)
167✔
242
        }
167✔
243

244
        var newTableID tableID
574✔
245
        recycled := false
574✔
246
        if id, ok := archetype.GetFreeTable(); ok {
578✔
247
                newTableID = id
4✔
248
                s.tables[newTableID].recycle(targets, relations)
4✔
249
                recycled = true
4✔
250
        } else {
574✔
251
                newTableID = tableID(len(s.tables))
570✔
252
                cap := s.config.initialCapacity
570✔
253
                if archetype.HasRelations() {
719✔
254
                        cap = s.config.initialCapacityRelations
149✔
255
                }
149✔
256
                s.tables = append(s.tables, newTable(
570✔
257
                        newTableID, archetype, uint32(cap), &s.registry,
570✔
258
                        targets, relations))
570✔
259
        }
260
        archetype.AddTable(&s.tables[newTableID])
574✔
261

574✔
262
        table := &s.tables[newTableID]
574✔
263
        if !recycled {
1,144✔
264
                for i := range s.components {
4,050✔
265
                        id := ID{id: uint8(i)}
3,480✔
266
                        comps := &s.components[i]
3,480✔
267
                        if archetype.mask.Get(id) {
5,842✔
268
                                comps.columns = append(comps.columns, table.GetColumn(id))
2,362✔
269
                        } else {
3,480✔
270
                                comps.columns = append(comps.columns, nil)
1,118✔
271
                        }
1,118✔
272
                }
273
        }
274

275
        s.cache.addTable(s, table)
574✔
276
        return table
574✔
277
}
278

279
// Removes empty archetypes that have a target relation to the given entity.
280
func (s *storage) cleanupArchetypes(target Entity) {
12✔
281
        newRelations := []RelationID{}
12✔
282
        for _, arch := range s.relationArchetypes {
31✔
283
                archetype := &s.archetypes[arch]
19✔
284
                len := len(archetype.tables)
19✔
285
                for i := len - 1; i >= 0; i-- {
47✔
286
                        table := &s.tables[archetype.tables[i]]
28✔
287

28✔
288
                        foundTarget := false
28✔
289
                        for _, rel := range table.relationIDs {
64✔
290
                                if rel.target.id == target.id {
50✔
291
                                        newRelations = append(newRelations, RelationID{component: rel.component, target: Entity{}})
14✔
292
                                        foundTarget = true
14✔
293
                                }
14✔
294
                        }
295
                        if !foundTarget {
42✔
296
                                continue
14✔
297
                        }
298

299
                        if table.Len() > 0 {
15✔
300
                                allRelations := s.getExchangeTargetsUnchecked(table, newRelations)
1✔
301
                                newTable, ok := archetype.GetTable(s, allRelations)
1✔
302
                                if !ok {
2✔
303
                                        newTable = s.createTable(archetype, newRelations)
1✔
304
                                }
1✔
305
                                s.moveEntities(table, newTable, uint32(table.Len()))
1✔
306
                        }
307
                        archetype.FreeTable(table.id)
14✔
308
                        s.cache.removeTable(s, table)
14✔
309

14✔
310
                        newRelations = newRelations[:0]
14✔
311
                }
312
                archetype.RemoveTarget(target)
19✔
313
        }
314
}
315

316
// moveEntities moves all entities from src to dst.
317
func (s *storage) moveEntities(src, dst *table, count uint32) {
14✔
318
        oldLen := dst.Len()
14✔
319
        dst.AddAll(src, count)
14✔
320

14✔
321
        newLen := dst.Len()
14✔
322
        newTable := dst.id
14✔
323
        for i := oldLen; i < newLen; i++ {
358✔
324
                entity := dst.GetEntity(uintptr(i))
344✔
325
                s.entities[entity.id] = entityIndex{table: newTable, row: uint32(i)}
344✔
326
        }
344✔
327
        src.Reset()
14✔
328
}
329

330
func (s *storage) getExchangeTargetsUnchecked(oldTable *table, relations []RelationID) []RelationID {
1✔
331
        // TODO: maybe use a pool of slices?
1✔
332
        targets := make([]Entity, len(oldTable.columns))
1✔
333
        for i := range oldTable.columns {
3✔
334
                targets[i] = oldTable.columns[i].target
2✔
335
        }
2✔
336
        for _, rel := range relations {
2✔
337
                column := oldTable.components[rel.component.id]
1✔
338
                if rel.target == targets[column.index] {
1✔
339
                        continue
×
340
                }
341
                targets[column.index] = rel.target
1✔
342
        }
343

344
        result := make([]RelationID, 0, len(oldTable.relationIDs))
1✔
345
        for i, e := range targets {
3✔
346
                if !oldTable.columns[i].isRelation {
3✔
347
                        continue
1✔
348
                }
349
                id := oldTable.ids[i]
1✔
350
                result = append(result, RelationID{component: id, target: e})
1✔
351
        }
352

353
        return result
1✔
354
}
355

356
func (s *storage) getExchangeTargets(oldTable *table, relations []RelationID) ([]RelationID, bool) {
65✔
357
        changed := false
65✔
358
        // TODO: maybe use a pool of slices?
65✔
359
        targets := make([]Entity, len(oldTable.columns))
65✔
360
        for i := range oldTable.columns {
304✔
361
                targets[i] = oldTable.columns[i].target
239✔
362
        }
239✔
363
        for _, rel := range relations {
131✔
364
                // Validity of the target is checked when creating a new table.
66✔
365
                // Whether the component is a relation is checked when creating a new table.
66✔
366
                column := oldTable.components[rel.component.id]
66✔
367
                if column == nil {
67✔
368
                        tp, _ := s.registry.ComponentType(rel.component.id)
1✔
369
                        panic(fmt.Sprintf("entity has no component of type %s to set relation target for", tp.Name()))
1✔
370
                }
371
                if rel.target == targets[column.index] {
66✔
372
                        continue
1✔
373
                }
374
                targets[column.index] = rel.target
64✔
375
                changed = true
64✔
376
        }
377
        if !changed {
65✔
378
                return nil, false
1✔
379
        }
1✔
380

381
        result := make([]RelationID, 0, len(oldTable.relationIDs))
63✔
382
        for i, e := range targets {
297✔
383
                if !oldTable.columns[i].isRelation {
402✔
384
                        continue
168✔
385
                }
386
                id := oldTable.ids[i]
66✔
387
                result = append(result, RelationID{component: id, target: e})
66✔
388
        }
389

390
        return result, true
63✔
391
}
392

393
func (s *storage) getTables(batch *Batch) []*table {
118✔
394
        tables := []*table{}
118✔
395

118✔
396
        if batch.cache != maxCacheID {
119✔
397
                cache := s.getRegisteredFilter(batch.cache)
1✔
398
                for _, tableID := range cache.tables {
3✔
399
                        table := &s.tables[tableID]
2✔
400
                        if table.Len() == 0 {
3✔
401
                                continue
1✔
402
                        }
403
                        if !table.Matches(batch.relations) {
1✔
404
                                continue
×
405
                        }
406
                        tables = append(tables, table)
1✔
407
                }
408
                return tables
1✔
409
        }
410

411
        for i := range s.archetypes {
543✔
412
                archetype := &s.archetypes[i]
426✔
413
                if !batch.filter.matches(archetype.mask) {
626✔
414
                        continue
200✔
415
                }
416

417
                if !archetype.HasRelations() {
434✔
418
                        table := &s.tables[archetype.tables[0]]
208✔
419
                        tables = append(tables, table)
208✔
420
                        continue
208✔
421
                }
422

423
                tableIDs := archetype.GetTables(batch.relations)
18✔
424
                for _, tab := range tableIDs {
42✔
425
                        table := &s.tables[tab]
24✔
426
                        if !table.Matches(batch.relations) {
24✔
427
                                continue
×
428
                        }
429
                        tables = append(tables, table)
24✔
430
                }
431
        }
432
        return tables
117✔
433
}
434

435
func (s *storage) getTableIDs(filter *filter, relations []RelationID) []tableID {
36✔
436
        tables := []tableID{}
36✔
437

36✔
438
        for i := range s.archetypes {
108✔
439
                archetype := &s.archetypes[i]
72✔
440
                if !filter.matches(archetype.mask) {
109✔
441
                        continue
37✔
442
                }
443

444
                if !archetype.HasRelations() {
45✔
445
                        tables = append(tables, archetype.tables[0])
10✔
446
                        continue
10✔
447
                }
448

449
                tableIDs := archetype.GetTables(relations)
25✔
450
                for _, tab := range tableIDs {
84✔
451
                        table := &s.tables[tab]
59✔
452
                        if !table.Matches(relations) {
59✔
453
                                continue
×
454
                        }
455
                        tables = append(tables, tab)
59✔
456
                }
457
        }
458
        return tables
36✔
459
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc