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

mlange-42 / ark / 13686913763

05 Mar 2025 10:35PM CUT coverage: 99.319%. Remained the same
13686913763

Pull #141

github

web-flow
Merge fb410149c into 2db7135fb
Pull Request #141: Add benchmark tables to user guide

5838 of 5878 relevant lines covered (99.32%)

34358.7 hits per line

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

97.83
/ecs/storage.go
1
package ecs
2

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

8
type storage struct {
9
        config     config
10
        registry   componentRegistry
11
        entities   []entityIndex
12
        isTarget   []bool
13
        entityPool entityPool
14
        graph      graph
15
        cache      cache
16

17
        archetypes         []archetype
18
        relationArchetypes []archetypeID
19
        tables             []table
20
        components         []componentStorage
21
}
22

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

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

196✔
30
        reg := newComponentRegistry()
196✔
31
        entities := make([]entityIndex, reservedEntities, config.initialCapacity+reservedEntities)
196✔
32
        isTarget := make([]bool, reservedEntities, config.initialCapacity+reservedEntities)
196✔
33
        // Reserved zero and wildcard entities
196✔
34
        for i := range reservedEntities {
588✔
35
                entities[i] = entityIndex{table: maxTableID, row: 0}
392✔
36
        }
392✔
37
        componentsMap := make([]int16, MaskTotalBits)
196✔
38
        for i := range MaskTotalBits {
50,372✔
39
                componentsMap[i] = -1
50,176✔
40
        }
50,176✔
41

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

60
func (s *storage) findOrCreateTable(oldTable *table, add []ID, remove []ID, relations []RelationID) *table {
514,279✔
61
        startNode := s.archetypes[oldTable.archetype].node
514,279✔
62

514,279✔
63
        node := s.graph.Find(startNode, add, remove)
514,279✔
64
        var arch *archetype
514,279✔
65
        if archID, ok := node.GetArchetype(); ok {
1,028,165✔
66
                arch = &s.archetypes[archID]
513,886✔
67
        } else {
514,279✔
68
                arch = s.createArchetype(node)
393✔
69
                node.archetype = arch.id
393✔
70
        }
393✔
71

72
        allRelation := appendNew(oldTable.relationIDs, relations...)
514,279✔
73
        table, ok := arch.GetTable(s, allRelation)
514,279✔
74
        if !ok {
514,727✔
75
                table = s.createTable(arch, allRelation)
448✔
76
        }
448✔
77
        return table
514,279✔
78
}
79

80
func (s *storage) AddComponent(id uint8) {
892✔
81
        if len(s.components) != int(id) {
893✔
82
                panic("components can only be added to a storage sequentially")
1✔
83
        }
84
        s.components = append(s.components, componentStorage{columns: make([]*column, len(s.tables))})
891✔
85
}
86

87
// RemoveEntity removes the given entity from the world.
88
func (s *storage) RemoveEntity(entity Entity) {
512,308✔
89
        if !s.entityPool.Alive(entity) {
512,309✔
90
                panic("can't remove a dead entity")
1✔
91
        }
92
        index := &s.entities[entity.id]
512,307✔
93
        table := &s.tables[index.table]
512,307✔
94

512,307✔
95
        swapped := table.Remove(index.row)
512,307✔
96

512,307✔
97
        s.entityPool.Recycle(entity)
512,307✔
98

512,307✔
99
        if swapped {
1,023,304✔
100
                swapEntity := table.GetEntity(uintptr(index.row))
510,997✔
101
                s.entities[swapEntity.id].row = index.row
510,997✔
102
        }
510,997✔
103
        index.table = maxTableID
512,307✔
104

512,307✔
105
        if s.isTarget[entity.id] {
512,310✔
106
                s.cleanupArchetypes(entity)
3✔
107
                s.isTarget[entity.id] = false
3✔
108
        }
3✔
109
}
110

111
func (s *storage) Reset() {
1✔
112
        s.entities = s.entities[:reservedEntities]
1✔
113
        s.entityPool.Reset()
1✔
114
        s.isTarget = s.isTarget[:reservedEntities]
1✔
115
        s.cache.Reset()
1✔
116

1✔
117
        for i := range s.archetypes {
5✔
118
                s.archetypes[i].Reset(s)
4✔
119
        }
4✔
120
}
121

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

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

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

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

148
func (s *storage) getRelation(entity Entity, comp ID) Entity {
347✔
149
        if !s.entityPool.Alive(entity) {
348✔
150
                panic("can't get relation for a dead entity")
1✔
151
        }
152
        return s.getRelationUnchecked(entity, comp)
346✔
153
}
154

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

160
func (s *storage) registerTargets(relations []RelationID) {
514,333✔
161
        for _, rel := range relations {
515,087✔
162
                s.isTarget[rel.target.id] = true
754✔
163
        }
754✔
164
}
165

166
func (s *storage) registerFilter(batch *Batch) cacheID {
31✔
167
        return s.cache.register(s, batch)
31✔
168
}
31✔
169

170
func (s *storage) unregisterFilter(entry cacheID) {
28✔
171
        s.cache.unregister(entry)
28✔
172
}
28✔
173

174
func (s *storage) getRegisteredFilter(id cacheID) *cacheEntry {
28✔
175
        return s.cache.getEntry(id)
28✔
176
}
28✔
177

178
func (s *storage) createEntity(table tableID) (Entity, uint32) {
513,736✔
179
        entity := s.entityPool.Get()
513,736✔
180

513,736✔
181
        idx := s.tables[table].Add(entity)
513,736✔
182
        len := len(s.entities)
513,736✔
183
        if int(entity.id) == len {
518,803✔
184
                s.entities = append(s.entities, entityIndex{table: table, row: idx})
5,067✔
185
                s.isTarget = append(s.isTarget, false)
5,067✔
186
        } else {
513,736✔
187
                s.entities[entity.id] = entityIndex{table: table, row: idx}
508,669✔
188
        }
508,669✔
189
        return entity, idx
513,736✔
190
}
191

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

144✔
196
        len := len(s.entities)
144✔
197
        for i := range count {
2,398✔
198
                index := uint32(startIdx + i)
2,254✔
199
                entity := s.entityPool.Get()
2,254✔
200
                table.SetEntity(index, entity)
2,254✔
201

2,254✔
202
                if int(entity.id) == len {
4,492✔
203
                        s.entities = append(s.entities, entityIndex{table: table.id, row: index})
2,238✔
204
                        s.isTarget = append(s.isTarget, false)
2,238✔
205
                        len++
2,238✔
206
                } else {
2,254✔
207
                        s.entities[entity.id] = entityIndex{table: table.id, row: index}
16✔
208
                }
16✔
209
        }
210
}
211

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

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

240
        var newTableID tableID
471✔
241
        if id, ok := archetype.GetFreeTable(); ok {
473✔
242
                newTableID = id
2✔
243
                s.tables[newTableID].recycle(targets, relations)
2✔
244
        } else {
471✔
245
                newTableID = tableID(len(s.tables))
469✔
246
                cap := s.config.initialCapacity
469✔
247
                if archetype.HasRelations() {
594✔
248
                        cap = s.config.initialCapacityRelations
125✔
249
                }
125✔
250
                s.tables = append(s.tables, newTable(
469✔
251
                        newTableID, archetype.id, uint32(cap), &s.registry,
469✔
252
                        archetype.components, archetype.componentsMap,
469✔
253
                        archetype.isRelation, targets, relations))
469✔
254
        }
255
        archetype.AddTable(&s.tables[newTableID])
471✔
256

471✔
257
        table := &s.tables[newTableID]
471✔
258
        for i := range s.components {
3,000✔
259
                id := ID{id: uint8(i)}
2,529✔
260
                comps := &s.components[i]
2,529✔
261
                if archetype.mask.Get(id) {
4,247✔
262
                        comps.columns = append(comps.columns, table.GetColumn(id))
1,718✔
263
                } else {
2,529✔
264
                        comps.columns = append(comps.columns, nil)
811✔
265
                }
811✔
266
        }
267

268
        s.cache.addTable(s, table)
471✔
269
        return table
471✔
270
}
271

272
func (s *storage) getExchangeMask(mask *Mask, add []ID, rem []ID) {
809✔
273
        for _, comp := range rem {
2,009✔
274
                if !mask.Get(comp) {
1,201✔
275
                        panic(fmt.Sprintf("entity does not have a component of type %v, can't remove", s.registry.Types[comp.id]))
1✔
276
                }
277
                mask.Set(comp, false)
1,199✔
278
        }
279
        for _, comp := range add {
1,990✔
280
                if mask.Get(comp) {
1,183✔
281
                        panic(fmt.Sprintf("entity already has component of type %v, can't add", s.registry.Types[comp.id]))
1✔
282
                }
283
                mask.Set(comp, true)
1,181✔
284
        }
285
}
286

287
// Removes empty archetypes that have a target relation to the given entity.
288
func (s *storage) cleanupArchetypes(target Entity) {
6✔
289
        newRelations := []RelationID{}
6✔
290
        for _, arch := range s.relationArchetypes {
19✔
291
                archetype := &s.archetypes[arch]
13✔
292
                len := len(archetype.tables)
13✔
293
                for i := len - 1; i >= 0; i-- {
33✔
294
                        table := &s.tables[archetype.tables[i]]
20✔
295

20✔
296
                        foundTarget := false
20✔
297
                        for _, rel := range table.relationIDs {
40✔
298
                                if rel.target.id == target.id {
29✔
299
                                        newRelations = append(newRelations, RelationID{component: rel.component, target: Entity{}})
9✔
300
                                        foundTarget = true
9✔
301
                                }
9✔
302
                        }
303
                        if !foundTarget {
31✔
304
                                continue
11✔
305
                        }
306

307
                        if table.Len() > 0 {
10✔
308
                                allRelations := s.getExchangeTargetsUnchecked(table, newRelations)
1✔
309
                                newTable, ok := archetype.GetTable(s, allRelations)
1✔
310
                                if !ok {
2✔
311
                                        newTable = s.createTable(archetype, newRelations)
1✔
312
                                }
1✔
313
                                s.moveEntities(table, newTable, uint32(table.Len()))
1✔
314
                        }
315
                        archetype.FreeTable(table.id)
9✔
316
                        s.cache.removeTable(s, table)
9✔
317

9✔
318
                        newRelations = newRelations[:0]
9✔
319
                }
320
                archetype.RemoveTarget(target)
13✔
321
        }
322
}
323

324
// moveEntities moves all entities from src to dst.
325
func (s *storage) moveEntities(src, dst *table, count uint32) {
10✔
326
        oldLen := dst.Len()
10✔
327
        dst.AddAll(src, count)
10✔
328

10✔
329
        newLen := dst.Len()
10✔
330
        newTable := dst.id
10✔
331
        for i := oldLen; i < newLen; i++ {
258✔
332
                entity := dst.GetEntity(uintptr(i))
248✔
333
                s.entities[entity.id] = entityIndex{table: newTable, row: uint32(i)}
248✔
334
        }
248✔
335
        src.Reset()
10✔
336
}
337

338
func (s *storage) getExchangeTargetsUnchecked(oldTable *table, relations []RelationID) []RelationID {
1✔
339
        targets := make([]Entity, len(oldTable.columns))
1✔
340
        for i := range oldTable.columns {
3✔
341
                targets[i] = oldTable.columns[i].target
2✔
342
        }
2✔
343
        for _, rel := range relations {
2✔
344
                index := oldTable.components[rel.component.id]
1✔
345
                if rel.target == targets[index] {
1✔
346
                        continue
×
347
                }
348
                targets[index] = rel.target
1✔
349
        }
350

351
        result := make([]RelationID, 0, len(oldTable.relationIDs))
1✔
352
        for i, e := range targets {
3✔
353
                if !oldTable.columns[i].isRelation {
3✔
354
                        continue
1✔
355
                }
356
                id := oldTable.ids[i]
1✔
357
                result = append(result, RelationID{component: id, target: e})
1✔
358
        }
359

360
        return result
1✔
361
}
362

363
func (s *storage) getExchangeTargets(oldTable *table, relations []RelationID) ([]RelationID, bool) {
54✔
364
        changed := false
54✔
365
        targets := make([]Entity, len(oldTable.columns))
54✔
366
        for i := range oldTable.columns {
201✔
367
                targets[i] = oldTable.columns[i].target
147✔
368
        }
147✔
369
        for _, rel := range relations {
109✔
370
                // Validity of the target is checked when creating a new table.
55✔
371
                // Whether the component is a relation is checked when creating a new table.
55✔
372
                index := oldTable.components[rel.component.id]
55✔
373
                if rel.target == targets[index] {
55✔
374
                        continue
×
375
                }
376
                targets[index] = rel.target
55✔
377
                changed = true
55✔
378
        }
379
        if !changed {
54✔
380
                return nil, false
×
381
        }
×
382

383
        result := make([]RelationID, 0, len(oldTable.relationIDs))
54✔
384
        for i, e := range targets {
201✔
385
                if !oldTable.columns[i].isRelation {
238✔
386
                        continue
91✔
387
                }
388
                id := oldTable.ids[i]
56✔
389
                result = append(result, RelationID{component: id, target: e})
56✔
390
        }
391

392
        return result, true
54✔
393
}
394

395
func (s *storage) getTables(batch *Batch) []*table {
91✔
396
        tables := []*table{}
91✔
397

91✔
398
        for i := range s.archetypes {
422✔
399
                archetype := &s.archetypes[i]
331✔
400
                if !batch.filter.matches(&archetype.mask) {
486✔
401
                        continue
155✔
402
                }
403

404
                if !archetype.HasRelations() {
340✔
405
                        table := &s.tables[archetype.tables[0]]
164✔
406
                        tables = append(tables, table)
164✔
407
                        continue
164✔
408
                }
409

410
                tableIDs := archetype.GetTables(batch.relations)
12✔
411
                for _, tab := range tableIDs {
27✔
412
                        table := &s.tables[tab]
15✔
413
                        if !table.Matches(batch.relations) {
15✔
414
                                continue
×
415
                        }
416
                        tables = append(tables, table)
15✔
417
                }
418
        }
419
        return tables
91✔
420
}
421

422
func (s *storage) getTableIDs(batch *Batch) []tableID {
33✔
423
        tables := []tableID{}
33✔
424

33✔
425
        for i := range s.archetypes {
99✔
426
                archetype := &s.archetypes[i]
66✔
427
                if !batch.filter.matches(&archetype.mask) {
100✔
428
                        continue
34✔
429
                }
430

431
                if !archetype.HasRelations() {
39✔
432
                        tables = append(tables, archetype.tables[0])
7✔
433
                        continue
7✔
434
                }
435

436
                tableIDs := archetype.GetTables(batch.relations)
25✔
437
                for _, tab := range tableIDs {
84✔
438
                        table := &s.tables[tab]
59✔
439
                        if !table.Matches(batch.relations) {
59✔
440
                                continue
×
441
                        }
442
                        tables = append(tables, tab)
59✔
443
                }
444
        }
445
        return tables
33✔
446
}
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