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

mlange-42 / arche / 12695144950

09 Jan 2025 05:19PM CUT coverage: 100.0%. Remained the same
12695144950

push

github

web-flow
Add benchmarks for 1-of-5 components ops. (#474)

6533 of 6533 relevant lines covered (100.0%)

114475.36 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
const layoutChunkSize uint8 = 16
12

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

16
// Helper for accessing data from an archetype
17
type archetypeAccess struct {
18
        basePointer          unsafe.Pointer // Pointer to the first component column layout.
19
        entityPointer        unsafe.Pointer // Pointer to the entity storage
20
        Mask                 Mask           // Archetype's mask
21
        RelationTarget       Entity         // Target entity of the archetype (if it has a relation component)
22
        RelationComponent    ID             // Relation component of the archetype
23
        HasRelationComponent bool           // Whether the archetype has a relation
24
}
25

26
// GetEntity returns the entity at the given index
27
func (a *archetypeAccess) GetEntity(index uint32) Entity {
7,462,854✔
28
        return *(*Entity)(unsafe.Add(a.entityPointer, entitySize*index))
7,462,854✔
29
}
7,462,854✔
30

31
// Get returns the component with the given ID at the given index
32
func (a *archetypeAccess) Get(index uint32, id ID) unsafe.Pointer {
2,991,632✔
33
        return a.getLayout(id).Get(index)
2,991,632✔
34
}
2,991,632✔
35

36
// HasComponent returns whether the archetype contains the given component ID.
37
func (a *archetypeAccess) HasComponent(id ID) bool {
514,807✔
38
        return a.getLayout(id).pointer != nil
514,807✔
39
}
514,807✔
40

41
// HasRelation returns whether the archetype has a relation component.
42
func (a *archetypeAccess) HasRelation() bool {
28,924✔
43
        return a.HasRelationComponent
28,924✔
44
}
28,924✔
45

46
// GetLayout returns the column layout for a component.
47
func (a *archetypeAccess) getLayout(id ID) *layout {
6,090,447✔
48
        return (*layout)(unsafe.Add(a.basePointer, layoutSize*uint32(id.id)))
6,090,447✔
49
}
6,090,447✔
50

51
// layout specification of a component column.
52
type layout struct {
53
        pointer  unsafe.Pointer // Pointer to the first element in the component column.
54
        itemSize uint32         // Component/step size
55
}
56

57
// Get returns a pointer to the item at the given index.
58
func (l *layout) Get(index uint32) unsafe.Pointer {
2,991,664✔
59
        if l.pointer == nil {
2,991,665✔
60
                return nil
1✔
61
        }
1✔
62
        return unsafe.Add(l.pointer, l.itemSize*index)
2,991,663✔
63
}
64

65
// archetype represents an ECS archetype
66
type archetype struct {
67
        *archetypeData
68
        node            *archNode // Node in the archetype graph.
69
        archetypeAccess           // Access helper, passed to queries.
70
        len             uint32    // Current number of entities.
71
        cap             uint32    // Current capacity.
72
}
73

74
type archetypeData struct {
75
        entityBuffer reflect.Value   // Reflection array containing entity data.
76
        layouts      []layout        // Column layouts by ID.
77
        buffers      []reflect.Value // Reflection arrays containing component data.
78
        indices      idMap[uint32]   // Mapping from IDs to buffer indices.
79
        index        int32           // Index of the archetype in the world.
80
}
81

82
// Init initializes an archetype
83
func (a *archetype) Init(node *archNode, data *archetypeData, index int32, forStorage bool, layouts uint8, relation Entity) {
1,526✔
84
        if !node.IsActive {
2,889✔
85
                node.IsActive = true
1,363✔
86
        }
1,363✔
87

88
        a.archetypeData = data
1,526✔
89
        a.buffers = make([]reflect.Value, len(node.Ids))
1,526✔
90
        a.indices = newIDMap[uint32]()
1,526✔
91
        a.index = index
1,526✔
92
        a.layouts = make([]layout, layouts)
1,526✔
93

1,526✔
94
        cap := 1
1,526✔
95
        if forStorage {
2,906✔
96
                cap = int(node.initialCapacity)
1,380✔
97
        }
1,380✔
98

99
        for i, id := range node.Ids {
7,154✔
100
                tp := node.Types[i]
5,628✔
101
                size, align := tp.Size(), uintptr(tp.Align())
5,628✔
102
                size = (size + (align - 1)) / align * align
5,628✔
103

5,628✔
104
                a.buffers[i] = reflect.New(reflect.ArrayOf(cap, tp)).Elem()
5,628✔
105
                a.layouts[id.id] = layout{
5,628✔
106
                        a.buffers[i].Addr().UnsafePointer(),
5,628✔
107
                        uint32(size),
5,628✔
108
                }
5,628✔
109
                a.indices.Set(id.id, uint32(i))
5,628✔
110
        }
5,628✔
111
        a.entityBuffer = reflect.New(reflect.ArrayOf(cap, entityType)).Elem()
1,526✔
112

1,526✔
113
        a.archetypeAccess = archetypeAccess{
1,526✔
114
                basePointer:          unsafe.Pointer(&a.layouts[0]),
1,526✔
115
                entityPointer:        a.entityBuffer.Addr().UnsafePointer(),
1,526✔
116
                Mask:                 node.Mask,
1,526✔
117
                RelationTarget:       relation,
1,526✔
118
                RelationComponent:    node.Relation,
1,526✔
119
                HasRelationComponent: node.HasRelation,
1,526✔
120
        }
1,526✔
121

1,526✔
122
        a.node = node
1,526✔
123

1,526✔
124
        a.len = 0
1,526✔
125
        a.cap = uint32(cap)
1,526✔
126
}
127

128
// Add adds an entity with optionally zeroed components to the archetype
129
func (a *archetype) Alloc(entity Entity) uint32 {
1,554,184✔
130
        idx := a.len
1,554,184✔
131
        a.extend(1)
1,554,184✔
132
        a.addEntity(idx, &entity)
1,554,184✔
133
        a.len++
1,554,184✔
134
        return idx
1,554,184✔
135
}
1,554,184✔
136

137
// AllocN allocates storage for the given number of entities.
138
func (a *archetype) AllocN(count uint32) {
27,641✔
139
        a.extend(count)
27,641✔
140
        a.len += count
27,641✔
141
}
27,641✔
142

143
// Remove removes an entity and its components from the archetype.
144
//
145
// Performs a swap-remove and reports whether a swap was necessary
146
// (i.e. not the last entity that was removed).
147
func (a *archetype) Remove(index uint32) bool {
1,549,206✔
148
        swapped := a.removeEntity(index)
1,549,206✔
149

1,549,206✔
150
        old := a.len - 1
1,549,206✔
151

1,549,206✔
152
        if index != old {
2,578,081✔
153
                for _, id := range a.node.Ids {
2,057,996✔
154
                        lay := a.getLayout(id)
1,029,121✔
155
                        size := lay.itemSize
1,029,121✔
156
                        if size == 0 {
1,029,431✔
157
                                continue
310✔
158
                        }
159
                        src := unsafe.Add(lay.pointer, old*size)
1,028,811✔
160
                        dst := unsafe.Add(lay.pointer, index*size)
1,028,811✔
161
                        a.copy(src, dst, size)
1,028,811✔
162
                }
163
        }
164

165
        // Zero the free memory to allow the garbage collector
166
        // to take into account pointers in the removed component.
167
        a.ZeroAll(old)
1,549,206✔
168
        a.len--
1,549,206✔
169

1,549,206✔
170
        return swapped
1,549,206✔
171
}
172

173
// ZeroAll resets a block of storage in all buffers.
174
func (a *archetype) ZeroAll(index uint32) {
1,549,206✔
175
        for _, id := range a.node.Ids {
2,583,823✔
176
                a.Zero(index, id)
1,034,617✔
177
        }
1,034,617✔
178
}
179

180
// Zero resets a block of storage in one buffer.
181
func (a *archetype) Zero(index uint32, id ID) {
1,034,617✔
182
        lay := a.getLayout(id)
1,034,617✔
183
        size := lay.itemSize
1,034,617✔
184
        if size == 0 {
1,037,770✔
185
                return
3,153✔
186
        }
3,153✔
187
        dst := unsafe.Add(lay.pointer, index*size)
1,031,464✔
188
        a.copy(a.node.zeroPointer, dst, size)
1,031,464✔
189
}
190

191
// SetEntity overwrites an entity
192
func (a *archetype) SetEntity(index uint32, entity Entity) {
2,759,882✔
193
        a.addEntity(index, &entity)
2,759,882✔
194
}
2,759,882✔
195

196
// Set overwrites a component with the data behind the given pointer.
197
//
198
// Deprecated: Method is slow and should not be used.
199
func (a *archetype) Set(index uint32, id ID, comp interface{}) unsafe.Pointer {
513,881✔
200
        lay := a.getLayout(id)
513,881✔
201
        dst := a.Get(index, id)
513,881✔
202
        size := lay.itemSize
513,881✔
203
        if size == 0 {
513,954✔
204
                return dst
73✔
205
        }
73✔
206
        rValue := reflect.ValueOf(comp).Elem()
513,808✔
207

513,808✔
208
        valueType := rValue.Type()
513,808✔
209
        valuePtr := reflect.NewAt(valueType, dst)
513,808✔
210
        valuePtr.Elem().Set(rValue)
513,808✔
211

513,808✔
212
        return dst
513,808✔
213
}
214

215
// SetPointer overwrites a component with the data behind the given pointer
216
func (a *archetype) SetPointer(index uint32, id ID, comp unsafe.Pointer) unsafe.Pointer {
6,171✔
217
        lay := a.getLayout(id)
6,171✔
218
        dst := a.Get(index, id)
6,171✔
219
        size := lay.itemSize
6,171✔
220
        if size == 0 {
10,710✔
221
                return dst
4,539✔
222
        }
4,539✔
223

224
        a.copy(comp, dst, size)
1,632✔
225
        return dst
1,632✔
226
}
227

228
// CopyFrom copies an entire component column from another archetype into this one,
229
// starting at startIndex in this one.
230
func (a *archetype) CopyFrom(other *archetype, id ID, startIndex uint32) {
50✔
231
        if !a.Mask.Get(id) {
71✔
232
                return
21✔
233
        }
21✔
234
        lay := a.getLayout(id)
29✔
235
        size := lay.itemSize
29✔
236
        if size == 0 {
41✔
237
                return
12✔
238
        }
12✔
239

240
        otherLay := other.getLayout(id)
17✔
241

17✔
242
        dst := lay.Get(uint32(startIndex))
17✔
243
        src := otherLay.Get(0)
17✔
244

17✔
245
        a.copy(src, dst, size*other.len)
17✔
246
}
247

248
// CopyFrom copies all entities from another archetype into this one,
249
// starting at startIndex in this one.
250
func (a *archetype) CopyEntitiesFrom(other *archetype, startIndex uint32) {
29✔
251
        dst := unsafe.Add(a.entityPointer, startIndex*entitySize)
29✔
252
        src := other.entityPointer
29✔
253

29✔
254
        a.copy(src, dst, entitySize*other.len)
29✔
255
}
29✔
256

257
// Reset removes all entities and components.
258
//
259
// Does NOT free the reserved memory.
260
func (a *archetype) Reset() {
52,555✔
261
        if a.len == 0 {
77,613✔
262
                return
25,058✔
263
        }
25,058✔
264
        a.len = 0
27,497✔
265
        for _, buf := range a.buffers {
55,029✔
266
                buf.SetZero()
27,532✔
267
        }
27,532✔
268
}
269

270
// Deactivate the archetype for later re-use.
271
func (a *archetype) Deactivate() {
27,427✔
272
        a.Reset()
27,427✔
273
        a.index = -1
27,427✔
274
}
27,427✔
275

276
// Activate reactivates a de-activated archetype.
277
func (a *archetype) Activate(target Entity, index int32) {
27,404✔
278
        a.index = index
27,404✔
279
        a.RelationTarget = target
27,404✔
280
}
27,404✔
281

282
func (a *archetype) ExtendLayouts(count uint8) {
8✔
283
        if len(a.layouts) >= int(count) {
10✔
284
                return
2✔
285
        }
2✔
286
        temp := a.layouts
6✔
287
        a.layouts = make([]layout, count)
6✔
288
        copy(a.layouts, temp)
6✔
289
        a.archetypeAccess.basePointer = unsafe.Pointer(&a.layouts[0])
6✔
290
}
291

292
// IsActive returns whether the archetype is active.
293
// Otherwise, it is eligible for re-use.
294
func (a *archetype) IsActive() bool {
5,102,574✔
295
        return a.index >= 0
5,102,574✔
296
}
5,102,574✔
297

298
// Components returns the component IDs for this archetype
299
func (a *archetype) Components() []ID {
515,940✔
300
        return a.node.Ids
515,940✔
301
}
515,940✔
302

303
// Len reports the number of entities in the archetype
304
func (a *archetype) Len() uint32 {
6,785,162✔
305
        return a.len
6,785,162✔
306
}
6,785,162✔
307

308
// Cap reports the current capacity of the archetype
309
func (a *archetype) Cap() uint32 {
5,100,047✔
310
        return a.cap
5,100,047✔
311
}
5,100,047✔
312

313
// Stats generates statistics for an archetype
314
func (a *archetype) Stats(reg *componentRegistry) stats.Archetype {
113✔
315
        ids := a.Components()
113✔
316
        aCompCount := len(ids)
113✔
317
        aTypes := make([]reflect.Type, aCompCount)
113✔
318
        for j, id := range ids {
225✔
319
                aTypes[j], _ = reg.ComponentType(id.id)
112✔
320
        }
112✔
321

322
        cap := int(a.Cap())
113✔
323
        memPerEntity := 0
113✔
324
        for _, id := range a.node.Ids {
225✔
325
                lay := a.getLayout(id)
112✔
326
                memPerEntity += int(lay.itemSize)
112✔
327
        }
112✔
328
        memory := cap * (int(entitySize) + memPerEntity)
113✔
329

113✔
330
        return stats.Archetype{
113✔
331
                IsActive: a.IsActive(),
113✔
332
                Size:     int(a.Len()),
113✔
333
                Capacity: cap,
113✔
334
                Memory:   memory,
113✔
335
        }
113✔
336
}
337

338
// UpdateStats updates statistics for an archetype
339
func (a *archetype) UpdateStats(node *stats.Node, stats *stats.Archetype, reg *componentRegistry) {
5,099,924✔
340
        cap := int(a.Cap())
5,099,924✔
341
        memory := cap * (int(entitySize) + node.MemoryPerEntity)
5,099,924✔
342

5,099,924✔
343
        stats.IsActive = a.IsActive()
5,099,924✔
344
        stats.Size = int(a.Len())
5,099,924✔
345
        stats.Capacity = cap
5,099,924✔
346
        stats.Memory = memory
5,099,924✔
347
}
5,099,924✔
348

349
// copy from one pointer to another.
350
func (a *archetype) copy(src, dst unsafe.Pointer, itemSize uint32) {
7,404,894✔
351
        dstSlice := (*[math.MaxInt32]byte)(dst)[:itemSize:itemSize]
7,404,894✔
352
        srcSlice := (*[math.MaxInt32]byte)(src)[:itemSize:itemSize]
7,404,894✔
353
        copy(dstSlice, srcSlice)
7,404,894✔
354
}
7,404,894✔
355

356
// extend the memory buffers if necessary for adding an entity.
357
func (a *archetype) extend(by uint32) {
1,581,828✔
358
        required := a.len + by
1,581,828✔
359
        if a.cap >= required {
3,163,595✔
360
                return
1,581,767✔
361
        }
1,581,767✔
362
        for a.cap < required {
144✔
363
                a.cap *= 2
83✔
364
        }
83✔
365
        a.cap = max(a.cap, a.node.initialCapacity)
61✔
366

61✔
367
        old := a.entityBuffer
61✔
368
        a.entityBuffer = reflect.New(reflect.ArrayOf(int(a.cap), entityType)).Elem()
61✔
369
        a.entityPointer = a.entityBuffer.Addr().UnsafePointer()
61✔
370
        reflect.Copy(a.entityBuffer, old)
61✔
371

61✔
372
        for _, id := range a.node.Ids {
121✔
373
                lay := a.getLayout(id)
60✔
374
                if lay.itemSize == 0 {
68✔
375
                        continue
8✔
376
                }
377
                index, _ := a.indices.Get(id.id)
52✔
378
                old := a.buffers[index]
52✔
379
                a.buffers[index] = reflect.New(reflect.ArrayOf(int(a.cap), old.Type().Elem())).Elem()
52✔
380
                lay.pointer = a.buffers[index].Addr().UnsafePointer()
52✔
381
                reflect.Copy(a.buffers[index], old)
52✔
382
        }
383
}
384

385
// Adds an entity at the given index. Does not extend the entity buffer.
386
func (a *archetype) addEntity(index uint32, entity *Entity) {
4,314,066✔
387
        dst := unsafe.Add(a.entityPointer, entitySize*index)
4,314,066✔
388
        src := unsafe.Pointer(entity)
4,314,066✔
389
        a.copy(src, dst, entitySize)
4,314,066✔
390
}
4,314,066✔
391

392
// removeEntity removes an entity from tne archetype.
393
// Components need to be removed separately.
394
func (a *archetype) removeEntity(index uint32) bool {
1,549,206✔
395
        old := a.len - 1
1,549,206✔
396

1,549,206✔
397
        if index == old {
2,069,537✔
398
                return false
520,331✔
399
        }
520,331✔
400

401
        src := unsafe.Add(a.entityPointer, old*entitySize)
1,028,875✔
402
        dst := unsafe.Add(a.entityPointer, index*entitySize)
1,028,875✔
403
        a.copy(src, dst, entitySize)
1,028,875✔
404

1,028,875✔
405
        return true
1,028,875✔
406
}
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