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

mlange-42 / ark / 13662837233

04 Mar 2025 09:00PM CUT coverage: 99.28%. Remained the same
13662837233

push

github

web-flow
User guide chapter on unsafe API (#127)

5788 of 5830 relevant lines covered (99.28%)

34813.73 hits per line

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

97.19
/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 {
195✔
28
        config := newConfig(capacity...)
195✔
29

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

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

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

505,691✔
63
        node := s.graph.Find(startNode, add, remove)
505,691✔
64
        var arch *archetype
505,691✔
65
        if archID, ok := node.GetArchetype(); ok {
1,010,989✔
66
                arch = &s.archetypes[archID]
505,298✔
67
        } else {
505,691✔
68
                arch = s.createArchetype(node)
393✔
69
                node.archetype = arch.id
393✔
70
        }
393✔
71

72
        allRelation := appendNew(oldTable.relationIDs, relations...)
505,691✔
73
        table, ok := arch.GetTable(s, allRelation)
505,691✔
74
        if !ok {
506,139✔
75
                table = s.createTable(arch, allRelation)
448✔
76
        }
448✔
77
        return table
505,691✔
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) {
503,541✔
89
        if !s.entityPool.Alive(entity) {
503,542✔
90
                panic("can't remove a dead entity")
1✔
91
        }
92
        index := &s.entities[entity.id]
503,540✔
93
        table := &s.tables[index.table]
503,540✔
94

503,540✔
95
        swapped := table.Remove(index.row)
503,540✔
96

503,540✔
97
        s.entityPool.Recycle(entity)
503,540✔
98

503,540✔
99
        if swapped {
1,005,851✔
100
                swapEntity := table.GetEntity(uintptr(index.row))
502,311✔
101
                s.entities[swapEntity.id].row = index.row
502,311✔
102
        }
502,311✔
103
        index.table = maxTableID
503,540✔
104

503,540✔
105
        if s.isTarget[entity.id] {
503,543✔
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 {
346✔
149
        if !s.entityPool.Alive(entity) {
347✔
150
                panic("can't get relation for a dead entity")
1✔
151
        }
152
        return s.getRelationUnchecked(entity, comp)
345✔
153
}
154

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

160
func (s *storage) registerTargets(relations []RelationID) {
505,744✔
161
        for _, rel := range relations {
506,497✔
162
                s.isTarget[rel.target.id] = true
753✔
163
        }
753✔
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) {
505,149✔
179
        entity := s.entityPool.Get()
505,149✔
180

505,149✔
181
        idx := s.tables[table].Add(entity)
505,149✔
182
        len := len(s.entities)
505,149✔
183
        if int(entity.id) == len {
510,180✔
184
                s.entities = append(s.entities, entityIndex{table: table, row: idx})
5,031✔
185
                s.isTarget = append(s.isTarget, false)
5,031✔
186
        } else {
505,149✔
187
                s.entities[entity.id] = entityIndex{table: table, row: idx}
500,118✔
188
        }
500,118✔
189
        return entity, idx
505,149✔
190
}
191

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

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

2,054✔
202
                if int(entity.id) == len {
4,092✔
203
                        s.entities = append(s.entities, entityIndex{table: table.id, row: index})
2,038✔
204
                        s.isTarget = append(s.isTarget, false)
2,038✔
205
                        len++
2,038✔
206
                } else {
2,054✔
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 {
470✔
224
        targets := make([]Entity, len(archetype.components))
470✔
225
        numRelations := uint8(0)
470✔
226
        for _, rel := range relations {
604✔
227
                idx := archetype.componentsMap[rel.component.id]
134✔
228
                targets[idx] = rel.target
134✔
229
                numRelations++
134✔
230
        }
134✔
231
        if numRelations != archetype.numRelations {
470✔
232
                panic("relations must be fully specified")
×
233
        }
234

235
        var newTableID tableID
470✔
236
        if id, ok := archetype.GetFreeTable(); ok {
472✔
237
                newTableID = id
2✔
238
                s.tables[newTableID].recycle(targets, relations)
2✔
239
        } else {
470✔
240
                newTableID = tableID(len(s.tables))
468✔
241
                cap := s.config.initialCapacity
468✔
242
                if archetype.HasRelations() {
592✔
243
                        cap = s.config.initialCapacityRelations
124✔
244
                }
124✔
245
                s.tables = append(s.tables, newTable(
468✔
246
                        newTableID, archetype.id, uint32(cap), &s.registry,
468✔
247
                        archetype.components, archetype.componentsMap,
468✔
248
                        archetype.isRelation, targets, relations))
468✔
249
        }
250
        archetype.AddTable(&s.tables[newTableID])
470✔
251

470✔
252
        table := &s.tables[newTableID]
470✔
253
        for i := range s.components {
2,998✔
254
                id := ID{id: uint8(i)}
2,528✔
255
                comps := &s.components[i]
2,528✔
256
                if archetype.mask.Get(id) {
4,245✔
257
                        comps.columns = append(comps.columns, table.GetColumn(id))
1,717✔
258
                } else {
2,528✔
259
                        comps.columns = append(comps.columns, nil)
811✔
260
                }
811✔
261
        }
262

263
        s.cache.addTable(s, table)
470✔
264
        return table
470✔
265
}
266

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

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

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

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

9✔
313
                        newRelations = newRelations[:0]
9✔
314
                }
315
                archetype.RemoveTarget(target)
13✔
316
        }
317
}
318

319
// moveEntities moves all entities from src to dst.
320
func (s *storage) moveEntities(src, dst *table, count uint32) {
10✔
321
        oldLen := dst.Len()
10✔
322
        dst.AddAll(src, count)
10✔
323

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

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

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

355
        return result
1✔
356
}
357

358
func (s *storage) getExchangeTargets(oldTable *table, relations []RelationID) ([]RelationID, bool) {
53✔
359
        changed := false
53✔
360
        targets := make([]Entity, len(oldTable.columns))
53✔
361
        for i := range oldTable.columns {
199✔
362
                targets[i] = oldTable.columns[i].target
146✔
363
        }
146✔
364
        for _, rel := range relations {
107✔
365
                if !rel.target.IsZero() && !s.entityPool.Alive(rel.target) {
54✔
366
                        panic("can't make a dead entity a relation target")
×
367
                }
368
                index := oldTable.components[rel.component.id]
54✔
369
                if !oldTable.columns[index].isRelation {
54✔
370
                        panic(fmt.Sprintf("component %d is not a relation component", rel.component.id))
×
371
                }
372
                if rel.target == targets[index] {
54✔
373
                        continue
×
374
                }
375
                targets[index] = rel.target
54✔
376
                changed = true
54✔
377
        }
378
        if !changed {
53✔
379
                return nil, false
×
380
        }
×
381

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

391
        return result, true
53✔
392
}
393

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

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

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

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

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

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

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

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