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

mlange-42 / ark / 13931462316

18 Mar 2025 07:06PM CUT coverage: 99.782%. Remained the same
13931462316

Pull #212

github

web-flow
Merge 9f2ebf72e into d6493674d
Pull Request #212: Fix removing relationship components

11 of 12 new or added lines in 3 files covered. (91.67%)

7 existing lines in 1 file now uncovered.

8251 of 8269 relevant lines covered (99.78%)

20742.54 hits per line

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

97.6
/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 {
511,211✔
60
        startNode := s.archetypes[oldTable.archetype].node
511,211✔
61

511,211✔
62
        node := s.graph.Find(startNode, add, remove, outMask)
511,211✔
63
        var arch *archetype
511,211✔
64
        if archID, ok := node.GetArchetype(); ok {
1,021,943✔
65
                arch = &s.archetypes[archID]
510,732✔
66
        } else {
511,211✔
67
                arch = s.createArchetype(node)
479✔
68
                node.archetype = arch.id
479✔
69
        }
479✔
70

71
        var allRelations []RelationID
511,211✔
72
        if len(relations) > 0 {
511,896✔
73
                allRelations = appendNew(oldTable.relationIDs, relations...)
685✔
74
        } else {
511,211✔
75
                allRelations = oldTable.relationIDs
510,526✔
76
        }
510,526✔
77
        table, ok := arch.GetTable(s, allRelations)
511,211✔
78
        if !ok {
511,754✔
79
                table = s.createTable(arch, allRelations)
543✔
80
        }
543✔
81
        return table
511,210✔
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) {
508,073✔
93
        if !s.entityPool.Alive(entity) {
508,074✔
94
                panic("can't remove a dead entity")
1✔
95
        }
96
        index := &s.entities[entity.id]
508,072✔
97
        table := &s.tables[index.table]
508,072✔
98

508,072✔
99
        swapped := table.Remove(index.row)
508,072✔
100

508,072✔
101
        s.entityPool.Recycle(entity)
508,072✔
102

508,072✔
103
        if swapped {
1,014,610✔
104
                swapEntity := table.GetEntity(uintptr(index.row))
506,538✔
105
                s.entities[swapEntity.id].row = index.row
506,538✔
106
        }
506,538✔
107
        index.table = maxTableID
508,072✔
108

508,072✔
109
        if s.isTarget[entity.id] {
508,075✔
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 {
455✔
152
        if !s.entityPool.Alive(entity) {
456✔
153
                panic("can't get relation for a dead entity")
1✔
154
        }
155
        return s.getRelationUnchecked(entity, comp)
454✔
156
}
157

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

163
func (s *storage) registerTargets(relations []RelationID) {
511,272✔
164
        for _, rel := range relations {
512,076✔
165
                s.isTarget[rel.target.id] = true
804✔
166
        }
804✔
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) {
510,527✔
182
        entity := s.entityPool.Get()
510,527✔
183

510,527✔
184
        idx := s.tables[table].Add(entity)
510,527✔
185
        len := len(s.entities)
510,527✔
186
        if int(entity.id) == len {
515,680✔
187
                s.entities = append(s.entities, entityIndex{table: table, row: idx})
5,153✔
188
                s.isTarget = append(s.isTarget, false)
5,153✔
189
        } else {
510,527✔
190
                s.entities[entity.id] = entityIndex{table: table, row: idx}
505,374✔
191
        }
505,374✔
192
        return entity, idx
510,527✔
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
        targets := make([]Entity, len(archetype.components))
574✔
228
        numRelations := uint8(0)
574✔
229
        for _, rel := range relations {
741✔
230
                idx := archetype.componentsMap[rel.component.id]
167✔
231
                targets[idx] = rel.target
167✔
232
                numRelations++
167✔
233
        }
167✔
234
        if numRelations < archetype.numRelations {
574✔
NEW
UNCOV
235
                panic("relation targets must be fully specified")
×
236
        }
237
        for i := range relations {
741✔
238
                rel := &relations[i]
167✔
239
                s.checkRelationComponent(rel.component)
167✔
240
                s.checkRelationTarget(rel.target)
167✔
241
        }
167✔
242

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

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

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

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

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

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

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

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

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

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

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

351
        return result
1✔
352
}
353

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

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

387
        return result, true
62✔
388
}
389

390
func (s *storage) getTables(batch *Batch) []*table {
118✔
391
        tables := []*table{}
118✔
392

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

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

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

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

432
func (s *storage) getTableIDs(filter *filter, relations []RelationID) []tableID {
36✔
433
        tables := []tableID{}
36✔
434

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

441
                if !archetype.HasRelations() {
45✔
442
                        tables = append(tables, archetype.tables[0])
10✔
443
                        continue
10✔
444
                }
445

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