1
0
mirror of https://github.com/tobspr/shapez.io.git synced 2025-06-13 13:04:03 +00:00
tobspr_shapez.io/src/ts/core/animation_frame.ts

62 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-11-18 01:33:12 +00:00
import { Signal } from "./signal";
2022-11-19 03:53:49 +00:00
2022-11-18 01:33:12 +00:00
// @ts-ignore
import BackgroundAnimationFrameEmitterWorker from "../webworkers/background_animation_frame_emittter.worker";
import { createLogger } from "./logging";
2022-11-19 03:53:49 +00:00
2022-11-18 15:20:54 +00:00
const logger = createLogger("animation_frame");
const maxDtMs = 1000;
const resetDtMs = 16;
2022-11-18 01:33:12 +00:00
export class AnimationFrame {
2022-11-19 03:53:49 +00:00
public frameEmitted = new Signal<[dt: number]>();
public bgFrameEmitted = new Signal<[dt: number]>();
2022-11-18 01:33:12 +00:00
public lastTime = performance.now();
public bgLastTime = performance.now();
2022-11-19 03:53:49 +00:00
2022-11-18 01:33:12 +00:00
public boundMethod = this.handleAnimationFrame.bind(this);
2022-11-19 03:53:49 +00:00
2022-11-18 01:33:12 +00:00
public backgroundWorker = new BackgroundAnimationFrameEmitterWorker();
constructor() {
2022-11-18 15:20:54 +00:00
this.backgroundWorker.addEventListener("error", err => {
2022-11-18 01:33:12 +00:00
logger.error("Error in background fps worker:", err);
});
this.backgroundWorker.addEventListener("message", this.handleBackgroundTick.bind(this));
}
2022-11-19 03:53:49 +00:00
2022-11-18 15:20:54 +00:00
handleBackgroundTick() {
const time = performance.now();
2022-11-19 03:53:49 +00:00
2022-11-18 15:20:54 +00:00
let dt = time - this.bgLastTime;
2022-11-19 03:53:49 +00:00
2022-11-18 01:33:12 +00:00
if (dt > maxDtMs) {
dt = resetDtMs;
}
2022-11-19 03:53:49 +00:00
2022-11-18 01:33:12 +00:00
this.bgFrameEmitted.dispatch(dt);
this.bgLastTime = time;
}
2022-11-19 03:53:49 +00:00
2022-11-18 15:20:54 +00:00
start() {
2022-11-18 01:33:12 +00:00
assertAlways(window.requestAnimationFrame, "requestAnimationFrame is not supported!");
2022-11-19 03:53:49 +00:00
this.handleAnimationFrame(0);
2022-11-18 01:33:12 +00:00
}
2022-11-19 03:53:49 +00:00
handleAnimationFrame(time: number) {
2022-11-18 15:20:54 +00:00
let dt = time - this.lastTime;
2022-11-19 03:53:49 +00:00
2022-11-18 01:33:12 +00:00
if (dt > maxDtMs) {
dt = resetDtMs;
}
2022-11-19 03:53:49 +00:00
2022-11-18 01:33:12 +00:00
try {
this.frameEmitted.dispatch(dt);
2022-11-19 03:53:49 +00:00
} catch (ex) {
2022-11-18 01:33:12 +00:00
console.error(ex);
}
this.lastTime = time;
window.requestAnimationFrame(this.boundMethod);
}
}