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

mlange-42 / arche / 4839118144

29 Apr 2023 01:53PM CUT coverage: 100.0%. Remained the same
4839118144

Pull #231

github

GitHub
Merge e982fe86a into c9fbc3a05
Pull Request #231: Entity relations

137 of 137 new or added lines in 8 files covered. (100.0%)

2827 of 2827 relevant lines covered (100.0%)

4403.7 hits per line

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

100.0
/ecs/archetype.go
1
package ecs
2

3
import (
4
        "math"
5
        "reflect"
6
        "unsafe"
7

8
        "github.com/mlange-42/arche/ecs/stats"
9
)
10

11
// layoutSize is the size of an archetype column layout in bytes.
12
var layoutSize = unsafe.Sizeof(layout{})
13

14
// archetypeNode is a node in the archetype graph.
15
type archetypeNode struct {
16
        mask             Mask       // Mask of the archetype
17
        archetype        *archetype // The archetype
18
        archetypes       map[Entity]*archetype
19
        TransitionAdd    idMap[*archetypeNode] // Mapping from component ID to add to the resulting archetype
20
        TransitionRemove idMap[*archetypeNode] // Mapping from component ID to remove to the resulting archetype
21
        relation         int8
22
}
23

24
// Creates a new archetypeNode
25
func newArchetypeNode(mask Mask, relation int8) archetypeNode {
1,218✔
26
        var arch map[Entity]*archetype
1,218✔
27
        if relation >= 0 {
1,224✔
28
                arch = map[Entity]*archetype{}
6✔
29
        }
6✔
30
        return archetypeNode{
1,218✔
31
                mask:             mask,
1,218✔
32
                archetypes:       arch,
1,218✔
33
                TransitionAdd:    newIDMap[*archetypeNode](),
1,218✔
34
                TransitionRemove: newIDMap[*archetypeNode](),
1,218✔
35
                relation:         relation,
1,218✔
36
        }
1,218✔
37
}
38

39
func (a *archetypeNode) GetArchetype(id Entity) *archetype {
7,539✔
40
        if a.relation >= 0 {
12,561✔
41
                return a.archetypes[id]
5,022✔
42
        }
5,022✔
43
        return a.archetype
2,517✔
44
}
45

46
func (a *archetypeNode) SetArchetype(id Entity, arch *archetype) {
1,220✔
47
        if a.relation >= 0 {
1,253✔
48
                a.archetypes[id] = arch
33✔
49
        } else {
1,220✔
50
                a.archetype = arch
1,187✔
51
        }
1,187✔
52
}
53

54
// Helper for accessing data from an archetype
55
type archetypeAccess struct {
56
        Mask              Mask           // Archetype's mask
57
        basePointer       unsafe.Pointer // Pointer to the first component column layout.
58
        entityPointer     unsafe.Pointer // Pointer to the entity storage
59
        Relation          Entity
60
        RelationComponent int8
61
}
62

63
// Matches checks if the archetype matches the given mask.
64
func (a *archetype) Matches(f Filter) bool {
3,140✔
65
        return f.Matches(a.Mask, &a.Relation)
3,140✔
66
}
3,140✔
67

68
// GetEntity returns the entity at the given index
69
func (a *archetypeAccess) GetEntity(index uintptr) Entity {
32,323✔
70
        return *(*Entity)(unsafe.Add(a.entityPointer, entitySize*index))
32,323✔
71
}
32,323✔
72

73
// Get returns the component with the given ID at the given index
74
func (a *archetypeAccess) Get(index uintptr, id ID) unsafe.Pointer {
147,152✔
75
        return a.getLayout(id).Get(index)
147,152✔
76
}
147,152✔
77

78
// GetEntity returns the entity at the given index
79
func (a *archetypeAccess) GetRelation() Entity {
1✔
80
        return a.Relation
1✔
81
}
1✔
82

83
// HasComponent returns whether the archetype contains the given component ID
84
func (a *archetypeAccess) HasComponent(id ID) bool {
48,494✔
85
        return a.getLayout(id).pointer != nil
48,494✔
86
}
48,494✔
87

88
// GetLayout returns the column layout for a component.
89
func (a *archetypeAccess) getLayout(id ID) *layout {
242,474✔
90
        return (*layout)(unsafe.Add(a.basePointer, layoutSize*uintptr(id)))
242,474✔
91
}
242,474✔
92

93
// layout specification of a component column.
94
type layout struct {
95
        pointer  unsafe.Pointer // Pointer to the first element in the component column.
96
        itemSize uintptr        // Component/step size
97
}
98

99
// Get returns a pointer to the item at the given index.
100
func (l *layout) Get(index uintptr) unsafe.Pointer {
147,150✔
101
        if l.pointer == nil {
147,151✔
102
                return nil
1✔
103
        }
1✔
104
        return unsafe.Add(l.pointer, l.itemSize*index)
147,149✔
105
}
106

107
// archetype represents an ECS archetype
108
type archetype struct {
109
        archetypeAccess                   // Access helper, passed to queries.
110
        graphNode         *archetypeNode  // Node in the archetype graph.
111
        Ids               []ID            // List of component IDs.
112
        layouts           []layout        // Column layouts by ID.
113
        indices           idMap[uint32]   // Mapping from IDs to buffer indices.
114
        buffers           []reflect.Value // Reflection arrays containing component data.
115
        entityBuffer      reflect.Value   // Reflection array containing entity data.
116
        len               uint32          // Current number of entities
117
        cap               uint32          // Current capacity
118
        capacityIncrement uint32          // Capacity increment
119
        zeroValue         []byte          // Used as source for setting storage to zero
120
        zeroPointer       unsafe.Pointer  // Points to zeroValue for fast access
121
}
122

123
// Init initializes an archetype
124
func (a *archetype) Init(node *archetypeNode, capacityIncrement int, forStorage bool, relation Entity, relationComp int8, components ...componentType) {
1,229✔
125
        var mask Mask
1,229✔
126
        if len(components) > 0 {
2,378✔
127
                a.Ids = make([]ID, len(components))
1,149✔
128
        }
1,149✔
129

130
        a.buffers = make([]reflect.Value, len(components))
1,229✔
131
        a.layouts = make([]layout, MaskTotalBits)
1,229✔
132
        a.indices = newIDMap[uint32]()
1,229✔
133

1,229✔
134
        cap := 1
1,229✔
135
        if forStorage {
2,374✔
136
                cap = capacityIncrement
1,145✔
137
        }
1,145✔
138

139
        prev := -1
1,229✔
140
        var maxSize uintptr = 0
1,229✔
141
        for i, c := range components {
6,535✔
142
                if int(c.ID) <= prev {
5,307✔
143
                        panic("component arguments must be sorted by ID")
1✔
144
                }
145
                prev = int(c.ID)
5,305✔
146
                mask.Set(c.ID, true)
5,305✔
147

5,305✔
148
                size, align := c.Type.Size(), uintptr(c.Type.Align())
5,305✔
149
                size = (size + (align - 1)) / align * align
5,305✔
150
                if size > maxSize {
6,425✔
151
                        maxSize = size
1,120✔
152
                }
1,120✔
153

154
                a.Ids[i] = c.ID
5,305✔
155
                a.buffers[i] = reflect.New(reflect.ArrayOf(cap, c.Type)).Elem()
5,305✔
156
                a.layouts[c.ID] = layout{
5,305✔
157
                        a.buffers[i].Addr().UnsafePointer(),
5,305✔
158
                        size,
5,305✔
159
                }
5,305✔
160
                a.indices.Set(c.ID, uint32(i))
5,305✔
161
        }
162
        a.entityBuffer = reflect.New(reflect.ArrayOf(cap, entityType)).Elem()
1,228✔
163

1,228✔
164
        a.archetypeAccess = archetypeAccess{
1,228✔
165
                basePointer:       unsafe.Pointer(&a.layouts[0]),
1,228✔
166
                entityPointer:     a.entityBuffer.Addr().UnsafePointer(),
1,228✔
167
                Mask:              mask,
1,228✔
168
                Relation:          relation,
1,228✔
169
                RelationComponent: relationComp,
1,228✔
170
        }
1,228✔
171

1,228✔
172
        a.graphNode = node
1,228✔
173

1,228✔
174
        a.capacityIncrement = uint32(capacityIncrement)
1,228✔
175
        a.len = 0
1,228✔
176
        a.cap = uint32(cap)
1,228✔
177

1,228✔
178
        if maxSize > 0 {
2,346✔
179
                a.zeroValue = make([]byte, maxSize)
1,118✔
180
                a.zeroPointer = unsafe.Pointer(&a.zeroValue[0])
1,118✔
181
        }
1,118✔
182
}
183

184
// Add adds an entity with optionally zeroed components to the archetype
185
func (a *archetype) Alloc(entity Entity) uintptr {
9,703✔
186
        idx := uintptr(a.len)
9,703✔
187
        a.extend(1)
9,703✔
188
        a.addEntity(idx, &entity)
9,703✔
189
        a.len++
9,703✔
190
        return idx
9,703✔
191
}
9,703✔
192

193
// Add adds storage to the archetype
194
func (a *archetype) AllocN(count uint32) {
28✔
195
        a.extend(count)
28✔
196
        a.len += count
28✔
197
}
28✔
198

199
// Add adds an entity with components to the archetype
200
func (a *archetype) Add(entity Entity, components ...Component) uintptr {
9✔
201
        if len(components) != len(a.Ids) {
10✔
202
                panic("Invalid number of components")
1✔
203
        }
204
        idx := uintptr(a.len)
8✔
205

8✔
206
        a.extend(1)
8✔
207
        a.addEntity(idx, &entity)
8✔
208
        for _, c := range components {
24✔
209
                lay := a.getLayout(c.ID)
16✔
210
                size := lay.itemSize
16✔
211
                if size == 0 {
18✔
212
                        continue
2✔
213
                }
214
                src := reflect.ValueOf(c.Comp).UnsafePointer()
14✔
215
                dst := a.Get(uintptr(idx), c.ID)
14✔
216
                a.copy(src, dst, size)
14✔
217
        }
218
        a.len++
8✔
219
        return idx
8✔
220
}
221

222
// Remove removes an entity and its components from the archetype.
223
//
224
// Performs a swap-remove and reports whether a swap was necessary
225
// (i.e. not the last entity that was removed).
226
func (a *archetype) Remove(index uintptr) bool {
4,915✔
227
        swapped := a.removeEntity(index)
4,915✔
228

4,915✔
229
        old := uintptr(a.len - 1)
4,915✔
230

4,915✔
231
        if index != old {
5,085✔
232
                for _, id := range a.Ids {
383✔
233
                        lay := a.getLayout(id)
213✔
234
                        size := lay.itemSize
213✔
235
                        if size == 0 {
216✔
236
                                continue
3✔
237
                        }
238
                        src := unsafe.Add(lay.pointer, old*size)
210✔
239
                        dst := unsafe.Add(lay.pointer, index*size)
210✔
240
                        a.copy(src, dst, size)
210✔
241
                }
242
        }
243
        a.ZeroAll(old)
4,915✔
244
        a.len--
4,915✔
245

4,915✔
246
        return swapped
4,915✔
247
}
248

249
// ZeroAll resets a block of storage in all buffers.
250
func (a *archetype) ZeroAll(index uintptr) {
4,915✔
251
        for _, id := range a.Ids {
7,777✔
252
                a.Zero(index, id)
2,862✔
253
        }
2,862✔
254
}
255

256
// ZeroAll resets a block of storage in one buffer.
257
func (a *archetype) Zero(index uintptr, id ID) {
2,862✔
258
        lay := a.getLayout(id)
2,862✔
259
        size := lay.itemSize
2,862✔
260
        if size == 0 {
5,378✔
261
                return
2,516✔
262
        }
2,516✔
263
        dst := unsafe.Add(lay.pointer, index*size)
346✔
264
        a.copy(a.zeroPointer, dst, size)
346✔
265
}
266

267
// SetEntity overwrites an entity
268
func (a *archetype) SetEntity(index uintptr, entity Entity) {
71,342✔
269
        a.addEntity(index, &entity)
71,342✔
270
}
71,342✔
271

272
// Set overwrites a component with the data behind the given pointer
273
func (a *archetype) Set(index uintptr, id ID, comp interface{}) unsafe.Pointer {
41,150✔
274
        lay := a.getLayout(id)
41,150✔
275
        dst := a.Get(index, id)
41,150✔
276
        size := lay.itemSize
41,150✔
277
        if size == 0 {
41,151✔
278
                return dst
1✔
279
        }
1✔
280
        rValue := reflect.ValueOf(comp)
41,149✔
281

41,149✔
282
        src := rValue.UnsafePointer()
41,149✔
283
        a.copy(src, dst, size)
41,149✔
284
        return dst
41,149✔
285
}
286

287
// SetPointer overwrites a component with the data behind the given pointer
288
func (a *archetype) SetPointer(index uintptr, id ID, comp unsafe.Pointer) unsafe.Pointer {
2,525✔
289
        lay := a.getLayout(id)
2,525✔
290
        dst := a.Get(index, id)
2,525✔
291
        size := lay.itemSize
2,525✔
292
        if size == 0 {
5,037✔
293
                return dst
2,512✔
294
        }
2,512✔
295

296
        a.copy(comp, dst, size)
13✔
297
        return dst
13✔
298
}
299

300
// Reset removes all entities and components.
301
//
302
// Does NOT free the reserved memory.
303
func (a *archetype) Reset() {
15✔
304
        a.len = 0
15✔
305
        for _, buf := range a.buffers {
31✔
306
                buf.SetZero()
16✔
307
        }
16✔
308
}
309

310
// Components returns the component IDs for this archetype
311
func (a *archetype) Components() []ID {
2,189✔
312
        return a.Ids
2,189✔
313
}
2,189✔
314

315
// Len reports the number of entities in the archetype
316
func (a *archetype) Len() uint32 {
2,501✔
317
        return a.len
2,501✔
318
}
2,501✔
319

320
// Cap reports the current capacity of the archetype
321
func (a *archetype) Cap() uint32 {
18✔
322
        return a.cap
18✔
323
}
18✔
324

325
// Stats generates statistics for an archetype
326
func (a *archetype) Stats(reg *componentRegistry[ID]) stats.ArchetypeStats {
5✔
327
        ids := a.Components()
5✔
328
        aCompCount := len(ids)
5✔
329
        aTypes := make([]reflect.Type, aCompCount)
5✔
330
        for j, id := range ids {
9✔
331
                aTypes[j], _ = reg.ComponentType(id)
4✔
332
        }
4✔
333

334
        cap := int(a.Cap())
5✔
335
        memPerEntity := 0
5✔
336
        for _, id := range a.Ids {
9✔
337
                lay := a.getLayout(id)
4✔
338
                memPerEntity += int(lay.itemSize)
4✔
339
        }
4✔
340
        memory := cap * (int(entitySize) + memPerEntity)
5✔
341

5✔
342
        return stats.ArchetypeStats{
5✔
343
                Size:            int(a.Len()),
5✔
344
                Capacity:        cap,
5✔
345
                Components:      aCompCount,
5✔
346
                ComponentIDs:    ids,
5✔
347
                ComponentTypes:  aTypes,
5✔
348
                Memory:          memory,
5✔
349
                MemoryPerEntity: memPerEntity,
5✔
350
        }
5✔
351
}
352

353
// UpdateStats updates statistics for an archetype
354
func (a *archetype) UpdateStats(stats *stats.ArchetypeStats) {
3✔
355
        cap := int(a.Cap())
3✔
356
        memory := cap * (int(entitySize) + stats.MemoryPerEntity)
3✔
357

3✔
358
        stats.Size = int(a.Len())
3✔
359
        stats.Capacity = cap
3✔
360
        stats.Memory = memory
3✔
361
}
3✔
362

363
// copy from one pointer to another.
364
func (a *archetype) copy(src, dst unsafe.Pointer, itemSize uintptr) {
122,955✔
365
        dstSlice := (*[math.MaxInt32]byte)(dst)[:itemSize:itemSize]
122,955✔
366
        srcSlice := (*[math.MaxInt32]byte)(src)[:itemSize:itemSize]
122,955✔
367
        copy(dstSlice, srcSlice)
122,955✔
368
}
122,955✔
369

370
// extend the memory buffers if necessary for adding an entity.
371
func (a *archetype) extend(by uint32) {
9,742✔
372
        required := a.len + by
9,742✔
373
        if a.cap >= required {
19,440✔
374
                return
9,698✔
375
        }
9,698✔
376
        a.cap = capacityU32(required, a.capacityIncrement)
44✔
377

44✔
378
        old := a.entityBuffer
44✔
379
        a.entityBuffer = reflect.New(reflect.ArrayOf(int(a.cap), entityType)).Elem()
44✔
380
        a.entityPointer = a.entityBuffer.Addr().UnsafePointer()
44✔
381
        reflect.Copy(a.entityBuffer, old)
44✔
382

44✔
383
        for _, id := range a.Ids {
102✔
384
                lay := a.getLayout(id)
58✔
385
                if lay.itemSize == 0 {
59✔
386
                        continue
1✔
387
                }
388
                index, _ := a.indices.Get(id)
57✔
389
                old := a.buffers[index]
57✔
390
                a.buffers[index] = reflect.New(reflect.ArrayOf(int(a.cap), old.Type().Elem())).Elem()
57✔
391
                lay.pointer = a.buffers[index].Addr().UnsafePointer()
57✔
392
                reflect.Copy(a.buffers[index], old)
57✔
393
        }
394
}
395

396
// Adds an entity at the given index. Does not extend the entity buffer.
397
func (a *archetype) addEntity(index uintptr, entity *Entity) {
81,053✔
398
        dst := unsafe.Add(a.entityPointer, entitySize*index)
81,053✔
399
        src := unsafe.Pointer(entity)
81,053✔
400
        a.copy(src, dst, entitySize)
81,053✔
401
}
81,053✔
402

403
// removeEntity removes an entity from tne archetype.
404
// Components need to be removed separately.
405
func (a *archetype) removeEntity(index uintptr) bool {
4,915✔
406
        old := uintptr(a.len - 1)
4,915✔
407

4,915✔
408
        if index == old {
9,660✔
409
                return false
4,745✔
410
        }
4,745✔
411

412
        src := unsafe.Add(a.entityPointer, old*entitySize)
170✔
413
        dst := unsafe.Add(a.entityPointer, index*entitySize)
170✔
414
        a.copy(src, dst, entitySize)
170✔
415

170✔
416
        return true
170✔
417
}
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