All files / player-browser/src/session/play play-scene-session.ts

93.7% Statements 119/127
86.95% Branches 120/138
87.5% Functions 14/16
94.64% Lines 106/112

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                                                                                                                    54x     54x     54x     54x 54x     54x 54x 54x         24x 2x 2x 2x   24x 24x         10x 10x 10x               11x 11x       29x         1x       25x 25x   3x 3x   2x       2x 2x 2x     4x 4x     2x 2x 2x     2x 2x   2x 2x                   10x 10x 10x                                         54x       57x 54x 54x 2x 2x   2x       57x       57x 57x 57x 57x 57x 57x               28x 29x 29x 29x       57x   57x 57x 57x 57x 57x 11x         11x       11x         5x   46x 8x 8x                 8x 6x 6x 6x 6x   8x 8x 8x   8x 8x 4x 8x   57x 57x 57x 57x 57x 57x     57x 57x 57x 57x 57x 57x         57x                                                                                     37x 34x           37x                       60x 60x             63x 62x 56x 44x    
import { resolveConstantVisibility } from '@be-music/player-scene-model';
import { diffReplayOptions, resolveReplayOptionsAt, type ReplayOptionState } from '@be-music/player-engine/replay';
import {
  parseRankingScoreTarget,
  pickLiveDisplayPlayOptions,
  resolvePlayOptions,
  resolveScoreTarget,
  type RankingScoreTarget,
} from '@be-music/player-scene-model';
/**
 * The play session as a scene session (`SceneSession`, `session/session-scene.ts`): what `createPlayScene` hands its
 * `SessionScene` so the scene's ticker reads a {@link PlayFrame} off the play every frame and the view's intents reach
 * it. The play's own keys stay the play's (`play-input.ts` listens on the window), so they reach the play directly
 * rather than through the scene; the view's touch lanes reach it as `lane` intents.
 */
 
import type { CourseView, LibraryChart, PlayOptions, SystemSoundSet } from '@be-music/player-scene-model';
import { SILENT_AUDIO } from '@be-music/player-skin-sdk';
import type { AudioService } from '../../runtime/audio-service.ts';
import type { PlayDisposeOptions } from './play-options.ts';
import type { PlayFrame, PlayIntent, PlayStage, PlayViewEvent } from '../../view/types.ts';
import type { SceneSession, SessionKeyEvent } from '../session-scene.ts';
import { drainSharedEngineSignals } from './play-engine.ts';
import { handleTouchLaneIntent } from './play-input.ts';
import type { PlaySession } from './play-session.ts';
import type { GhostPaceScore, GhostPresentation } from './ghost/ghost.ts';
import { canSeekPlay } from './play-seek.ts';
import type { PlayMoment } from './play-session-theme.ts';
import { playViewEventFromMoment } from './play-view-events.ts';
import { changePlayView, updateReplayView } from './play-view-settings.ts';
 
/**
 * What a play's frames carry besides the play itself: the chart picked, its course stage and the play options; and the
 * audio service the view's own sounds play through as the session's (a beatoraja skin's Lua sounds), stopped as the
 * scene leaves the stage.
 */
export interface PlaySceneFacts {
  readonly chart: LibraryChart;
  readonly course?: CourseView;
  readonly playOptions: PlayOptions;
  readonly scoreTargets?: PlayFrame['scoreTargets'];
  /**
   * The EX score at a ranking target's place on the chart's ranking, or `undefined` when the chart has no ranking (or
   * no host fetches one). Asked once per target the play shows; the target is drawn from when it settles.
   */
  readonly rankingTarget?: (target: RankingScoreTarget) => Promise<number | undefined>;
  readonly playerName?: string;
  readonly audio?: Pick<AudioService, 'stopOwned' | 'playCue'>;
  readonly sounds?: SystemSoundSet;
  /**
   * Whether the view drawing the play now shows the play's ghost (`PlaySession.ghost`): a built-in family view does,
   * the LR2 and beatoraja ones have no second field to draw it in. Without it the ghost is not shown.
   */
  readonly showsGhost?: () => boolean;
}
 
/** A play session driven by a `SessionScene`. See the module comment. */
export class PlaySceneSession implements SceneSession<PlayFrame, PlayIntent> {
  public readonly kind = 'play' as const;
  public readonly play: PlaySession;
  /** How the play's audio ends when the scene is disposed. */
  public disposeOptions: PlayDisposeOptions = {};
  private readonly facts: PlaySceneFacts;
  private recordedOptions: ReplayOptionState | undefined;
  private pending: PlayViewEvent[] = [];
  /** The play options the frames carry: the ones the play started with, and its display options as changed since. */
  private playOptions: PlayOptions;
  private enteredAtMs = 0;
  private failureSoundPlayed = false;
 
  public constructor(play: PlaySession, facts: PlaySceneFacts) {
    this.play = play;
    this.facts = facts;
    this.playOptions = facts.playOptions;
  }
 
  /** A moment the play raised for its view (the session's theme `moment`), queued for the next frame. */
  public queueEvent(event: PlayMoment): void {
    if (event.kind === 'exit-close' && !this.failureSoundPlayed) {
      this.failureSoundPlayed = true;
      const sound = this.facts.sounds?.playStop;
      if (sound !== undefined) void this.facts.audio?.playCue(sound, { owner: this });
    }
    const mapped = playViewEventFromMoment(event);
    Eif (mapped !== undefined) this.pending.push(mapped);
  }
 
  /** The play is on the stage: its own input listens (the scene gave the play its host before the view attached). */
  public enter(nowMs: number): void {
    this.enteredAtMs = nowMs;
    const host = this.play.host;
    Eif (host !== undefined) this.play.attachInput(host);
  }
 
  /**
   * The play left the stage: its input stops, and so do the sounds the view played as the session's (a beatoraja
   * skin's loops); the engine and the chart's sound run on (a play that ended keeps its tail).
   */
  public exit(): void {
    this.play.detachInput();
    this.facts.audio?.stopOwned(this);
  }
 
  public dispose(): void {
    this.play.dispose(this.disposeOptions);
  }
 
  /** Keys reach the play through its own listeners (`play-input.ts`), not through the scene. */
  public handleKey(_event: SessionKeyEvent): boolean {
    return false;
  }
 
  public dispatch(intent: PlayIntent): void {
    const play = this.play;
    switch (intent.type) {
      case 'hi-speed':
        changePlayView(play, intent.command);
        return;
      case 'constant-visibility': {
        const value = resolveConstantVisibility({
          durationMs: intent.durationMs ?? play.options.noteDurationMs,
          fadeMs: intent.fadeMs ?? play.options.constantFadeMs,
        });
        play.options.noteDurationMs = value.durationMs;
        play.options.constantFadeMs = value.fadeMs;
        return;
      }
      case 'cover':
        changePlayView(play, intent.command);
        return;
      case 'display-options': {
        // Only the display options: what shapes the chart, the judgment or the record stays as the play started.
        const live = pickLiveDisplayPlayOptions(intent.values);
        Eif (live !== undefined) this.playOptions = { ...this.playOptions, ...live };
        return;
      }
      case 'pause':
        play.requestTogglePause();
        return;
      case 'quit':
        play.requestExit();
        return;
      case 'restart':
        play.requestRestart();
        return;
      case 'seek':
        void play.seek(intent.seconds);
        return;
      case 'lane':
        // A touch lane the view's fingers pressed or let go: the engine takes it as the keyboard's lane keys. A
        // ghost's lane takes nothing.
        Iif (play.ghost !== undefined && !play.laneChannels.includes(intent.channel)) return;
        handleTouchLaneIntent(play, intent.channel, intent.pressed, intent.atMs);
        return;
    }
  }
 
  /**
   * Advances the play to now — the engine's UI signals drained into the play state, the replay's view recorded or
   * replayed, the score readout eased — and returns what the view draws.
   */
  /** The host's score targets with the fixed target, kept while the target, the note count and the host's object stay. */
  private fixedScoreTargets:
    | {
        id: PlayOptions['scoreTarget'];
        rate: number;
        rankingEXScore: number | undefined;
        totalNotes: number;
        host: PlayFrame['scoreTargets'];
        resolved: PlayFrame['scoreTargets'];
      }
    | undefined;
 
  /** The ranking targets asked for so far, each with its score once the host's ranking gave one. */
  private readonly rankingScores = new Map<PlayOptions['scoreTarget'], number | undefined>();
 
  /** The score at a ranking target's place, asking the host the first time the play shows that target. */
  private rankingEXScore(id: PlayOptions['scoreTarget']): number | undefined {
    if (this.rankingScores.has(id)) return this.rankingScores.get(id);
    const target = parseRankingScoreTarget(id);
    if (target === undefined) return undefined;
    this.rankingScores.set(id, undefined);
    void this.facts.rankingTarget?.(target).then(
      (score) => {
        if (score !== undefined) this.rankingScores.set(id, score);
      },
      () => undefined,
    );
    return undefined;
  }
 
  private resolveHostScoreTargets(options: PlayOptions, totalNotes: number): PlayFrame['scoreTargets'] {
    const host = this.facts.scoreTargets;
    const id = options.scoreTarget;
    const rate = options.scoreTargetRate;
    const rankingEXScore = this.rankingEXScore(id);
    const kept = this.fixedScoreTargets;
    if (
      kept !== undefined &&
      kept.id === id &&
      kept.rate === rate &&
      kept.rankingEXScore === rankingEXScore &&
      kept.totalNotes === totalNotes &&
      kept.host === host
    )
      return kept.resolved;
    const resolved = resolveFixedScoreTargets(host, id, totalNotes, { rate, rankingEXScore });
    this.fixedScoreTargets = { id, rate, rankingEXScore, totalNotes, host, resolved };
    return resolved;
  }
 
  public frame(nowMs: number): PlayFrame {
    const play = this.play;
    // A paused play drains too: a seek moves it while it stays paused.
    Eif (!play.disposed) drainSharedEngineSignals(play);
    const seconds = play.currentSeconds();
    const replay = play.options.replay;
    let playOptions = this.playOptions;
    if (replay?.play.options !== undefined || replay?.play.optionChanges !== undefined) {
      const recorded = resolveReplayOptionsAt(
        replay.play.options,
        replay.play.optionChanges,
        Math.round(seconds * 1_000_000),
      );
      playOptions = resolvePlayOptions({
        ...playOptions,
        ...recorded,
      });
      if (
        playOptions.judgeTimingAutoAdjust !== 'OFF' &&
        typeof recorded.judgeTimingMs === 'number' &&
        Number.isSafeInteger(recorded.judgeTimingMs)
      ) {
        playOptions = { ...playOptions, judgeTimingMs: recorded.judgeTimingMs };
      }
    } else if (replay === undefined && play.sharedEngineInputSignals !== undefined) {
      const userHiSpeed = play.playState.view.hiSpeed.chartBase ?? play.playState.view.hiSpeed;
      const liveOptions: PlayOptions = {
        ...playOptions,
        hiSpeed: userHiSpeed.player,
        floatingHiSpeed: userHiSpeed.floating !== undefined,
        judgeTimingMs: play.options.judgeTimingMs ?? playOptions.judgeTimingMs,
        noteDurationMs: play.options.noteDurationMs ?? playOptions.noteDurationMs,
        constantFadeMs: play.options.constantFadeMs ?? playOptions.constantFadeMs,
        ...(userHiSpeed.normalLevel !== undefined ? { normalHiSpeedLevel: userHiSpeed.normalLevel } : {}),
      };
      for (const cover of play.playState.view.covers) {
        const heightKey = cover.side === '1P' ? 'lift1P' : 'lift2P';
        const onKey = cover.side === '1P' ? 'liftOn1P' : 'liftOn2P';
        liveOptions[heightKey] = cover.lift;
        liveOptions[onKey] = cover.liftOn ?? cover.lift > 0;
      }
      playOptions = liveOptions;
      const current: ReplayOptionState = { ...liveOptions };
      const change = diffReplayOptions(this.recordedOptions ?? { ...playOptions }, current);
      // Calibration is recorded synchronously by the engine; do not echo a stale rendered value back to it.
      Iif (change && (play.options.judgeTimingAutoAdjust ?? 'OFF') !== 'OFF') delete change.judgeTimingMs;
      if (change && Object.keys(change).length > 0)
        play.sharedEngineInputSignals.pushCommand({ kind: 'options', values: change });
      this.recordedOptions = current;
    }
    Eif (!play.paused && !play.disposed) updateReplayView(play, seconds);
    play.updateDisplayedScore();
    const events = this.pending;
    this.pending = [];
    const stage = resolvePlayStage(play);
    const bpm = play.displayBPM(seconds);
    // The ghost draws through the playfield the view reads, and only on a view that shows one; a ghost with no field of
    // its own (a pacemaker) keeps running on any view.
    const shows = this.facts.showsGhost?.() === true;
    const ghost = play.ghost;
    const running = ghost !== undefined && (shows || !ghost.drawsOnPlayfield) ? ghost : undefined;
    running?.update(seconds, play.playClock());
    const playfield = running !== undefined && shows ? running.present(play) : play;
    const scoreTargets = resolveFrameScoreTargets(
      this.resolveHostScoreTargets(playOptions, play.score.total),
      running,
      play.score,
    );
    return {
      clock: { nowMs, enteredAtMs: this.enteredAtMs },
      chart: play.chart ?? this.facts.chart,
      ...(this.facts.course !== undefined ? { course: this.facts.course } : {}),
      playOptions,
      ...(scoreTargets !== undefined ? { scoreTargets } : {}),
      ...(this.facts.playerName !== undefined ? { playerName: this.facts.playerName } : {}),
      state: play.playState,
      ...(playfield.secondPlayer !== undefined ? { state2P: playfield.secondPlayer.playState } : {}),
      stage,
      ...(stage === 'loading' ? { progress: this.play.loadProgress } : {}),
      seconds,
      chartText: play.engineFrame?.chartText,
      seekable: canSeekPlay(play),
      beat: play.currentBeat(seconds),
      ...(bpm !== undefined ? { bpm } : {}),
      autoPlay: play.options.autoPlay === true,
      replay: play.options.replay !== undefined,
      notes: { notes: play.notes, mines: play.mineNotes, invisible: play.invisibleNotes },
      heldLanes: play.pressedChannels,
      events,
      // Analysed only when a view reads it: only audio-reactive skins do, and the analysis (an FFT and the waveform,
      // every frame) is wasted on the rest and with effects off.
      get audio() {
        return play.audioAnalyzer?.sample(play.playClock()) ?? SILENT_AUDIO;
      },
      shown: play.shown,
      playfield,
    };
  }
}
 
/**
 * The host's score targets with the target the player picked (`PlayOptions.scoreTarget`) when the host names none: a
 * rank border, MAX, the next rank or a score rate (`rate`, in percent) for the play's note count, or a ranking
 * target once its score is known (`rankingEXScore`).
 */
export function resolveFixedScoreTargets(
  host: PlayFrame['scoreTargets'],
  scoreTarget: PlayOptions['scoreTarget'],
  totalNotes: number,
  extra: { readonly rate?: number; readonly rankingEXScore?: number | undefined } = {},
): PlayFrame['scoreTargets'] {
  if (host?.targetEXScore !== undefined) return host;
  const target = resolveScoreTarget(scoreTarget, {
    totalNotes,
    ...(extra.rate !== undefined ? { rate: extra.rate } : {}),
    ...(extra.rankingEXScore !== undefined ? { rankingEXScore: extra.rankingEXScore } : {}),
    ...(host?.bestEXScore !== undefined ? { bestEXScore: host.bestEXScore } : {}),
  });
  return target === undefined ? host : { ...host, targetEXScore: target.exScore, targetLabel: target.label };
}
 
/**
 * A frame's score targets: the host's (the best record's EX score), with a running ghost's pacemaker in place of the
 * target when it shows one. The host's object comes back as it is without one.
 */
export function resolveFrameScoreTargets(
  host: PlayFrame['scoreTargets'],
  ghost: Pick<GhostPresentation, 'scoreTarget'> | undefined,
  score: GhostPaceScore,
): PlayFrame['scoreTargets'] {
  const pacemaker = ghost?.scoreTarget?.(score);
  return pacemaker === undefined ? host : { ...host, ...pacemaker };
}
 
/** Where a play is: paused, ending (the lead-out and fade), loading its assets, in its intro, or playing. */
export function resolvePlayStage(
  play: Pick<PlaySession, 'paused' | 'exiting' | 'chartEnded' | 'assetsLoading' | 'isIntroPlaying'>,
): PlayStage {
  if (play.paused) return 'paused';
  if (play.exiting || play.chartEnded) return 'ending';
  if (play.assetsLoading) return 'loading';
  return play.isIntroPlaying() ? 'intro' : 'playing';
}