soiz1 commited on
Commit
a1f16fd
·
verified ·
1 Parent(s): 2807575

Create userscript.js

Browse files
Files changed (1) hide show
  1. src/addons/addons/fps/userscript.js +59 -0
src/addons/addons/fps/userscript.js ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import addSmallStageClass from "../../libraries/common/cs/small-stage.js";
2
+
3
+ export default async function ({ addon, console, msg }) {
4
+ const { vm } = addon.tab.traps;
5
+ const { runtime } = vm;
6
+ if (!vm.editingTarget) {
7
+ await new Promise((resolve) => runtime.once("PROJECT_LOADED", resolve));
8
+ }
9
+
10
+ let fpsCounterElement = document.createElement("span");
11
+ fpsCounterElement.className = "fps-counter";
12
+ addon.tab.displayNoneWhileDisabled(fpsCounterElement);
13
+ addSmallStageClass();
14
+
15
+ let lastRender;
16
+ let lastFps;
17
+ let wasRunning = false;
18
+
19
+ const { renderer } = runtime;
20
+ const _draw = renderer.draw;
21
+ renderer.draw = function () {
22
+ _draw.call(this);
23
+
24
+ const now = runtime.currentMSecs;
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;
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;
40
+
41
+ // Show/Hide the element based on if there are any threads running
42
+ if (runtime.threads.length === 0) {
43
+ if (wasRunning) fpsCounterElement.classList.remove("show");
44
+ wasRunning = false;
45
+ return;
46
+ }
47
+ if (!wasRunning) fpsCounterElement.classList.add("show");
48
+ if (fps !== lastFps || !wasRunning) fpsCounterElement.innerText = msg("fpsCounter", { fps: (lastFps = fps) });
49
+ wasRunning = true;
50
+ };
51
+
52
+ while (true) {
53
+ await addon.tab.waitForElement('[class*="controls_controls-container"]', {
54
+ markAsSeen: true,
55
+ reduxEvents: ["scratch-gui/mode/SET_PLAYER", "fontsLoaded/SET_FONTS_LOADED", "scratch-gui/locales/SELECT_LOCALE"],
56
+ });
57
+ addon.tab.appendToSharedSpace({ space: "afterStopButton", element: fpsCounterElement, order: 3 });
58
+ }
59
+ }