/
animationLoop.js
110 lines (87 loc) · 2.34 KB
/
animationLoop.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
import filter from './filter';
import now from 'performance-now';
import raf from 'raf';
function renderSubscriber(alpha, subscriber) {
subscriber.render(alpha, subscriber.value, subscriber.prevValue);
return subscriber.active;
}
const prototype = {
running: false,
shouldStop: false,
lastTime: 0,
accumulatedTime: 0,
subscribe(step, render, value) {
const subscriber = {
value: value,
prevValue: value,
step: step,
render: render,
active: true,
};
this.state.push(subscriber);
return function unsubscribe() {
subscriber.active = false;
};
},
loop() {
const currentTime = now();
if (this.shouldStop) {
this.running = this.shouldStop = false;
return;
}
const timeStep = this.timeStep;
const frameTime = currentTime - this.lastTime;
this.lastTime = currentTime;
this.accumulatedTime += frameTime * this.timeScale;
if (this.accumulatedTime > timeStep * this.maxSteps) {
this.accumulatedTime = 0;
}
while (this.accumulatedTime > 0) {
this.state.forEach(this.step);
this.accumulatedTime -= timeStep;
}
// Render and filter in one iteration.
this.state = filter(
this.state,
renderSubscriber,
1 + this.accumulatedTime / timeStep
);
if (this.state.length === 0) {
this.shouldStop = true;
}
raf(this.loop);
},
start() {
if (this.state.length) {
if (this.shouldStop) {
this.shouldStop = false;
} else if (!this.running) {
this.running = true;
this.lastTime = now();
this.accumulatedTime = 0;
raf(this.loop);
}
}
},
// stop() {
// this.shouldStop = true;
// return this;
// },
};
export default function createAnimationLoop({timeStep, timeScale, maxSteps}) {
const animationLoop = Object.create(prototype);
animationLoop.loop = animationLoop.loop.bind(animationLoop);
animationLoop.state = [];
// timeStep is in milliseconds
animationLoop.timeStep = timeStep * 1000; // seconds
animationLoop.timeScale = timeScale;
animationLoop.maxSteps = maxSteps;
animationLoop.step = subscriber => {
if (subscriber.active) {
const value = subscriber.value;
subscriber.prevValue = value;
subscriber.value = subscriber.step(timeStep, value);
}
};
return animationLoop;
}