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

mlange-42 / arche / 12591073240

03 Jan 2025 01:05AM CUT coverage: 100.0%. Remained the same
12591073240

push

github

web-flow
Fix PR reference #455 in CHANGELOG (#456)

6487 of 6487 relevant lines covered (100.0%)

114915.78 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,590,963✔
28
        return *(*Entity)(unsafe.Add(a.entityPointer, entitySize*index))
7,590,963✔
29
}
7,590,963✔
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 {
3,056,616✔
33
        return a.getLayout(id).Get(index)
3,056,616✔
34
}
3,056,616✔
35

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

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

46
// GetLayout returns the column layout for a component.
47
func (a *archetypeAccess) getLayout(id ID) *layout {
6,101,263✔
48
        return (*layout)(unsafe.Add(a.basePointer, layoutSize*uint32(id.id)))
6,101,263✔
49
}
6,101,263✔
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 {
3,056,614✔
59
        if l.pointer == nil {
3,056,615✔
60
                return nil
1✔
61
        }
1✔
62
        return unsafe.Add(l.pointer, l.itemSize*index)
3,056,613✔
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,519✔
84
        if !node.IsActive {
2,875✔
85
                node.IsActive = true
1,356✔
86
        }
1,356✔
87

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

1,519✔
94
        cap := 1
1,519✔
95
        if forStorage {
2,894✔
96
                cap = int(node.capacityIncrement)
1,375✔
97
        }
1,375✔
98

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

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

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

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

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

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

137
// AllocN allocates storage for the given number of entities.
138
func (a *archetype) AllocN(count uint32) {
27,636✔
139
        a.extend(count)
27,636✔
140
        a.len += count
27,636✔
141
}
27,636✔
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,521,083✔
148
        swapped := a.removeEntity(index)
1,521,083✔
149

1,521,083✔
150
        old := a.len - 1
1,521,083✔
151

1,521,083✔
152
        if index != old {
2,542,335✔
153
                for _, id := range a.node.Ids {
2,042,749✔
154
                        lay := a.getLayout(id)
1,021,497✔
155
                        size := lay.itemSize
1,021,497✔
156
                        if size == 0 {
1,021,806✔
157
                                continue
309✔
158
                        }
159
                        src := unsafe.Add(lay.pointer, old*size)
1,021,188✔
160
                        dst := unsafe.Add(lay.pointer, index*size)
1,021,188✔
161
                        a.copy(src, dst, size)
1,021,188✔
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,521,083✔
168
        a.len--
1,521,083✔
169

1,521,083✔
170
        return swapped
1,521,083✔
171
}
172

173
// ZeroAll resets a block of storage in all buffers.
174
func (a *archetype) ZeroAll(index uint32) {
1,521,083✔
175
        for _, id := range a.node.Ids {
2,547,898✔
176
                a.Zero(index, id)
1,026,815✔
177
        }
1,026,815✔
178
}
179

180
// Zero resets a block of storage in one buffer.
181
func (a *archetype) Zero(index uint32, id ID) {
1,026,815✔
182
        lay := a.getLayout(id)
1,026,815✔
183
        size := lay.itemSize
1,026,815✔
184
        if size == 0 {
1,029,966✔
185
                return
3,151✔
186
        }
3,151✔
187
        dst := unsafe.Add(lay.pointer, index*size)
1,023,664✔
188
        a.copy(a.node.zeroPointer, dst, size)
1,023,664✔
189
}
190

191
// SetEntity overwrites an entity
192
func (a *archetype) SetEntity(index uint32, entity Entity) {
2,761,728✔
193
        a.addEntity(index, &entity)
2,761,728✔
194
}
2,761,728✔
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 {
493,558✔
200
        lay := a.getLayout(id)
493,558✔
201
        dst := a.Get(index, id)
493,558✔
202
        size := lay.itemSize
493,558✔
203
        if size == 0 {
493,631✔
204
                return dst
73✔
205
        }
73✔
206
        rValue := reflect.ValueOf(comp).Elem()
493,485✔
207

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

493,485✔
212
        return dst
493,485✔
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 {
8,071✔
217
        lay := a.getLayout(id)
8,071✔
218
        dst := a.Get(index, id)
8,071✔
219
        size := lay.itemSize
8,071✔
220
        if size == 0 {
13,450✔
221
                return dst
5,379✔
222
        }
5,379✔
223

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

228
// Reset removes all entities and components.
229
//
230
// Does NOT free the reserved memory.
231
func (a *archetype) Reset() {
52,552✔
232
        if a.len == 0 {
77,609✔
233
                return
25,057✔
234
        }
25,057✔
235
        a.len = 0
27,495✔
236
        for _, buf := range a.buffers {
55,024✔
237
                buf.SetZero()
27,529✔
238
        }
27,529✔
239
}
240

241
// Deactivate the archetype for later re-use.
242
func (a *archetype) Deactivate() {
27,427✔
243
        a.Reset()
27,427✔
244
        a.index = -1
27,427✔
245
}
27,427✔
246

247
// Activate reactivates a de-activated archetype.
248
func (a *archetype) Activate(target Entity, index int32) {
27,404✔
249
        a.index = index
27,404✔
250
        a.RelationTarget = target
27,404✔
251
}
27,404✔
252

253
func (a *archetype) ExtendLayouts(count uint8) {
8✔
254
        if len(a.layouts) >= int(count) {
10✔
255
                return
2✔
256
        }
2✔
257
        temp := a.layouts
6✔
258
        a.layouts = make([]layout, count)
6✔
259
        copy(a.layouts, temp)
6✔
260
        a.archetypeAccess.basePointer = unsafe.Pointer(&a.layouts[0])
6✔
261
}
262

263
// IsActive returns whether the archetype is active.
264
// Otherwise, it is eligible for re-use.
265
func (a *archetype) IsActive() bool {
5,102,573✔
266
        return a.index >= 0
5,102,573✔
267
}
5,102,573✔
268

269
// Components returns the component IDs for this archetype
270
func (a *archetype) Components() []ID {
495,613✔
271
        return a.node.Ids
495,613✔
272
}
495,613✔
273

274
// Len reports the number of entities in the archetype
275
func (a *archetype) Len() uint32 {
6,757,017✔
276
        return a.len
6,757,017✔
277
}
6,757,017✔
278

279
// Cap reports the current capacity of the archetype
280
func (a *archetype) Cap() uint32 {
5,100,047✔
281
        return a.cap
5,100,047✔
282
}
5,100,047✔
283

284
// Stats generates statistics for an archetype
285
func (a *archetype) Stats(reg *componentRegistry) stats.Archetype {
113✔
286
        ids := a.Components()
113✔
287
        aCompCount := len(ids)
113✔
288
        aTypes := make([]reflect.Type, aCompCount)
113✔
289
        for j, id := range ids {
225✔
290
                aTypes[j], _ = reg.ComponentType(id.id)
112✔
291
        }
112✔
292

293
        cap := int(a.Cap())
113✔
294
        memPerEntity := 0
113✔
295
        for _, id := range a.node.Ids {
225✔
296
                lay := a.getLayout(id)
112✔
297
                memPerEntity += int(lay.itemSize)
112✔
298
        }
112✔
299
        memory := cap * (int(entitySize) + memPerEntity)
113✔
300

113✔
301
        return stats.Archetype{
113✔
302
                IsActive: a.IsActive(),
113✔
303
                Size:     int(a.Len()),
113✔
304
                Capacity: cap,
113✔
305
                Memory:   memory,
113✔
306
        }
113✔
307
}
308

309
// UpdateStats updates statistics for an archetype
310
func (a *archetype) UpdateStats(node *stats.Node, stats *stats.Archetype, reg *componentRegistry) {
5,099,924✔
311
        cap := int(a.Cap())
5,099,924✔
312
        memory := cap * (int(entitySize) + node.MemoryPerEntity)
5,099,924✔
313

5,099,924✔
314
        stats.IsActive = a.IsActive()
5,099,924✔
315
        stats.Size = int(a.Len())
5,099,924✔
316
        stats.Capacity = cap
5,099,924✔
317
        stats.Memory = memory
5,099,924✔
318
}
5,099,924✔
319

320
// copy from one pointer to another.
321
func (a *archetype) copy(src, dst unsafe.Pointer, itemSize uint32) {
7,357,872✔
322
        dstSlice := (*[math.MaxInt32]byte)(dst)[:itemSize:itemSize]
7,357,872✔
323
        srcSlice := (*[math.MaxInt32]byte)(src)[:itemSize:itemSize]
7,357,872✔
324
        copy(dstSlice, srcSlice)
7,357,872✔
325
}
7,357,872✔
326

327
// extend the memory buffers if necessary for adding an entity.
328
func (a *archetype) extend(by uint32) {
1,554,987✔
329
        required := a.len + by
1,554,987✔
330
        if a.cap >= required {
3,109,866✔
331
                return
1,554,879✔
332
        }
1,554,879✔
333
        a.cap = capacityU32(required, a.node.capacityIncrement)
108✔
334

108✔
335
        old := a.entityBuffer
108✔
336
        a.entityBuffer = reflect.New(reflect.ArrayOf(int(a.cap), entityType)).Elem()
108✔
337
        a.entityPointer = a.entityBuffer.Addr().UnsafePointer()
108✔
338
        reflect.Copy(a.entityBuffer, old)
108✔
339

108✔
340
        for _, id := range a.node.Ids {
218✔
341
                lay := a.getLayout(id)
110✔
342
                if lay.itemSize == 0 {
117✔
343
                        continue
7✔
344
                }
345
                index, _ := a.indices.Get(id.id)
103✔
346
                old := a.buffers[index]
103✔
347
                a.buffers[index] = reflect.New(reflect.ArrayOf(int(a.cap), old.Type().Elem())).Elem()
103✔
348
                lay.pointer = a.buffers[index].Addr().UnsafePointer()
103✔
349
                reflect.Copy(a.buffers[index], old)
103✔
350
        }
351
}
352

353
// Adds an entity at the given index. Does not extend the entity buffer.
354
func (a *archetype) addEntity(index uint32, entity *Entity) {
4,289,076✔
355
        dst := unsafe.Add(a.entityPointer, entitySize*index)
4,289,076✔
356
        src := unsafe.Pointer(entity)
4,289,076✔
357
        a.copy(src, dst, entitySize)
4,289,076✔
358
}
4,289,076✔
359

360
// removeEntity removes an entity from tne archetype.
361
// Components need to be removed separately.
362
func (a *archetype) removeEntity(index uint32) bool {
1,521,083✔
363
        old := a.len - 1
1,521,083✔
364

1,521,083✔
365
        if index == old {
2,020,914✔
366
                return false
499,831✔
367
        }
499,831✔
368

369
        src := unsafe.Add(a.entityPointer, old*entitySize)
1,021,252✔
370
        dst := unsafe.Add(a.entityPointer, index*entitySize)
1,021,252✔
371
        a.copy(src, dst, entitySize)
1,021,252✔
372

1,021,252✔
373
        return true
1,021,252✔
374
}
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