forked from microbit-apps/pxt-arcadeshield
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventcontext.ts
276 lines (238 loc) · 8.58 KB
/
eventcontext.ts
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
namespace context {
export function onEvent(src: number, value: number, handler: () => void, flags = 16) { // EVENT_LISTENER_DEFAULT_FLAGS
const ctx = eventContext();
if (!ctx)
control.onEvent(src, value, handler, flags);
else
ctx.registerHandler(src, value, handler, flags);
}
export class FrameCallback {
order: number
handler: () => void
}
class EventHandler {
constructor(
public src: number,
public value: number,
public handler: () => void,
public flags: number
) { }
register() {
control.onEvent(this.src, this.value, () => {
if (this.handler) this.handler();
}, this.flags)
}
unregister() {
control.onEvent(this.src, this.value, doNothing, this.flags);
}
}
function doNothing() { }
export class EventContext {
private handlers: EventHandler[];
private frameCallbacks: FrameCallback[];
private frameWorker: number;
private framesInSample: number;
private timeInSample: number;
private lastPerfDump: number;
public deltaTimeMillis: number;
private prevTimeMillis: number;
private idleCallbacks: (() => void)[];
static lastStats: string;
static onStats: (stats: string) => void;
constructor() {
this.handlers = [];
this.framesInSample = 0;
this.timeInSample = 0;
this.deltaTimeMillis = 0;
this.frameWorker = 0;
this.idleCallbacks = undefined;
if (!EventContext.lastStats) {
EventContext.lastStats = "";
}
}
get deltaTime() {
return this.deltaTimeMillis / 1000;
}
private runCallbacks() {
control.enablePerfCounter("all frame callbacks")
let loopStart = control.millis()
this.deltaTimeMillis = loopStart - this.prevTimeMillis;
this.prevTimeMillis = loopStart;
for (let f of this.frameCallbacks) {
f.handler()
}
const now = control.millis()
let runtime = now - loopStart
this.timeInSample += runtime
this.framesInSample++
if (this.timeInSample > 1000 || this.framesInSample > 30) {
const realTimeInSample = now - this.lastPerfDump
this.lastPerfDump = now
const fps = this.framesInSample / (this.timeInSample / 1000);
EventContext.lastStats = `fps:${Math.round(fps)}`;
if (fps < 99)
EventContext.lastStats += "." + (Math.round(fps * 10) % 10)
if (control.profilingEnabled()) {
control.dmesg(`${(fps * 100) | 0}/100 fps - ${this.framesInSample} frames (${this.timeInSample}ms/${realTimeInSample}ms)`)
control.gc()
control.dmesgPerfCounters()
}
this.timeInSample = 0
this.framesInSample = 0
}
let delay = Math.max(1, 20 - runtime)
return delay
}
private runningCallbacks: boolean;
private registerFrameCallbacks() {
if (!this.frameCallbacks) return;
const worker = this.frameWorker;
control.runInParallel(() => {
if (this.runningCallbacks) {
// this context is still running in a different fiber;
// delay until the other fiber doing so has ceased.
pauseUntil(() => !this.runningCallbacks);
}
this.runningCallbacks = true;
this.framesInSample = 0;
this.timeInSample = 0;
this.deltaTimeMillis = 0;
this.prevTimeMillis = control.millis();
while (worker == this.frameWorker) {
let delay = this.runCallbacks()
pause(delay)
}
this.runningCallbacks = false;
})
}
register() {
for (const h of this.handlers)
h.register();
this.registerFrameCallbacks();
}
unregister() {
for (const h of this.handlers)
h.unregister();
this.frameWorker++;
}
registerFrameHandler(order: number, handler: () => void): FrameCallback {
if (!this.frameCallbacks) {
this.frameCallbacks = [];
this.registerFrameCallbacks();
}
const fn = new FrameCallback()
fn.order = order
fn.handler = handler
for (let i = 0; i < this.frameCallbacks.length; ++i) {
if (this.frameCallbacks[i].order > order) {
this.frameCallbacks.insertAt(i, fn)
return fn;
}
}
this.frameCallbacks.push(fn);
return fn;
}
unregisterFrameHandler(fn: FrameCallback) {
if (!fn || !this.frameCallbacks) return;
const i = this.frameCallbacks.indexOf(fn);
if (i > -1)
this.frameCallbacks.splice(i, 1);
}
registerHandler(src: number, value: number, handler: () => void, flags: number) {
// already there?
for (const h of this.handlers) {
if (h.src == src && h.value == value) {
h.flags = flags;
h.handler = handler;
return;
}
}
// register and push
const hn = new EventHandler(src, value, handler, flags);
this.handlers.push(hn);
hn.register();
}
addIdleHandler(handler: () => void) {
if (!this.idleCallbacks) {
this.idleCallbacks = [];
this.registerHandler(15/*DAL.DEVICE_ID_SCHEDULER*/, 2/*DAL.DEVICE_SCHEDULER_EVT_IDLE*/, () => this.runIdleHandler(), 16);
}
this.idleCallbacks.push(handler);
}
removeIdleHandler(handler: () => void) {
if (handler && this.idleCallbacks)
this.idleCallbacks.removeElement(handler);
}
private runIdleHandler() {
if (this.idleCallbacks) {
const ics = this.idleCallbacks.slice(0);
ics.forEach(ic => ic());
}
}
}
let eventContexts: EventContext[];
/**
* Gets the current event context if any
*/
export function eventContext(): EventContext {
return eventContexts ? eventContexts[eventContexts.length - 1] : undefined;
}
/**
* Pushes a new event context and clears all handlers
*/
export function pushEventContext(): EventContext {
if (!eventContexts)
eventContexts = [];
// unregister previous context
const ctx = eventContext();
if (ctx) ctx.unregister();
// register again
const n = new EventContext();
eventContexts.push(n);
return n;
}
/**
* Pops the current event context and restore handlers if any previous context
*/
export function popEventContext() {
if (!eventContexts) return;
// clear current context
const ctx = eventContexts.pop();
if (!ctx) return;
ctx.unregister();
// register old context again
const context = eventContexts[eventContexts.length - 1];
if (context)
context.register();
else
eventContexts = undefined;
}
let _idleCallbacks: (() => void)[];
/**
* Registers a function to run when the device is idling
* @param handler
*/
export function onIdle(handler: () => void) {
if (!handler) return;
const ctx = eventContext();
if (ctx) ctx.addIdleHandler(handler);
else {
if (!_idleCallbacks) {
_idleCallbacks = [];
control.runInBackground(function () {
while (_idleCallbacks) {
_idleCallbacks.slice(0).forEach(cb => cb());
pause(20);
}
})
}
_idleCallbacks.push(handler);
}
}
export function removeIdleHandler(handler: () => void) {
if (!handler) return;
const ctx = eventContext();
if (ctx) ctx.removeIdleHandler(handler);
else if (_idleCallbacks) _idleCallbacks.removeElement(handler);
}
}