Skip to content

Commit

Permalink
Added autoCorrectTimeOffset (closes #11)
Browse files Browse the repository at this point in the history
  • Loading branch information
yandeu committed Nov 29, 2021
1 parent 779ad95 commit 70fb3a8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
21 changes: 19 additions & 2 deletions src/snapshot-interpolation.ts
Expand Up @@ -3,6 +3,10 @@ import { Vault } from './vault'
import { lerp, degreeLerp, radianLerp } from './lerp'
import { quatSlerp } from './slerp'

interface Config {
autoCorrectTimeOffset?: boolean
}

/** A Snapshot Interpolation library. */
export class SnapshotInterpolation {
/** Access the vault. */
Expand All @@ -12,8 +16,11 @@ export class SnapshotInterpolation {
/** The current server time based on the current snapshot interpolation. */
public serverTime = 0

constructor(serverFPS?: number) {
public config: Config

constructor(serverFPS?: number | null, config: Config = {}) {
if (serverFPS) this._interpolationBuffer = (1000 / serverFPS) * 3
this.config = { autoCorrectTimeOffset: true, ...config }
}

public get interpolationBuffer() {
Expand Down Expand Up @@ -82,11 +89,21 @@ export class SnapshotInterpolation {
}

private addSnapshot(snapshot: Snapshot): void {
const timeNow = SnapshotInterpolation.Now()
const timeSnapshot = snapshot.time

if (this._timeOffset === -1) {
// the time offset between server and client is calculated,
// by subtracting the current client date from the server time of the
// first snapshot
this._timeOffset = SnapshotInterpolation.Now() - snapshot.time
this._timeOffset = timeNow - timeSnapshot
}

// correct time offset
if (this.config?.autoCorrectTimeOffset === true) {
const timeOffset = timeNow - timeSnapshot
const timeDifference = Math.abs(this._timeOffset - timeOffset)
if (timeDifference > 50) this._timeOffset = timeOffset
}

this.vault.add(snapshot)
Expand Down
2 changes: 1 addition & 1 deletion test/compression.test.js
Expand Up @@ -18,7 +18,7 @@ const delay = () => {
})
}

const SI = new SnapshotInterpolation()
const SI = new SnapshotInterpolation(null, { autoCorrectTimeOffset: false }) // false, for testing
SI.interpolationBuffer.set(30) // this is only that low for testing

const playerSchema = BufferSchema.schema('player', {
Expand Down

0 comments on commit 70fb3a8

Please sign in to comment.