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
|
// Package engine implements the fixed-step game tick loop and subscription
// dispatch that the MUD systems run on.
package engine
import (
"math/rand"
"reflect"
"sort"
"sync"
"time"
)
type Callback func() bool
type subscriber struct {
id uint64
interval int
callback Callback
ticks int
}
type Engine struct {
tickMu sync.Mutex // serializes manual ticks and successive ticker runs
mu sync.Mutex
subscribers map[uint64]*subscriber
nextID uint64
ticker *time.Ticker
running bool
stopCh chan struct{}
loopDone chan struct{}
}
func New() *Engine {
return &Engine{
subscribers: make(map[uint64]*subscriber),
}
}
func (e *Engine) Subscribe(interval int, cb Callback) uint64 {
e.mu.Lock()
defer e.mu.Unlock()
e.nextID++
e.subscribers[e.nextID] = &subscriber{
id: e.nextID,
interval: interval,
callback: cb,
}
return e.nextID
}
func (e *Engine) Unsubscribe(id uint64) {
e.mu.Lock()
defer e.mu.Unlock()
delete(e.subscribers, id)
}
func (e *Engine) Start(tickLengthMs int) {
e.mu.Lock()
defer e.mu.Unlock()
if e.running {
return
}
e.running = true
if tickLengthMs < 50 {
tickLengthMs = 50
}
e.ticker = time.NewTicker(time.Duration(tickLengthMs) * time.Millisecond)
e.stopCh = make(chan struct{})
// Capture this run's resources. A quick Stop/Start must not make the
// old goroutine consume the replacement ticker or stop channel.
ticker, stopCh := e.ticker, e.stopCh
loopDone := make(chan struct{})
e.loopDone = loopDone
go func() {
defer close(loopDone)
for {
select {
case <-ticker.C:
e.processTick()
case <-stopCh:
return
}
}
}()
}
// Stop requests that the ticker loop exit. It is idempotent, but does not
// wait for an in-flight callback; it is not a graceful-shutdown save barrier.
func (e *Engine) Stop() {
e.mu.Lock()
defer e.mu.Unlock()
if e.ticker != nil {
e.ticker.Stop()
}
e.running = false
if e.stopCh != nil {
close(e.stopCh)
e.stopCh = nil
}
}
// StopAndWait stops the ticker AND joins any in-flight callback: it waits
// until the currently running tick has completed and the loop goroutine has
// exited. Use this for graceful shutdown, where the final tick must finish
// before owned state is saved.
func (e *Engine) StopAndWait() {
e.mu.Lock()
loopDone := e.loopDone
e.mu.Unlock()
e.Stop()
// Wait for the ticker loop goroutine to exit. This is the real save
// barrier: the loop may already have received from the ticker and be
// about to call processTick, which locking tickMu alone would not catch.
if loopDone != nil {
<-loopDone
}
// Also join a direct Tick() that is mid-callback on another goroutine.
e.tickMu.Lock()
defer e.tickMu.Unlock()
}
// Tick fires every due subscriber synchronously and returns. Subscribers
// are invoked in ascending subscription-ID (registration) order. Tick calls
// are serialized; a callback must not call Tick recursively.
func (e *Engine) Tick() { e.processTick() }
func (e *Engine) processTick() {
e.tickMu.Lock()
defer e.tickMu.Unlock()
e.mu.Lock()
snapshot := make(map[uint64]*subscriber, len(e.subscribers))
for id, sub := range e.subscribers {
snapshot[id] = sub
}
e.mu.Unlock()
ids := make([]uint64, 0, len(snapshot))
for id := range snapshot {
ids = append(ids, id)
}
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
for _, id := range ids {
sub := snapshot[id]
sub.ticks++
if sub.ticks >= sub.interval {
sub.ticks = 0
if !sub.callback() {
e.mu.Lock()
delete(e.subscribers, id)
e.mu.Unlock()
}
}
}
}
func ToTicks(base float64) int {
if base < 1 {
base = 1
}
floor := int(base)
if rand.Float64() < base-float64(floor) {
return floor + 1
}
return floor
}
func ValuesEqual(a, b any) bool {
ai, aok := NumericValue(a)
bi, bok := NumericValue(b)
if aok && bok {
return ai == bi
}
// == panics when both operands share an uncomparable dynamic type (a
// YAML list or map used as a flag value). Fall back to DeepEqual so a
// tick system cannot panic on authored content.
ta, tb := reflect.TypeOf(a), reflect.TypeOf(b)
if ta != tb {
return false
}
if ta != nil && !ta.Comparable() {
return reflect.DeepEqual(a, b)
}
return a == b
}
func NumericValue(v any) (float64, bool) {
switch x := v.(type) {
case int:
return float64(x), true
case int64:
return float64(x), true
case float64:
return x, true
}
return 0, false
}
|