Repository navigation
Expand file tree
/
Copy pathruntime_events.go
More file actions
485 lines (430 loc) · 14.2 KB
/
Copy pathruntime_events.go
File metadata and controls
485 lines (430 loc) · 14.2 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
/*
* Copyright (c) 2021 The XGo Authors (xgo.dev). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package spx
import (
"github.com/goplus/spbase/mathf"
coreevent "github.com/goplus/spx/v3/internal/core/event"
coreruntime "github.com/goplus/spx/v3/internal/core/runtime"
"github.com/goplus/spx/v3/internal/coroutine"
"github.com/goplus/spx/v3/internal/engine"
spxlog "github.com/goplus/spx/v3/internal/log"
itime "github.com/goplus/spx/v3/internal/time"
)
const (
clickTimerGlobal = -1
clickTimerStage = 0
)
var scriptEventDispatchHooks = coreevent.DispatchHooks{
Spawn: func(start bool, owner any, call func()) coreevent.DispatchTask {
return gco.CreateAndStart(start, owner, func(coroutine.Thread) int {
call()
return 0
})
},
Join: func(tasks []coreevent.DispatchTask) {
if len(tasks) == 0 {
return
}
if len(tasks) == 1 {
if th, ok := tasks[0].(coroutine.Thread); ok && th != nil {
gco.Join(th)
}
return
}
threads := make([]coroutine.Thread, 0, len(tasks))
for _, task := range tasks {
th, ok := task.(coroutine.Thread)
if !ok || th == nil {
continue
}
threads = append(threads, th)
}
gco.JoinAll(threads)
},
}
// -----------------------------------------------------------------------------
// Event Bindings
// -----------------------------------------------------------------------------
type eventSink = coreevent.Sink
type scriptEventBindings struct {
*scriptEventRegistry
pthis threadObj
}
type scriptEventRegistry struct {
manager coreevent.Manager
}
func (p *scriptEventBindings) init(registry *scriptEventRegistry, this threadObj) {
p.scriptEventRegistry = registry
p.pthis = this
}
func (p *scriptEventBindings) initFrom(src *scriptEventBindings, this threadObj) {
p.scriptEventRegistry = src.scriptEventRegistry
p.pthis = this
}
func (p *scriptEventBindings) doDeleteClone() {
p.scriptEventRegistry.manager.DeleteOwner(p.pthis)
}
func (p *scriptEventBindings) doWhenSwipe(direction Direction, target threadObj) {
p.scriptEventRegistry.doWhenSwipe(direction, target)
}
func (p *scriptEventBindings) onAwake(onAwake func()) {
pthis := p.pthis
p.scriptEventRegistry.manager.AddAwake(coreevent.NewSink(p.pthis, onAwake, coreevent.MatchOwnerOrNil(pthis)))
}
func (p *scriptEventBindings) OnStart(onStart func()) {
sink := coreevent.NewSink(p.pthis, onStart)
if p.scriptEventRegistry.manager.TryAddStart(sink) {
return
}
if sprite, ok := sink.Owner.(*SpriteImpl); ok && sprite.spriteState.Cloned {
return
}
spxlog.Warn("Event: ignoring late OnStart registration for %s", nameOf(sink.Owner))
}
func (p *scriptEventBindings) OnClick(onClick func()) {
pthis := p.pthis
p.scriptEventRegistry.manager.AddClick(coreevent.NewSink(pthis, onClick, coreevent.MatchOwner(pthis)))
}
func (p *scriptEventBindings) OnAnyKey(onKey func(key Key)) {
p.scriptEventRegistry.manager.AddKeyPressed(coreevent.NewSink(p.pthis, onKey))
}
func (p *scriptEventBindings) OnTimer(time float64, call func()) {
itime.RegisterTimer(time)
p.scriptEventRegistry.manager.AddTimer(coreevent.NewSink(
p.pthis,
coreevent.TapVoid1(call, coreevent.If1(isDebugEventEnabled, func(float64) {
spxlog.Debug("OnTimer: %s", nameOf(p.pthis))
})),
coreevent.MatchApproxFloat(time, 0.001),
))
}
func (p *scriptEventBindings) OnKey__0(key Key, onKey func()) {
p.scriptEventRegistry.manager.AddKeyPressed(coreevent.NewSink(
p.pthis,
coreevent.TapVoid1(onKey, coreevent.If1(isDebugEventEnabled, func(Key) {
spxlog.Debug("OnKey: %v, %s", key, nameOf(p.pthis))
})),
coreevent.MatchValue(key),
))
}
func (p *scriptEventBindings) OnSwipe__0(direction Direction, onSwipe func()) {
p.scriptEventRegistry.manager.AddSwipe(coreevent.NewSink(
p.pthis,
coreevent.TapVoid1(onSwipe, coreevent.If1(isDebugEventEnabled, func(Direction) {
spxlog.Debug("OnSwipe: %v, %s", direction, nameOf(p.pthis))
})),
coreevent.MatchValue(direction),
))
}
func (p *scriptEventBindings) OnKey__1(keys []Key, onKey func(Key)) {
p.scriptEventRegistry.manager.AddKeyPressed(coreevent.NewSink(
p.pthis,
coreevent.Tap1(onKey, coreevent.If1(isDebugEventEnabled, func(key Key) {
spxlog.Debug("OnKey: %v, %s", keys, nameOf(p.pthis))
})),
coreevent.MatchAnyOf(keys),
))
}
func (p *scriptEventBindings) OnKey__2(keys []Key, onKey func()) {
p.OnKey__1(keys, coreevent.Ignore1[Key](onKey))
}
func (p *scriptEventBindings) OnMsg__0(onMsg func(msg MsgName, data any)) {
p.scriptEventRegistry.manager.AddIReceive(coreevent.NewSink(p.pthis, onMsg))
}
func (p *scriptEventBindings) OnMsg__1(msg MsgName, onMsg func()) {
p.scriptEventRegistry.manager.AddIReceive(coreevent.NewSink(
p.pthis,
coreevent.TapVoid2(onMsg, coreevent.If2(isDebugEventEnabled, func(msg string, data any) {
spxlog.Debug("OnMsg: %s, %s", msg, nameOf(p.pthis))
})),
coreevent.MatchValue(msg),
))
}
func (p *scriptEventBindings) OnBackdrop__0(onBackdrop func(name BackdropName)) {
p.scriptEventRegistry.manager.AddBackdropChanged(coreevent.NewSink(p.pthis, onBackdrop))
}
func (p *scriptEventBindings) OnBackdrop__1(name BackdropName, onBackdrop func()) {
p.scriptEventRegistry.manager.AddBackdropChanged(coreevent.NewSink(
p.pthis,
coreevent.TapVoid1(onBackdrop, coreevent.If1(isDebugEventEnabled, func(name BackdropName) {
spxlog.Debug("OnBackdrop: %s, %s", name, nameOf(p.pthis))
})),
coreevent.MatchValue(name),
))
}
func (p *scriptEventBindings) Stop(kind StopKind) {
if kind == AllStop {
if game := activeGame(); game != nil {
game.resetGraphicEffectsOnStopAll()
}
}
current := gco.Current()
filter, abort := coreevent.ResolveStop(
kind,
p.pthis,
func(obj any) bool { return isSprite(obj) },
func(obj any) bool { return isGame(obj) },
)
if filter != nil {
gco.StopIf(func(th coroutine.Thread) bool {
return filter(th.Obj, th == current)
})
}
if abort {
gco.Abort()
}
}
// Scratch clears graphic effects for the stage and every sprite when a
// project-wide stop is triggered, including the `stop all` control block.
func (p *Game) resetGraphicEffectsOnStopAll() {
p.baseObj.clearGraphicEffects()
shapes := append([]Shape(nil), p.getAllShapes()...)
for _, item := range shapes {
sprite, ok := item.(*SpriteImpl)
if !ok {
continue
}
sprite.clearGraphicEffects()
}
}
// -----------------------------------------------------------------------------
// Click Dispatch
// -----------------------------------------------------------------------------
type clicker interface {
threadObj
doWhenClick(this threadObj)
getProxy() *engine.Sprite
Visible() bool
}
func (p *Game) pointHitsClickTarget(target clicker, point mathf.Vec2) bool {
syncSprite := target.getProxy()
if syncSprite == nil || !target.Visible() {
return false
}
sprite, ok := target.(*SpriteImpl)
if ok {
sprite.ensureProxyQueryStateSynced()
if sprite.isFullyGhosted() {
return false
}
}
return p.engine().SpriteMgr.CheckCollisionWithPoint(syncSprite.GetId(), point, true)
}
func (p *Game) findClickTarget(point mathf.Vec2) (coreruntime.ClickSelection[clicker, *SpriteImpl], bool) {
return coreruntime.FindClickTarget(p.getTempShapes(), func(item Shape) (coreruntime.ClickSelection[clicker, *SpriteImpl], bool) {
o, ok := item.(clicker)
if !ok {
return coreruntime.ClickSelection[clicker, *SpriteImpl]{}, false
}
if !p.pointHitsClickTarget(o, point) {
return coreruntime.ClickSelection[clicker, *SpriteImpl]{}, false
}
if sprite, ok := o.(*SpriteImpl); ok {
return coreruntime.ClickSelection[clicker, *SpriteImpl]{Target: o, SwipeTarget: sprite}, true
}
return coreruntime.ClickSelection[clicker, *SpriteImpl]{Target: o}, true
})
}
func (p *Game) doWhenLeftButtonUp(ev *eventLeftButtonUp) {
p.inputMgr.finishSwipeTracking(ev.Pos)
}
func (p *Game) doWhenLeftButtonDown(ev *eventLeftButtonDown) {
coreruntime.HandleLeftButtonDown(ev.Pos, coreruntime.ClickDownHooks[clicker, *SpriteImpl, int64]{
FindTarget: p.findClickTarget,
BeginSwipe: p.inputMgr.beginSwipeTracking,
CanTrigger: func(id int64) bool {
return p.inputMgr.canTriggerClickEvent(id)
},
GlobalID: clickTimerGlobal,
StageID: clickTimerStage,
TargetID: func(target clicker) (int64, bool) {
syncSprite := target.getProxy()
if syncSprite == nil {
return 0, false
}
return syncSprite.GetId(), true
},
DispatchTarget: func(target clicker) {
target.doWhenClick(target)
},
DispatchStage: func() {
p.scriptEvents.doWhenClick(p)
},
})
}
// -----------------------------------------------------------------------------
// Message Broadcast
// -----------------------------------------------------------------------------
func (p *Game) Broadcast__0(msg MsgName) {
p.doBroadcast(msg, nil, false)
}
func (p *Game) Broadcast__1(msg MsgName, data any) {
p.doBroadcast(msg, data, false)
}
func (p *Game) BroadcastAndWait__0(msg MsgName) {
p.doBroadcast(msg, nil, true)
}
func (p *Game) BroadcastAndWait__1(msg MsgName, data any) {
p.doBroadcast(msg, data, true)
}
func (p *Game) doBroadcast(msg MsgName, data any, wait bool) {
if isDebugInstrEnabled() {
spxlog.Debug("Broadcast: msg=%s, wait=%v", msg, wait)
}
p.scriptEvents.doWhenIReceive(msg, data, wait)
}
// -----------------------------------------------------------------------------
// Event Routing
// -----------------------------------------------------------------------------
func (p *Game) handleEvent(ev event) {
switch e := ev.(type) {
case *eventLeftButtonUp:
p.doWhenLeftButtonUp(e)
case *eventLeftButtonDown:
p.doWhenLeftButtonDown(e)
case *eventMouseMove:
p.inputMgr.onMouseMove(e.Pos)
case *eventKeyDown:
// Note: key-up callbacks are not part of the current event sink API.
p.scriptEvents.doWhenKeyPressed(e.Key)
case *eventStart:
runStartPhase := func() {
p.scriptEvents.doWhenStart()
p.lifecycleState.StartDispatched.Store(true)
}
if gco != nil && !gco.IsInCoroutine() {
// Keep OnStart handlers in one coroutine phase and advance them in
// registration order to their first yield.
gco.CreateAndStart(false, p, func(coroutine.Thread) int {
runStartPhase()
return 0
})
} else {
runStartPhase()
}
case *eventTimer:
p.scriptEvents.doWhenTimer(e.Time)
}
}
func (p *Game) fireEvent(ev event) {
if p.queueEventWithPolicy(ev) {
return
}
if isDebugInstrEnabled() {
spxlog.Warn("Event buffer is full (policy=%s). Drop event: %v", p.gameRuntimeState.EventQueuePolicy, ev)
}
}
// -----------------------------------------------------------------------------
// Event Dispatch
// -----------------------------------------------------------------------------
func (p *scriptEventRegistry) doWhenStart() {
sinks := p.manager.SnapshotStartOnce()
if len(sinks) == 0 {
return
}
run := func() {
for i := range sinks {
ev := &sinks[i]
if ev.Cond != nil && !ev.Cond(nil) {
continue
}
thread := gco.CreateAndStart(false, ev.Owner, func(coroutine.Thread) int {
coreevent.If0(isDebugEventEnabled, func() {
spxlog.Debug("OnStart: %s", nameOf(ev.Owner))
})()
ev.Handler.(func())()
return 0
})
gco.JoinYieldedOrDone(thread)
}
}
if gco != nil && !gco.IsInCoroutine() {
gco.CreateAndStart(false, engine.GetGame(), func(coroutine.Thread) int {
run()
return 0
})
return
}
run()
}
func (p *scriptEventRegistry) doWhenAwake(this threadObj) {
p.dispatchSync(coreevent.BucketAwake, this, func(ev *eventSink) {
coreevent.If0(isDebugEventEnabled, func() {
spxlog.Debug("OnAwake: %s", nameOf(ev.Owner))
})()
ev.Handler.(func())()
})
}
func (p *scriptEventRegistry) doWhenTimer(time float64) {
p.dispatchAsync(coreevent.BucketTimer, false, time, func(ev *eventSink) {
ev.Handler.(func(float64))(time)
})
}
func (p *scriptEventRegistry) doWhenKeyPressed(key Key) {
p.dispatchAsync(coreevent.BucketKeyPressed, false, key, func(ev *eventSink) {
ev.Handler.(func(Key))(key)
})
}
func (p *scriptEventRegistry) doWhenSwipe(direction Direction, this threadObj) {
p.dispatchAsync(coreevent.BucketSwipe, false, direction, func(ev *eventSink) {
if ev.Owner == this {
ev.Handler.(func(Direction))(direction)
}
})
}
func (p *scriptEventRegistry) doWhenClick(this threadObj) {
p.dispatchAsync(coreevent.BucketClick, false, this, func(ev *eventSink) {
coreevent.If0(isDebugEventEnabled, func() {
spxlog.Debug("OnClick: %s", nameOf(this))
})()
ev.Handler.(func())()
})
}
func (p *scriptEventRegistry) doWhenTouchStart(this threadObj, obj *SpriteImpl) {
p.dispatchAsync(coreevent.BucketTouchStart, false, this, func(ev *eventSink) {
coreevent.If0(isDebugEventEnabled, func() {
spxlog.Debug("OnTouchStart: %s, %s", nameOf(this), obj.name)
})()
ev.Handler.(func(Sprite))(obj.sprite)
})
}
func (p *scriptEventRegistry) doWhenCloned(this threadObj, data any) {
p.dispatchAsync(coreevent.BucketCloned, true, this, func(ev *eventSink) {
coreevent.If0(isDebugEventEnabled, func() {
spxlog.Debug("OnCloned: %s", nameOf(this))
})()
ev.Handler.(func(any))(data)
})
}
func (p *scriptEventRegistry) doWhenIReceive(msg string, data any, wait bool) {
p.dispatch(coreevent.BucketIReceive, wait, msg, func(ev *eventSink) {
ev.Handler.(func(string, any))(msg, data)
})
}
func (p *scriptEventRegistry) doWhenBackdropChanged(name BackdropName, wait bool) {
p.dispatch(coreevent.BucketBackdropChanged, wait, name, func(ev *eventSink) {
ev.Handler.(func(BackdropName))(name)
})
}
func (p *scriptEventRegistry) dispatchAsync(bucket coreevent.Bucket, start bool, data any, do func(*eventSink)) {
p.manager.DispatchBucketAsync(bucket, start, data, scriptEventDispatchHooks, do)
}
func (p *scriptEventRegistry) dispatchSync(bucket coreevent.Bucket, data any, do func(*eventSink)) {
p.manager.DispatchBucketSync(bucket, data, scriptEventDispatchHooks, do)
}
func (p *scriptEventRegistry) dispatch(bucket coreevent.Bucket, wait bool, data any, do func(*eventSink)) {
p.manager.DispatchBucket(bucket, wait, data, scriptEventDispatchHooks, do)
}