-
Notifications
You must be signed in to change notification settings - Fork 43
/
filtercomponent.go
82 lines (74 loc) · 1.85 KB
/
filtercomponent.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
78
79
80
81
82
package cardinal
import (
"github.com/rotisserie/eris"
"pkg.world.dev/world-engine/cardinal/types"
)
// This package involves primitives for search.
// It involves creating and combining primitives that represent
// filtering properties on components.
type FilterFn func(wCtx WorldContext, id types.EntityID) (bool, error)
//revive:disable-next-line:unexported-return
func ComponentFilter[T types.Component](f func(comp T) bool) FilterFn {
return func(wCtx WorldContext, id types.EntityID) (bool, error) {
var t T
c, err := wCtx.getComponentByName(t.Name())
if err != nil {
return false, err
}
// Get current component value
compValue, err := wCtx.storeReader().GetComponentForEntity(c, id)
if err != nil {
return false, err
}
// Type assert the component value to the component type
var comp *T
t, ok := compValue.(T)
if !ok {
comp, ok = compValue.(*T)
if !ok {
return false, eris.New("no result found.")
}
} else {
comp = &t
}
return f(*comp), nil
}
}
//revive:disable-next-line:unexported-return
func AndFilter(fns ...FilterFn) FilterFn {
return func(wCtx WorldContext, id types.EntityID) (bool, error) {
var result = true
var errCount = 0
for _, fn := range fns {
res, err := fn(wCtx, id)
if err != nil {
errCount++
continue
}
result = result && res
}
if errCount == len(fns) {
return false, eris.New("all filters failed")
}
return result, nil
}
}
//revive:disable-next-line:unexported-return
func OrFilter(fns ...FilterFn) FilterFn {
return func(wCtx WorldContext, id types.EntityID) (bool, error) {
var result = false
var errCount = 0
for _, fn := range fns {
res, err := fn(wCtx, id)
if err != nil {
errCount++
continue
}
result = result || res
}
if errCount == len(fns) {
return false, eris.New("all filters failed")
}
return result, nil
}
}