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

mlange-42 / arche / 12169480381 / 1

Source File

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 {
4,996,303✔
28
        return *(*Entity)(unsafe.Add(a.entityPointer, entitySize*index))
4,996,303✔
29
}
4,996,303✔
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,505,933✔
33
        return a.getLayout(id).Get(index)
1,505,933✔
34
}
1,505,933✔
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,558,125✔
48
        return (*layout)(unsafe.Add(a.basePointer, layoutSize*uint32(id.id)))
2,558,125✔
49
}
2,558,125✔
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,505,931✔
59
        if l.pointer == nil {
1,505,932✔
60
                return nil
1✔
61
        }
1✔
62
        return unsafe.Add(l.pointer, l.itemSize*index)
1,505,930✔
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 {
529,801✔
130
        idx := a.len
529,801✔
131
        a.extend(1)
529,801✔
132
        a.addEntity(idx, &entity)
529,801✔
133
        a.len++
529,801✔
134
        return idx
529,801✔
135
}
529,801✔
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 {
524,429✔
148
        swapped := a.removeEntity(index)
524,429✔
149

524,429✔
150
        old := a.len - 1
524,429✔
151

524,429✔
152
        if index != old {
1,042,529✔
153
                for _, id := range a.node.Ids {
1,036,445✔
154
                        lay := a.getLayout(id)
518,345✔
155
                        size := lay.itemSize
518,345✔
156
                        if size == 0 {
518,654✔
157
                                continue
309✔
158
                        }
159
                        src := unsafe.Add(lay.pointer, old*size)
518,036✔
160
                        dst := unsafe.Add(lay.pointer, index*size)
518,036✔
161
                        a.copy(src, dst, size)
518,036✔
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)
524,429✔
168
        a.len--
524,429✔
169

524,429✔
170
        return swapped
524,429✔
171
}
172

173
// ZeroAll resets a block of storage in all buffers.
174
func (a *archetype) ZeroAll(index uint32) {
524,429✔
175
        for _, id := range a.node.Ids {
1,047,212✔
176
                a.Zero(index, id)
522,783✔
177
        }
522,783✔
178
}
179

180
// Zero resets a block of storage in one buffer.
181
func (a *archetype) Zero(index uint32, id ID) {
522,783✔
182
        lay := a.getLayout(id)
522,783✔
183
        size := lay.itemSize
522,783✔
184
        if size == 0 {
525,934✔
185
                return
3,151✔
186
        }
3,151✔
187
        dst := unsafe.Add(lay.pointer, index*size)
519,632✔
188
        a.copy(a.node.zeroPointer, dst, size)
519,632✔
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 {
938✔
198
        lay := a.getLayout(id)
938✔
199
        dst := a.Get(index, id)
938✔
200
        size := lay.itemSize
938✔
201
        if size == 0 {
1,011✔
202
                return dst
73✔
203
        }
73✔
204
        rValue := reflect.ValueOf(comp)
865✔
205

865✔
206
        src := rValue.UnsafePointer()
865✔
207
        a.copy(src, dst, size)
865✔
208
        return dst
865✔
209
}
210

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

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

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

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

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

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

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

265
// Components returns the component IDs for this archetype
266
func (a *archetype) Components() []ID {
2,991✔
267
        return a.node.Ids
2,991✔
268
}
2,991✔
269

270
// Len reports the number of entities in the archetype
271
func (a *archetype) Len() uint32 {
5,758,363✔
272
        return a.len
5,758,363✔
273
}
5,758,363✔
274

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

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

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

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

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

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

316
// copy from one pointer to another.
317
func (a *archetype) copy(src, dst unsafe.Pointer, itemSize uint32) {
4,850,854✔
318
        dstSlice := (*[math.MaxInt32]byte)(dst)[:itemSize:itemSize]
4,850,854✔
319
        srcSlice := (*[math.MaxInt32]byte)(src)[:itemSize:itemSize]
4,850,854✔
320
        copy(dstSlice, srcSlice)
4,850,854✔
321
}
4,850,854✔
322

323
// extend the memory buffers if necessary for adding an entity.
324
func (a *archetype) extend(by uint32) {
557,440✔
325
        required := a.len + by
557,440✔
326
        if a.cap >= required {
1,114,803✔
327
                return
557,363✔
328
        }
557,363✔
329
        a.cap = capacityU32(required, a.node.capacityIncrement)
77✔
330

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

77✔
336
        for _, id := range a.node.Ids {
156✔
337
                lay := a.getLayout(id)
79✔
338
                if lay.itemSize == 0 {
86✔
339
                        continue
7✔
340
                }
341
                index, _ := a.indices.Get(id.id)
72✔
342
                old := a.buffers[index]
72✔
343
                a.buffers[index] = reflect.New(reflect.ArrayOf(int(a.cap), old.Type().Elem())).Elem()
72✔
344
                lay.pointer = a.buffers[index].Addr().UnsafePointer()
72✔
345
                reflect.Copy(a.buffers[index], old)
72✔
346
        }
347
}
348

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

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

524,429✔
361
        if index == old {
530,758✔
362
                return false
6,329✔
363
        }
6,329✔
364

365
        src := unsafe.Add(a.entityPointer, old*entitySize)
518,100✔
366
        dst := unsafe.Add(a.entityPointer, index*entitySize)
518,100✔
367
        a.copy(src, dst, entitySize)
518,100✔
368

518,100✔
369
        return true
518,100✔
370
}
  • Back to Build 12169480381
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