Calculate FPS

This commit is contained in:
Andras Schmelczer 2023-05-21 09:41:19 +01:00
parent 9d8c975776
commit 52799a6bf0
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
2 changed files with 34 additions and 5 deletions

View file

@ -1,7 +1,16 @@
export class DeltaTimeCalculator {
private previousTime: DOMHighResTimeStamp | null = null;
import { clamp } from './clamp';
import { exponentialDecay } from './exponential-decay';
constructor(private readonly maxDeltaTimeInSeconds: number = 1 / 30) {
export class DeltaTimeCalculator {
private static FPS_EXPONENTIAL_DECAY_STRENGTH = 0.1;
private previousTime: DOMHighResTimeStamp | null = null;
private deltaTimeAccumulator: number | null = null;
constructor(
private readonly maxDeltaTimeInSeconds: number = 1 / 30,
private readonly minDeltaTimeInSeconds: number = 1 / 240
) {
document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
}
@ -14,8 +23,15 @@ export class DeltaTimeCalculator {
const delta = currentTime - this.previousTime;
this.previousTime = currentTime;
return 1 / 60;
return Math.min(delta / 1000, this.maxDeltaTimeInSeconds);
const deltaInSeconds = delta / 1000;
this.deltaTimeAccumulator = exponentialDecay({
accumulator: this.deltaTimeAccumulator ?? deltaInSeconds,
nextValue: deltaInSeconds,
biasOfNextValue: DeltaTimeCalculator.FPS_EXPONENTIAL_DECAY_STRENGTH,
});
return clamp(delta / 1000, this.minDeltaTimeInSeconds, this.maxDeltaTimeInSeconds);
}
private handleVisibilityChange() {
@ -23,4 +39,8 @@ export class DeltaTimeCalculator {
this.previousTime = null;
}
}
public get fps() {
return 1 / this.deltaTimeAccumulator;
}
}

View file

@ -0,0 +1,9 @@
export const exponentialDecay = ({
accumulator,
nextValue,
biasOfNextValue,
}: {
accumulator: number;
nextValue: number;
biasOfNextValue: number;
}) => accumulator * (1 - biasOfNextValue) + nextValue * biasOfNextValue;