All files / player-engine/src/replay view.ts

92.16% Statements 153/166
88.51% Branches 131/148
100% Functions 30/30
94.69% Lines 125/132

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366                                                                                                                              336x                               25x 25x 27x 18x 18x 18x 4x 4x 4x     25x                 4x 4x 6x 3x   4x         381x                       9x 9x 7x   7x 7x 7x   9x 5x 5x 5x 5x               9x                           11x 11x 6x 4x 4x   3x     336x     11x                         17x 17x 17x 8x 8x   17x       17x       17x 3x 3x   17x 11x 9x 13x 13x   9x 3x 3x     17x                   50x 50x 50x 50x 49x             50x       106x                                                     38x 38x 38x 38x   13x 9x 9x 6x 6x 6x     2x 2x 1x 1x           72x 72x 72x     336x     7x 7x 6x         10x 10x 7x 7x 6x   9x 2x 1x   8x 1x 1x   8x         8x 4x 4x 4x 4x 4x 1x   3x               6x         2x 2x 2x 2x 2x 2x 2x 2x 2x           3x 3x 3x 4x 4x 4x 4x 3x 3x 3x 2x      
import { expectFiniteNumber, expectRecord, ReplayParseError } from './parse.ts';
 
/**
 * What the player saw and how fast the play ran, apart from what was judged: the hi-speed, the lane covers (SUDDEN+,
 * HIDDEN+, LIFT) and the tempo, at the start and every change during the play. None of it changes a judgment (inputs
 * and notes are in chart time), so a re-simulation ignores it; a replay or a ghost reads it to show the play as it
 * looked, as far as its viewer asks ({@link ReplayPlaybackOptions}).
 */
 
/** One play side's lane cover, each part as a fraction (0 to 1) of the lane height; 0 = off. */
export interface ReplayLaneCover {
  side: '1P' | '2P';
  /** SUDDEN+: the cover over the top of the lanes. */
  sudden: number;
  /** HIDDEN+: the cover just above the judgement line. */
  hidden: number;
  /** LIFT: how far the judgement line is raised. */
  lift: number;
}
 
/** The view settings in force, or the ones that changed: every field is optional in a change. */
export interface ReplayViewState {
  /** The scroll speed multiplier the scene drew with (its own hi-speed scale, {@link hiSpeedScale}). */
  hiSpeed?: number;
  /**
   * The scale {@link hiSpeed} is on, named by the scene family that drew it (`be-music` for the built-in and LR2
   * scenes, `beatoraja`): the same hi-speed scrolls at another speed on another scale. Absent = the viewer's own.
   */
  hiSpeedScale?: string;
  /** The hi-speed fix the scene kept the scroll with: `OFF`, `MAXBPM`, `MINBPM`, `AVERAGE`, `CONSTANT` or `STARTBPM`. */
  hsFix?: string;
  /**
   * How long a note stays visible below SUDDEN+, in ms (the white number; × 0.6 is the green number), at the chart's main
   * BPM and without `#SCROLL` / `#SPEED`, so the speed compares across scenes and hi-speed scales.
   */
  visibleMs?: number;
  /** The lane covers per play side that has lanes. A change lists only the sides that changed. */
  covers?: ReplayLaneCover[];
}
 
/** A view change during the play, at a chart time (µs, the replay's clock). */
export interface ReplayViewChange extends ReplayViewState {
  timeUs: number;
}
 
/** A tempo change during the play (`PlayerOptions.speed`), at a chart time (µs). */
export interface ReplayTempoChange {
  timeUs: number;
  tempo: number;
}
 
/**
 * Which recorded settings a replay or ghost reproduces; the rest stay the viewer's own. Hosts offer these as options.
 * All on by default.
 */
export interface ReplayPlaybackOptions {
  tempo: boolean;
  hiSpeed: boolean;
  /** SUDDEN+ and HIDDEN+. */
  covers: boolean;
  lift: boolean;
}
 
export const DEFAULT_REPLAY_PLAYBACK_OPTIONS: Readonly<ReplayPlaybackOptions> = {
  tempo: true,
  hiSpeed: true,
  covers: true,
  lift: true,
};
 
/**
 * The view settings in force at `timeUs`: `initial` with every change at or before it applied in order (a cover change
 * replaces that side's cover).
 */
export function resolveReplayViewAt(
  initial: ReplayViewState | undefined,
  changes: readonly ReplayViewChange[] | undefined,
  timeUs: number,
): ReplayViewState {
  const state: ReplayViewState = cloneView(initial ?? {});
  for (const change of changes ?? []) {
    if (change.timeUs > timeUs) break;
    const { timeUs: _timeUs, covers, ...rest } = change;
    Object.assign(state, rest);
    if (covers !== undefined) {
      const merged = new Map((state.covers ?? []).map((cover) => [cover.side, cover]));
      for (const cover of covers) merged.set(cover.side, { ...cover });
      state.covers = [...merged.values()].sort((left, right) => left.side.localeCompare(right.side));
    }
  }
  return state;
}
 
/** The tempo in force at `timeUs`: `initial` (1 when absent), then the last change at or before it. */
export function resolveReplayTempoAt(
  initial: number | undefined,
  changes: readonly ReplayTempoChange[] | undefined,
  timeUs: number,
): number {
  let tempo = initial ?? 1;
  for (const change of changes ?? []) {
    if (change.timeUs > timeUs) break;
    tempo = change.tempo;
  }
  return tempo;
}
 
/** Whether a play ran at any tempo other than 1, at its start or after a change. */
export function playedAtAnotherTempo(play: { tempo?: number; tempoChanges?: readonly ReplayTempoChange[] }): boolean {
  return (play.tempo ?? 1) !== 1 || (play.tempoChanges ?? []).some((change) => change.tempo !== 1);
}
 
/**
 * The view a replay or ghost shows at `timeUs`: the recorded view for what `replay` reproduces, the viewer's own
 * (`own`) for the rest. The tempo is resolved apart ({@link resolveReplayTempoAt}).
 */
export function resolveReplayView(
  recorded: ReplayViewState,
  own: ReplayViewState,
  replay: Readonly<ReplayPlaybackOptions>,
): ReplayViewState {
  const view: ReplayViewState = cloneView(own);
  if (replay.hiSpeed) {
    Eif (recorded.hiSpeed !== undefined) view.hiSpeed = recorded.hiSpeed;
    // The recorded hi-speed is on the recorded scale; one recorded without a scale is taken to be on the viewer's.
    if (recorded.hiSpeedScale !== undefined) view.hiSpeedScale = recorded.hiSpeedScale;
    if (recorded.hsFix !== undefined) view.hsFix = recorded.hsFix;
    if (recorded.visibleMs !== undefined) view.visibleMs = recorded.visibleMs;
  }
  if ((replay.covers || replay.lift) && recorded.covers !== undefined) {
    const ownCovers = new Map((own.covers ?? []).map((cover) => [cover.side, cover]));
    view.covers = recorded.covers.map((cover) => {
      const mine = ownCovers.get(cover.side) ?? { side: cover.side, sudden: 0, hidden: 0, lift: 0 };
      return {
        side: cover.side,
        sudden: replay.covers ? cover.sudden : mine.sudden,
        hidden: replay.covers ? cover.hidden : mine.hidden,
        lift: replay.lift ? cover.lift : mine.lift,
      };
    });
  }
  return view;
}
 
/**
 * The hi-speed a scene on `scale` draws to show `view` (a {@link resolveReplayView} result): `view.hiSpeed` when it is
 * on the same scale (or names none), else the hi-speed that shows `view.visibleMs`, which `fromVisibleMs` works out
 * with the scene's own lane height and covers, else the recorded `view.hiSpeed` when nothing converts it. `undefined`
 * when the view has no speed at all.
 */
export function resolveReplayHiSpeed(
  view: ReplayViewState,
  scale: string,
  fromVisibleMs: (visibleMs: number) => number | undefined,
): number | undefined {
  const sameScale = view.hiSpeedScale === undefined || view.hiSpeedScale === scale;
  if (sameScale && view.hiSpeed !== undefined) return view.hiSpeed;
  if (view.visibleMs !== undefined && view.visibleMs > 0) {
    const converted = fromVisibleMs(view.visibleMs);
    if (converted !== undefined && Number.isFinite(converted) && converted > 0) return converted;
  }
  return sameScale ? undefined : view.hiSpeed;
}
 
const COVER_EPSILON = 1e-6;
 
function sameCover(left: ReplayLaneCover, right: ReplayLaneCover): boolean {
  return (
    Math.abs(left.sudden - right.sudden) < COVER_EPSILON &&
    Math.abs(left.hidden - right.hidden) < COVER_EPSILON &&
    Math.abs(left.lift - right.lift) < COVER_EPSILON
  );
}
 
/**
 * What changed from `previous` to `next`, as a {@link ReplayViewChange} without its time: each scalar field whose value
 * differs (a field `next` leaves out is not a change), and the full cover of each side whose cover differs. `undefined`
 * when nothing did.
 */
export function diffReplayView(previous: ReplayViewState, next: ReplayViewState): ReplayViewState | undefined {
  const change: ReplayViewState = {};
  let changed = false;
  if (next.hiSpeed !== undefined && next.hiSpeed !== previous.hiSpeed) {
    change.hiSpeed = next.hiSpeed;
    changed = true;
  }
  Iif (next.hiSpeedScale !== undefined && next.hiSpeedScale !== previous.hiSpeedScale) {
    change.hiSpeedScale = next.hiSpeedScale;
    changed = true;
  }
  Iif (next.hsFix !== undefined && next.hsFix !== previous.hsFix) {
    change.hsFix = next.hsFix;
    changed = true;
  }
  if (next.visibleMs !== undefined && next.visibleMs !== previous.visibleMs) {
    change.visibleMs = next.visibleMs;
    changed = true;
  }
  if (next.covers !== undefined) {
    const before = new Map((previous.covers ?? []).map((cover) => [cover.side, cover]));
    const covers = next.covers.filter((cover) => {
      const old = before.get(cover.side);
      return old === undefined || !sameCover(old, cover);
    });
    if (covers.length > 0) {
      change.covers = covers.map((cover) => ({ ...cover }));
      changed = true;
    }
  }
  return changed ? change : undefined;
}
 
/**
 * `view` at the precision a replay records it, so float noise (`0.09999999999999999` for a cover of 0.1 computed as
 * `ratio × (1 - lift)`) neither lands in the log nor counts as a change: the hi-speed on the 1/1000 grid hosts step
 * it on, the visible time to whole ms, and each cover part to 4 decimals (1/10000 of the lane height). Scenes round
 * the view they record with this.
 */
export function roundReplayView(view: ReplayViewState): ReplayViewState {
  const rounded: ReplayViewState = { ...view };
  if (view.hiSpeed !== undefined) rounded.hiSpeed = roundTo(view.hiSpeed, 1000);
  if (view.visibleMs !== undefined) rounded.visibleMs = Math.round(view.visibleMs);
  if (view.covers !== undefined) {
    rounded.covers = view.covers.map((cover) => ({
      side: cover.side,
      sudden: roundTo(cover.sudden, 10_000),
      hidden: roundTo(cover.hidden, 10_000),
      lift: roundTo(cover.lift, 10_000),
    }));
  }
  return rounded;
}
 
function roundTo(value: number, steps: number): number {
  return Math.round(value * steps) / steps;
}
 
/** Folds a live view into the view changes a replay records: {@link createReplayViewCoalescer}. */
export interface ReplayViewCoalescer {
  /**
   * Takes the view in force at `nowMs` (any monotonic clock, e.g. the host's frame time) and returns the change to
   * record now, if any: everything that changed since the last change it returned, at most one every `minIntervalMs`.
   * A change held back is returned on a later call once the interval has passed, merged with what changed meanwhile.
   */
  observe(view: ReplayViewState, nowMs: number): ReplayViewState | undefined;
  /**
   * Returns what changed since the last change it returned, whatever the interval: called once as the play ends, so a
   * change still held back is not lost.
   */
  flush(view: ReplayViewState): ReplayViewState | undefined;
}
 
/**
 * Coalesces a scene's live view (sampled each frame) into the changes its replay records, so a wheel spin or a held
 * key records a handful of changes instead of one per frame: `initial` is the view recorded at the start
 * (`play.view`), and a change is returned at most every `minIntervalMs` (default 100 ms) — the first one at once.
 */
export function createReplayViewCoalescer(
  initial: ReplayViewState,
  options: { minIntervalMs?: number } = {},
): ReplayViewCoalescer {
  const minIntervalMs = options.minIntervalMs ?? 100;
  let recorded = cloneView(initial);
  let lastAtMs = -Infinity;
  return {
    observe: (view, nowMs) => {
      if (nowMs - lastAtMs < minIntervalMs) return undefined;
      const change = diffReplayView(recorded, view);
      if (change === undefined) return undefined;
      recorded = resolveReplayViewAt(recorded, [{ timeUs: 0, ...change }], 0);
      lastAtMs = nowMs;
      return change;
    },
    flush: (view) => {
      const change = diffReplayView(recorded, view);
      if (change === undefined) return undefined;
      recorded = resolveReplayViewAt(recorded, [{ timeUs: 0, ...change }], 0);
      return change;
    },
  };
}
 
function cloneView(view: ReplayViewState): ReplayViewState {
  const copy: ReplayViewState = { ...view };
  if (view.covers !== undefined) copy.covers = view.covers.map((cover) => ({ ...cover }));
  return copy;
}
 
const SIDES: ReadonlySet<string> = new Set(['1P', '2P']);
 
function parseFraction(value: unknown, path: string): number {
  const fraction = expectFiniteNumber(value, path);
  if (fraction < 0 || fraction > 1) throw new ReplayParseError(`${path}: expected a fraction from 0 to 1`);
  return fraction;
}
 
/** Reads a recorded view state (`play.view`, or a change without its `timeUs`). */
export function parseReplayViewState(raw: Record<string, unknown>, path: string): ReplayViewState {
  const view: ReplayViewState = {};
  if (raw.hiSpeed !== undefined) {
    const hiSpeed = expectFiniteNumber(raw.hiSpeed, `${path}.hiSpeed`);
    if (!(hiSpeed > 0)) throw new ReplayParseError(`${path}.hiSpeed: expected a positive number`);
    view.hiSpeed = hiSpeed;
  }
  if (raw.hiSpeedScale !== undefined) {
    if (typeof raw.hiSpeedScale !== 'string') throw new ReplayParseError(`${path}.hiSpeedScale: expected a string`);
    view.hiSpeedScale = raw.hiSpeedScale;
  }
  if (raw.hsFix !== undefined) {
    Iif (typeof raw.hsFix !== 'string') throw new ReplayParseError(`${path}.hsFix: expected a string`);
    view.hsFix = raw.hsFix;
  }
  Iif (raw.visibleMs !== undefined) {
    const visibleMs = expectFiniteNumber(raw.visibleMs, `${path}.visibleMs`);
    if (visibleMs < 0) throw new ReplayParseError(`${path}.visibleMs: expected a non-negative number`);
    view.visibleMs = visibleMs;
  }
  if (raw.covers !== undefined) {
    Iif (!Array.isArray(raw.covers)) throw new ReplayParseError(`${path}.covers: expected an array`);
    view.covers = raw.covers.map((entry, index) => {
      const coverPath = `${path}.covers[${index}]`;
      const cover = expectRecord(entry, coverPath);
      if (typeof cover.side !== 'string' || !SIDES.has(cover.side)) {
        throw new ReplayParseError(`${coverPath}.side: expected '1P' | '2P'`);
      }
      return {
        side: cover.side as '1P' | '2P',
        sudden: parseFraction(cover.sudden, `${coverPath}.sudden`),
        hidden: parseFraction(cover.hidden, `${coverPath}.hidden`),
        lift: parseFraction(cover.lift, `${coverPath}.lift`),
      };
    });
  }
  return view;
}
 
/** Reads `play.viewChanges`: changes in chart-time order. */
export function parseReplayViewChanges(raw: unknown, path: string): ReplayViewChange[] {
  Iif (!Array.isArray(raw)) throw new ReplayParseError(`${path}: expected an array`);
  let last = -Infinity;
  return raw.map((entry, index) => {
    const changePath = `${path}[${index}]`;
    const record = expectRecord(entry, changePath);
    const timeUs = expectFiniteNumber(record.timeUs, `${changePath}.timeUs`);
    Iif (timeUs < last) throw new ReplayParseError(`${changePath}.timeUs: expected changes in time order`);
    last = timeUs;
    return { timeUs, ...parseReplayViewState(record, changePath) };
  });
}
 
/** Reads `play.tempoChanges`: positive tempos in chart-time order. */
export function parseReplayTempoChanges(raw: unknown, path: string): ReplayTempoChange[] {
  Iif (!Array.isArray(raw)) throw new ReplayParseError(`${path}: expected an array`);
  let last = -Infinity;
  return raw.map((entry, index) => {
    const changePath = `${path}[${index}]`;
    const record = expectRecord(entry, changePath);
    const timeUs = expectFiniteNumber(record.timeUs, `${changePath}.timeUs`);
    if (timeUs < last) throw new ReplayParseError(`${changePath}.timeUs: expected changes in time order`);
    last = timeUs;
    const tempo = expectFiniteNumber(record.tempo, `${changePath}.tempo`);
    if (!(tempo > 0)) throw new ReplayParseError(`${changePath}.tempo: expected a positive number`);
    return { timeUs, tempo };
  });
}