Skip to content

Commit bb88c76

Browse files
committed
change the way we calculate FPS again using smoothing
and also prevent a double render causing Infinity.
1 parent 7f251b5 commit bb88c76

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

addons/fps/userscript.js

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,26 +12,31 @@ export default async function ({ addon, console, msg }) {
1212
addon.tab.displayNoneWhileDisabled(fpsCounterElement);
1313
addSmallStageClass();
1414

15-
const renderTimes = [];
16-
let lastFps = 0;
15+
let lastRender;
16+
let lastFps;
1717
let wasRunning = false;
1818

1919
const { renderer } = runtime;
2020
const _draw = renderer.draw;
2121
renderer.draw = function () {
2222
_draw.call(this);
2323

24-
// Every time this function is ran, store the current time and remove times from half a second ago
2524
const now = runtime.currentMSecs;
26-
while (renderTimes.length > 0 && renderTimes[0] <= now - 500) renderTimes.shift();
27-
// Calculate FPS times of each render frame.
28-
const allFps = renderTimes.map((time, i) => 1000 / ((renderTimes[i + 1] ?? now) - time));
29-
renderTimes.push(now);
30-
let fps = 0;
31-
if (allFps.length !== 0) {
32-
// Average FPS times.
33-
fps = Math.round(allFps.reduce((prev, curr) => prev + curr, 0) / allFps.length);
25+
// If it's been more than 500ms since the last draw, we want to reset the variables.
26+
if (typeof lastRender !== "number" || now - lastRender > 500) {
27+
lastRender = now
28+
lastFps = null;
29+
return;
3430
}
31+
// If the current time has been rendered, return, Don't show infinity.
32+
if (now === lastRender) return;
33+
// Every time this function is ran, store the current time and remove times from half a second ago
34+
let smoothing = 0.9;
35+
let calculatedFps = 1000 / (now - lastRender);
36+
if (typeof lastFps !== "number") lastFps = calculatedFps;
37+
// Calculate a smoothed FPS so that numbers aren't changing too fast.
38+
const fps = Math.round(lastFps * smoothing + calculatedFps * (1 - smoothing));
39+
lastRender = now;
3540

3641
// Show/Hide the element based on if there are any threads running
3742
if (runtime.threads.length === 0) {
@@ -40,10 +45,8 @@ export default async function ({ addon, console, msg }) {
4045
return;
4146
}
4247
if (!wasRunning) fpsCounterElement.classList.add("show");
48+
if (fps !== lastFps || !wasRunning) fpsCounterElement.innerText = msg("fpsCounter", { fps: (lastFps = fps) });
4349
wasRunning = true;
44-
45-
// Update element text
46-
if (fps !== lastFps) fpsCounterElement.innerText = msg("fpsCounter", { fps: (lastFps = fps) });
4750
};
4851

4952
while (true) {

0 commit comments

Comments
 (0)