All files / app-play/src course-flow.ts

96.24% Statements 128/133
94.2% Branches 130/138
100% Functions 38/38
100% Lines 103/103

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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456                                                                                                                        53x 51x 13x   38x 36x 30x                                                                     3x 3x 3x 1x 1x 1x 1x 1x   2x   1x 1x 1x 1x 1x                           5x 5x                 13x 2x                                                 68x     133x 68x                           51x 51x 50x 50x 15x 15x               16x 16x   6x 4x 6x   10x 6x         6x 6x 4x               14x 14x 12x               11x 11x                               6x 6x 15x   6x 6x 17x 36x 14x 14x 14x 27x     6x 15x 15x           5x 5x                         11x 11x     24x           7x         11x       24x 24x         24x           8x 8x         23x               26x 26x         6x 3x         3x 3x 3x                   4x 4x 4x 3x 3x 3x                           15x 15x 12x                           17x 17x 15x       22x                                         16x 10x               7x 4x                       5x                             26x 23x 3x    
import { playerText } from './player-copy.ts';
import {
  CourseRun,
  createRandomMixCourse,
  givenUpCourseStageShowsResult,
  type CourseConstraint,
  type CourseDefinition,
  type CourseRunStagePlan,
  type RandomCourseDrawFailure,
} from '@be-music/player-engine/course';
import {
  listCourseReplayStageCharts,
  matchesCourseReplayStageChart,
  planCourseReplayPlayback,
  resolveCoursePlayedRuleset,
  type BeMusicCourseReplay,
  type BeMusicReplay,
  type CourseReplayStageChart,
  type CourseReplayStagePlayback,
  type ReplayCourseResult,
} from '@be-music/player-engine/replay';
import {
  resolveCourseView,
  resolveLibraryChartKeyMode,
  type CourseView,
  type LibraryChart,
  type LibraryCourse,
  type PlayResult,
} from '@be-music/player-scene-model';
import { createDrawnRandomMixEntry } from '@be-music/player-browser/collection';
import type { RandomMixDrawnStage } from './random-mix-draw.ts';
import type { RandomMixRun } from './random-mix-save.ts';
import { EMPTY_COURSE_STAGE_HISTORY, type CourseStageHistory } from './course-result.ts';
import type { NonstopPlayFailure } from './nonstop-course.ts';
import { courseRunKeepsRecord, courseRunRecordPlay, type RecordPlay } from '@be-music/player-engine/records';
import { rulesetRecordKey } from './chart-best-records.ts';
import { resolveDanRankUpdate } from './dan-ranks.ts';
import type { DanRank } from '@be-music/player-engine/records';
 
/**
 * The decisions the player's course flow takes, kept apart from the scenes that act on them so they can be tested: what
 * a course bar starts, what a stage's end leads to, and which runs keep a record.
 */
 
/** What picking a course bar starts. */
export type CourseStartPlan =
  /** A NEW COURSE bar: start making a course of its folder's kind. */
  | { action: 'make'; kind: LibraryCourse['definition']['kind'] }
  /** A RANDOM MIX bar: draw a course of its folder's kind, keep it, then play it. */
  | { action: 'random-mix'; kind: 'expert' | 'nonstop' }
  /** A course with a stage missing from the collection: nothing starts. */
  | { action: 'unplayable' }
  /** A random course: draw its stages first, then plan the drawn course. */
  | { action: 'draw' }
  /** A NONSTOP course: stitch its stages and play them as one chart. */
  | { action: 'nonstop' }
  /** Any other course: play its stages one by one. */
  | { action: 'stages' };
 
export function planCourseStart(entry: LibraryCourse): CourseStartPlan {
  if (entry.newCourse === true) return { action: 'make', kind: entry.definition.kind };
  if (entry.randomMix === true && entry.definition.kind !== 'grade') {
    return { action: 'random-mix', kind: entry.definition.kind };
  }
  if (!entry.playable) return { action: 'unplayable' };
  if (entry.random !== undefined) return { action: 'draw' };
  return entry.definition.kind === 'nonstop' ? { action: 'nonstop' } : { action: 'stages' };
}
 
/** An EXPERT / GRADE course being played: the course bar it started from and its run. */
export interface ActiveCourse {
  course: LibraryCourse;
  run: CourseRun<LibraryChart, CourseStageHistory>;
  /** Set when the run plays a course replay back: the log, and the stage replays it plays up to where it stopped. */
  replay?: ActiveCourseReplay;
  /** Set on an endless RANDOM MIX: its stages are drawn as the run reaches them. */
  endless?: EndlessRandomMix;
  /**
   * Set on a RANDOM MIX run not kept as a course (an endless one): no bar lists it, so its run keeps no course record
   * and saves into no replay slot.
   */
  unkept?: true;
  /** Set on a RANDOM MIX run: what it was started with, for the save dialog once it is over. */
  randomMix?: RandomMixRun;
}
 
/** The draw an endless RANDOM MIX takes its stages from, and the stages drawn so far. */
export interface EndlessRandomMix {
  readonly next: () => Promise<RandomMixDrawnStage | undefined>;
  /** The stages in the run, in order. */
  readonly stages: RandomMixDrawnStage[];
  /** The stage after the last one in the run, drawn ahead so the skins can show what comes next. */
  lookahead?: Promise<RandomMixDrawnStage | undefined>;
}
 
/**
 * Before an endless RANDOM MIX's next stage: once the run has played every stage it holds, the stage drawn ahead joins
 * it (the course growing by that stage), and the stage after it is drawn ahead. Returns `false` when no chart is left
 * to draw, so the run is over. A run with stages left, or not endless, is left as it is.
 */
export async function prepareEndlessStage(active: ActiveCourse): Promise<boolean> {
  const endless = active.endless;
  Iif (endless === undefined || active.run.finished) return true;
  if (active.run.stagesPlayed < active.run.stageCount) return true;
  const drawn = await (endless.lookahead ?? endless.next());
  endless.lookahead = undefined;
  Iif (drawn === undefined) return false;
  endless.stages.push(drawn);
  const definition = createRandomMixCourse(
    'expert',
    endless.stages.map((stage) => stage.stage),
  )!;
  active.run.appendStage(definition, drawn.chart);
  endless.lookahead = endless.next();
  const next = await endless.lookahead;
  active.course = endlessRandomMixEntry(active.course.id, definition, endless.stages, next);
  return true;
}
 
/**
 * The course bar of an endless RANDOM MIX: the stages in the run and, after them, the one drawn ahead (`next`), which
 * the skins list as the next stage, so no stage of an endless run reads as the final one.
 */
export function endlessRandomMixEntry(
  id: string,
  definition: CourseDefinition,
  stages: readonly RandomMixDrawnStage[],
  next?: RandomMixDrawnStage,
): LibraryCourse {
  // Not one of the player's saved courses: no course-maker edits.
  const { editable: _editable, ...entry } = createDrawnRandomMixEntry(definition, stages);
  return {
    ...entry,
    id,
    ...(next !== undefined ? { stages: [...entry.stages, { title: next.chart.title, chart: next.chart }] } : {}),
  };
}
 
/** An endless run's course bar as it was played: the stages in its run, none drawn ahead. */
export function settleEndlessCourse(active: ActiveCourse): void {
  if (active.endless === undefined) return;
  active.course = endlessRandomMixEntry(active.course.id, active.run.definition, active.endless.stages);
}
 
/** A course replay being played back as a course run. */
export interface ActiveCourseReplay {
  log: BeMusicCourseReplay;
  stages: CourseReplayStagePlayback[];
}
 
/** A stage of a running course as the player plays it: the run's plan, with the course as the skins show it there. */
export interface CourseStagePlay extends CourseRunStagePlan<LibraryChart> {
  courseInfo: CourseView;
  /** The stage's recorded replay, when the run plays a course replay back: it plays with the state it carried in. */
  replay?: BeMusicReplay;
}
 
/**
 * Starts a run of a course whose stages are all in the collection (`CourseRun` refuses one with a stage missing), or,
 * with `replay`, a run that plays that course replay back ({@link planCourseReplayPlayback}).
 */
export function startCourseRun(
  course: LibraryCourse,
  replay?: BeMusicCourseReplay,
  options: { endless?: EndlessRandomMix; unkept?: boolean } = {},
): ActiveCourse {
  const { endless } = options;
  // An endless run holds the stages drawn so far; the one drawn ahead is only listed on the bar.
  const stages =
    endless !== undefined ? endless.stages.map((stage) => stage.chart) : course.stages.map((stage) => stage.chart);
  return {
    course,
    run: new CourseRun(course.definition, stages, endless !== undefined ? { endless: true } : {}),
    ...(endless !== undefined ? { endless } : {}),
    ...(options.unkept === true ? { unkept: true as const } : {}),
    ...(replay !== undefined ? { replay: { log: replay, stages: planCourseReplayPlayback(replay) } } : {}),
  };
}
 
/**
 * The next stage of a running course, with the course as the skins show it there; `undefined` once the run is over. A
 * course replay's run is over once its recorded stages have played, and each stage plays its own replay.
 */
export function nextCourseStagePlay(active: ActiveCourse): CourseStagePlay | undefined {
  const plan = active.run.nextStage();
  if (plan === undefined) return undefined;
  const courseInfo = resolveCourseView(active.course, plan.index);
  if (active.replay === undefined) return { ...plan, courseInfo };
  const recorded = active.replay.stages[plan.index];
  return recorded === undefined ? undefined : { ...plan, courseInfo, replay: recorded.replay };
}
 
/**
 * Records a finished stage on the run. A course replay's stage records its recorded replay (the replay played back
 * records none), and a stage the recorded run gave up is recorded as given up, so the run goes on or ends as it did.
 */
export function recordCourseStage(active: ActiveCourse, result: PlayResult): void {
  const recorded = active.replay?.stages[active.run.stagesPlayed];
  if (recorded === undefined) {
    // A stage given up with ESC whose result shows comes here too: it is recorded as given up.
    if (result.replay?.play.aborted === true) active.run.giveUp(result.replay, result);
    else active.run.recordStage(result.replay, result);
    return;
  }
  if (recorded.replay.play.aborted === true) active.run.giveUp(recorded.replay, result);
  else active.run.recordStage(recorded.replay, result);
}
 
/** Whether the run goes on after this stage ({@link recordCourseStage} leaving it unfinished). */
export function courseGoesOnAfter(active: ActiveCourse, result: PlayResult): boolean {
  const recorded = active.replay?.stages[active.run.stagesPlayed];
  if (recorded === undefined) return active.run.goesOnAfter(result.replay, result.stageOutcome);
  return recorded.end === 'next' && active.run.goesOnAfter(recorded.replay, result.stageOutcome);
}
 
/**
 * Whether a course stage given up with ESC shows its result, as FAILED, before the run goes on or ends: the course
 * gauge's rule (`givenUpCourseStageShowsResult`), read from the stage's replay or, without one, its live outcome.
 */
export function givenUpStageShowsResult(replay: BeMusicReplay | undefined, result: PlayResult | undefined): boolean {
  const native = replay?.results?.native ?? result?.stageOutcome;
  if (native === undefined) return false;
  return givenUpCourseStageShowsResult(replay?.play.judgeRuleset ?? native.ruleset, native);
}
 
/**
 * Whether the stage just played is one the recorded run gave up and that shows no stage result, as a stage given up
 * live shows none under that gauge ({@link givenUpStageShowsResult}): the run goes on or ends there as it did.
 */
export function courseReplayStageGivenUp(active: ActiveCourse | undefined, result?: PlayResult): boolean {
  const recorded = active?.replay?.stages[active.run.stagesPlayed]?.replay;
  return recorded?.play.aborted === true && !givenUpStageShowsResult(recorded, result);
}
 
/**
 * A course replay's stages matched against the library: each stage's chart, or `undefined` when no loaded chart is the
 * stage's. `keysOf` gives a loaded chart's hashes and, when a stage is named by its fingerprint alone, its chart
 * fingerprint.
 */
export async function matchCourseReplayCharts(
  courseLog: Pick<BeMusicCourseReplay, 'stages'>,
  charts: readonly LibraryChart[],
  keysOf: (
    chartEntry: LibraryChart,
    needFingerprint: boolean,
  ) => Promise<{ sha256?: string; md5?: string; chartFingerprint?: string } | undefined>,
): Promise<Array<{ stage: CourseReplayStageChart; chart?: LibraryChart }>> {
  const stages = listCourseReplayStageCharts(courseLog);
  const needFingerprint = stages.some(
    (stage) => stage.sha256 === undefined && stage.md5 === undefined && stage.chartFingerprint !== undefined,
  );
  const found = new Map<number, LibraryChart>();
  for (const chartEntry of charts) {
    if (found.size === stages.length) break;
    const pending = stages.filter((stage) => !found.has(stage.index));
    const keys = await keysOf(chartEntry, needFingerprint);
    Iif (keys === undefined) continue;
    for (const stage of pending) {
      if (matchesCourseReplayStageChart(stage, keys)) found.set(stage.index, chartEntry);
    }
  }
  return stages.map((stage) => {
    const chart = found.get(stage.index);
    return chart !== undefined ? { stage, chart } : { stage };
  });
}
 
/** How the missing-chart dialog names a stage: its title, else the hash it was looked for by. */
export function describeCourseReplayStage(stage: CourseReplayStageChart): string {
  const name = stage.title ?? stage.sha256 ?? stage.md5 ?? stage.chartFingerprint ?? 'unknown chart';
  return `Stage ${stage.index + 1}: ${name}${stage.title !== undefined && stage.artist !== undefined ? ` / ${stage.artist}` : ''}`;
}
 
/**
 * The course a course replay was played on, rebuilt from the log and its stages' charts as found in the library: its
 * name, kind, constraints and trophies as recorded, a NONSTOP run's connections, and each stage by its hashes. No course
 * file stands behind it, so it reads as a beatoraja course (no LR2 GRADE resets: the stage replays carry their setup).
 * `charts` lists each stage's chart by stage index; a course with one missing is not playable.
 */
export function courseFromReplay(
  courseLog: BeMusicCourseReplay,
  charts: ReadonlyArray<LibraryChart | undefined>,
): LibraryCourse {
  const stages = listCourseReplayStageCharts(courseLog);
  const definition: CourseDefinition = {
    name: courseLog.course.name,
    kind: courseLog.course.kind,
    stages: stages.map((stage) => ({
      ...(stage.sha256 !== undefined ? { sha256: stage.sha256 } : {}),
      ...(stage.md5 !== undefined ? { md5: stage.md5 } : {}),
      ...(charts[stage.index]?.title !== undefined ? { title: charts[stage.index]!.title } : {}),
    })),
    constraints: courseLog.course.constraints as CourseConstraint[],
    trophies: courseLog.course.trophies.map((trophy) => ({ ...trophy })),
    release: courseLog.course.release !== false,
    ...(courseLog.nonstop !== undefined ? { connections: [...courseLog.nonstop.connections] } : {}),
    source: { format: 'beatoraja-json' },
  };
  return {
    id: `replay:${courseLog.course.name}`,
    definition,
    stages: stages.map((stage) => {
      const chart = charts[stage.index];
      return {
        title: chart?.title ?? stage.title ?? `Stage ${stage.index + 1}`,
        ...(chart !== undefined ? { chart } : {}),
      };
    }),
    playable: charts.length === stages.length && charts.every((chart) => chart !== undefined),
  };
}
 
/** The course as the skins show it at the stage last played (none before the first one). */
export function activeCourseInfo(active: ActiveCourse): CourseView {
  const played = active.run.stagesPlayed;
  return resolveCourseView(active.course, played > 0 ? played - 1 : undefined);
}
 
/** The graphs of every stage played, in order: a stage given up, or played without graphs, has empty ones. */
export function courseStageHistories(active: ActiveCourse): CourseStageHistory[] {
  return active.run.stageExtras.map((history) => history ?? EMPTY_COURSE_STAGE_HISTORY);
}
 
/**
 * The song the decide screen shows before a course's first stage. It names the selected bar, the course, as LR2's
 * splash does; the first stage's chart supplies the rest, without the stage's own subtitle, artist and genre.
 */
export function courseDecideSong(course: LibraryCourse, first: LibraryChart): LibraryChart {
  const { subtitle: _subtitle, artist: _artist, genre: _genre, ...stage } = first;
  return { ...stage, title: course.definition.name };
}
 
/** The status line for a course that cannot start because some of its stages are not in the collection. */
export function describeUnplayableCourse(course: LibraryCourse): string {
  const missing = course.stages.filter((stage) => stage.chart === undefined).length;
  return playerText().course.stageMissing(course.definition.name, missing);
}
 
/** The status line for a random course whose stages could not be drawn. */
export function describeRandomCourseDrawFailure(name: string, failure: RandomCourseDrawFailure): string {
  const copy = playerText().course;
  const stage = failure.stage + 1;
  return failure.reason === 'no-candidates'
    ? copy.randomNoChart(name, stage)
    : copy.randomBadFilter(name, stage, failure.error ?? '');
}
 
/** The status line for a NONSTOP course that could not be stitched. */
export function describeNonstopPrepareFailure(
  name: string,
  failure: { reason: NonstopPlayFailure; stage?: number },
): string {
  const copy = playerText().course;
  const stage = failure.stage !== undefined ? copy.stageNote(failure.stage + 1) : '';
  if (failure.reason === 'generic-layout-mismatch') return copy.nonstopLayout(name, stage);
  Iif (failure.reason === 'lrx-mixed') return copy.nonstopLRXMixed(name, stage);
  Iif (failure.reason === 'lrx-layout-mismatch') return copy.nonstopLRXLayout(name, stage);
  return copy.nonstopStitch(name, failure.reason, stage);
}
 
/**
 * The record a course run leaves under the course's `key`, kept under the judge ruleset the run was played on
 * (`resolveCoursePlayedRuleset`), or `undefined` when the run keeps none: an auto-played run, one at another tempo,
 * which is practice (and the Leaderboard refuses it as `tempo`), and one whose stages were judged under different
 * rulesets.
 */
export function resolveCourseBestRecordUpdate(
  courseLog: Pick<BeMusicCourseReplay, 'stages' | 'nonstop'>,
  result: ReplayCourseResult,
  key: string,
): { key: string; play: RecordPlay } | undefined {
  const ruleset = resolveCoursePlayedRuleset(courseLog);
  if (ruleset === undefined || !courseRunKeepsRecord(courseLog)) return undefined;
  return { key: rulesetRecordKey(ruleset, key), play: courseRunRecordPlay(result) };
}
 
/**
 * The dan rank a course run certifies and the key it is kept under (`resolveDanRankUpdate`), or `undefined`: only a run
 * that keeps a best record ({@link resolveCourseBestRecordUpdate}) can certify one, under the judge ruleset it was played
 * on, in the key mode the course names or its stages' charts share. Existing records are never read back into ranks: a
 * rank comes from runs played from now on.
 */
export function resolveCourseDanRankUpdate(
  course: Pick<LibraryCourse, 'definition' | 'stages'>,
  courseLog: Pick<BeMusicCourseReplay, 'stages' | 'nonstop'>,
  result: Pick<ReplayCourseResult, 'lamp'>,
): { key: string; rank: DanRank } | undefined {
  const ruleset = resolveCoursePlayedRuleset(courseLog);
  if (ruleset === undefined || !courseRunKeepsRecord(courseLog)) return undefined;
  return resolveDanRankUpdate(
    {
      definition: course.definition,
      stageKeyModes: course.stages.map((stage) =>
        stage.chart !== undefined ? resolveLibraryChartKeyMode(stage.chart) : undefined,
      ),
      lamp: result.lamp,
    },
    ruleset,
  );
}
 
/** What a play is, for the gameplay exits below. */
export interface CoursePlayKind {
  /** A stage of a running EXPERT / GRADE course. */
  courseStage: boolean;
  /** A NONSTOP course's stitched play. */
  nonstop: boolean;
}
 
/**
 * Where ESC leads: a running course is given up and ends as a failed run (its course result shows), a NONSTOP run shows
 * its result as it stands, and a single chart goes back to the select screen.
 */
export function resolveGameplayExit(play: CoursePlayKind): 'give-up-course' | 'nonstop-result' | 'select' {
  if (play.courseStage) return 'give-up-course';
  return play.nonstop ? 'nonstop-result' : 'select';
}
 
/**
 * Where F5 (restart) leads: a NONSTOP course is stitched and played again, as LR2 allows quick retry there; in a course
 * stage it gives the course up, since quick retry is off there; a single chart plays again.
 */
export function resolveGameplayRestart(play: CoursePlayKind): 'restitch' | 'abandon-course' | 'replay' {
  if (play.nonstop) return 'restitch';
  return play.courseStage ? 'abandon-course' : 'replay';
}
 
/**
 * The overrides a single chart plays again with (F5): the play's own AUTO and replay, not the Options dialog's. Without
 * them an AUTO play started from a skin's AUTO button would start again as a manual play, and a replay as a live play
 * that keeps a record.
 */
export function playAgainOverrides<L>(play: { autoPlay: boolean; replay?: L | undefined }): {
  autoPlay: boolean;
  replay?: L;
} {
  return { autoPlay: play.autoPlay, ...(play.replay !== undefined ? { replay: play.replay } : {}) };
}
 
/**
 * What R on the result does: a NONSTOP run is stitched and played again; a single chart plays again when the last
 * play started is this chart's; a course stage or a course result offers no retry, as LR2 and beatoraja disable quick
 * retry there.
 */
export function resolveResultRetry<T>(options: {
  /** Whether the result offers quick retry at all (`resolveResultPresentation`). */
  quickRetry: boolean;
  nonstopRetry?: () => void;
  chartId: string;
  lastPlay?: { chartId: string; play: T };
}): { kind: 'nonstop'; retry: () => void } | { kind: 'replay'; play: T } | undefined {
  if (options.nonstopRetry !== undefined) return { kind: 'nonstop', retry: options.nonstopRetry };
  if (!options.quickRetry || options.lastPlay?.chartId !== options.chartId) return undefined;
  return { kind: 'replay', play: options.lastPlay.play };
}