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

98.38% Statements 61/62
86.25% Branches 69/80
100% Functions 8/8
100% Lines 54/54

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                                                                                          46x                                                               13x 13x 13x 11x 5x   7x               5x   5x     5x               6x                             10x 8x 5x 5x     2x                                                                                                                           16x 1x 1x   15x 15x 15x 2x 2x 2x     2x 2x   1x 1x   1x 1x   2x 2x 2x 2x   2x   13x 13x 13x 2x 2x   11x 11x       11x 11x 9x 9x 8x                       25x 1x   24x 24x                       25x 25x                                                                                                
/**
 * The ending of a play (`PlaySession`): how it ends ({@link resolvePlayEnding}), the theme's exit timeline (the fade-out
 * of a normal exit, or the stop of a failed play) before the host takes over, and the result the play hands the host.
 *
 * The exit timeline and the result read and write the scene's state through {@link PlayEndingContext}; the play
 * session passes itself.
 */
 
import type { SecondPlayerState } from './play-state.ts';
import type { TimingResolver } from '@be-music/chart-model';
import type { PlayerSummary } from '@be-music/player-engine';
import type { BeMusicReplay } from '@be-music/player-engine/replay';
import type { ScoreSummary } from '@be-music/player-engine/ruleset';
import type { PlayerGaugeSummary, PlayerUIFramePayload } from '@be-music/player-engine/signals';
import {
  gaugePercent,
  playResultFromPlayState,
  type LibraryChart,
  type PlayResult,
  type PlayState,
} from '@be-music/player-scene-model';
import type { AudioBusHandle } from '../../runtime/audio-bus.ts';
import { chartToElapsedSeconds } from '../../runtime/play-tempo.ts';
import type { PlaySessionTheme } from './play-session-theme.ts';
import { resolvePostChartResultDelayMs } from './result-delay.ts';
 
/**
 * How a play ends, shared by every gameplay family (built-in, LR2 and beatoraja), so they time their outro the same way:
 *
 * - A play that reaches its end holds the scene for a lead-out after the last note (`resolvePostChartResultDelayMs`,
 *   in chart time), then runs the theme / skin fade-out (LR2 timer 2, beatoraja `TIMER_FADEOUT`), then shows the
 *   result. Escape and F5 run the same fade-out. Escape once every note is judged ({@link isEveryNoteJudged}) ends the
 *   play this way too, skipping what is left of the lead-out, rather than giving it up.
 * - A play cut short by its gauge emptying (a course stage, a HARD gauge ending on failure) stops at once, as LR2 and
 *   beatoraja do: no lead-out and no fade-out timer; the failure moment (LR2 timer 3, beatoraja `TIMER_FAILED`) starts,
 *   the sound fades out over the close (Be-Music's choice: LR2 and beatoraja cut it), and the result shows after the
 *   skin's close time (LR2 `#CLOSE`, beatoraja `close`). A theme
 *   without a close time (the built-in skins) holds for {@link FAILED_CLOSE_MS} instead, fading its picture. A gauge
 *   that emptied but played on to the end ends normally.
 */
 
/**
 * How long a failed play holds before its result shows on a theme with no close time of its own (Be-Music's choice:
 * LR2 and beatoraja wait for the skin's close time, 1500 ms on beatoraja's default skins).
 */
export const FAILED_CLOSE_MS = 1500;
 
/** A note's span, as the lead-out reads it. */
export type PlayEndingNote = { beat: number; endBeat?: number; seconds: number; endSeconds?: number };
 
export interface PlayEndingInput {
  /** The engine's final summary, when the play has ended (`undefined` while a held play is still open). */
  summary: Pick<PlayerSummary, 'gauge'> | undefined;
  /** The chart's judged notes. */
  notes: ReadonlyArray<PlayEndingNote>;
  timing: Pick<TimingResolver, 'beatToSeconds'> | undefined;
  /** Where the play is, in chart seconds. */
  currentSeconds: number;
  /** The play tempo: the lead-out is chart time, so at another tempo it takes 1 / tempo as long. */
  tempo: number;
  /** Optional family timing: chart seconds to music end, then a wall-clock finish margin. */
  musicEndDelayMs?: number;
  finishMarginMs?: number;
  /** AUTO's last chart event; manual play defaults to its last judged note/tail. */
  chartEndSeconds?: number;
}
 
export interface PlayEnding {
  /** The play was cut short by its gauge emptying, with notes still to come: it stops instead of fading out. */
  failed: boolean;
  /** Wall-clock ms to hold the scene before the exit starts. */
  leadOutMs: number;
  musicEndAtSeconds?: number;
  finishMarginMs?: number;
}
 
export function resolvePlayEnding(input: PlayEndingInput): PlayEnding {
  const { notes, currentSeconds } = input;
  const failed = input.summary?.gauge?.failedMidPlay === true && notes.some((note) => note.seconds > currentSeconds);
  if (failed) return { failed, leadOutMs: 0 };
  if (input.musicEndDelayMs !== undefined && Number.isFinite(input.musicEndDelayMs) && input.musicEndDelayMs >= 0) {
    const lastNote = notes.reduce(
      (last, note) =>
        Math.max(
          last,
          note.endSeconds ??
            (note.endBeat !== undefined ? input.timing?.beatToSeconds(note.endBeat) : undefined) ??
            note.seconds,
        ),
      0,
    );
    const musicEndAtSeconds = (input.chartEndSeconds ?? lastNote) + input.musicEndDelayMs / 1000;
    const finishMarginMs =
      input.finishMarginMs !== undefined && Number.isFinite(input.finishMarginMs) && input.finishMarginMs > 0
        ? input.finishMarginMs
        : 0;
    return {
      failed,
      musicEndAtSeconds,
      finishMarginMs,
      leadOutMs:
        chartToElapsedSeconds(Math.max(0, (musicEndAtSeconds - currentSeconds) * 1000), input.tempo) + finishMarginMs,
    };
  }
  return {
    failed,
    leadOutMs: chartToElapsedSeconds(resolvePostChartResultDelayMs(notes, input.timing, currentSeconds), input.tempo),
  };
}
 
/**
 * Whether the engine's frame has judged every note of the play: its scored judgments (`judgedNoteCount`, which leaves
 * out empty POORs and mine hits) reach the chart's judgment count, and so do a two-player play's 2P judgments. ESC
 * from then on finishes the play rather than giving it up, as beatoraja does (`BMSPlayer.stopPlay` moves to
 * `STATE_FINISHED` once the judged notes reach the chart's note count). A chart with nothing to judge never counts.
 */
export function isEveryNoteJudged(
  frame: Pick<PlayerUIFramePayload, 'summary' | 'summary2P' | 'judgedNoteCount'> | undefined,
): boolean {
  if (frame === undefined || frame.judgedNoteCount === undefined) return false;
  if (frame.summary.total <= 0 || frame.judgedNoteCount < frame.summary.total) return false;
  const second = frame.summary2P;
  if (second === undefined) return true;
  // The 2P summary carries no judged count of its own: its POORs may include mine hits, so this can run ahead of the
  // last 2P note on a chart with mines.
  return second.perfect + second.great + second.good + second.bad + second.poor >= second.total;
}
 
/** The scene's members the ending reads and writes: the play session's members of these names. */
export interface PlayEndingContext {
  readonly theme: PlaySessionTheme;
  readonly disposed: boolean;
  exiting: boolean;
  exitFadeOutMs: number;
  exitFadeStartedAt: number | undefined;
  exitFadeOutHandle: number | undefined;
  exitCloseHandle: number | undefined;
  readonly audioBus: AudioBusHandle | undefined;
  readonly chart: LibraryChart | undefined;
  readonly score: ScoreSummary;
  /** The engine's gauge as of its last frame: its clear border and the TOTAL it runs on. */
  readonly gaugeState: PlayerGaugeSummary;
  playState: PlayState;
  secondPlayer?: SecondPlayerState;
  readonly fastCount: number;
  readonly slowCount: number;
  readonly replay: BeMusicReplay | undefined;
  /** The replay the play plays back, when it is one. */
  readonly options: { readonly replay?: BeMusicReplay | undefined; readonly autoPlay?: boolean | undefined };
  readonly practice?: boolean;
  playClock(): number;
  currentSeconds(): number;
  resolveChartDurationSeconds(): number;
  resolveJudgeRuleset(): string;
  /** Whether `score.poor` folds the empty POORs in (LR2). */
  resolveEmptyPoorCountsInPoorDisplay(): boolean;
}
 
export interface ExitSequenceOptions {
  /** The play failed: it stops ({@link beginExitSequence}) instead of fading out. */
  failed?: boolean;
  /** Whether a normal exit's sound fades with the picture (default `true`; the chart's end lets its keysounds ring). */
  fadeAudio?: boolean;
}
 
/**
 * Drives the theme's scene-exit timeline before handing control back to the host. Idempotent: re-entry while one is in
 * flight calls `callback` at once (a frantic second ESC press does not double-fire the host callback twice over).
 *
 * - **A normal exit** (the chart's end, Escape, F5) raises `exit-fade-out` (LR2 timer 2, beatoraja `TIMER_FADEOUT`)
 *   and fades the picture (and, unless `fadeAudio` is `false`, the sound) over the theme's fade-out (LR2 `#FADEOUT`,
 *   beatoraja `fadeout`), then calls
 *   `callback`. It never starts the failure timer: LR2 starts timer 3 only on a failure (OpenLR2 `LR2f.cpp`
 *   L12686-L12697, L12915-L12925; the chart's end and ESC start timer 2 alone, L12976-L12978, L7732-L7741). A theme
 *   with no fade-out calls `callback` at once.
 * - **A failed play** (`failed`) stops at once, as LR2 (`procPhase = 3`) and beatoraja (`STATE_FAILED`) do: it raises
 *   `exit-close` (LR2 timer 3, beatoraja `TIMER_FAILED`), fades the sound out over the close (the speakers, after the
 *   recording tap; LR2 and beatoraja cut it at once, which jars against the skin's closing animation), and calls
 *   `callback` after the theme's close time (LR2 `#CLOSE`, beatoraja `close`; OpenLR2 L7748-L7752,
 *   beatoraja `BMSPlayer` L693-L742) with no fade-out timer. A theme with no close time holds for
 *   {@link FAILED_CLOSE_MS}, fading its picture over it.
 */
export function beginExitSequence(
  ctx: PlayEndingContext,
  callback: () => void,
  options: ExitSequenceOptions = {},
): void {
  if (ctx.exiting || ctx.disposed) {
    callback();
    return;
  }
  ctx.exiting = true;
  const at = ctx.playClock();
  if (options.failed === true) {
    const closeMs = ctx.theme.timing().closeMs;
    const holdMs = closeMs > 0 ? closeMs : FAILED_CLOSE_MS;
    ctx.theme.moment({ kind: 'exit-close', at });
    // LR2 stops every keysound and beatoraja every sound at once; here the sound fades with the close, as the picture
    // does. The post-tap gain keeps a recording's mix whole.
    ctx.audioBus?.fadeOutAudibleTo(0, holdMs);
    if (closeMs <= 0) {
      // No close time of its own: the picture fades over the hold (the built-in skins' look).
      ctx.exitFadeOutMs = holdMs;
      ctx.exitFadeStartedAt = at;
    } else {
      ctx.exitFadeOutMs = 0;
      ctx.exitFadeStartedAt = undefined;
    }
    ctx.exitCloseHandle = window.setTimeout(() => {
      ctx.exitCloseHandle = undefined;
      Iif (ctx.disposed) return;
      callback();
    }, holdMs);
    return;
  }
  const fadeOutMs = ctx.theme.timing().fadeOutMs;
  ctx.exitFadeOutMs = fadeOutMs;
  if (fadeOutMs <= 0) {
    callback();
    return;
  }
  ctx.exitFadeStartedAt = at;
  ctx.theme.moment({ kind: 'exit-fade-out', at });
  // Drive the audio bus's post-tap fade in lock-step with `applyExitFadeAlpha`'s screen-alpha animation. The fade
  // node sits AFTER the recording tap, so a recording in flight keeps capturing the unattenuated mix; only the
  // speakers go quiet.
  if (options.fadeAudio !== false) ctx.audioBus?.fadeOutAudibleTo(0, fadeOutMs);
  ctx.exitFadeOutHandle = window.setTimeout(() => {
    ctx.exitFadeOutHandle = undefined;
    if (ctx.disposed) return;
    callback();
  }, fadeOutMs);
}
 
/**
 * The play as a result (`PlaySession.getResultData`): read off the play state (`playResultFromPlayState`), with the
 * graphs ending at the playhead so they reach the right edge even when the last judgment came well before the chart's
 * end, the clear lamp by the one clear-lamp rule, and the scores as the readouts show them (under LR2 with the POOR
 * judgments alone beside them, `judgedPoor`, so a record's BP counts each empty POOR once); with the gauge's clear
 * border (in percent) and TOTAL, which a beatoraja result skin shows.
 */
export function getResultData(ctx: PlayEndingContext): PlayResult | undefined {
  if (!ctx.chart) {
    return undefined;
  }
  const gauge = ctx.gaugeState;
  const result = playResultFromPlayState(ctx.playState, {
    chart: ctx.chart,
    ...(ctx.practice === true ? { practice: true } : {}),
    score: ctx.score,
    seconds: ctx.currentSeconds(),
    judgeRuleset: ctx.resolveJudgeRuleset(),
    fast: ctx.fastCount,
    slow: ctx.slowCount,
    ...(ctx.replay !== undefined ? { replay: ctx.replay } : {}),
    ...(ctx.options.replay !== undefined ? { fromReplay: true } : {}),
    ...(ctx.options.autoPlay === true ? { autoPlay: true } : {}),
  });
  const second = ctx.secondPlayer;
  return {
    ...result,
    ...(second !== undefined
      ? {
          secondPlayer: playResultFromPlayState(second.playState, {
            chart: ctx.chart,
            score: second.score,
            seconds: ctx.currentSeconds(),
            judgeRuleset: ctx.resolveJudgeRuleset(),
            ...(ctx.options.autoPlay === true ? { autoPlay: true } : {}),
          }),
        }
      : {}),
    ...(ctx.playState.courseCombo !== undefined
      ? {
          stageOutcome: {
            ruleset: ctx.resolveJudgeRuleset(),
            judge: {
              pgreat: ctx.score.perfect,
              great: ctx.score.great,
              good: ctx.score.good,
              bad: ctx.score.bad,
              poor: ctx.score.poor - (ctx.resolveEmptyPoorCountsInPoorDisplay() ? ctx.score.emptyPoor : 0),
              emptyPoor: ctx.score.emptyPoor,
            },
            fast: ctx.fastCount,
            slow: ctx.slowCount,
            exScore: ctx.score.exScore,
            noteCount: ctx.score.total,
            maxCombo: ctx.playState.maxCombo,
            gauge: {
              type: gauge.type ?? 'GROOVE',
              ...(gauge.values ? { values: { ...gauge.values } } : {}),
              final: ctx.playState.gauge,
              cleared: ctx.playState.cleared,
              ...(gauge.failedMidPlay ? { failedMidPlay: true } : {}),
            },
            course: { combo: ctx.playState.courseCombo.combo, maxCombo: ctx.playState.courseCombo.maxCombo },
          },
        }
      : {}),
    // Folded, `score.poor` is the engine's `poor + emptyPoor` (`resolveDisplayedPoor`).
    ...(ctx.resolveEmptyPoorCountsInPoorDisplay() ? { judgedPoor: ctx.score.poor - ctx.score.emptyPoor } : {}),
    ...(gauge.max > 0 ? { gaugeBorder: gaugePercent({ current: gauge.clearThreshold, max: gauge.max }) } : {}),
    // The TOTAL the engine reports; the placeholder gauge before its first frame has none.
    ...(gauge.effectiveTotal > 0 ? { gaugeTotal: gauge.effectiveTotal } : {}),
  };
}