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

mlange-42 / arche / 11314190155

13 Oct 2024 12:06PM CUT coverage: 100.0%. Remained the same
11314190155

push

github

web-flow
Improve documentation on internal methods (#430)

6385 of 6385 relevant lines covered (100.0%)

76494.31 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 {
5,004,301✔
28
        return *(*Entity)(unsafe.Add(a.entityPointer, entitySize*index))
5,004,301✔
29
}
5,004,301✔
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 {
1,510,427✔
33
        return a.getLayout(id).Get(index)
1,510,427✔
34
}
1,510,427✔
35

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

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

46
// GetLayout returns the column layout for a component.
47
func (a *archetypeAccess) getLayout(id ID) *layout {
2,564,514✔
48
        return (*layout)(unsafe.Add(a.basePointer, layoutSize*uint32(id.id)))
2,564,514✔
49
}
2,564,514✔
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 {
1,510,425✔
59
        if l.pointer == nil {
1,510,426✔
60
                return nil
1✔
61
        }
1✔
62
        return unsafe.Add(l.pointer, l.itemSize*index)
1,510,424✔
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,512✔
84
        if !node.IsActive {
2,861✔
85
                node.IsActive = true
1,349✔
86
        }
1,349✔
87

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

1,512✔
94
        cap := 1
1,512✔
95
        if forStorage {
2,884✔
96
                cap = int(node.capacityIncrement)
1,372✔
97
        }
1,372✔
98

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

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

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

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

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

128
// Add adds an entity with optionally zeroed components to the archetype
129
func (a *archetype) Alloc(entity Entity) uint32 {
530,760✔
130
        idx := a.len
530,760✔
131
        a.extend(1)
530,760✔
132
        a.addEntity(idx, &entity)
530,760✔
133
        a.len++
530,760✔
134
        return idx
530,760✔
135
}
530,760✔
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
// Add adds an entity with components to the archetype.
144
func (a *archetype) Add(entity Entity, components ...Component) uint32 {
9✔
145
        if len(components) != len(a.node.Ids) {
10✔
146
                panic("Invalid number of components")
1✔
147
        }
148
        idx := a.len
8✔
149

8✔
150
        a.extend(1)
8✔
151
        a.addEntity(idx, &entity)
8✔
152
        for _, c := range components {
24✔
153
                lay := a.getLayout(c.ID)
16✔
154
                size := lay.itemSize
16✔
155
                if size == 0 {
18✔
156
                        continue
2✔
157
                }
158
                src := reflect.ValueOf(c.Comp).UnsafePointer()
14✔
159
                dst := a.Get(idx, c.ID)
14✔
160
                a.copy(src, dst, size)
14✔
161
        }
162
        a.len++
8✔
163
        return idx
8✔
164
}
165

166
// Remove removes an entity and its components from the archetype.
167
//
168
// Performs a swap-remove and reports whether a swap was necessary
169
// (i.e. not the last entity that was removed).
170
func (a *archetype) Remove(index uint32) bool {
525,385✔
171
        swapped := a.removeEntity(index)
525,385✔
172

525,385✔
173
        old := a.len - 1
525,385✔
174

525,385✔
175
        if index != old {
1,044,425✔
176
                for _, id := range a.node.Ids {
1,038,325✔
177
                        lay := a.getLayout(id)
519,285✔
178
                        size := lay.itemSize
519,285✔
179
                        if size == 0 {
519,594✔
180
                                continue
309✔
181
                        }
182
                        src := unsafe.Add(lay.pointer, old*size)
518,976✔
183
                        dst := unsafe.Add(lay.pointer, index*size)
518,976✔
184
                        a.copy(src, dst, size)
518,976✔
185
                }
186
        }
187

188
        // Zero the free memory to allow the garbage collector
189
        // to take into account pointers in the removed component.
190
        a.ZeroAll(old)
525,385✔
191
        a.len--
525,385✔
192

525,385✔
193
        return swapped
525,385✔
194
}
195

196
// ZeroAll resets a block of storage in all buffers.
197
func (a *archetype) ZeroAll(index uint32) {
525,385✔
198
        for _, id := range a.node.Ids {
1,049,124✔
199
                a.Zero(index, id)
523,739✔
200
        }
523,739✔
201
}
202

203
// Zero resets a block of storage in one buffer.
204
func (a *archetype) Zero(index uint32, id ID) {
523,739✔
205
        lay := a.getLayout(id)
523,739✔
206
        size := lay.itemSize
523,739✔
207
        if size == 0 {
526,890✔
208
                return
3,151✔
209
        }
3,151✔
210
        dst := unsafe.Add(lay.pointer, index*size)
520,588✔
211
        a.copy(a.node.zeroPointer, dst, size)
520,588✔
212
}
213

214
// SetEntity overwrites an entity
215
func (a *archetype) SetEntity(index uint32, entity Entity) {
2,761,728✔
216
        a.addEntity(index, &entity)
2,761,728✔
217
}
2,761,728✔
218

219
// Set overwrites a component with the data behind the given pointer
220
func (a *archetype) Set(index uint32, id ID, comp interface{}) unsafe.Pointer {
922✔
221
        lay := a.getLayout(id)
922✔
222
        dst := a.Get(index, id)
922✔
223
        size := lay.itemSize
922✔
224
        if size == 0 {
993✔
225
                return dst
71✔
226
        }
71✔
227
        rValue := reflect.ValueOf(comp)
851✔
228

851✔
229
        src := rValue.UnsafePointer()
851✔
230
        a.copy(src, dst, size)
851✔
231
        return dst
851✔
232
}
233

234
// SetPointer overwrites a component with the data behind the given pointer
235
func (a *archetype) SetPointer(index uint32, id ID, comp unsafe.Pointer) unsafe.Pointer {
8,071✔
236
        lay := a.getLayout(id)
8,071✔
237
        dst := a.Get(index, id)
8,071✔
238
        size := lay.itemSize
8,071✔
239
        if size == 0 {
13,450✔
240
                return dst
5,379✔
241
        }
5,379✔
242

243
        a.copy(comp, dst, size)
2,692✔
244
        return dst
2,692✔
245
}
246

247
// Reset removes all entities and components.
248
//
249
// Does NOT free the reserved memory.
250
func (a *archetype) Reset() {
52,552✔
251
        if a.len == 0 {
77,609✔
252
                return
25,057✔
253
        }
25,057✔
254
        a.len = 0
27,495✔
255
        for _, buf := range a.buffers {
55,024✔
256
                buf.SetZero()
27,529✔
257
        }
27,529✔
258
}
259

260
// Deactivate the archetype for later re-use.
261
func (a *archetype) Deactivate() {
27,427✔
262
        a.Reset()
27,427✔
263
        a.index = -1
27,427✔
264
}
27,427✔
265

266
// Activate reactivates a de-activated archetype.
267
func (a *archetype) Activate(target Entity, index int32) {
27,404✔
268
        a.index = index
27,404✔
269
        a.RelationTarget = target
27,404✔
270
}
27,404✔
271

272
func (a *archetype) ExtendLayouts(count uint8) {
8✔
273
        if len(a.layouts) >= int(count) {
10✔
274
                return
2✔
275
        }
2✔
276
        temp := a.layouts
6✔
277
        a.layouts = make([]layout, count)
6✔
278
        copy(a.layouts, temp)
6✔
279
        a.archetypeAccess.basePointer = unsafe.Pointer(&a.layouts[0])
6✔
280
}
281

282
// IsActive returns whether the archetype is active.
283
// Otherwise, it is eligible for re-use.
284
func (a *archetype) IsActive() bool {
5,102,573✔
285
        return a.index >= 0
5,102,573✔
286
}
5,102,573✔
287

288
// Components returns the component IDs for this archetype
289
func (a *archetype) Components() []ID {
2,991✔
290
        return a.node.Ids
2,991✔
291
}
2,991✔
292

293
// Len reports the number of entities in the archetype
294
func (a *archetype) Len() uint32 {
5,759,319✔
295
        return a.len
5,759,319✔
296
}
5,759,319✔
297

298
// Cap reports the current capacity of the archetype
299
func (a *archetype) Cap() uint32 {
5,100,047✔
300
        return a.cap
5,100,047✔
301
}
5,100,047✔
302

303
// Stats generates statistics for an archetype
304
func (a *archetype) Stats(reg *componentRegistry) stats.Archetype {
113✔
305
        ids := a.Components()
113✔
306
        aCompCount := len(ids)
113✔
307
        aTypes := make([]reflect.Type, aCompCount)
113✔
308
        for j, id := range ids {
225✔
309
                aTypes[j], _ = reg.ComponentType(id.id)
112✔
310
        }
112✔
311

312
        cap := int(a.Cap())
113✔
313
        memPerEntity := 0
113✔
314
        for _, id := range a.node.Ids {
225✔
315
                lay := a.getLayout(id)
112✔
316
                memPerEntity += int(lay.itemSize)
112✔
317
        }
112✔
318
        memory := cap * (int(entitySize) + memPerEntity)
113✔
319

113✔
320
        return stats.Archetype{
113✔
321
                IsActive: a.IsActive(),
113✔
322
                Size:     int(a.Len()),
113✔
323
                Capacity: cap,
113✔
324
                Memory:   memory,
113✔
325
        }
113✔
326
}
327

328
// UpdateStats updates statistics for an archetype
329
func (a *archetype) UpdateStats(node *stats.Node, stats *stats.Archetype, reg *componentRegistry) {
5,099,924✔
330
        cap := int(a.Cap())
5,099,924✔
331
        memory := cap * (int(entitySize) + node.MemoryPerEntity)
5,099,924✔
332

5,099,924✔
333
        stats.IsActive = a.IsActive()
5,099,924✔
334
        stats.Size = int(a.Len())
5,099,924✔
335
        stats.Capacity = cap
5,099,924✔
336
        stats.Memory = memory
5,099,924✔
337
}
5,099,924✔
338

339
// copy from one pointer to another.
340
func (a *archetype) copy(src, dst unsafe.Pointer, itemSize uint32) {
4,854,657✔
341
        dstSlice := (*[math.MaxInt32]byte)(dst)[:itemSize:itemSize]
4,854,657✔
342
        srcSlice := (*[math.MaxInt32]byte)(src)[:itemSize:itemSize]
4,854,657✔
343
        copy(dstSlice, srcSlice)
4,854,657✔
344
}
4,854,657✔
345

346
// extend the memory buffers if necessary for adding an entity.
347
func (a *archetype) extend(by uint32) {
558,407✔
348
        required := a.len + by
558,407✔
349
        if a.cap >= required {
1,116,738✔
350
                return
558,331✔
351
        }
558,331✔
352
        a.cap = capacityU32(required, a.node.capacityIncrement)
76✔
353

76✔
354
        old := a.entityBuffer
76✔
355
        a.entityBuffer = reflect.New(reflect.ArrayOf(int(a.cap), entityType)).Elem()
76✔
356
        a.entityPointer = a.entityBuffer.Addr().UnsafePointer()
76✔
357
        reflect.Copy(a.entityBuffer, old)
76✔
358

76✔
359
        for _, id := range a.node.Ids {
154✔
360
                lay := a.getLayout(id)
78✔
361
                if lay.itemSize == 0 {
85✔
362
                        continue
7✔
363
                }
364
                index, _ := a.indices.Get(id.id)
71✔
365
                old := a.buffers[index]
71✔
366
                a.buffers[index] = reflect.New(reflect.ArrayOf(int(a.cap), old.Type().Elem())).Elem()
71✔
367
                lay.pointer = a.buffers[index].Addr().UnsafePointer()
71✔
368
                reflect.Copy(a.buffers[index], old)
71✔
369
        }
370
}
371

372
// Adds an entity at the given index. Does not extend the entity buffer.
373
func (a *archetype) addEntity(index uint32, entity *Entity) {
3,292,496✔
374
        dst := unsafe.Add(a.entityPointer, entitySize*index)
3,292,496✔
375
        src := unsafe.Pointer(entity)
3,292,496✔
376
        a.copy(src, dst, entitySize)
3,292,496✔
377
}
3,292,496✔
378

379
// removeEntity removes an entity from tne archetype.
380
// Components need to be removed separately.
381
func (a *archetype) removeEntity(index uint32) bool {
525,385✔
382
        old := a.len - 1
525,385✔
383

525,385✔
384
        if index == old {
531,730✔
385
                return false
6,345✔
386
        }
6,345✔
387

388
        src := unsafe.Add(a.entityPointer, old*entitySize)
519,040✔
389
        dst := unsafe.Add(a.entityPointer, index*entitySize)
519,040✔
390
        a.copy(src, dst, entitySize)
519,040✔
391

519,040✔
392
        return true
519,040✔
393
}
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