Calculate FPS
This commit is contained in:
parent
9d8c975776
commit
52799a6bf0
2 changed files with 32 additions and 3 deletions
|
|
@ -1,7 +1,16 @@
|
||||||
export class DeltaTimeCalculator {
|
import { clamp } from './clamp';
|
||||||
private previousTime: DOMHighResTimeStamp | null = null;
|
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));
|
document.addEventListener('visibilitychange', this.handleVisibilityChange.bind(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -14,8 +23,15 @@ export class DeltaTimeCalculator {
|
||||||
|
|
||||||
const delta = currentTime - this.previousTime;
|
const delta = currentTime - this.previousTime;
|
||||||
this.previousTime = currentTime;
|
this.previousTime = currentTime;
|
||||||
return 1 / 60;
|
const deltaInSeconds = delta / 1000;
|
||||||
return Math.min(delta / 1000, this.maxDeltaTimeInSeconds);
|
|
||||||
|
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() {
|
private handleVisibilityChange() {
|
||||||
|
|
@ -23,4 +39,8 @@ export class DeltaTimeCalculator {
|
||||||
this.previousTime = null;
|
this.previousTime = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public get fps() {
|
||||||
|
return 1 / this.deltaTimeAccumulator;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
9
src/utils/exponential-decay.ts
Normal file
9
src/utils/exponential-decay.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
export const exponentialDecay = ({
|
||||||
|
accumulator,
|
||||||
|
nextValue,
|
||||||
|
biasOfNextValue,
|
||||||
|
}: {
|
||||||
|
accumulator: number;
|
||||||
|
nextValue: number;
|
||||||
|
biasOfNextValue: number;
|
||||||
|
}) => accumulator * (1 - biasOfNextValue) + nextValue * biasOfNextValue;
|
||||||
Loading…
Reference in a new issue