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
use RafLoop;
use crateError;
use crateget_window;
use info;
use Cell;
use RefCell;
use Rc;
use *;
use JsCast;
use Window;
///Options for start_main_loop()
/// A Rust port of https://github.com/IceCreamYou/MainLoop.js
///
/// It's pretty much a direct port, except for two differences:
/// 1. it all runs in one loop with a branch (probably cheaper than passing the required Rc/RefCells around)
/// 2. starting/stopping is explicit via cancelling and restarting (there is no reset_frame_delta() or runtime fps cap)
///
///
/// @begin: A function that runs at the beginning of the main loop.
///
/// The begin() function is typically used to process input before the
/// updates run. Processing input here (in chunks) can reduce the running
/// time of event handlers, which is useful because long-running event
/// handlers can sometimes delay frames.
///
/// Unlike update(), which can run zero or more times per
/// frame, begin() always runs exactly once per frame. This makes it useful
/// for any updates that are not dependent on time in the simulation.
/// Examples include adjusting HUD calculations or performing long-running
/// updates incrementally. Compared to end(), generally
/// actions should occur in begin() if they affect anything that
/// update() or draw() use
///
/// * timestamp
///
/// The current timestamp (when the frame started), in milliseconds. This
/// should only be used for comparison to other timestamps because the
/// epoch (i.e. the "zero" time) depends on the engine running this code.
/// In engines that support `DOMHighResTimeStamp` (all modern browsers
/// except iOS Safari 8) the epoch is the time the page started loading,
/// specifically `performance.timing.navigationStart`. Everywhere else,
/// including node.js, the epoch is the Unix epoch (1970-01-01T00:00:00Z).
///
/// * delta
///
/// The total elapsed time that has not yet been simulated, in
/// milliseconds.
///
/// @update: The function that runs updates (e.g. AI and physics).
///
/// The update() function should simulate anything that is affected by time.
/// It can be called zero or more times per frame depending on the frame
/// rate.
///
/// As with everything in the main loop, the running time of update()
/// directly affects the frame rate. If update() takes long enough that the
/// frame rate drops below the target ("budgeted") frame rate, parts of the
/// update() function that do not need to execute between every frame can be
/// moved into Web Workers. (Various sources on the internet sometimes
/// suggest other scheduling patterns using setTimeout() or setInterval().
/// These approaches sometimes offer modest improvements with minimal
/// changes to existing code, but because JavaScript is single-threaded, the
/// updates will still block rendering and drag down the frame rate. Web
/// Workers execute in separate threads, so they free up more time in the
/// main loop.)
///
/// This script can be imported into a Web Worker using importScripts() and
/// used to run a second main loop in the worker. Some considerations:
///
/// - Profile your code before doing the work to move it into Web Workers.
/// It could be the rendering that is the bottleneck, in which case the
/// solution is to decrease the visual complexity of the scene.
/// - It doesn't make sense to move the *entire* contents of update() into
/// workers unless draw() can interpolate between frames.
/// The lowest-hanging fruit is background updates (like calculating
/// citizens' happiness in a city-building game), physics that doesn't
/// affect the scene (like flags waving in the wind), and anything that is
/// occluded or happening far off screen.
/// - If draw() needs to interpolate physics based on activity that occurs
/// in a worker, the worker needs to pass the interpolation value back to
/// the main thread so that is is available to draw().
/// - Web Workers can't access the state of the main thread, so they can't
/// directly modify objects in your scene. Moving data to and from Web
/// Workers is a pain. The fastest way to do it is with Transferable
/// Objects: basically, you can pass an ArrayBuffer to a worker,
/// destroying the original reference in the process.
///
/// You can read more about Web Workers and Transferable Objects at
/// [HTML5 Rocks](http://www.html5rocks.com/en/tutorials/workers/basics/).
///
/// * delta
///
/// The amount of time in milliseconds to simulate in the update. In most
/// cases this timestep never changes in order to ensure deterministic
/// updates. The timestep is the same as that returned by
/// `MainLoop.getSimulationTimestep()`.
///
/// @draw: A function that draws things on the screen.
///
/// The draw() function gets passed the percent of time that the next run of
/// update() will simulate that has actually elapsed, as
/// a decimal. In other words, draw() gets passed how far between update()
/// calls it is. This is useful because the time simulated by update() and
/// the time between draw() calls is usually different, so the parameter to
/// draw() can be used to interpolate motion between frames to make
/// rendering appear smoother. To illustrate, if update() advances the
/// simulation at each vertical bar in the first row below, and draw() calls
/// happen at each vertical bar in the second row below, then some frames
/// will have time left over that is not yet simulated by update() when
/// rendering occurs in draw():
///
/// update() timesteps: | | | | | | | | |
/// draw() calls: | | | | | | |
///
/// To interpolate motion for rendering purposes, objects' state after the
/// last update() must be retained and used to calculate an intermediate
/// state. Note that this means renders will be up to one update() behind.
/// This is still better than extrapolating (projecting objects' state after
/// a future update()) which can produce bizarre results. Storing multiple
/// states can be difficult to set up, and keep in mind that running this
/// process takes time that could push the frame rate down, so it's often
/// not worthwhile unless stuttering is visible.
///
/// * interpolation_percentage
///
/// The cumulative amount of time that hasn't been simulated yet, divided
/// by the amount of time that will be simulated the next time update()
/// runs. Useful for interpolating frames.
///
/// @end: A function that runs at the end of the main loop.
///
/// Unlike update(), which can run zero or more times per
/// frame, end() always runs exactly once per frame. This makes it useful
/// for any updates that are not dependent on time in the simulation.
/// Examples include cleaning up any temporary state set up by
/// begin(), lowering the visual quality if the frame rate
/// is too low, or performing long-running updates incrementally. Compared
/// to begin(), generally actions should occur in end() if they use anything
/// that update() or draw() affect.
///
/// * fps
///
/// The exponential moving average of the frames per second. It can be used
/// to take action when the FPS is too low (or to restore to normalcy if the FPS
/// moves back up). Examples of actions to take if the FPS is too low
/// include exiting the application, lowering the visual quality, stopping
/// or reducing activities outside of the main loop like event handlers or
/// audio playback, performing non-critical updates less frequently, or
/// restarting with a higher simulation timestep. Note that this last option
/// results in more time being simulated per update() call, which causes
/// the application to behave non-deterministically.
///
/// * end_panic
///
/// Indicates whether the simulation has fallen too far behind real time.
/// Specifically, `panic` will be `true` if too many updates occurred in
/// one frame. In networked lockstep applications, the application should
/// wait for some amount of time to see if the user can catch up before
/// dropping the user. In networked but non-lockstep applications, this
/// typically indicates that the user needs to be snapped or eased to the
/// current authoritative state. When this happens, it may be convenient
/// to call `MainLoop.resetFrameDelta()` to discard accumulated pending
/// updates. In non-networked applications, it may be acceptable to allow
/// the application to keep running for awhile to see if it will catch up.
/// However, this could also cause the application to look like it is
/// running very quickly for a few frames as it transitions through the
/// intermediate states. If the application panics
/// frequently, this is an indication that the main loop is running too
/// slowly. However, most of the time the drop in frame rate will probably
/// be noticeable before a panic occurs. To help the application catch up
/// after a panic caused by a spiral of death, the same steps can be taken
/// that are suggested above if the FPS drops too low.