This repository has been archived by the owner on Dec 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathtime.js
1110 lines (1043 loc) · 38.7 KB
/
time.js
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview Provides support for both time-based and cycle-based callbacks
* @author <a href="mailto:[email protected]">Jeff Parsons</a>
* @copyright © 2012-2019 Jeff Parsons
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*
* PCjs is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* PCjs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCjs. If not,
* see <http://www.gnu.org/licenses/gpl.html>.
*
* You are required to include the above copyright notice in every modified copy of this work
* and to display that copyright notice when the software starts running; see COPYRIGHT in
* <https://www.pcjs.org/modules/devices/machine.js>.
*
* Some PCjs files also attempt to load external resource files, such as character-image files,
* ROM files, and disk image files. Those external resource files are not considered part of PCjs
* for purposes of the GNU General Public License, and the author does not claim any copyright
* as to their contents.
*/
"use strict";
/**
* Timer objects
*
* addTimer() and setTimer() create and manage Timer objects that are used for operations that must
* occur after a certain amount of "real time" has elapsed (eg, key/button events that need to be timed-out
* after a predefined period).
*
* These functions are preferred over JavaScript's setTimeout(), because our timers convert "real time"
* into cycle countdowns, which are effectively paused whenever cycle generation is paused (eg, when the
* user stops the emulation). Moreover, setTimeout() handlers only run after run() yields, which may be
* too granular for certain devices (eg, when a serial port tries to simulate interrupts at high baud rates).
*
* WARNING: If you need to set the 'cyclesPerSecond' TimeConfig property below 60Hz, then 1) you will have
* to also set 'cyclesMinimum' to an equally low value, otherwise the default minimum will be used, and 2) any
* timers configured to fire at a faster rate will not be able to; for example, if the machine is configured
* for 1Hz, then a 60Hz timer will only be able to fire at most 1Hz as well. In practice, this shouldn't be
* an issue, as long as the timer is firing at least as frequently as any other work being performed.
*
* addClocker() should be used for devices that are cycle-driven (ie, that need to be "clocked") rather than
* time-driven; they must define a clocker() function and install it with addClocker().
*
* Finally, addAnimator() should be used by any device that wants to perform high-speed animations (normally
* 60Hz); a separate 60Hz timer could be used as well, but using an addAnimator() callback imposes slightly less
* overhead, since the duration is fixed. Also, certain types of updates may benefit from the subsequent yield
* (eg, DOM updates), but you should avoid making expensive updates at such a high frequency.
*
* NOTE: addAnimator() used to rely on our onYield() timer callback, which meant that our animation callbacks
* were limited by the current clock frequency, which could be below 60Hz, but now we use requestAnimationFrame(),
* so it should now be possible to continue having high-speed animations, regardless of our own clock speed.
* However, we still automatically stop all animations whenever our own clock is stopped as well.
*
* @typedef {Object} Timer
* @property {string} id
* @property {function()} callBack
* @property {number} msAuto
* @property {number} nCyclesLeft
*/
/**
* @typedef {Config} TimeConfig
* @property {string} class
* @property {Object} [bindings]
* @property {number} [version]
* @property {Array.<string>} [overrides]
* @property {number} [cyclesMinimum]
* @property {number} [cyclesMaximum]
* @property {number} [cyclesPerSecond]
* @property {number} [yieldsPerSecond]
* @property {number} [yieldsPerUpdate]
* @property {boolean} [requestAnimationFrame]
* @property {boolean} [clockByFrame]
*/
/**
* @class {Time}
* @unrestricted
* @property {TimeConfig} config
* @property {number} nCyclesMinimum
* @property {number} nCyclesMaximum
* @property {number} nCyclesPerSecond
* @property {number} nYieldsPerSecond
* @property {number} nYieldsPerUpdate
* @property {boolean} fClockByFrame
*/
class Time extends Device {
/**
* Time(idMachine, idDevice, config)
*
* Sample config:
*
* "clock": {
* "class": "Time",
* "cyclesPerSecond": 650000,
* "clockByFrame": true,
* "bindings": {
* "run": "runTI57",
* "speed": "speedTI57",
* "step": "stepTI57"
* },
* "overrides": ["cyclesPerSecond","yieldsPerSecond","yieldsPerUpdate"]
* }
*
* @this {Time}
* @param {string} idMachine
* @param {string} idDevice
* @param {TimeConfig} [config]
*/
constructor(idMachine, idDevice, config)
{
super(idMachine, idDevice, Time.VERSION, config);
/*
* NOTE: The default speed of 650,000Hz (0.65Mhz) was a crude approximation based on real world TI-57
* device timings. I had originally assumed the speed as 1,600,000Hz (1.6Mhz), based on timing information
* in TI's patents, but in hindsight, that speed seems rather high for a mid-1970's device, and reality
* suggests it was much lower. The TMS-1500 does burn through a lot of cycles (minimum of 128) per instruction,
* but either that cycle burn was much higher, or the underlying clock speed was much lower. I assume the latter.
*/
this.nCyclesMinimum = this.getDefaultNumber('cyclesMinimum', 100000);
this.nCyclesMaximum = this.getDefaultNumber('cyclesMaximum', 3000000);
this.nCyclesPerSecond = this.getBounded(this.getDefaultNumber('cyclesPerSecond', 650000), this.nCyclesMinimum, this.nCyclesMaximum);
this.nYieldsPerSecond = this.getBounded(this.getDefaultNumber('yieldsPerSecond', Time.YIELDS_PER_SECOND), 30, 120);
this.nYieldsPerUpdate = this.getBounded(this.getDefaultNumber('yieldsPerUpdate', Time.YIELDS_PER_UPDATE), 1, this.nYieldsPerSecond);
this.fClockByFrame = this.getDefaultBoolean('clockByFrame', this.nCyclesPerSecond <= 120);
this.fRequestAnimationFrame = this.fClockByFrame || this.getDefaultBoolean('requestAnimationFrame', true);
this.nBaseMultiplier = this.nCurrentMultiplier = this.nTargetMultiplier = 1;
this.mhzBase = (this.nCyclesPerSecond / 10000) / 100;
this.mhzCurrent = this.mhzTarget = this.mhzBase * this.nTargetMultiplier;
this.nYields = 0;
this.msYield = Math.round(1000 / this.nYieldsPerSecond);
this.aAnimators = [];
this.aClockers = [];
this.aTimers = [];
this.aUpdaters = [];
this.fRunning = this.fYield = this.fThrottling = false;
this.nStepping = 0;
this.idRunTimeout = this.idStepTimeout = 0;
this.onRunTimeout = this.run.bind(this);
this.onAnimationFrame = this.animate.bind(this);
this.requestAnimationFrame = (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.setTimeout).bind(window);
/*
* When fClockByFrame is true, we rely exclusively on requestAnimationFrame() instead of setTimeout()
* to drive the clock, which means we automatically yield after every frame, so no yield timer is required.
*/
if (!this.fClockByFrame) {
let time = this;
this.timerYield = this.addTimer("timerYield", function onYield() {
time.onYield();
}, this.msYield);
}
else {
/*
* When clocking exclusively by animation frames, setSpeed() calculates how many cycles
* each animation frame should "deposit" in our cycle bank:
*
* this.nCyclesDepositPerFrame = (nCyclesPerSecond / 60) + 0.00000001;
*
* After that amount is added to our "balance" (this.nCyclesDeposited), we make a "withdrawal"
* whenever the balance is >= 1.0 and call all our clocking functions with the maximum number
* of cycles we were able to withdraw.
*
* setSpeed() also adds a tiny amount of "interest" to each "deposit" (0.00000001); otherwise
* you can end up in situations where the deposit amount is, say, 0.2499999 instead of 0.25,
* and four such deposits would still fall short of the 1-cycle threshold.
*/
this.nCyclesDeposited = this.nCyclesDepositPerFrame = 0;
}
this.resetSpeed();
}
/**
* addAnimator(callBack)
*
* Animators are functions that used to be called with YIELDS_PER_SECOND frequency, when animate()
* was called on every onYield() call, but now we rely on requestAnimationFrame(), so the frequency
* is browser-dependent (but presumably at least 60Hz).
*
* @this {Time}
* @param {function(number)} callBack
*/
addAnimator(callBack)
{
this.aAnimators.push(callBack);
}
/**
* addBinding(binding, element)
*
* @this {Time}
* @param {string} binding
* @param {Element} element
*/
addBinding(binding, element)
{
let time = this, elementInput;
switch(binding) {
case Time.BINDING.RUN:
element.onclick = function onClickRun() {
time.onRun();
};
break;
case Time.BINDING.STEP:
element.onclick = function onClickStep() {
time.onStep();
};
break;
case Time.BINDING.THROTTLE:
elementInput = /** @type {HTMLInputElement} */ (element);
elementInput.addEventListener("mousedown", function onThrottleStart() {
time.fThrottling = true;
});
elementInput.addEventListener("mouseup", function onThrottleStop() {
time.setSpeedThrottle();
time.fThrottling = false;
});
elementInput.addEventListener("mousemove", function onThrottleChange() {
if (time.fThrottling) {
time.setSpeedThrottle();
}
});
elementInput.addEventListener("change", function onThrottleChange() {
time.fThrottling = true;
time.setSpeedThrottle();
time.fThrottling = false;
});
break;
}
super.addBinding(binding, element);
}
/**
* addClocker(callBack)
*
* Adds a clocker function that's called from doBurst() to process a specified number of cycles.
*
* @this {Time}
* @param {function(number)} callBack
*/
addClocker(callBack)
{
this.aClockers.push(callBack);
}
/**
* addTimer(id, callBack, msAuto)
*
* Devices that want to have timers that fire after some number of milliseconds call addTimer() to create
* the timer, and then setTimer() when they want to arm it. Alternatively, they can specify an automatic
* timeout value (in milliseconds) to have the timer fire automatically at regular intervals. There is
* currently no removeTimer() because these are generally used for the entire lifetime of a device.
*
* A timer is initially dormant; dormant timers have a cycle count of -1 (although any negative number will
* suffice) and active timers have a non-negative cycle count.
*
* @this {Time}
* @param {string} id
* @param {function()} callBack
* @param {number} [msAuto] (if set, enables automatic setTimer calls)
* @returns {number} timer index (1-based)
*/
addTimer(id, callBack, msAuto = -1)
{
let nCyclesLeft = -1;
let iTimer = this.aTimers.length + 1;
this.aTimers.push({id, callBack, msAuto, nCyclesLeft});
if (msAuto >= 0) this.setTimer(iTimer, msAuto);
return iTimer;
}
/**
* addUpdater(callBack)
*
* Adds a status update function that's called from updateStatus(), either as the result
* of periodic status updates from onYield(), single-step updates from step(), or transitional
* updates from start() and stop().
*
* @this {Time}
* @param {function(boolean)} callBack
*/
addUpdater(callBack)
{
this.aUpdaters.push(callBack);
}
/**
* animate(t)
*
* This is the callback function we supply to requestAnimationFrame(). The callback has a single
* (DOMHighResTimeStamp) argument, which indicates the current time (returned from performance.now())
* for when requestAnimationFrame() starts to fire callbacks.
*
* See: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame
*
* @this {Time}
* @param {number} [t]
*/
animate(t)
{
if (this.fClockByFrame) {
/*
* Mimic the logic in run()
*/
if (!this.fRunning) return;
this.snapStart();
try {
this.fYield = false;
do {
/*
* Execute the burst and then update all timers.
*/
this.updateTimers(this.endBurst(this.doBurst(this.getCyclesPerFrame())));
} while (this.fRunning && !this.fYield);
}
catch (err) {
this.println(err.message);
this.stop();
return;
}
this.snapStop();
}
for (let i = 0; i < this.aAnimators.length; i++) {
this.aAnimators[i](t);
}
if (this.fRunning && this.fRequestAnimationFrame) this.requestAnimationFrame(this.onAnimationFrame);
}
/**
* calcCycles()
*
* Calculate the maximum number of cycles we should attempt to process before the next yield.
*
* @this {Time}
*/
calcCycles()
{
let nMultiplier = this.mhzCurrent / this.mhzBase;
if (!nMultiplier || nMultiplier > this.nTargetMultiplier) {
nMultiplier = this.nTargetMultiplier;
}
/*
* nCyclesPerYield is now allowed to be a fractional number, so that for machines configured
* to run at an extremely slow speed (eg, less than 60Hz), a fractional value here will signal
* to snapStop() that it should increase msYield to a proportionally higher value.
*/
this.nCyclesPerYield = (this.nCyclesPerSecond / this.nYieldsPerSecond * nMultiplier);
this.nCurrentMultiplier = nMultiplier;
}
/**
* calcSpeed(nCycles, msElapsed)
*
* @this {Time}
* @param {number} nCycles
* @param {number} msElapsed
*/
calcSpeed(nCycles, msElapsed)
{
if (msElapsed) {
this.mhzCurrent = (nCycles / (msElapsed * 10)) / 100;
}
}
/**
* doBurst(nCycles)
*
* @this {Time}
* @param {number} nCycles
* @returns {number} (number of cycles actually executed)
*/
doBurst(nCycles)
{
this.nCyclesBurst = this.nCyclesRemain = nCycles;
if (!this.aClockers.length) {
this.nCyclesRemain = 0;
return this.nCyclesBurst;
}
let iClocker = 0;
while (this.nCyclesRemain > 0) {
if (iClocker < this.aClockers.length) {
nCycles = this.aClockers[iClocker++](nCycles) || 1;
} else {
iClocker = nCycles = 0;
}
this.nCyclesRemain -= nCycles;
}
return this.nCyclesBurst - this.nCyclesRemain;
}
/**
* doOutside(fn)
*
* Use this function to perform any work outside of normal time (eg, DOM updates),
* to prevent that work from disrupting our speed calculations.
*
* @this {Time}
* @param {function()} fn (should return true only if the function actually performed any work)
* @returns {boolean}
*/
doOutside(fn)
{
let msStart = Date.now();
if (fn()) {
let msStop = Date.now();
this.msOutsideThisRun += msStop - msStart;
return true;
}
return false;
}
/**
* endBurst(nCycles)
*
* @this {Time}
* @param {number} [nCycles]
* @returns {number} (number of cycles executed in burst)
*/
endBurst(nCycles = this.nCyclesBurst - this.nCyclesRemain)
{
if (this.fClockByFrame) {
this.nCyclesDeposited -= nCycles;
if (this.nCyclesDeposited < 1) {
this.fYield = true;
}
}
this.nCyclesBurst = this.nCyclesRemain = 0;
this.nCyclesThisRun += nCycles;
this.nCyclesRun += nCycles;
if (!this.fRunning) this.nCyclesRun = 0;
return nCycles;
}
/**
* getCycles(ms)
*
* If no time period is specified, this returns the current number of cycles per second.
*
* @this {Time}
* @param {number} ms (default is 1000)
* @returns {number} number of corresponding cycles
*/
getCycles(ms = 1000)
{
return Math.ceil((this.nCyclesPerSecond * this.nCurrentMultiplier) / 1000 * ms);
}
/**
* getCyclesPerBurst()
*
* This tells us how many cycles to execute as a burst.
*
* @this {Time}
* @returns {number} (the maximum number of cycles we should execute in the next burst)
*/
getCyclesPerBurst()
{
let nCycles = this.getCycles(this.msYield);
for (let iTimer = this.aTimers.length; iTimer > 0; iTimer--) {
let timer = this.aTimers[iTimer-1];
this.assert(!isNaN(timer.nCyclesLeft));
if (timer.nCyclesLeft < 0) continue;
if (nCycles > timer.nCyclesLeft) {
nCycles = timer.nCyclesLeft;
}
}
return nCycles;
}
/**
* getCyclesPerFrame()
*
* This tells us how many cycles to execute per frame (assuming fClockByFrame).
*
* @this {Time}
* @returns {number} (the maximum number of cycles we should execute in the next burst)
*/
getCyclesPerFrame()
{
let nCycles = (this.nCyclesDeposited += this.nCyclesDepositPerFrame);
if (nCycles < 1) {
nCycles = 0;
} else {
nCycles |= 0;
for (let iTimer = this.aTimers.length; iTimer > 0; iTimer--) {
let timer = this.aTimers[iTimer-1];
this.assert(!isNaN(timer.nCyclesLeft));
if (timer.nCyclesLeft < 0) continue;
if (nCycles > timer.nCyclesLeft) {
nCycles = timer.nCyclesLeft;
}
}
}
return nCycles;
}
/**
* getSpeed(mhz)
*
* @this {Time}
* @param {number} mhz
* @returns {string} the given speed, as a formatted string
*/
getSpeed(mhz)
{
let s;
if (mhz >= 1) {
s = mhz.toFixed(2) + "Mhz";
} else {
let hz = Math.round(mhz * 1000000);
if (hz <= 999) {
s = hz + "Hz";
} else {
s = Math.ceil(hz / 1000) + "Khz";
}
}
return s;
}
/**
* getSpeedCurrent()
*
* @this {Time}
* @returns {string} the current speed, as a formatted string
*/
getSpeedCurrent()
{
return (this.fRunning && this.mhzCurrent)? this.getSpeed(this.mhzCurrent) : "Stopped";
}
/**
* getSpeedTarget()
*
* @this {Time}
* @returns {string} the target speed, as a formatted string
*/
getSpeedTarget()
{
return this.getSpeed(this.mhzTarget);
}
/**
* isRunning()
*
* @this {Time}
* @returns {boolean}
*/
isRunning()
{
return this.fRunning;
}
/**
* isTimerSet(iTimer)
*
* NOTE: Even if the timer is armed, we return false if the clock is currently stopped;
* in that sense, perhaps this function should be named isTimerArmedAndWillItFireOnTime().
*
* @this {Time}
* @param {number} iTimer
* @returns {boolean}
*/
isTimerSet(iTimer)
{
if (this.fRunning) {
if (iTimer > 0 && iTimer <= this.aTimers.length) {
let timer = this.aTimers[iTimer - 1];
return (timer.nCyclesLeft >= 0);
}
}
return false;
}
/**
* onRun()
*
* This handles the "run" button, if any, attached to the Time device.
*
* Note that this serves a different purpose than the "power" button that's managed by the Input device,
* because toggling power also requires resetting the program counter prior to start() OR clearing the display
* after stop(). See the Chip's onPower() function for details.
*
* @this {Time}
*/
onRun()
{
if (this.fRunning) {
this.stop();
} else {
this.start();
}
}
/**
* onStep(nRepeat)
*
* This handles the "step" button, if any, attached to the Time device.
*
* @this {Time}
* @param {number} [nRepeat]
*/
onStep(nRepeat)
{
if (!this.fRunning) {
if (this.nStepping) {
this.stop();
} else {
this.step(nRepeat);
}
} else {
this.println("already running");
}
}
/**
* onYield()
*
* @this {Time}
*/
onYield()
{
this.fYield = true;
let nYields = this.nYields;
let nCyclesPerSecond = this.getCycles();
if (nCyclesPerSecond >= this.nYieldsPerSecond) {
this.nYields++;
} else {
/*
* Let's imagine that nCyclesPerSecond has dropped to 4, whereas the usual nYieldsPerSecond is 60;
* that's means we're yielding at 1/15th the usual rate, so to compensate, we want to bump nYields
* by 15 instead of 1.
*/
this.nYields += Math.ceil(this.nYieldsPerSecond / nCyclesPerSecond);
}
if (this.nYields >= this.nYieldsPerUpdate && nYields < this.nYieldsPerUpdate) {
this.updateStatus();
}
if (this.nYields >= this.nYieldsPerSecond) {
this.nYields = 0;
}
}
/**
* resetSpeed()
*
* Resets speed and cycle information as part of any reset() or restore(); this typically occurs during powerUp().
* It's important that this be called BEFORE the actual restore() call, because restore() may want to call setSpeed(),
* which in turn assumes that all the cycle counts have been initialized to sensible values.
*
* @this {Time}
*/
resetSpeed()
{
this.nCyclesRun = this.nCyclesBurst = this.nCyclesRemain = 0;
if (!this.setSpeedThrottle()) this.setSpeed(this.nBaseMultiplier);
}
/**
* resetTimers()
*
* When the target speed multiplier is altered, it's a good idea to run through all the timers that
* have a fixed millisecond period and re-arm them, because the timers are using cycle counts that were based
* on a previous multiplier.
*
* @this {Time}
*/
resetTimers()
{
for (let iTimer = this.aTimers.length; iTimer > 0; iTimer--) {
let timer = this.aTimers[iTimer-1];
if (timer.msAuto >= 0) this.setTimer(iTimer, timer.msAuto, true);
}
}
/**
* run()
*
* @this {Time}
*/
run()
{
this.idRunTimeout = 0;
if (!this.fRunning) return;
this.snapStart();
try {
this.fYield = false;
do {
/*
* Execute the burst and then update all timers.
*/
this.updateTimers(this.endBurst(this.doBurst(this.getCyclesPerBurst())));
} while (this.fRunning && !this.fYield);
}
catch(err) {
this.println(err.message);
this.stop();
return;
}
if (this.fRunning) {
this.assert(!this.idRunTimeout);
this.idRunTimeout = setTimeout(this.onRunTimeout, this.snapStop());
if (!this.fRequestAnimationFrame) this.animate();
}
}
/**
* setSpeedThrottle()
*
* This handles speed adjustments requested by the throttling slider.
*
* @this {Time}
* @returns {boolean} (true if a throttle exists, false if not)
*/
setSpeedThrottle()
{
/*
* We're not going to assume any direct relationship between the slider's min/max/value
* and our own nCyclesMinimum/nCyclesMaximum/nCyclesPerSecond. We're just going to calculate
* a new target nCyclesPerSecond that is proportional, and then convert that to a speed multiplier.
*/
let elementInput = this.bindings[Time.BINDING.THROTTLE];
if (elementInput) {
let ratio = (elementInput.value - elementInput.min) / (elementInput.max - elementInput.min);
let nCycles = Math.floor((this.nCyclesMaximum - this.nCyclesMinimum) * ratio + this.nCyclesMinimum);
let nMultiplier = nCycles / this.nCyclesPerSecond;
this.assert(nMultiplier >= 1);
this.setSpeed(nMultiplier);
return true;
}
return false;
}
/**
* setSpeed(nMultiplier)
*
* @this {Time}
* @param {number} [nMultiplier] is the new proposed multiplier (reverts to default if target was too high)
* @returns {boolean} true if successful, false if not
*
* @desc Whenever the speed is changed, the running cycle count and corresponding start time must be reset,
* so that the next effective speed calculation obtains sensible results. In fact, when run() initially calls
* setSpeed() with no parameters, that's all this function does (it doesn't change the current speed setting).
*/
setSpeed(nMultiplier)
{
let fSuccess = true;
if (nMultiplier !== undefined) {
/*
* If we haven't reached 90% (0.9) of the current target speed, revert to the default multiplier.
*/
if (!this.fThrottling && this.mhzCurrent > 0 && this.mhzCurrent < this.mhzTarget * 0.9) {
nMultiplier = this.nBaseMultiplier;
fSuccess = false;
}
this.nTargetMultiplier = nMultiplier;
let mhzTarget = this.mhzBase * this.nTargetMultiplier;
if (this.mhzTarget != mhzTarget) {
this.mhzTarget = mhzTarget;
this.setBindingText(Time.BINDING.SPEED, this.getSpeedTarget());
}
/*
* After every yield, calcSpeed() will update mhzCurrent, but we also need to be optimistic
* and set it to the mhzTarget now, so that the next calcCycles() call will make a reasonable
* initial estimate.
*/
this.mhzCurrent = this.mhzTarget;
}
if (this.fClockByFrame) {
let nCyclesPerSecond = this.mhzCurrent * 1000000;
this.nCyclesDepositPerFrame = (nCyclesPerSecond / 60) + 0.00000001;
this.nCyclesDeposited = 0;
}
this.nCyclesRun = 0;
this.msStartRun = this.msEndRun = 0;
this.calcCycles(); // calculate a new value for the current cycle multiplier
this.resetTimers(); // and then update all the fixed-period timers using the new cycle multiplier
return fSuccess;
}
/**
* setTimer(iTimer, ms, fReset)
*
* Using the timer index from a previous addTimer() call, this sets that timer to fire after the
* specified number of milliseconds.
*
* @this {Time}
* @param {number} iTimer
* @param {number} ms (converted into a cycle countdown internally)
* @param {boolean} [fReset] (true if the timer should be reset even if already armed)
* @returns {number} (number of cycles used to arm timer, or -1 if error)
*/
setTimer(iTimer, ms, fReset)
{
let nCycles = -1;
if (iTimer > 0 && iTimer <= this.aTimers.length) {
let timer = this.aTimers[iTimer-1];
if (fReset || timer.nCyclesLeft < 0) {
nCycles = this.getCycles(ms);
/*
* If we're currently executing a burst of cycles, the number of cycles it has executed in
* that burst so far must NOT be charged against the cycle timeout we're about to set. The simplest
* way to resolve that is to immediately call endBurst() and bias the cycle timeout by the number
* of cycles that the burst executed.
*/
if (this.fRunning) {
nCycles += this.endBurst();
}
timer.nCyclesLeft = nCycles;
}
}
return nCycles;
}
/**
* snapStart()
*
* @this {Time}
*/
snapStart()
{
this.calcCycles();
this.nCyclesThisRun = 0;
this.msOutsideThisRun = 0;
this.msStartThisRun = Date.now();
if (!this.msStartRun) this.msStartRun = this.msStartThisRun;
/*
* Try to detect situations where the browser may have throttled us, such as when the user switches
* to a different tab; in those situations, Chrome and Safari may restrict setTimeout() callbacks
* to roughly one per second.
*
* Another scenario: the user resizes the browser window. setTimeout() callbacks are not throttled,
* but there can still be enough of a lag between the callbacks that speed will be noticeably
* erratic if we don't compensate for it here.
*
* We can detect throttling/lagging by verifying that msEndRun (which was set at the end of the
* previous run and includes any requested sleep time) is comparable to the current msStartThisRun;
* if the delta is significant, we compensate by bumping msStartRun forward by that delta.
*
* This shouldn't be triggered when the Debugger stops time, because setSpeed() -- which is called
* whenever the time starts again -- zeroes msEndRun.
*/
let msDelta = 0;
if (this.msEndRun) {
msDelta = this.msStartThisRun - this.msEndRun;
if (msDelta > this.msYield) {
this.msStartRun += msDelta;
/*
* Bumping msStartRun forward should NEVER cause it to exceed msStartThisRun; however, just
* in case, I make absolutely sure it cannot happen, since doing so could result in negative
* speed calculations.
*/
this.assert(this.msStartRun <= this.msStartThisRun);
if (this.msStartRun > this.msStartThisRun) {
this.msStartRun = this.msStartThisRun;
}
}
}
}
/**
* snapStop()
*
* @this {Time}
* @returns {number}
*/
snapStop()
{
this.msEndRun = Date.now();
if (this.msOutsideThisRun) {
this.msStartRun += this.msOutsideThisRun;
this.msStartThisRun += this.msOutsideThisRun;
}
let msYield = this.msYield;
if (this.nCyclesThisRun) {
/*
* Normally, we assume we executed a full quota of work over msYield. If nCyclesThisRun is correct,
* then the ratio of nCyclesThisRun/nCyclesPerYield should represent the percentage of work we performed,
* and so applying that percentage to msYield should give us a better estimate of work vs. time.
*/
msYield = Math.round(msYield * this.nCyclesThisRun / this.nCyclesPerYield);
}
let msElapsedThisRun = this.msEndRun - this.msStartThisRun;
let msRemainsThisRun = msYield - msElapsedThisRun;
let nCycles = this.nCyclesRun;
let msElapsed = this.msEndRun - this.msStartRun;
if (DEBUG && msRemainsThisRun < 0 && this.nTargetMultiplier > 1) {
this.println("warning: updates @" + msElapsedThisRun + "ms (prefer " + Math.round(msYield) + "ms)");
}
this.calcSpeed(nCycles, msElapsed);
if (msRemainsThisRun < 0) {
/*
* Try "throwing out" the effects of large anomalies, by moving the overall run start time up;
* ordinarily, this should only happen when the someone is using an external Debugger or some other
* tool or feature that is interfering with our overall execution.
*/
if (msRemainsThisRun < -1000) {
this.msStartRun -= msRemainsThisRun;
}
/*
* If the last burst took MORE time than we allotted (ie, it's taking more than 1 second to simulate
* nCyclesPerSecond), all we can do is yield for as little time as possible (ie, 0ms) and hope that the
* simulation is at least usable.
*/
msRemainsThisRun = 0;
}
else if (this.mhzCurrent < this.mhzTarget) {
msRemainsThisRun = 0;
}
this.msEndRun += msRemainsThisRun;
if (this.isCategoryOn(Device.CATEGORY.TIME)) {
this.printf("after running %d cycles, resting for %dms\n", this.nCyclesThisRun, msRemainsThisRun);
}
return msRemainsThisRun;
}
/**
* start()
*
* @this {Time}
* @returns {boolean}
*/
start()
{
if (this.fRunning || this.nStepping) {
return false;
}
if (this.idRunTimeout) {
clearTimeout(this.idRunTimeout);
this.idRunTimeout = 0;
}
this.fRunning = true;
this.msStartRun = this.msEndRun = 0;
this.updateStatus(true);
/*
* Kickstart both the clockers and requestAnimationFrame; it's a little premature to start
* animation here, because the first run() should take place before the first animate(), but
* since clock speed is now decoupled from animation speed, this isn't something we should
* worry about.
*/
if (!this.fClockByFrame) {
this.assert(!this.idRunTimeout);
this.idRunTimeout = setTimeout(this.onRunTimeout, 0);
}
if (this.fRequestAnimationFrame) this.requestAnimationFrame(this.onAnimationFrame);
return true;
}
/**
* step(nRepeat)
*
* @this {Time}
* @param {number} [nRepeat]
* @returns {boolean} true if successful, false if already running
*/
step(nRepeat = 1)
{
if (!this.fRunning) {
if (nRepeat && !this.nStepping) {
this.nStepping = nRepeat;
}
if (this.nStepping) {
/*
* Execute a minimum-cycle burst and then update all timers.
*/
let nCycles = (this.fClockByFrame? (this.getCyclesPerFrame() || 1) : 1);
this.nStepping--;
this.updateTimers(this.endBurst(this.doBurst(nCycles)));
this.updateStatus();
if (this.nStepping) {
let time = this;