-
Notifications
You must be signed in to change notification settings - Fork 1
/
query.go
77 lines (71 loc) · 1.54 KB
/
query.go
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
package ecs
import (
"reflect"
)
type Query struct {
types []reflect.Type
numTypes int
}
func NewQuery(types ...reflect.Type) Query {
return Query{types, len(types)}
}
func (query Query) MatchState(world World, state State) (State, bool) {
for _, other := range world.state {
if reflect.TypeOf(state) == reflect.TypeOf(other) {
return other, true
}
}
return nil, false
}
func (query Query) Match(entity *Entity) ([]Component, bool) {
if len(entity.components) < query.numTypes {
return nil, false
}
components := make([]Component, query.numTypes)
numFound := 0
ComponentLoop:
for _, c := range entity.Components() {
for i, t := range query.types {
if ComponentTypeIsA(c, t) {
components[i] = c
numFound++
if numFound == query.numTypes {
break ComponentLoop
}
break
}
}
}
if numFound != query.numTypes {
return nil, false
}
return components, true
}
func (query Query) MatchMut(entity *Entity) ([]ComponentRef, bool) {
if len(entity.components) < query.numTypes {
return nil, false
}
numFound := 0
components := make([]ComponentRef, query.numTypes)
ComponentLoop:
for i := 0; i < entity.NumComponents(); i++ {
c, err := entity.MutComponent(i)
if err != nil {
return nil, false
}
for j, t := range query.types {
if ComponentTypeIsA(*c, t) {
components[j] = ComponentRef{Index: i, Type: (*c).Type()}
numFound++
if numFound == query.numTypes {
break ComponentLoop
}
break
}
}
}
if numFound != query.numTypes {
return nil, false
}
return components, true
}