Interpreter fixes, enhancements, features ()

* Thread stepping rework; interp.redraw equivalent

* Add turbo mode and pause mode

* Yielding behavior to match Scratch 2.0

* Implement warp-mode procedure threads

* Add check for recursive call

* Inline wait block timer

* Revert to setInterval and always drawing

* Restore yielding in glide

* 30TPS compatibility mode

* 5-call count recursion limit

* Removing dead primitive code

* To simplify, access runtime.threads inline in `stepThreads`.

* Warp mode/timer fixes; recursive check fixes; clean-up

* Add basic single-stepping

* Add single-stepping speed slider

* Allow yielding threads to run in single-stepping

* Restore inactive threads tracking for block glows

* Add clock pausing during pause mode

* Documentation and clean-up throughout

* Don't look for block glows in `thread.topBlock`.

* Add null check for block glows; rename `_updateScriptGlows` to reflect block glowing

* Use the current executed block for glow, instead of stack

* Add more comments to `stepToProcedure`, and re-arrange to match 2.0

* Tweak to Blocks.prototype.getTopLevelScript

* Revert previous

* Fix threads array to be resilient to changes during `stepThreads`

* Restore inactive threads filtering

* Fix typo in "procedure"

* !! instead of == true
This commit is contained in:
Tim Mickel 2016-10-17 23:23:16 -04:00 committed by GitHub
parent 060d1ab2a5
commit e49f076fa1
14 changed files with 705 additions and 281 deletions
src/engine

View file

@ -17,87 +17,163 @@ function Sequencer (runtime) {
}
/**
* 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}
* Time to run a warp-mode thread, in ms.
* @type {number}
*/
Sequencer.WORK_TIME = 10;
Sequencer.WARP_TIME = 500;
/**
* Step through all threads in `this.threads`, running them in order.
* @param {Array.<Thread>} threads List of which threads to step.
* @return {Array.<Thread>} All threads which have finished in this iteration.
* Step through all threads in `this.runtime.threads`, running them in order.
* @return {Array.<!Thread>} List of inactive threads after stepping.
*/
Sequencer.prototype.stepThreads = function (threads) {
// Start counting toward WORK_TIME
Sequencer.prototype.stepThreads = function () {
// Work time is 75% of the thread stepping interval.
var WORK_TIME = 0.75 * this.runtime.currentStepTime;
// Start counting toward WORK_TIME.
this.timer.start();
// List of threads which have been killed by this step.
// Count of active threads.
var numActiveThreads = Infinity;
// Whether `stepThreads` has run through a full single tick.
var ranFirstTick = false;
var inactiveThreads = [];
// If all of the threads are yielding, we should yield.
var numYieldingThreads = 0;
// Clear all yield statuses that were for the previous frame.
for (var t = 0; t < threads.length; t++) {
if (threads[t].status === Thread.STATUS_YIELD_FRAME) {
threads[t].setStatus(Thread.STATUS_RUNNING);
}
}
// While there are still threads to run and we are within WORK_TIME,
// continue executing threads.
while (threads.length > 0 &&
threads.length > numYieldingThreads &&
this.timer.timeElapsed() < Sequencer.WORK_TIME) {
// New threads at the end of the iteration.
var newThreads = [];
// Reset yielding thread count.
numYieldingThreads = 0;
// Attempt to run each thread one time
for (var i = 0; i < threads.length; i++) {
var activeThread = threads[i];
if (activeThread.status === Thread.STATUS_RUNNING) {
// Normal-mode thread: step.
this.startThread(activeThread);
} else if (activeThread.status === Thread.STATUS_YIELD ||
activeThread.status === Thread.STATUS_YIELD_FRAME) {
// Yielding thread: do nothing for this step.
numYieldingThreads++;
}
if (activeThread.stack.length === 0 &&
// Conditions for continuing to stepping threads:
// 1. We must have threads in the list, and some must be active.
// 2. Time elapsed must be less than WORK_TIME.
// 3. Either turbo mode, or no redraw has been requested by a primitive.
while (this.runtime.threads.length > 0 &&
numActiveThreads > 0 &&
this.timer.timeElapsed() < WORK_TIME &&
(this.runtime.turboMode || !this.runtime.redrawRequested)) {
numActiveThreads = 0;
// Inline copy of the threads, updated on each step.
var threadsCopy = this.runtime.threads.slice();
// Attempt to run each thread one time.
for (var i = 0; i < threadsCopy.length; i++) {
var activeThread = threadsCopy[i];
if (activeThread.stack.length === 0 ||
activeThread.status === Thread.STATUS_DONE) {
// Finished with this thread - tell runtime to clean it up.
inactiveThreads.push(activeThread);
} else {
// Keep this thead in the loop.
newThreads.push(activeThread);
// Finished with this thread.
if (inactiveThreads.indexOf(activeThread) < 0) {
inactiveThreads.push(activeThread);
}
continue;
}
if (activeThread.status === Thread.STATUS_YIELD_TICK &&
!ranFirstTick) {
// Clear single-tick yield from the last call of `stepThreads`.
activeThread.status = Thread.STATUS_RUNNING;
}
if (activeThread.status === Thread.STATUS_RUNNING ||
activeThread.status === Thread.STATUS_YIELD) {
// Normal-mode thread: step.
this.stepThread(activeThread);
activeThread.warpTimer = null;
}
if (activeThread.status === Thread.STATUS_RUNNING) {
// After stepping, status is still running.
// If we're in single-stepping mode, mark the thread as
// a single-tick yield so it doesn't re-execute
// until the next frame.
if (this.runtime.singleStepping) {
activeThread.status = Thread.STATUS_YIELD_TICK;
}
numActiveThreads++;
}
}
// Effectively filters out threads that have stopped.
threads = newThreads;
// We successfully ticked once. Prevents running STATUS_YIELD_TICK
// threads on the next tick.
ranFirstTick = true;
}
// Filter inactive threads from `this.runtime.threads`.
this.runtime.threads = this.runtime.threads.filter(function(thread) {
if (inactiveThreads.indexOf(thread) > -1) {
return false;
}
return true;
});
return inactiveThreads;
};
/**
* Step the requested thread
* @param {!Thread} thread Thread object to step
* Step the requested thread for as long as necessary.
* @param {!Thread} thread Thread object to step.
*/
Sequencer.prototype.startThread = function (thread) {
Sequencer.prototype.stepThread = function (thread) {
var currentBlockId = thread.peekStack();
if (!currentBlockId) {
// A "null block" - empty branch.
// Yield for the frame.
thread.popStack();
thread.setStatus(Thread.STATUS_YIELD_FRAME);
return;
}
// Execute the current block
execute(this, thread);
// If the block executed without yielding and without doing control flow,
// move to done.
if (thread.status === Thread.STATUS_RUNNING &&
thread.peekStack() === currentBlockId) {
this.proceedThread(thread);
while (thread.peekStack()) {
var isWarpMode = thread.peekStackFrame().warpMode;
if (isWarpMode && !thread.warpTimer) {
// Initialize warp-mode timer if it hasn't been already.
// This will start counting the thread toward `Sequencer.WARP_TIME`.
thread.warpTimer = new Timer();
thread.warpTimer.start();
}
// Execute the current block.
// Save the current block ID to notice if we did control flow.
currentBlockId = thread.peekStack();
execute(this, thread);
thread.blockGlowInFrame = currentBlockId;
// If the thread has yielded or is waiting, yield to other threads.
if (thread.status === Thread.STATUS_YIELD) {
// Mark as running for next iteration.
thread.status = Thread.STATUS_RUNNING;
// In warp mode, yielded blocks are re-executed immediately.
if (isWarpMode &&
thread.warpTimer.timeElapsed() <= Sequencer.WARP_TIME) {
continue;
}
return;
} else if (thread.status === Thread.STATUS_PROMISE_WAIT) {
// A promise was returned by the primitive. Yield the thread
// until the promise resolves. Promise resolution should reset
// thread.status to Thread.STATUS_RUNNING.
return;
}
// If no control flow has happened, switch to next block.
if (thread.peekStack() === currentBlockId) {
thread.goToNextBlock();
}
// If no next block has been found at this point, look on the stack.
while (!thread.peekStack()) {
thread.popStack();
if (thread.stack.length === 0) {
// No more stack to run!
thread.status = Thread.STATUS_DONE;
return;
}
if (thread.peekStackFrame().isLoop) {
// The current level of the stack is marked as a loop.
// Return to yield for the frame/tick in general.
// Unless we're in warp mode - then only return if the
// warp timer is up.
if (!isWarpMode ||
thread.warpTimer.timeElapsed() > Sequencer.WARP_TIME) {
// Don't do anything to the stack, since loops need
// to be re-executed.
return;
} else {
// Don't go to the next block for this level of the stack,
// since loops need to be re-executed.
continue;
}
} else if (thread.peekStackFrame().waitingReporter) {
// This level of the stack was waiting for a value.
// This means a reporter has just returned - so don't go
// to the next block for this level of the stack.
return;
}
// Get next block of existing block on the stack.
thread.goToNextBlock();
}
// In single-stepping mode, force `stepThread` to only run one block
// at a time.
if (this.runtime.singleStepping) {
return;
}
}
};
@ -105,8 +181,9 @@ Sequencer.prototype.startThread = function (thread) {
* Step a thread into a block's branch.
* @param {!Thread} thread Thread object to step to branch.
* @param {Number} branchNum Which branch to step to (i.e., 1, 2).
* @param {Boolean} isLoop Whether this block is a loop.
*/
Sequencer.prototype.stepToBranch = function (thread, branchNum) {
Sequencer.prototype.stepToBranch = function (thread, branchNum, isLoop) {
if (!branchNum) {
branchNum = 1;
}
@ -115,11 +192,11 @@ Sequencer.prototype.stepToBranch = function (thread, branchNum) {
currentBlockId,
branchNum
);
thread.peekStackFrame().isLoop = isLoop;
if (branchId) {
// Push branch ID to the thread's stack.
thread.pushStack(branchId);
} else {
// Push null, so we come back to the current block.
thread.pushStack(null);
}
};
@ -127,56 +204,39 @@ Sequencer.prototype.stepToBranch = function (thread, branchNum) {
/**
* Step a procedure.
* @param {!Thread} thread Thread object to step to procedure.
* @param {!string} procedureName Name of procedure defined in this target.
* @param {!string} procedureCode Procedure code of procedure to step to.
*/
Sequencer.prototype.stepToProcedure = function (thread, procedureName) {
var definition = thread.target.blocks.getProcedureDefinition(procedureName);
Sequencer.prototype.stepToProcedure = function (thread, procedureCode) {
var definition = thread.target.blocks.getProcedureDefinition(procedureCode);
if (!definition) {
return;
}
// Check if the call is recursive.
// If so, set the thread to yield after pushing.
var isRecursive = thread.isRecursiveCall(procedureCode);
// To step to a procedure, we put its definition on the stack.
// Execution for the thread will proceed through the definition hat
// and on to the main definition of the procedure.
// When that set of blocks finishes executing, it will be popped
// from the stack by the sequencer, returning control to the caller.
thread.pushStack(definition);
// Check if the call is recursive. If so, yield.
// @todo: Have behavior match Scratch 2.0.
if (thread.stack.indexOf(definition) > -1) {
thread.setStatus(Thread.STATUS_YIELD_FRAME);
}
};
/**
* Step a thread into an input reporter, and manage its status appropriately.
* @param {!Thread} thread Thread object to step to reporter.
* @param {!string} blockId ID of reporter block.
* @param {!string} inputName Name of input on parent block.
* @return {boolean} True if yielded, false if it finished immediately.
*/
Sequencer.prototype.stepToReporter = function (thread, blockId, inputName) {
var currentStackFrame = thread.peekStackFrame();
// Push to the stack to evaluate the reporter block.
thread.pushStack(blockId);
// Save name of input for `Thread.pushReportedValue`.
currentStackFrame.waitingReporter = inputName;
// Actually execute the block.
this.startThread(thread);
// If a reporter yielded, caller must wait for it to unyield.
// The value will be populated once the reporter unyields,
// and passed up to the currentStackFrame on next execution.
return thread.status === Thread.STATUS_YIELD;
};
/**
* Finish stepping a thread and proceed it to the next block.
* @param {!Thread} thread Thread object to proceed.
*/
Sequencer.prototype.proceedThread = function (thread) {
var currentBlockId = thread.peekStack();
// Mark the status as done and proceed to the next block.
// Pop from the stack - finished this level of execution.
thread.popStack();
// Push next connected block, if there is one.
var nextBlockId = thread.target.blocks.getNextBlock(currentBlockId);
if (nextBlockId) {
thread.pushStack(nextBlockId);
}
// If we can't find a next block to run, mark the thread as done.
if (!thread.peekStack()) {
thread.setStatus(Thread.STATUS_DONE);
// In known warp-mode threads, only yield when time is up.
if (thread.peekStackFrame().warpMode &&
thread.warpTimer.timeElapsed() > Sequencer.WARP_TIME) {
thread.status = Thread.STATUS_YIELD;
} else {
// Look for warp-mode flag on definition, and set the thread
// to warp-mode if needed.
var definitionBlock = thread.target.blocks.getBlock(definition);
var doWarp = definitionBlock.mutation.warp;
if (doWarp) {
thread.peekStackFrame().warpMode = true;
} else {
// In normal-mode threads, yield any time we have a recursive call.
if (isRecursive) {
thread.status = Thread.STATUS_YIELD;
}
}
}
};
@ -188,7 +248,7 @@ Sequencer.prototype.retireThread = function (thread) {
thread.stack = [];
thread.stackFrame = [];
thread.requestScriptGlowInFrame = false;
thread.setStatus(Thread.STATUS_DONE);
thread.status = Thread.STATUS_DONE;
};
module.exports = Sequencer;