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

mlange-42 / arche / 12455637666

22 Dec 2024 03:48PM CUT coverage: 100.0%. Remained the same
12455637666

Pull #442

github

web-flow
Merge dcf4cea1c into 30c1f4bc4
Pull Request #442: Update CHANGELOG for release v0.14.0

6411 of 6411 relevant lines covered (100.0%)

114030.79 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,342,207✔
28
        return *(*Entity)(unsafe.Add(a.entityPointer, entitySize*index))
7,342,207✔
29
}
7,342,207✔
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,919,793✔
33
        return a.getLayout(id).Get(index)
2,919,793✔
34
}
2,919,793✔
35

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

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

46
// GetLayout returns the column layout for a component.
47
func (a *archetypeAccess) getLayout(id ID) *layout {
5,907,240✔
48
        return (*layout)(unsafe.Add(a.basePointer, layoutSize*uint32(id.id)))
5,907,240✔
49
}
5,907,240✔
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,919,791✔
59
        if l.pointer == nil {
2,919,792✔
60
                return nil
1✔
61
        }
1✔
62
        return unsafe.Add(l.pointer, l.itemSize*index)
2,919,790✔
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,514✔
84
        if !node.IsActive {
2,865✔
85
                node.IsActive = true
1,351✔
86
        }
1,351✔
87

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

1,514✔
94
        cap := 1
1,514✔
95
        if forStorage {
2,887✔
96
                cap = int(node.capacityIncrement)
1,373✔
97
        }
1,373✔
98

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

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

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

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

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

128
// Add adds an entity with optionally zeroed components to the archetype
129
func (a *archetype) Alloc(entity Entity) uint32 {
1,498,257✔
130
        idx := a.len
1,498,257✔
131
        a.extend(1)
1,498,257✔
132
        a.addEntity(idx, &entity)
1,498,257✔
133
        a.len++
1,498,257✔
134
        return idx
1,498,257✔
135
}
1,498,257✔
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,492,517✔
148
        swapped := a.removeEntity(index)
1,492,517✔
149

1,492,517✔
150
        old := a.len - 1
1,492,517✔
151

1,492,517✔
152
        if index != old {
2,489,809✔
153
                for _, id := range a.node.Ids {
1,994,829✔
154
                        lay := a.getLayout(id)
997,537✔
155
                        size := lay.itemSize
997,537✔
156
                        if size == 0 {
997,846✔
157
                                continue
309✔
158
                        }
159
                        src := unsafe.Add(lay.pointer, old*size)
997,228✔
160
                        dst := unsafe.Add(lay.pointer, index*size)
997,228✔
161
                        a.copy(src, dst, size)
997,228✔
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,492,517✔
168
        a.len--
1,492,517✔
169

1,492,517✔
170
        return swapped
1,492,517✔
171
}
172

173
// ZeroAll resets a block of storage in all buffers.
174
func (a *archetype) ZeroAll(index uint32) {
1,492,517✔
175
        for _, id := range a.node.Ids {
2,495,436✔
176
                a.Zero(index, id)
1,002,919✔
177
        }
1,002,919✔
178
}
179

180
// Zero resets a block of storage in one buffer.
181
func (a *archetype) Zero(index uint32, id ID) {
1,002,919✔
182
        lay := a.getLayout(id)
1,002,919✔
183
        size := lay.itemSize
1,002,919✔
184
        if size == 0 {
1,006,070✔
185
                return
3,151✔
186
        }
3,151✔
187
        dst := unsafe.Add(lay.pointer, index*size)
999,768✔
188
        a.copy(a.node.zeroPointer, dst, size)
999,768✔
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
func (a *archetype) Set(index uint32, id ID, comp interface{}) unsafe.Pointer {
488,890✔
198
        lay := a.getLayout(id)
488,890✔
199
        dst := a.Get(index, id)
488,890✔
200
        size := lay.itemSize
488,890✔
201
        if size == 0 {
488,963✔
202
                return dst
73✔
203
        }
73✔
204
        rValue := reflect.ValueOf(comp).Elem()
488,817✔
205

488,817✔
206
        valueType := rValue.Type()
488,817✔
207
        valuePtr := reflect.NewAt(valueType, dst)
488,817✔
208
        valuePtr.Elem().Set(rValue)
488,817✔
209

488,817✔
210
        return dst
488,817✔
211
}
212

213
// SetPointer overwrites a component with the data behind the given pointer
214
func (a *archetype) SetPointer(index uint32, id ID, comp unsafe.Pointer) unsafe.Pointer {
8,071✔
215
        lay := a.getLayout(id)
8,071✔
216
        dst := a.Get(index, id)
8,071✔
217
        size := lay.itemSize
8,071✔
218
        if size == 0 {
13,450✔
219
                return dst
5,379✔
220
        }
5,379✔
221

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

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

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

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

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

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

267
// Components returns the component IDs for this archetype
268
func (a *archetype) Components() []ID {
490,943✔
269
        return a.node.Ids
490,943✔
270
}
490,943✔
271

272
// Len reports the number of entities in the archetype
273
func (a *archetype) Len() uint32 {
6,728,451✔
274
        return a.len
6,728,451✔
275
}
6,728,451✔
276

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

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

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

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

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

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

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

325
// extend the memory buffers if necessary for adding an entity.
326
func (a *archetype) extend(by uint32) {
1,525,896✔
327
        required := a.len + by
1,525,896✔
328
        if a.cap >= required {
3,051,692✔
329
                return
1,525,796✔
330
        }
1,525,796✔
331
        a.cap = capacityU32(required, a.node.capacityIncrement)
100✔
332

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

100✔
338
        for _, id := range a.node.Ids {
202✔
339
                lay := a.getLayout(id)
102✔
340
                if lay.itemSize == 0 {
109✔
341
                        continue
7✔
342
                }
343
                index, _ := a.indices.Get(id.id)
95✔
344
                old := a.buffers[index]
95✔
345
                a.buffers[index] = reflect.New(reflect.ArrayOf(int(a.cap), old.Type().Elem())).Elem()
95✔
346
                lay.pointer = a.buffers[index].Addr().UnsafePointer()
95✔
347
                reflect.Copy(a.buffers[index], old)
95✔
348
        }
349
}
350

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

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

1,492,517✔
363
        if index == old {
1,987,742✔
364
                return false
495,225✔
365
        }
495,225✔
366

367
        src := unsafe.Add(a.entityPointer, old*entitySize)
997,292✔
368
        dst := unsafe.Add(a.entityPointer, index*entitySize)
997,292✔
369
        a.copy(src, dst, entitySize)
997,292✔
370

997,292✔
371
        return true
997,292✔
372
}
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