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

mlange-42 / ark / 13898493716

17 Mar 2025 11:37AM CUT coverage: 99.782%. Remained the same
13898493716

push

github

web-flow
Update how to cite (#209)

8244 of 8262 relevant lines covered (99.78%)

20288.75 hits per line

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

97.58
/ecs/storage.go
1
package ecs
2

3
import (
4
        "unsafe"
5
)
6

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

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

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

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

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

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

499,606✔
61
        node := s.graph.Find(startNode, add, remove, outMask)
499,606✔
62
        var arch *archetype
499,606✔
63
        if archID, ok := node.GetArchetype(); ok {
998,733✔
64
                arch = &s.archetypes[archID]
499,127✔
65
        } else {
499,606✔
66
                arch = s.createArchetype(node)
479✔
67
                node.archetype = arch.id
479✔
68
        }
479✔
69

70
        var allRelations []RelationID
499,606✔
71
        if len(relations) > 0 {
500,291✔
72
                allRelations = appendNew(oldTable.relationIDs, relations...)
685✔
73
        } else {
499,606✔
74
                allRelations = oldTable.relationIDs
498,921✔
75
        }
498,921✔
76
        table, ok := arch.GetTable(s, allRelations)
499,606✔
77
        if !ok {
500,149✔
78
                table = s.createTable(arch, allRelations)
543✔
79
        }
543✔
80
        return table
499,605✔
81
}
82

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

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

496,913✔
98
        swapped := table.Remove(index.row)
496,913✔
99

496,913✔
100
        s.entityPool.Recycle(entity)
496,913✔
101

496,913✔
102
        if swapped {
992,224✔
103
                swapEntity := table.GetEntity(uintptr(index.row))
495,311✔
104
                s.entities[swapEntity.id].row = index.row
495,311✔
105
        }
495,311✔
106
        index.table = maxTableID
496,913✔
107

496,913✔
108
        if s.isTarget[entity.id] {
496,916✔
109
                s.cleanupArchetypes(entity)
3✔
110
                s.isTarget[entity.id] = false
3✔
111
        }
3✔
112
}
113

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

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

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

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

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

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

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

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

162
func (s *storage) registerTargets(relations []RelationID) {
499,667✔
163
        for _, rel := range relations {
500,471✔
164
                s.isTarget[rel.target.id] = true
804✔
165
        }
804✔
166
}
167

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

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

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

180
func (s *storage) createEntity(table tableID) (Entity, uint32) {
498,923✔
181
        entity := s.entityPool.Get()
498,923✔
182

498,923✔
183
        idx := s.tables[table].Add(entity)
498,923✔
184
        len := len(s.entities)
498,923✔
185
        if int(entity.id) == len {
504,211✔
186
                s.entities = append(s.entities, entityIndex{table: table, row: idx})
5,288✔
187
                s.isTarget = append(s.isTarget, false)
5,288✔
188
        } else {
498,923✔
189
                s.entities[entity.id] = entityIndex{table: table, row: idx}
493,635✔
190
        }
493,635✔
191
        return entity, idx
498,923✔
192
}
193

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

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

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

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

225
func (s *storage) createTable(archetype *archetype, relations []RelationID) *table {
574✔
226
        targets := make([]Entity, len(archetype.components))
574✔
227
        numRelations := uint8(0)
574✔
228
        for _, rel := range relations {
741✔
229
                idx := archetype.componentsMap[rel.component.id]
167✔
230
                targets[idx] = rel.target
167✔
231
                numRelations++
167✔
232
        }
167✔
233
        if numRelations != archetype.numRelations {
574✔
234
                panic("relations must be fully specified")
×
235
        }
236
        for i := range relations {
741✔
237
                rel := &relations[i]
167✔
238
                s.checkRelationComponent(rel.component)
167✔
239
                s.checkRelationTarget(rel.target)
167✔
240
        }
167✔
241

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

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

273
        s.cache.addTable(s, table)
574✔
274
        return table
574✔
275
}
276

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

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

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

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

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

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

328
func (s *storage) getExchangeTargetsUnchecked(oldTable *table, relations []RelationID) []RelationID {
1✔
329
        targets := make([]Entity, len(oldTable.columns))
1✔
330
        for i := range oldTable.columns {
3✔
331
                targets[i] = oldTable.columns[i].target
2✔
332
        }
2✔
333
        for _, rel := range relations {
2✔
334
                column := oldTable.components[rel.component.id]
1✔
335
                if rel.target == targets[column.index] {
1✔
336
                        continue
×
337
                }
338
                targets[column.index] = rel.target
1✔
339
        }
340

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

350
        return result
1✔
351
}
352

353
func (s *storage) getExchangeTargets(oldTable *table, relations []RelationID) ([]RelationID, bool) {
62✔
354
        changed := false
62✔
355
        targets := make([]Entity, len(oldTable.columns))
62✔
356
        for i := range oldTable.columns {
293✔
357
                targets[i] = oldTable.columns[i].target
231✔
358
        }
231✔
359
        for _, rel := range relations {
125✔
360
                // Validity of the target is checked when creating a new table.
63✔
361
                // Whether the component is a relation is checked when creating a new table.
63✔
362
                column := oldTable.components[rel.component.id]
63✔
363
                if rel.target == targets[column.index] {
63✔
364
                        continue
×
365
                }
366
                targets[column.index] = rel.target
63✔
367
                changed = true
63✔
368
        }
369
        if !changed {
62✔
370
                return nil, false
×
371
        }
×
372

373
        result := make([]RelationID, 0, len(oldTable.relationIDs))
62✔
374
        for i, e := range targets {
293✔
375
                if !oldTable.columns[i].isRelation {
398✔
376
                        continue
167✔
377
                }
378
                id := oldTable.ids[i]
64✔
379
                result = append(result, RelationID{component: id, target: e})
64✔
380
        }
381

382
        return result, true
62✔
383
}
384

385
func (s *storage) getTables(batch *Batch) []*table {
118✔
386
        tables := []*table{}
118✔
387

118✔
388
        if batch.cache != maxCacheID {
119✔
389
                cache := s.getRegisteredFilter(batch.cache)
1✔
390
                for _, tableID := range cache.tables {
3✔
391
                        table := &s.tables[tableID]
2✔
392
                        if table.Len() == 0 {
3✔
393
                                continue
1✔
394
                        }
395
                        if !table.Matches(batch.relations) {
1✔
396
                                continue
×
397
                        }
398
                        tables = append(tables, table)
1✔
399
                }
400
                return tables
1✔
401
        }
402

403
        for i := range s.archetypes {
543✔
404
                archetype := &s.archetypes[i]
426✔
405
                if !batch.filter.matches(&archetype.mask) {
626✔
406
                        continue
200✔
407
                }
408

409
                if !archetype.HasRelations() {
434✔
410
                        table := &s.tables[archetype.tables[0]]
208✔
411
                        tables = append(tables, table)
208✔
412
                        continue
208✔
413
                }
414

415
                tableIDs := archetype.GetTables(batch.relations)
18✔
416
                for _, tab := range tableIDs {
42✔
417
                        table := &s.tables[tab]
24✔
418
                        if !table.Matches(batch.relations) {
24✔
419
                                continue
×
420
                        }
421
                        tables = append(tables, table)
24✔
422
                }
423
        }
424
        return tables
117✔
425
}
426

427
func (s *storage) getTableIDs(filter *filter, relations []RelationID) []tableID {
36✔
428
        tables := []tableID{}
36✔
429

36✔
430
        for i := range s.archetypes {
108✔
431
                archetype := &s.archetypes[i]
72✔
432
                if !filter.matches(&archetype.mask) {
109✔
433
                        continue
37✔
434
                }
435

436
                if !archetype.HasRelations() {
45✔
437
                        tables = append(tables, archetype.tables[0])
10✔
438
                        continue
10✔
439
                }
440

441
                tableIDs := archetype.GetTables(relations)
25✔
442
                for _, tab := range tableIDs {
84✔
443
                        table := &s.tables[tab]
59✔
444
                        if !table.Matches(relations) {
59✔
445
                                continue
×
446
                        }
447
                        tables = append(tables, tab)
59✔
448
                }
449
        }
450
        return tables
36✔
451
}
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