forked from TyphoonMC/TyphoonCore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.go
109 lines (91 loc) · 2.01 KB
/
event.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
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
package typhoon
import (
"reflect"
)
type EventCallback struct {
Callback interface{}
MetaData map[string]string
}
type Event interface{}
type PlayerJoinEvent struct {
Player *Player
}
type PlayerPreJoinEvent struct {
Player *Player
}
type PlayerQuitEvent struct {
Player *Player
}
type PlayerKickEvent struct {
Player *Player
Reason string
}
type PlayerChatEvent struct {
Player *Player
Message string
}
type PlayerClickType byte
const (
PlayerRightClick PlayerClickType = iota
PlayerLeftClick
)
type PlayerInteractEvent struct {
Player *Player
ClickType PlayerClickType
}
// Will not dispatch this for now.
type PlayerMoveEvent struct {
Player *Player
FromX float64
ToX float64
FromY float64
ToY float64
FromZ float64
ToZ float64
OnGound bool
}
type PluginMessageEvent struct {
Channel string
Data []byte
}
func (c *Core) On(handler interface{}) {
typ := reflect.TypeOf(handler).In(0)
cb := EventCallback{handler, nil}
if arr, ok := c.eventHandlers[typ]; ok {
c.eventHandlers[typ] = append(arr, cb)
} else {
arr := make([]EventCallback, 1)
arr[0] = cb
c.eventHandlers[typ] = arr
}
}
func (c *Core) OnPluginMessage(channel string, handler interface{}) {
typ := reflect.TypeOf(handler).In(0)
cb := EventCallback{handler, make(map[string]string)}
cb.MetaData["channel"] = channel
if arr, ok := c.eventHandlers[typ]; ok {
c.eventHandlers[typ] = append(arr, cb)
} else {
arr := make([]EventCallback, 1)
arr[0] = cb
c.eventHandlers[typ] = arr
}
}
func (c *Core) callEventInternal(callback interface{}, event Event) {
reflect.ValueOf(callback).Call([]reflect.Value{reflect.ValueOf(event)})
}
func (c *Core) CallEvent(event Event) {
typ := reflect.TypeOf(event)
for _, f := range c.eventHandlers[typ] {
if f.MetaData == nil {
c.callEventInternal(f.Callback, event)
} else {
switch event.(type) {
case *PluginMessageEvent:
if f.MetaData["channel"] == event.(*PluginMessageEvent).Channel {
c.callEventInternal(f.Callback, event)
}
}
}
}
}