feat: threading

This commit is contained in:
aarthificial
2022-02-19 23:00:41 +01:00
parent 34c95cfda9
commit e9f6b2ad08
3 changed files with 38 additions and 2 deletions

View File

@@ -12,6 +12,7 @@ import {
waitFor,
waitUntil,
sequence,
threads,
} from './animations';
Konva.autoDrawEnabled = false;
@@ -75,7 +76,10 @@ export class Project extends Stage {
this.scenes.forEach(scene => scene.layer.destroy());
this.scenes = [];
this.frame = 0;
this.runner = this.runnerFactory(this);
this.runner = this.threads(join => {
this.join = join;
return this.runnerFactory(this);
});
}
public next(): boolean {
@@ -94,6 +98,8 @@ export class Project extends Stage {
return frames / this.framesPerSeconds;
}
public join: (...runners: Generator[]) => Generator;
public threads = threads;
public waitFor = waitFor;
public waitUntil = waitUntil;
public tween = tween;

View File

@@ -5,4 +5,5 @@ export * from './surfaceTransition';
export * from './tween';
export * from './TimeTween';
export * from './scheduling';
export * from './sequence';
export * from './sequence';
export * from './threads';

29
src/animations/threads.ts Normal file
View File

@@ -0,0 +1,29 @@
export function* threads(
factory: (join: (...tasks: Generator[]) => Generator) => Generator,
): Generator {
let runners: Generator[] = [];
const join = function* (...tasks: Generator[]): Generator {
while (tasks.find(runner => runners.includes(runner))) {
yield;
}
};
runners.push(factory(join));
while (runners.length > 0) {
const newRunners = [];
for (let i = 0; i < runners.length; i++) {
const runner = runners[i];
const result = runner.next();
if (result.value?.next) {
if (!result.done) {
runners.push(runner);
}
runners.push(result.value);
} else if (!result.done) {
newRunners.push(runner);
}
}
runners = newRunners;
if (runners.length > 0) yield;
}
}