-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathcoverage_ecs.html
More file actions
2821 lines (2346 loc) · 117 KB
/
coverage_ecs.html
File metadata and controls
2821 lines (2346 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ecs: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/argus-labs/world-engine/pkg/cardinal/ecs/archetype.go (97.2%)</option>
<option value="file1">github.com/argus-labs/world-engine/pkg/cardinal/ecs/column.go (97.8%)</option>
<option value="file2">github.com/argus-labs/world-engine/pkg/cardinal/ecs/command.go (87.5%)</option>
<option value="file3">github.com/argus-labs/world-engine/pkg/cardinal/ecs/component.go (89.5%)</option>
<option value="file4">github.com/argus-labs/world-engine/pkg/cardinal/ecs/ecs.go (36.4%)</option>
<option value="file5">github.com/argus-labs/world-engine/pkg/cardinal/ecs/event.go (93.9%)</option>
<option value="file6">github.com/argus-labs/world-engine/pkg/cardinal/ecs/internal/testutils/commands.go (0.0%)</option>
<option value="file7">github.com/argus-labs/world-engine/pkg/cardinal/ecs/internal/testutils/components.go (0.0%)</option>
<option value="file8">github.com/argus-labs/world-engine/pkg/cardinal/ecs/scheduler.go (94.7%)</option>
<option value="file9">github.com/argus-labs/world-engine/pkg/cardinal/ecs/search.go (93.5%)</option>
<option value="file10">github.com/argus-labs/world-engine/pkg/cardinal/ecs/sparse.go (100.0%)</option>
<option value="file11">github.com/argus-labs/world-engine/pkg/cardinal/ecs/system.go (73.7%)</option>
<option value="file12">github.com/argus-labs/world-engine/pkg/cardinal/ecs/system_event.go (90.9%)</option>
<option value="file13">github.com/argus-labs/world-engine/pkg/cardinal/ecs/system_state.go (67.5%)</option>
<option value="file14">github.com/argus-labs/world-engine/pkg/cardinal/ecs/world.go (58.3%)</option>
<option value="file15">github.com/argus-labs/world-engine/pkg/cardinal/ecs/world_state.go (94.9%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package ecs
import (
"github.com/argus-labs/world-engine/pkg/assert"
cardinalv1 "github.com/argus-labs/world-engine/proto/gen/go/worldengine/cardinal/v1"
"github.com/kelindar/bitmap"
"github.com/rotisserie/eris"
)
// archetypeID is the unique identifier for an archetype.
// It is used internally to track and manage archetypes efficiently.
type archetypeID = int
// archetype represents a collection of entities with the same component types.
// NOTE: We store the compCount instead of using Bitmap.Count() because counting bits is O(n). This
// saves us around 10ns/op, which is 10x speed up in low # of components. We store columns in a
// slice instead of a map because it's faster for small # of components.
type archetype struct {
id archetypeID // Corresponds to the index in the archetypes array
components bitmap.Bitmap // Bitmap of components contained in this archetype
rows sparseSet // Maps entity ID -> row index in entities and columns
entities []EntityID // List of entities of this archetype
columns []abstractColumn // List of columns containing component data
compCount int // Number of component types in the archetype
}
// newArchetype creates an archetype for the given component types.
func newArchetype(aid archetypeID, components bitmap.Bitmap, columns []abstractColumn) archetype <span class="cov8" title="1">{
assert.That(components.Count() == len(columns), "mismatched number of columns and components")
return archetype{
id: aid,
components: components,
rows: newSparseSet(),
entities: make([]EntityID, 0),
columns: columns,
compCount: len(columns),
}
}</span>
// exact returns true if the given components matches the archetype's exactly.
func (a *archetype) exact(components bitmap.Bitmap) bool <span class="cov8" title="1">{
if a.compCount != components.Count() </span><span class="cov8" title="1">{
return false
}</span>
<span class="cov8" title="1">return a.contains(components)</span>
}
// contains returns true if the archetype contains all of the components in the given components.
func (a *archetype) contains(components bitmap.Bitmap) bool <span class="cov8" title="1">{
intersect := components.Clone(nil)
intersect.And(a.components)
return intersect.Count() == components.Count()
}</span>
// -------------------------------------------------------------------------------------------------
// Entity operations
// -------------------------------------------------------------------------------------------------
// newEntity adds the entity to the archetype. It initializes the entity's components with their
// zero values. This is done to ensure the length of each column matches the length of the entities
// slice.
func (a *archetype) newEntity(eid EntityID) <span class="cov8" title="1">{
// Add to the entities slice.
a.entities = append(a.entities, eid)
// Extend the archetype's columns to make space for the new entity's components.
for _, column := range a.columns </span><span class="cov8" title="1">{
column.extend()
assert.That(column.len() == len(a.entities), "column components length doesn't match entities")
}</span>
// Map entity ID to its row.
<span class="cov8" title="1">a.rows.set(eid, len(a.entities)-1)</span>
}
// removeEntity removes an entity from the archetype. A remove swaps the last entity in the slice
// with the entity to remove, and returns the swapped entity ID. If the entity is the
// Expects the caller to check that the entity belongs to this archetype and is alive.
func (a *archetype) removeEntity(eid EntityID) <span class="cov8" title="1">{
row, exists := a.rows.get(eid)
assert.That(exists, "entity is not in archetype")
lastIndex := len(a.entities) - 1
// Swap the entity to remove with the last entity in the array.
a.entities[row] = a.entities[lastIndex]
// Truncate the array to remove the last entity.
a.entities = a.entities[:lastIndex]
// Remove the components of the entity.
for _, column := range a.columns </span><span class="cov8" title="1">{
column.remove(row)
assert.That(column.len() == len(a.entities), "column components length doesn't match entities")
}</span>
// Remove the entity from the row mapping.
<span class="cov8" title="1">ok := a.rows.remove(eid)
assert.That(ok, "entity isn't removed from sparse set")
// If the entity is the last item in the slice, nothing is swapped so we can just return.
if row == lastIndex </span><span class="cov8" title="1">{
return
}</span>
// Else, we ppdate the swapped entity metadata to point to the correct row.
<span class="cov8" title="1">movedID := a.entities[row]
a.rows.set(movedID, row)</span>
}
// moveEntity moves an entity from one archetype to another. It creates a new entity in the
// destination archetype, copies the component data from the current archetype, and removes the
// entity in the current archetype. Returns the swapped entity ID from the remove operation and the
// row in the destination archetype.
func (a *archetype) moveEntity(destination *archetype, eid EntityID) <span class="cov8" title="1">{
// Normally I'd assert(src != dst) here, but since we have newEntityWithArchetype({}) is valid,
// we'll just no-op instead of panic.
if a == destination </span><span class="cov8" title="1">{
return
}</span>
<span class="cov8" title="1">row, exists := a.rows.get(eid)
assert.That(exists, "entity is not in archetype")
// Create a new entity in the destination archetype with the id.
destination.newEntity(eid)
newRow, exists := destination.rows.get(eid)
assert.That(exists, "new entity isn't created in the destination archetype")
// Move entity's components to the new archetype.
for _, dst := range destination.columns </span><span class="cov8" title="1">{
for _, src := range a.columns </span><span class="cov8" title="1">{
if dst.name() == src.name() </span><span class="cov8" title="1">{
value := src.getAbstract(row)
dst.setAbstract(newRow, value)
}</span>
}
}
// Remove the entity from the current archetype, which also updates the row mapping.
<span class="cov8" title="1">a.removeEntity(eid)</span>
}
// -------------------------------------------------------------------------------------------------
// Serialization
// -------------------------------------------------------------------------------------------------
// toProto converts the archetype to a protobuf message for serialization.
func (a *archetype) toProto() (*cardinalv1.Archetype, error) <span class="cov8" title="1">{
componentsBitmap := a.components.ToBytes()
entities := make([]uint32, len(a.entities))
for i, eid := range a.entities </span><span class="cov8" title="1">{
entities[i] = uint32(eid)
}</span>
<span class="cov8" title="1">columns := make([]*cardinalv1.Column, len(a.columns))
for i, column := range a.columns </span><span class="cov8" title="1">{
data, err := column.toProto()
if err != nil </span><span class="cov0" title="0">{
return nil, eris.Wrapf(err, "failed to serialize column %d", i)
}</span>
<span class="cov8" title="1">columns[i] = data</span>
}
<span class="cov8" title="1">return &cardinalv1.Archetype{
Id: int32(a.id), //nolint:gosec // it's ok
ComponentsBitmap: componentsBitmap,
Entities: entities,
Columns: columns,
Rows: a.rows.toInt64Slice(),
}, nil</span>
}
// fromProto populates the archetype from a protobuf message. We pass a reference to the component
// manager to get the column factories needed to create the correct column[T].
func (a *archetype) fromProto(pb *cardinalv1.Archetype, cm *componentManager) error <span class="cov8" title="1">{
if pb == nil </span><span class="cov0" title="0">{
return eris.New("protobuf archetype is nil")
}</span>
<span class="cov8" title="1">a.id = archetypeID(pb.GetId())
a.components = bitmap.FromBytes(pb.GetComponentsBitmap())
a.rows.fromInt64Slice(pb.GetRows())
a.entities = make([]EntityID, len(pb.GetEntities()))
for i, eid := range pb.GetEntities() </span><span class="cov8" title="1">{
a.entities[i] = EntityID(eid)
}</span>
<span class="cov8" title="1">a.columns = make([]abstractColumn, len(pb.GetColumns()))
for i, pbCol := range pb.GetColumns() </span><span class="cov8" title="1">{
cid, err := cm.getID(pbCol.GetComponentName())
if err != nil </span><span class="cov8" title="1">{
return eris.Wrap(err, "failed to get component id")
}</span>
<span class="cov8" title="1">factory := cm.factories[cid]
column := factory()
if err := column.fromProto(pbCol); err != nil </span><span class="cov8" title="1">{
return eris.Wrapf(err, "failed to deserialize column %d", i)
}</span>
<span class="cov8" title="1">a.columns[i] = column</span>
}
<span class="cov8" title="1">a.compCount = len(a.columns)
return nil</span>
}
</pre>
<pre class="file" id="file1" style="display: none">package ecs
import (
"github.com/argus-labs/world-engine/pkg/assert"
cardinalv1 "github.com/argus-labs/world-engine/proto/gen/go/worldengine/cardinal/v1"
"github.com/goccy/go-json"
"github.com/rotisserie/eris"
)
// columnFactory is a function that creates a new abstractColumn instance.
type columnFactory func() abstractColumn
// abstractColumn is an internal interface for generic column operations.
type abstractColumn interface {
len() int
name() string
extend()
setAbstract(row int, component Component)
getAbstract(row int) Component
remove(row int)
toProto() (*cardinalv1.Column, error)
fromProto(*cardinalv1.Column) error
}
var _ abstractColumn = &column[Component]{}
// column stores the component data of entities in an archetype. The length of the components slice
// must match the length of the entities slice in the archetype.
type column[T Component] struct {
compName string // The name of the component stored in this column
components []T // Array containing the component data
}
const columnCapacity = 16
// newColumn creates a new column with the specified type.
func newColumn[T Component]() column[T] <span class="cov8" title="1">{
var zero T
return column[T]{
compName: zero.Name(),
components: make([]T, 0, columnCapacity),
}
}</span>
// newColumnFactory returns a function that constructs a new column of type T.
func newColumnFactory[T Component]() columnFactory <span class="cov8" title="1">{
return func() abstractColumn </span><span class="cov8" title="1">{
col := newColumn[T]()
return &col
}</span>
}
// len returns the length of the components slice.
func (c *column[T]) len() int <span class="cov8" title="1">{
return len(c.components)
}</span>
// name returns the name of the component type.
func (c *column[T]) name() string <span class="cov8" title="1">{
return c.compName
}</span>
// extend adds a new row to the components slice and initializes them with the zero value.
func (c *column[T]) extend() <span class="cov8" title="1">{
// Double the capacity when the capacity is reached.
if len(c.components) == cap(c.components) </span><span class="cov8" title="1">{
newCap := cap(c.components) * 2
newComponents := make([]T, len(c.components), newCap)
copy(newComponents, c.components)
c.components = newComponents
}</span>
<span class="cov8" title="1">var zero T
c.components = append(c.components, zero)</span>
}
// set sets the component in a given row. A row corresponds to a single entity. Whenever possible
// prefer this method over setAbstract since it avoids the type assertion and avoids boxing the
// component data, which does allocations.
func (c *column[T]) set(row int, component T) <span class="cov8" title="1">{
assert.That(row < len(c.components), "column isn't extended when entity is created")
c.components[row] = component
}</span>
// setAbstract sets the component in a given row. A row corresponds to a single entity. Use this
// method only when you don't know the concrete type of the component.
func (c *column[T]) setAbstract(row int, component Component) <span class="cov8" title="1">{
concrete, ok := component.(T)
assert.That(ok, "tried to set the wrong component type")
c.set(row, concrete)
}</span>
// get gets the value from a given row. A row corresponds to a single entity. Expects the caller
// to make sure the row is inside the column. Whenever possible prefer this method over getAbstract
// since it avoids the type assertion and avoids boxing the component data, which does allocations.
func (c *column[T]) get(row int) T <span class="cov8" title="1">{
assert.That(row < len(c.components), "component doesn't exist")
return c.components[row]
}</span>
// getAbstract gets the value from a given row. A row corresponds to a single entity. Expects the
// caller to make sure the row is inside the column. Use this method only when you don't know the
// concrete type of the component.
func (c *column[T]) getAbstract(row int) Component <span class="cov8" title="1">{
return c.get(row)
}</span>
// remove removes a given row. A row corresponds to a single entity. Expects the caller to make sure
// the row is inside the column. A remove swaps the last value in the slice with the row to remove.
func (c *column[T]) remove(row int) <span class="cov8" title="1">{
assert.That(row < len(c.components), "tried to remove component that doesn't exist")
lastIndex := len(c.components) - 1
// Removing a component is the same as moving the entity to another archetype.
// Swap the component to remove with the last component in the array.
c.components[row] = c.components[lastIndex]
// Truncate the array to remove the last component.
c.components = c.components[:lastIndex]
}</span>
// toProto converts the column to a protobuf message for serialization.
func (c *column[T]) toProto() (*cardinalv1.Column, error) <span class="cov8" title="1">{
componentData := make([][]byte, len(c.components))
for i, component := range c.components </span><span class="cov8" title="1">{
data, err := json.Marshal(component)
if err != nil </span><span class="cov0" title="0">{
return nil, eris.Wrapf(err, "failed to serialize component at index %d", i)
}</span>
<span class="cov8" title="1">componentData[i] = data</span>
}
<span class="cov8" title="1">return &cardinalv1.Column{
ComponentName: c.compName,
Components: componentData,
}, nil</span>
}
// fromProto populates the column from a protobuf message.
func (c *column[T]) fromProto(pb *cardinalv1.Column) error <span class="cov8" title="1">{
if pb == nil </span><span class="cov8" title="1">{
return eris.New("protobuf column is nil")
}</span>
<span class="cov8" title="1">if pb.GetComponentName() != c.compName </span><span class="cov8" title="1">{
return eris.Errorf("component name mismatch: expected %s, got %s", c.compName, pb.GetComponentName())
}</span>
<span class="cov8" title="1">components := make([]T, len(pb.GetComponents()))
for i, data := range pb.GetComponents() </span><span class="cov8" title="1">{
var component T
if err := json.Unmarshal(data, &component); err != nil </span><span class="cov8" title="1">{
return eris.Wrapf(err, "failed to deserialize component at index %d", i)
}</span>
<span class="cov8" title="1">components[i] = component</span>
}
<span class="cov8" title="1">c.components = components
return nil</span>
}
</pre>
<pre class="file" id="file2" style="display: none">package ecs
import (
"math"
"github.com/argus-labs/world-engine/pkg/assert"
"github.com/argus-labs/world-engine/pkg/micro"
"github.com/rotisserie/eris"
)
// CommandID is a unique identifier for a command type.
type CommandID uint32
// MaxCommandID is the maximum number of command types that can be registered.
const MaxCommandID = math.MaxUint32 - 1
// Command is the interface that all commands must implement.
// Commands are predefined user actions that are handled by systems.
type Command interface { //nolint:iface // ecs.Command must be a subset of micro.ShardCommand
micro.ShardCommand
}
// commandManager manages the registration and storage of commands.
type commandManager struct {
nextID CommandID // The next command ID
catalog map[string]CommandID // Command name -> Command ID
commands [][]micro.Command // Command ID -> command
}
// newCommandManager creates a new commandManager.
func newCommandManager() commandManager <span class="cov8" title="1">{
return commandManager{
nextID: 0,
catalog: make(map[string]CommandID),
commands: make([][]micro.Command, 0),
}
}</span>
// register registers a new command type. If the command is already registered, the existing ID
// is returned.
func (c *commandManager) register(name string) (CommandID, error) <span class="cov8" title="1">{
if name == "" </span><span class="cov0" title="0">{
return 0, eris.New("command name cannot be empty")
}</span>
// If the command is already registered, return the existing ID.
<span class="cov8" title="1">if id, exists := c.catalog[name]; exists </span><span class="cov8" title="1">{
return id, nil
}</span>
<span class="cov8" title="1">if c.nextID > MaxCommandID </span><span class="cov0" title="0">{
return 0, eris.New("max number of commands exceeded")
}</span>
<span class="cov8" title="1">const initialCommandBufferCapacity = 128
c.catalog[name] = c.nextID
c.commands = append(c.commands, make([]micro.Command, 0, initialCommandBufferCapacity))
c.nextID++
assert.That(int(c.nextID) == len(c.commands), "command id doesn't match number of commands")
return c.nextID - 1, nil</span>
}
// get retrieves a list of commands for a given command name.
func (c *commandManager) get(name string) ([]micro.Command, error) <span class="cov8" title="1">{
id, exists := c.catalog[name]
if !exists </span><span class="cov0" title="0">{
return nil, eris.Errorf("command %s is not registered", name)
}</span>
<span class="cov8" title="1">return c.commands[id], nil</span>
}
// clear clears the command buffer.
func (c *commandManager) clear() <span class="cov8" title="1">{
for id := range c.commands </span><span class="cov8" title="1">{
c.commands[id] = c.commands[id][:0]
assert.That(len(c.commands[id]) == 0, "commands not cleared properly")
}</span>
}
// receiveCommands receives a list of commands and stores them in the commandManager.
// All commands are assumed to be pre-validated by the micro layer (micro.commandManager.Enqueue),
// which rejects unregistered commands before they reach ECS. An unknown command name here indicates
// a mismatch between micro and ECS command registration, which is a programming error, so we should
// fail fast (and loudly) instead of silently ignoring it.
func (c *commandManager) receiveCommands(commands []micro.Command) <span class="cov8" title="1">{
for _, command := range commands </span><span class="cov8" title="1">{
id, exists := c.catalog[command.Command.Body.Name]
assert.That(exists, "command %s is not registered", command.Command.Body.Name)
c.commands[id] = append(c.commands[id], command)
}</span>
}
</pre>
<pre class="file" id="file3" style="display: none">package ecs
import (
"regexp"
"github.com/argus-labs/world-engine/pkg/assert"
"github.com/rotisserie/eris"
)
// Component is the interface that all components must implement.
// Components are pure data containers that can be attached to entities.
type Component interface { //nolint:iface // We may add more methods in the future.
// Name returns a unique string identifier for the component type.
// This should be consistent across program executions.
//
// Component names must follow these rules:
// - Start with a letter (a-z, A-Z) or underscore (_)
// - Contain only letters, digits (0-9), and underscores
// - Cannot contain hyphens (-), spaces, dots (.), or other special characters
//
// Valid examples: "Health", "PlayerData", "player_health", "_internal", "Component123"
// Invalid examples: "player-data", "123Invalid", "my.component", "has space"
//
// These rules ensure component names work correctly in query expressions.
Name() string
}
// componentID is a unique identifier for a component type.
// It is used internally to track and manage component types efficiently.
type componentID = uint32
// componentManager manages component type registration and lookup.
type componentManager struct {
nextID componentID // The next available component ID
catalog map[string]componentID // Component name -> component ID
factories []columnFactory // Component ID -> column factory
}
// newComponentManager creates a new component manager.
func newComponentManager() componentManager <span class="cov8" title="1">{
return componentManager{
nextID: 0,
catalog: make(map[string]componentID),
factories: make([]columnFactory, 0),
}
}</span>
var componentNamePattern = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)
// validateComponentName validates that a component name follows expr identifier rules.
// See: https://expr-lang.org/docs/language-definition#variables
func validateComponentName(name string) error <span class="cov8" title="1">{
if name == "" </span><span class="cov0" title="0">{
return eris.New("component name cannot be empty")
}</span>
<span class="cov8" title="1">if !componentNamePattern.MatchString(name) </span><span class="cov8" title="1">{
return eris.Errorf(
"component name '%s' is invalid: must start with a letter or underscore, "+
"and contain only letters, digits, and underscores",
name,
)
}</span>
<span class="cov8" title="1">return nil</span>
}
// register registers a new component type and returns its ID.
// If the component is already registered, no-op.
func (cm *componentManager) register(name string, factory columnFactory) (componentID, error) <span class="cov8" title="1">{
// Validate component name follows expr identifier rules
if err := validateComponentName(name); err != nil </span><span class="cov0" title="0">{
return 0, err
}</span>
// If component already exists, no-op.
<span class="cov8" title="1">if cid, exists := cm.catalog[name]; exists </span><span class="cov8" title="1">{
return cid, nil
}</span>
<span class="cov8" title="1">cm.catalog[name] = cm.nextID
cm.factories = append(cm.factories, factory)
cm.nextID++
assert.That(int(cm.nextID) == len(cm.factories), "component id doesn't match number of components")
return cm.nextID - 1, nil</span>
}
// getID returns a component's ID given a name.
func (cm *componentManager) getID(name string) (componentID, error) <span class="cov8" title="1">{
id, exists := cm.catalog[name]
if !exists </span><span class="cov8" title="1">{
return 0, eris.Wrapf(ErrComponentNotFound, "component %s", name)
}</span>
<span class="cov8" title="1">return id, nil</span>
}
</pre>
<pre class="file" id="file4" style="display: none">package ecs
import "github.com/rotisserie/eris"
// Create creates an entity without any components.
func Create(ws *worldState) EntityID <span class="cov8" title="1">{
return ws.newEntity()
}</span>
// Destroy deletes an entity and all its components from the world. Returns true if the entity is
// deleted, false otherwise.
func Destroy(ws *worldState, eid EntityID) bool <span class="cov8" title="1">{
return ws.removeEntity(eid)
}</span>
// Alive checks if an entity exists in the world.
func Alive(ws *worldState, eid EntityID) bool <span class="cov0" title="0">{
_, exists := ws.entityArch.get(eid)
return exists
}</span>
// Set sets a component on an entity. If the entity contains the component type, it will update the
// value. If it doesn't, it will add the component.
func Set[T Component](ws *worldState, eid EntityID, component T) error <span class="cov8" title="1">{
return setComponent(ws, eid, component)
}</span>
// Get gets a component from an entity.
// Returns an error if the entity doesn't exist or doesn't contain the component type.
func Get[T Component](ws *worldState, eid EntityID) (T, error) <span class="cov8" title="1">{
return getComponent[T](ws, eid)
}</span>
// Remove removes a component from an entity.
// Returns an error if the entity or the component to remove doesn't exist.
func Remove[T Component](ws *worldState, eid EntityID) error <span class="cov0" title="0">{
return removeComponent[T](ws, eid)
}</span>
// Has checks if an entity has a specific component type.
// Returns false if either the entity doesn't exist or doesn't have the component.
func Has[T Component](ws *worldState, eid EntityID) bool <span class="cov0" title="0">{
_, err := Get[T](ws, eid)
if err == nil </span><span class="cov0" title="0">{
return true
}</span>
<span class="cov0" title="0">return eris.Is(err, ErrComponentNotFound)</span>
}
</pre>
<pre class="file" id="file5" style="display: none">package ecs
import (
"sync"
"github.com/argus-labs/world-engine/pkg/assert"
"github.com/rotisserie/eris"
)
// Event is an interface that all events must implement.
// Events are packets of information that are sent from systems to the outside world.
type Event = Command
// EventKind is a type that represents the kind of event.
type EventKind uint8
const (
// EventKindDefault is the default event kind.
EventKindDefault EventKind = 1
// Reserve 0 for zero value / unspecified event kind in protobuf.
// Reserve 14 more values (2...15) for future ecs event kind.
// Users of the `ecs` package should start with CustomEventKindStart for their custom event kinds.
// Example:
//
// const (
// EventKindCustom = iota + ecs.CustomEventKindStart
// )
)
const CustomEventKindStart = 16
// RawEvent is the format of ECS output. It has a kind and a payload. The kind determines the type
// of event contained in the payload. Users of ECS can define custom event kinds and handle them in
// their own event handlers.
type RawEvent struct {
Kind EventKind // The kind of event
Payload any // The payload of the event
}
const (
defaultEventChannelCapacity = 1024
defaultEventBufferCapacity = 128
)
// eventManager manages the registration and storage of events.
type eventManager struct {
events chan RawEvent // Channel for collecting events emitted by systems
buffer []RawEvent // Buffer for storing events to be outputted
mu sync.Mutex // Mutex for buffer access during flush
registry map[string]uint32 // Map from event name to event ID
nextID uint32 // Next available event ID
}
// newEventManager creates a new eventManager with optional configuration.
func newEventManager(opts ...eventManagerOption) *eventManager <span class="cov8" title="1">{
em := &eventManager{
events: make(chan RawEvent, defaultEventChannelCapacity),
buffer: make([]RawEvent, 0, defaultEventBufferCapacity),
registry: make(map[string]uint32),
nextID: 0,
}
for _, opt := range opts </span><span class="cov8" title="1">{
opt(em)
}</span>
<span class="cov8" title="1">return em</span>
}
// register registers an event type and returns its ID. If already registered, returns existing ID.
// This is used just to check for duplicate WithEvent handlers in a system.
func (e *eventManager) register(name string) (uint32, error) <span class="cov8" title="1">{
if name == "" </span><span class="cov0" title="0">{
return 0, eris.New("event name cannot be empty")
}</span>
<span class="cov8" title="1">if id, exists := e.registry[name]; exists </span><span class="cov8" title="1">{
return id, nil
}</span>
<span class="cov8" title="1">if e.nextID > MaxCommandID </span><span class="cov0" title="0">{
return 0, eris.New("max number of events exceeded")
}</span>
<span class="cov8" title="1">e.registry[name] = e.nextID
e.nextID++
return e.nextID - 1, nil</span>
}
// enqueue enqueues an event into the eventManager.
// If the channel is full, it flushes the channel to the buffer first.
func (e *eventManager) enqueue(kind EventKind, payload any) <span class="cov8" title="1">{
event := RawEvent{Kind: kind, Payload: payload}
select </span>{
case e.events <- event:<span class="cov8" title="1"></span>
// Happy path: channel has capacity.
default:<span class="cov8" title="1">
// Channel full: flush to buffer, then send.
e.mu.Lock()
e.flush()
e.mu.Unlock()
e.events <- event</span>
}
}
// getEvents retrieves all events from the eventManager.
func (e *eventManager) getEvents() []RawEvent <span class="cov8" title="1">{
e.mu.Lock()
defer e.mu.Unlock()
e.flush()
return e.buffer
}</span>
// flush drains the channel into the buffer. Called when channel is full.
// TThis method expects the caller to hold tthe mutex lock.
func (e *eventManager) flush() <span class="cov8" title="1">{
for </span><span class="cov8" title="1">{
select </span>{
case event := <-e.events:<span class="cov8" title="1">
e.buffer = append(e.buffer, event)</span>
default:<span class="cov8" title="1">
return</span>
}
}
}
// clear clears the event buffer.
func (e *eventManager) clear() <span class="cov8" title="1">{
e.mu.Lock()
defer e.mu.Unlock()
e.buffer = e.buffer[:0]
assert.That(len(e.buffer) == 0, "event buffer not cleared properly")
}</span>
// -------------------------------------------------------------------------------------------------
// Options
// -------------------------------------------------------------------------------------------------
type eventManagerOption func(*eventManager)
func withChannelCapacity(capacity int) eventManagerOption <span class="cov8" title="1">{
return func(em *eventManager) </span><span class="cov8" title="1">{
em.events = make(chan RawEvent, capacity)
}</span>
}
</pre>
<pre class="file" id="file6" style="display: none">package testutils
// Commands.
type AttackPlayerCommand struct{ Value int }
func (AttackPlayerCommand) Name() string <span class="cov0" title="0">{ return "attack-player" }</span>
type InvalidEmptyCommand struct{}
func (InvalidEmptyCommand) Name() string <span class="cov0" title="0">{ return "" }</span>
type CreatePlayerCommand struct{ Value int }
func (CreatePlayerCommand) Name() string <span class="cov0" title="0">{ return "create-player" }</span>
// Events.
type PlayerDeathEvent struct{ Value int }
func (PlayerDeathEvent) Name() string <span class="cov0" title="0">{ return "player-death" }</span>
type ItemDropEvent struct{ Value int }
func (ItemDropEvent) Name() string <span class="cov0" title="0">{ return "item-drop" }</span>
type EmptySubjectEvent struct{ Value int }
func (EmptySubjectEvent) Name() string <span class="cov0" title="0">{ return "" }</span>
// System events.
type PlayerDeathSystemEvent struct{ Value int }
func (PlayerDeathSystemEvent) Name() string <span class="cov0" title="0">{ return "player-death-system" }</span>
type ItemDropSystemEvent struct{ Value int }
func (ItemDropSystemEvent) Name() string <span class="cov0" title="0">{ return "item-drop-system" }</span>
</pre>
<pre class="file" id="file7" style="display: none">package testutils
type Health struct {
Value int `json:"value"`
}
func (Health) Name() string <span class="cov0" title="0">{ return "Health" }</span>
type Position struct{ X, Y int }
func (Position) Name() string <span class="cov0" title="0">{ return "Position" }</span>
type Velocity struct{ X, Y int }
func (Velocity) Name() string <span class="cov0" title="0">{ return "Velocity" }</span>
type Experience struct{ Value int }
func (Experience) Name() string <span class="cov0" title="0">{ return "Experience" }</span>
type PlayerTag struct{ Tag string }
func (PlayerTag) Name() string <span class="cov0" title="0">{ return "PlayerTag" }</span>
type Level struct{ Value int }
func (Level) Name() string <span class="cov0" title="0">{ return "Level" }</span>
type MapComponent struct {
Items map[string]int `json:"items"`
}
func (MapComponent) Name() string <span class="cov0" title="0">{ return "MapComponent" }</span>
</pre>
<pre class="file" id="file8" style="display: none">package ecs
import (
"sync/atomic"
"slices"
"github.com/kelindar/bitmap"
"github.com/rotisserie/eris"
"golang.org/x/sync/errgroup"
)
// systemMetadata contains the metadata for a system.
type systemMetadata struct {
name string // The name of the system
deps bitmap.Bitmap // Bitmap of system dependencies (components + system events)
fn func() error // Function that wraps a System
}
// systemScheduler manages the execution of systems in a dependency-aware concurrent manner.
// It orders systems based on their component and system event dependencies and is optimized to
// maximize parallelism while maintaining correct order.
type systemScheduler struct {
systems []systemMetadata // The systems to run
tier0 []int // The first execution tier
graph map[int][]int // Mapping of systems -> systems that depend on it
activeIndegree uint8 // Determines which indegree is currently active (0 or 1)
// indegree0 and indegree1 are double-buffered counters tracking remaining dependencies
// for each system. They alternate between runs to avoid reinitialization.
indegree0 []atomic.Int32
indegree1 []atomic.Int32
}
// newSystemScheduler creates a new system scheduler.
func newSystemScheduler() systemScheduler <span class="cov8" title="1">{
return systemScheduler{
systems: make([]systemMetadata, 0),
tier0: make([]int, 0),
graph: make(map[int][]int),
activeIndegree: 0,
}
}</span>
// register registers a system with the scheduler.
func (s *systemScheduler) register(name string, systemDep bitmap.Bitmap, systemFn func() error) <span class="cov8" title="1">{
s.systems = append(s.systems, systemMetadata{name: name, deps: systemDep, fn: systemFn})
}</span>
// Run executes the systems in the order of their dependencies. It returns an error if any system
// returns an error. If multiple systems fail, all errors are wrapped in a single error.
func (s *systemScheduler) Run() error <span class="cov8" title="1">{
// Fast path: no systems in hook.
if len(s.systems) == 0 </span><span class="cov0" title="0">{
return nil
}</span>
<span class="cov8" title="1">executionQueue := make(chan int, len(s.systems))