2016-04-26 15:00:45 -04:00
|
|
|
var Timer = require('../util/Timer');
|
|
|
|
|
2016-04-26 09:49:52 -04:00
|
|
|
function Sequencer () {
|
2016-04-26 15:00:45 -04:00
|
|
|
/**
|
|
|
|
* A utility timer for timing thread sequencing.
|
|
|
|
* @type {!Timer}
|
|
|
|
*/
|
|
|
|
this.timer = new Timer();
|
2016-04-18 17:20:30 -04:00
|
|
|
}
|
|
|
|
|
2016-04-26 15:00:45 -04:00
|
|
|
/**
|
|
|
|
* The sequencer does as much work as it can within WORK_TIME milliseconds,
|
|
|
|
* then yields. This is essentially a rate-limiter for blocks.
|
|
|
|
* In Scratch 2.0, this is set to 75% of the target stage frame-rate (30fps).
|
|
|
|
* @const {!number}
|
|
|
|
*/
|
|
|
|
Sequencer.WORK_TIME = 1000 / 60;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Step through all threads in `this.threads`, running them in order.
|
2016-04-26 15:51:14 -04:00
|
|
|
* @return {Array.<Thread>} New threads after this round of execution.
|
2016-04-26 15:00:45 -04:00
|
|
|
*/
|
2016-04-26 15:51:14 -04:00
|
|
|
Sequencer.prototype.stepThreads = function (threads) {
|
2016-04-26 15:00:45 -04:00
|
|
|
// Start counting toward WORK_TIME
|
|
|
|
this.timer.start();
|
|
|
|
// While there are still threads to run and we are within WORK_TIME,
|
|
|
|
// continue executing threads.
|
2016-04-26 15:51:14 -04:00
|
|
|
while (threads.length > 0 &&
|
2016-04-26 15:00:45 -04:00
|
|
|
this.timer.timeElapsed() < Sequencer.WORK_TIME) {
|
|
|
|
// New threads at the end of the iteration.
|
|
|
|
var newThreads = [];
|
|
|
|
// Attempt to run each thread one time
|
2016-04-26 15:51:14 -04:00
|
|
|
for (var i = 0; i < threads.length; i++) {
|
|
|
|
var activeThread = threads[i];
|
2016-04-26 15:00:45 -04:00
|
|
|
this.stepThread(activeThread);
|
|
|
|
if (activeThread.nextBlock !== null) {
|
|
|
|
newThreads.push(activeThread);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Effectively filters out threads that have stopped.
|
2016-04-26 15:51:14 -04:00
|
|
|
threads = newThreads;
|
2016-04-26 15:00:45 -04:00
|
|
|
}
|
2016-04-26 15:51:14 -04:00
|
|
|
return threads;
|
2016-04-26 15:00:45 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Step the requested thread
|
|
|
|
* @param {!Thread} thread Thread object to step
|
|
|
|
*/
|
2016-04-26 15:51:14 -04:00
|
|
|
Sequencer.prototype.stepThread = function (thread) {
|
2016-04-26 15:00:45 -04:00
|
|
|
// @todo
|
|
|
|
};
|
|
|
|
|
2016-04-18 17:20:30 -04:00
|
|
|
module.exports = Sequencer;
|