Skip to content

Commit

Permalink
Reduce the amplitude of the frequency increase
Browse files Browse the repository at this point in the history
  • Loading branch information
qgh committed Feb 2, 2024
1 parent 6685e33 commit fd3f818
Showing 1 changed file with 31 additions and 12 deletions.
43 changes: 31 additions & 12 deletions pal/pacer/pacer-web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const FRAME_RESET_TIME = 2000;

export class Pacer {
private _stHandle = 0;
private _timeId = 0;
private _onTick: (() => void) | null = null;
private _targetFrameRate = 60;
private _frameTime = 0;
Expand Down Expand Up @@ -88,9 +89,6 @@ export class Pacer {
const recordStartTime = EDITOR || this._rAF === undefined || globalThis.__globalXR?.isWebXR;
const updateCallback = (): void => {
if (recordStartTime) this._startTime = performance.now();
if (this._isPlaying) {
this._stHandle = this._stTime(updateCallback);
}
if (this._onTick) {
this._onTick();
}
Expand All @@ -106,25 +104,46 @@ export class Pacer {
if (!this._isPlaying) return;
this._ctTime(this._stHandle);
this._stHandle = 0;
if (this._timeId) {
clearTimeout(this._timeId);
this._timeId = 0;
}
this._isPlaying = false;
this._frameCount = 0;
}

_handleRAF = (): void => {
const elapseTime = performance.now() - this._startTime;
if (!this._isPlaying) {
return;
}
const nowTime = performance.now();
const elapseTime = nowTime - this._startTime;
const elapseFrame = Math.floor(elapseTime / this._frameTime);
if (elapseFrame < this._frameCount) {
this._rAF.call(window, this._handleRAF);
} else {
this._frameCount++;
if (this._callback) {
this._callback();
const sleepMs = this._frameCount * this._frameTime - elapseTime;
if (sleepMs > 16) {
this._stHandle = this._rAF.call(window, this._handleRAF);
return;
} else if (sleepMs > 4) {
// Avoid timing to sleepMs because timing has accuracy issues.
this._timeId = setTimeout(this._handleRAF, sleepMs - 4);
return;
} else if (sleepMs > 1) {
this._timeId = setTimeout(this._handleRAF, 0);
return;
} else {
// Acceptance tolerance within 1ms.
}
}
if (performance.now() - this._startTime > FRAME_RESET_TIME) {
this._startTime = performance.now();
this._frameCount = 0;
this._frameCount++;
if (this._callback) {
this._callback();
}
if (nowTime - this._startTime > FRAME_RESET_TIME) {
this._startTime = nowTime;
this._frameCount = 1;
}
this._timeId = setTimeout(this._handleRAF, 0);
};

private _stTime (callback: () => void): number {
Expand Down

0 comments on commit fd3f818

Please sign in to comment.