Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/player/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"save-file": "^2.3.1",
"semver": "^7.7.4",
"source-map-js": "^1.2.1",
"stats.js": "^1.0.0",
"stats.js": "^0.17.0",
"uid": "^2.0.2",
"vite-plugin-svgr": "catalog:",
"vite-plugin-wasm": "catalog:"
Expand Down
19 changes: 11 additions & 8 deletions packages/player/src/components/StatsComponent/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect, useRef } from "react";
import * as Stats from "stats.js";
import { statsHooks } from "../../utils/merge-raf";

export const StatsComponent = () => {
const containerRef = useRef<HTMLDivElement | null>(null);
Expand All @@ -11,8 +12,12 @@ export const StatsComponent = () => {
return;
}

// 创建 stats.js 的性能指标监控实例
const statsInstance = new StatsConstructor();

// 设置显示面板指标(0表示帧率FPS,1表示单帧耗时MS)
statsInstance.showPanel(0);

const domNode = statsInstance.dom || statsInstance.domElement;

if (!(domNode instanceof Node)) {
Expand All @@ -32,16 +37,14 @@ export const StatsComponent = () => {
(domNode as HTMLElement).style.left = "0";
(domNode as HTMLElement).style.top = "0";

let animationFrameId: number;
const update = () => {
statsInstance.begin();
statsInstance.end();
animationFrameId = requestAnimationFrame(update);
};
animationFrameId = requestAnimationFrame(update);
// 绑定生命周期钩子,借助全局动画调度循环记录时间
statsHooks.begin = () => statsInstance.begin();
statsHooks.end = () => statsInstance.end();

return () => {
cancelAnimationFrame(animationFrameId);
// 组件卸载时重置钩子函数,避免引起空引用或内存泄漏
statsHooks.begin = () => {};
statsHooks.end = () => {};
if (container.contains(domNode)) {
container.removeChild(domNode);
}
Expand Down
12 changes: 12 additions & 0 deletions packages/player/src/utils/merge-raf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,17 @@ let manualMode = false;
let manualRafStepTime = 0;
let animateState = newState();

/**
* 全局性能指标钩子,用于绑定性能监控面板的计时起点与终点
*/
export const statsHooks = {
begin: () => {},
end: () => {},
};

function runRafs(time: number) {
// 记录本帧开始执行渲染和动画逻辑的时间
statsHooks.begin();
const curState = animateState;
animateState = newState();
for (const raf of curState.rafMap.values()) {
Expand All @@ -34,6 +44,8 @@ function runRafs(time: number) {
console.error(e);
}
}
// 记录本帧执行结束的时间并进行渲染耗时统计
statsHooks.end();
}

window.manualRafEnable = () => {
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.