@@ -12,26 +12,31 @@ export default async function ({ addon, console, msg }) {
12
12
addon . tab . displayNoneWhileDisabled ( fpsCounterElement ) ;
13
13
addSmallStageClass ( ) ;
14
14
15
- const renderTimes = [ ] ;
16
- let lastFps = 0 ;
15
+ let lastRender ;
16
+ let lastFps ;
17
17
let wasRunning = false ;
18
18
19
19
const { renderer } = runtime ;
20
20
const _draw = renderer . draw ;
21
21
renderer . draw = function ( ) {
22
22
_draw . call ( this ) ;
23
23
24
- // Every time this function is ran, store the current time and remove times from half a second ago
25
24
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 ;
34
30
}
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 ;
35
40
36
41
// Show/Hide the element based on if there are any threads running
37
42
if ( runtime . threads . length === 0 ) {
@@ -40,10 +45,8 @@ export default async function ({ addon, console, msg }) {
40
45
return ;
41
46
}
42
47
if ( ! wasRunning ) fpsCounterElement . classList . add ( "show" ) ;
48
+ if ( fps !== lastFps || ! wasRunning ) fpsCounterElement . innerText = msg ( "fpsCounter" , { fps : ( lastFps = fps ) } ) ;
43
49
wasRunning = true ;
44
-
45
- // Update element text
46
- if ( fps !== lastFps ) fpsCounterElement . innerText = msg ( "fpsCounter" , { fps : ( lastFps = fps ) } ) ;
47
50
} ;
48
51
49
52
while ( true ) {
0 commit comments