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

94.73% Statements 198/209
86.66% Branches 130/150
88.88% Functions 24/27
96.35% Lines 185/192

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 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599                                                                                                                                                                                                                                                                                                                                                                                                              33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x 33x                 31x 31x   31x 1x 1x 1x   30x 1x   1x 1x   29x 12x 12x   17x 17x 17x   17x 5x 10x           5x     5x 1x 1x   4x 4x 4x   16x 1x 1x   15x   15x 31x       15x       9x 1x       3x 2x 2x 2x                             12x 12x 12x           3x   2x   2x       12x   11x 11x 11x 11x 11x 11x 10x 10x                 10x 10x 10x 10x   10x           10x     19x         10x 10x   14x     10x 1x 1x 1x   9x 9x   9x 10x 10x 10x 10x 2x 2x 2x 2x   7x 1x   10x   7x     10x       10x 10x       5x 2x                     2x 2x 1x               8x 8x 4x 4x 4x 4x 3x 3x                 4x 4x 4x 4x 4x 1x 1x 1x   3x     3x           24x   24x       24x 24x 24x 1x 1x   23x 24x 24x   24x 6x         6x   17x                     16x 14x 16x               14x 14x 1x 1x     13x 13x   13x   13x 14x         14x     14x         13x   2x   13x   2x 2x 2x 11x 8x 8x   8x   8x         8x   8x   13x 13x   13x     2x   4x   2x           2x               2x 1x 1x       12x 12x                            
// The course route: a course bar started on the select screen (a NEW COURSE bar starting the course maker, a random
// course or a RANDOM MIX drawn first, a NONSTOP course handed to `nonstop.ts`), an EXPERT / GRADE course's decide screen, each of its
// stages in turn, and its course result. The run it acts on is the course run service's (`services/courses.ts`); the
// screens are the app's.
 
import {
  createCourseChartRecord,
  createDrawnRandomMixEntry,
  createRandomMixCandidate,
  createRandomMixEntry,
  drawBrowserRandomCourse,
  resolveRandomMixBPM,
  type CourseMaker,
} from '@be-music/player-browser/collection';
import {
  createRandomMixCourse,
  filterRandomMixCandidates,
  hasRandomMixFirstStage,
  isRandomMixKept,
  listRandomMixKeyModes,
  resolveRandomMixCount,
  type RandomMixConditions,
} from '@be-music/player-engine/course';
import { RandomMixDraw, type RandomMixPoolChart } from '../../random-mix-draw.ts';
import type { RandomMixDialogRequest, RandomMixDialogResult } from '../../ui/random-mix-dialog.ts';
import {
  finishRandomMix,
  saveFinishedRandomMix,
  type FinishedRandomMix,
  type RandomMixRun,
  type RandomMixSaveRequest,
} from '../../random-mix-save.ts';
import { playerText } from '../../player-copy.ts';
import type {
  BeMusicCourseReplay,
  BeMusicReplay,
  ReplayCourseResult,
  ReplayRecorderInfo,
} from '@be-music/player-engine/replay';
import {
  resolveCourseView,
  type BrowseSnapshot,
  type CourseView,
  type LibraryChart,
  type LibraryCourse,
  type PlayResult,
} from '@be-music/player-scene-model';
import {
  courseDecideSong,
  courseStageHistories,
  describeRandomCourseDrawFailure,
  endlessRandomMixEntry,
  prepareEndlessStage,
  settleEndlessCourse,
  describeUnplayableCourse,
  nextCourseStagePlay,
  planCourseStart,
  resolveCourseBestRecordUpdate,
  resolveCourseDanRankUpdate,
  type CourseStagePlay,
  type EndlessRandomMix,
} from '../../course-flow.ts';
import { buildCourseResultData, courseBestRecordKey, joinCourseStageHistories } from '../../course-result.ts';
import { pickActiveFamilyForScene } from '../../family-dispatch.ts';
import type { LeaderboardPanel } from '../../leaderboard-ui.ts';
import type { CourseRunService } from '../../services/courses.ts';
import type { LibraryService } from '../../services/library.ts';
import type { ReplayAutoSave } from '../../services/replays.ts';
import type { RecordsService } from '../../services/records.ts';
import type { ResultReplaySlots } from '../../services/replay-slot-service.ts';
import type { ResultRoute } from './result.ts';
import type { FamilyKits } from '../family-kits.ts';
 
/** A course run's replay and native result, as its course result screen reports them. */
export interface CourseResultLog {
  log: BeMusicCourseReplay;
  native: ReplayCourseResult;
}
 
export interface CourseRouteDeps {
  /** The course run in progress. */
  readonly courses: CourseRunService;
  /** The library: the charts a random course draws its stages from. */
  readonly library: Pick<LibraryService, 'collection' | 'prepareDrawnCourse'>;
  /** The chart hashes a random course's stage filters match, and the course's best record. */
  readonly records: Pick<
    RecordsService,
    'resolveChartHashes' | 'peekChartBestRecord' | 'recordCourseResult' | 'recordDanRank'
  >;
  /**
   * The course maker, which a NEW COURSE bar starts and which keeps a RANDOM MIX's conditions, LR2 settings and last
   * draw.
   */
  readonly courseMaker: {
    readonly maker: Pick<
      CourseMaker,
      | 'start'
      | 'keepRandomMix'
      | 'randomMixConditions'
      | 'setRandomMixConditions'
      | 'randomMixSettings'
      | 'setRandomMixSettings'
      | 'defaultConnection'
      | 'setDefaultConnection'
      | 'saveRandomMix'
    >;
  };
  /** Opens the RANDOM MIX dialog: what it held when it closed and whether OK confirmed it. */
  readonly promptRandomMix: (request: RandomMixDialogRequest) => Promise<RandomMixDialogResult | undefined>;
  /**
   * Opens the RANDOM MIX save dialog once a run is over: the name to save its course under, or `undefined` when the
   * player does not save it.
   */
  readonly promptRandomMixSave: (request: RandomMixSaveRequest) => Promise<string | undefined>;
  /** The clock a RANDOM MIX run's end is read from (the name the save dialog offers). Default `new Date()`. */
  readonly now?: () => Date;
  /** The source of chance a RANDOM MIX draws with. Default `Math.random`. */
  readonly random?: () => number;
  /** The course replay's auto-save, by the setting latched at the last stage's start. */
  readonly replayAutoSave: Pick<ReplayAutoSave, 'saveCourse'>;
  /** Ranks the course run as one. */
  readonly leaderboard: Pick<LeaderboardPanel, 'maybeSubmitCourse'>;
  /** The family the course result is drawn by. */
  readonly familyKits: Pick<FamilyKits, 'familyDispatchState'>;
  /** This app as the recorder of its replays (`recorder` in the course replay). */
  readonly replayRecorder: Omit<ReplayRecorderInfo, 'engine'>;
  /** Where the select screen is: its position on the stage or off it, else the one last kept. */
  readonly selectNavigation: () => BrowseSnapshot | undefined;
  readonly setStatus: (text: string) => void;
  /** Lists the stages a decided course is missing from the collection, with where to download them. */
  readonly showMissingCourseStages: (course: LibraryCourse) => void;
  /** Starts a NONSTOP course (`NonstopRoute`), with its decide screen when the course bar starts it. */
  readonly startNonstopCourse: (course: LibraryCourse, options: { decide?: boolean }) => Promise<void>;
  readonly showSelect: () => Promise<void>;
  /** Shows the decide screen for `song`, which leads to `then.start` instead of playing `song`. */
  readonly showDecide: (
    chartEntry: LibraryChart,
    overrides: { autoPlay?: boolean },
    then: { start: () => Promise<void>; cancel?: () => void; shown?: () => void },
  ) => Promise<void>;
  /** Plays a course stage, with the course's AUTO when it was started with one, or its recorded replay. */
  readonly playChart: (
    chartEntry: LibraryChart,
    overrides: { courseStage: CourseStagePlay; autoPlay?: boolean; replay?: BeMusicReplay },
  ) => Promise<void>;
  /** The course run's replay slots (`ResultRoute.courseReplaySlots`). */
  readonly courseReplaySlots: ResultRoute['courseReplaySlots'];
  /** Shows the course result on the LR2 or built-in result screen. */
  readonly showResult: (
    data: PlayResult,
    mode: { course: CourseView; courseLog?: CourseResultLog; replaySlots?: ResultReplaySlots },
  ) => Promise<void>;
  /**
   * Shows the course result on the beatoraja theme's course-result (or result) skin. Resolves `false` when the theme has
   * neither or it failed to load.
   */
  readonly showBeatorajaResult: (
    data: PlayResult,
    options: {
      run: 'course';
      course: { info: CourseView; result?: CourseResultLog };
      replaySlots?: ResultReplaySlots;
    },
  ) => Promise<boolean>;
  /** Re-enables the options a play latched, once its result shows. */
  readonly unlockReplayOptions: () => void;
}
 
/** A course from its course bar to its course result. */
export class CourseRoute {
  private readonly courses: CourseRouteDeps['courses'];
  private readonly library: CourseRouteDeps['library'];
  private readonly records: CourseRouteDeps['records'];
  private readonly courseMaker: CourseRouteDeps['courseMaker'];
  private readonly promptRandomMix: CourseRouteDeps['promptRandomMix'];
  private readonly promptRandomMixSave: CourseRouteDeps['promptRandomMixSave'];
  private readonly now: () => Date;
  /** The NONSTOP RANDOM MIX being played: its course bar, which its result names, and what it was started with. */
  private nonstopRandomMix: { course: LibraryCourse; run: RandomMixRun } | undefined;
  /** A RANDOM MIX run that is over, its save dialog not yet shown: it opens once the select screen is back. */
  private finishedRandomMix: FinishedRandomMix | undefined;
  private readonly random: () => number;
  private readonly replayAutoSave: CourseRouteDeps['replayAutoSave'];
  private readonly leaderboard: CourseRouteDeps['leaderboard'];
  private readonly familyKits: CourseRouteDeps['familyKits'];
  private readonly replayRecorder: CourseRouteDeps['replayRecorder'];
  private readonly selectNavigation: CourseRouteDeps['selectNavigation'];
  private readonly setStatus: CourseRouteDeps['setStatus'];
  private readonly showMissingCourseStages: CourseRouteDeps['showMissingCourseStages'];
  private readonly startNonstopCourse: CourseRouteDeps['startNonstopCourse'];
  private readonly showSelect: CourseRouteDeps['showSelect'];
  private readonly showDecide: CourseRouteDeps['showDecide'];
  private readonly playChart: CourseRouteDeps['playChart'];
  private readonly showResult: CourseRouteDeps['showResult'];
  private readonly courseReplaySlots: CourseRouteDeps['courseReplaySlots'];
  private readonly showBeatorajaResult: CourseRouteDeps['showBeatorajaResult'];
  private readonly unlockReplayOptions: CourseRouteDeps['unlockReplayOptions'];
 
  public constructor(deps: CourseRouteDeps) {
    this.courses = deps.courses;
    this.library = deps.library;
    this.records = deps.records;
    this.courseMaker = deps.courseMaker;
    this.promptRandomMix = deps.promptRandomMix;
    this.promptRandomMixSave = deps.promptRandomMixSave;
    this.now = deps.now ?? (() => new Date());
    this.random = deps.random ?? Math.random;
    this.replayAutoSave = deps.replayAutoSave;
    this.leaderboard = deps.leaderboard;
    this.familyKits = deps.familyKits;
    this.replayRecorder = deps.replayRecorder;
    this.selectNavigation = deps.selectNavigation;
    this.setStatus = deps.setStatus;
    this.showMissingCourseStages = deps.showMissingCourseStages;
    this.startNonstopCourse = deps.startNonstopCourse;
    this.showSelect = deps.showSelect;
    this.showDecide = deps.showDecide;
    this.playChart = deps.playChart;
    this.showResult = deps.showResult;
    this.courseReplaySlots = deps.courseReplaySlots;
    this.showBeatorajaResult = deps.showBeatorajaResult;
    this.unlockReplayOptions = deps.unlockReplayOptions;
  }
 
  /**
   * Starts a course from its first stage. A beatoraja random course first draws its stages from the library (each
   * stage filter against the songs and their chart hashes); a stage that finds no chart leaves it unstarted.
   */
  public async startCourse(entry: LibraryCourse, options: { autoPlay?: boolean } = {}): Promise<void> {
    // AUTO on a course bar plays every stage itself; PLAY follows the Options dialog's auto play.
    this.courses.start(options.autoPlay);
    const plan = planCourseStart(entry);
    // A NEW COURSE bar starts making a course of its folder's kind; songs decided from now on join it.
    if (plan.action === 'make') {
      this.courseMaker.maker.start(plan.kind);
      this.setStatus(playerText().course.making);
      return;
    }
    if (plan.action === 'unplayable') {
      this.setStatus(describeUnplayableCourse(entry));
      // A random course is unplayable for a bad filter, not a missing chart: the status says which.
      Eif (entry.random === undefined) this.showMissingCourseStages(entry);
      return;
    }
    if (plan.action === 'random-mix') {
      await this.startRandomMix(plan.kind);
      return;
    }
    let course = entry;
    const navigation = this.selectNavigation();
    this.courses.leaveSelect(navigation);
    let rememberDraw: (() => void) | undefined;
    if (plan.action === 'draw') {
      const candidates = await Promise.all(
        this.library.collection.charts.map(async (chartEntry) => ({
          chart: chartEntry,
          ...(await this.records.resolveChartHashes(chartEntry)),
        })),
      );
      // The candidates are hashed by now, so each one's best record is found by its hash.
      const drawn = drawBrowserRandomCourse(entry, candidates, Math.random, (chartEntry) =>
        this.records.peekChartBestRecord(chartEntry),
      );
      if (!drawn.ok) {
        this.setStatus(describeRandomCourseDrawFailure(entry.definition.name, drawn));
        return;
      }
      const prepared = this.library.prepareDrawnCourse(drawn.course, navigation);
      course = prepared.course;
      rememberDraw = prepared.remember;
    }
    if (planCourseStart(course).action === 'nonstop') {
      await this.startNonstopCourse(course, { decide: true });
      return;
    }
    const active = this.courses.beginRun(course);
    // LR2 shows the decide screen once, before the first stage (a stage after it starts from the previous result).
    const first = course.stages[0]?.chart;
    Iif (first === undefined) {
      await this.playNextCourseStage();
      return;
    }
    await this.showDecide(
      courseDecideSong(course, first),
      {},
      {
        start: () => this.playNextCourseStage(),
        cancel: () => this.courses.cancelRun(active),
        ...(rememberDraw !== undefined
          ? {
              shown: () => {
                if (this.courses.active !== active) return;
                rememberDraw();
                Eif (navigation !== undefined)
                  this.courses.leaveSelect({ ...navigation, focusKey: `course:${course.id}` });
              },
            }
          : {}),
      },
    );
  }
 
  /**
   * A RANDOM MIX bar: the RANDOM MIX dialog asks which charts to draw from and how many stages, then one run is drawn
   * and played. Its result leads back to the select screen, as any course's does; deciding the bar again draws afresh. What the dialog held is kept for the next one, OK or not. Only the library's facts at hand are read to list the charts that fit; a
   * chart's BPMs are read once a draw walks it and its chart file hashed once it is drawn, so starting a mix costs the
   * same however large the library is.
   */
  private async startRandomMix(kind: 'expert' | 'nonstop'): Promise<void> {
    const pool = this.library.collection.charts.map(createRandomMixCandidate);
    const maker = this.courseMaker.maker;
    const closed = await this.promptRandomMix({
      kind,
      keyModes: listRandomMixKeyModes(pool),
      initial: maker.randomMixConditions,
      settings: maker.randomMixSettings,
      defaultConnection: maker.defaultConnection,
      countMatches: (asked) => filterRandomMixCandidates(pool, asked).length,
      canStart: (asked) =>
        hasRandomMixFirstStage(filterRandomMixCandidates(pool, asked.conditions), {
          settings: asked.settings,
          bpmOf: (candidate) => resolveRandomMixBPM(candidate.chart),
          allowBPMChanges: asked.conditions.allowBPMChanges,
        }),
    });
    if (closed === undefined) return;
    // What the dialog held is kept for the next one, confirmed or not.
    const { choice } = closed;
    const { conditions } = choice;
    maker.setRandomMixConditions(conditions);
    maker.setRandomMixSettings(choice.settings);
    if (kind === 'nonstop') maker.setDefaultConnection(choice.defaultConnection);
    if (!closed.confirmed) return;
    this.courses.leaveSelect(this.selectNavigation());
    await this.playRandomMix(kind, pool);
  }
 
  /**
   * Draws one RANDOM MIX run by the conditions last confirmed and plays it: a counted run is kept as its folder's newest
   * course, as LR2 keeps its draw; an endless one is played without being kept, and draws each stage as it reaches it.
   * The run remembers what it was started with, which the save dialog shows once it is over.
   */
  private async playRandomMix(kind: 'expert' | 'nonstop', pool: readonly RandomMixPoolChart[]): Promise<void> {
    const maker = this.courseMaker.maker;
    const conditions = maker.randomMixConditions;
    const count = resolveRandomMixCount(kind, conditions.count);
    const endless = count === 'infinity';
    // What the run is started with, which the save dialog shows once it is over.
    const setup = {
      kind,
      conditions: { ...conditions, difficulties: [...conditions.difficulties], count },
      settings: { ...maker.randomMixSettings },
      defaultConnection: maker.defaultConnection,
    };
    const draw = new RandomMixDraw(filterRandomMixCandidates(pool, conditions), {
      settings: maker.randomMixSettings,
      bpmOf: resolveRandomMixBPM,
      md5Of: async (chartEntry) => (await this.records.resolveChartHashes(chartEntry))?.md5,
      random: this.random,
      allowBPMChanges: conditions.allowBPMChanges,
      endless,
    });
    const stages = await draw.take(endless ? 1 : count);
    const course = createRandomMixCourse(
      kind,
      stages.map((drawn) => drawn.stage),
      { defaultConnection: maker.defaultConnection },
    );
    if (course === undefined) {
      this.setStatus(playerText().course.randomMixNoMatch);
      await this.showSelect();
      return;
    }
    const kept = isRandomMixKept(count);
    if (kept) maker.keepRandomMix(course);
    // A kept draw is its folder's newest course, where the cursor comes back; otherwise the RANDOM MIX bar.
    const barId = kept ? `maker:${kind}#0` : createRandomMixEntry(kind).id;
    const navigation = this.courses.takeReturnNavigation() ?? this.selectNavigation();
    this.courses.leaveSelect(navigation !== undefined ? { ...navigation, focusKey: `course:${barId}` } : undefined);
    const run: RandomMixRun = { setup, ...(kept ? { kept: course } : {}) };
    if (kind === 'nonstop') {
      const entry = createDrawnRandomMixEntry(course, stages);
      this.nonstopRandomMix = { course: entry, run };
      await this.startNonstopCourse(entry, { decide: true });
      return;
    }
    const endlessMix: EndlessRandomMix | undefined = endless
      ? { next: () => draw.next(), stages: [...stages] }
      : undefined;
    if (endlessMix !== undefined) endlessMix.lookahead = draw.next();
    const entry =
      endlessMix !== undefined
        ? endlessRandomMixEntry(barId, course, stages, await endlessMix.lookahead)
        : { ...createDrawnRandomMixEntry(course, stages), id: barId };
    const active = this.courses.beginRun(entry, undefined, {
      ...(endlessMix !== undefined ? { endless: endlessMix } : {}),
      ...(kept ? {} : { unkept: true }),
    });
    active.randomMix = run;
    await this.showDecide(
      courseDecideSong(entry, stages[0]!.chart),
      {},
      {
        start: () => this.playNextCourseStage(),
        cancel: () => this.courses.cancelRun(active),
      },
    );
  }
 
  /**
   * Called when a NONSTOP run played live reaches its result (`NonstopRoute`): when it is the NONSTOP RANDOM MIX being
   * played, the mix is over, and the select screen offers to save it once the result is left. A retry from the result
   * plays it again, and the save waits for the run that leaves it.
   */
  public noteNonstopResult(course: LibraryCourse): void {
    const mix = this.nonstopRandomMix;
    if (mix === undefined || mix.course !== course) return;
    this.finishedRandomMix = finishRandomMix(mix.run, course, this.now());
  }
 
  /**
   * Opens the save dialog for a RANDOM MIX run that is over, once the select screen is back (its result left); does
   * nothing when no run waits. Saving keeps the run's course as one of the player's own, named as the dialog says.
   */
  public async offerRandomMixSave(): Promise<void> {
    const finished = this.finishedRandomMix;
    if (finished === undefined) return;
    this.finishedRandomMix = undefined;
    if (this.nonstopRandomMix?.course.definition === finished.course) this.nonstopRandomMix = undefined;
    const name = await this.promptRandomMixSave(finished.request);
    if (name === undefined) return;
    const saved = saveFinishedRandomMix(this.courseMaker.maker, finished, name);
    this.setStatus(playerText().course.saved(saved.name));
  }
 
  /**
   * Plays a course replay back as a course run (`courseFromReplay` rebuilt its course from the log): its decide screen,
   * then each recorded stage in order with the state it carried in, each stage's result, and the course result, up to
   * where the recorded run stopped. Nothing is kept: no stage or course record, no saved replay, no Leaderboard run.
   */
  public async startCourseReplay(course: LibraryCourse, courseLog: BeMusicCourseReplay): Promise<void> {
    this.courses.start(undefined);
    this.courses.leaveSelect(this.selectNavigation());
    const active = this.courses.beginRun(course, courseLog);
    const first = course.stages[0]?.chart;
    if (first === undefined || active.replay?.stages.length === 0) {
      this.courses.cancelRun(active);
      this.setStatus(`${course.definition.name}: the course replay has no stage to play`);
      return;
    }
    await this.showDecide(
      courseDecideSong(course, first),
      {},
      { start: () => this.playNextCourseStage(), cancel: () => this.courses.cancelRun(active) },
    );
  }
 
  /** Plays the running course's next stage, or shows the course result when it is over. */
  private async playNextCourseStage(): Promise<void> {
    const active = this.courses.active;
    // An endless RANDOM MIX draws the stage it reaches now; no chart left to draw ends the run.
    Iif (active?.endless !== undefined && !(await prepareEndlessStage(active))) {
      if (this.courses.active === active) await this.showCourseResult();
      return;
    }
    Iif (this.courses.active !== active) return;
    const stage = active !== undefined ? nextCourseStagePlay(active) : undefined;
    if (active === undefined || stage === undefined) {
      await this.showCourseResult();
      return;
    }
    const replaying = stage.replay !== undefined ? ' (replay)' : '';
    const stageCount = active.endless !== undefined ? '∞' : stage.stageCount;
    this.setStatus(`${active.course.definition.name}: stage ${stage.index + 1} / ${stageCount}${replaying}`);
    // A course replay's stage plays its recorded replay (an AUTO stage as AUTO), as a dropped replay plays.
    if (stage.replay !== undefined) {
      await this.playChart(stage.stage, {
        courseStage: stage,
        replay: stage.replay,
        autoPlay: stage.replay.play.mode === 'auto',
      });
      return;
    }
    await this.playChart(stage.stage, {
      courseStage: stage,
      ...(this.courses.autoPlay !== undefined ? { autoPlay: this.courses.autoPlay } : {}),
    });
  }
 
  /**
   * Called when a stage's result is dismissed during a course: the next stage starts, or the course result shows once
   * the course is over. Returns false outside a course.
   */
  public continueCourse(): boolean {
    if (this.courses.active === undefined) return false;
    void (this.courses.active.run.finished ? this.showCourseResult() : this.playNextCourseStage());
    return true;
  }
 
  /**
   * The course result: the course replay built from the stages played, its native result shown on the result scene
   * as one run, saved (when auto-save is on) and kept as the course's best record.
   */
  public async showCourseResult(): Promise<void> {
    const active = this.courses.finishRun();
    if (active === undefined || active.run.stagesPlayed === 0) {
      await this.showSelect();
      return;
    }
    // An endless run's course is the stages it played, the one drawn ahead dropped.
    settleEndlessCourse(active);
    const { course, run } = active;
    // A RANDOM MIX is over, played through or given up: the select screen offers to save it once the result is left.
    if (active.randomMix !== undefined) this.finishedRandomMix = finishRandomMix(active.randomMix, course, this.now());
    // A course replay shows the run it recorded, and keeps nothing.
    const replay = active.replay !== undefined && !run.practice;
    const courseLog = run.practice
      ? undefined
      : replay
        ? active.replay!.log
        : run.buildReplay({ createdAt: new Date().toISOString(), recorder: this.replayRecorder });
    const result = run.practice
      ? run.buildPracticeResult()
      : (courseLog?.results?.native ?? (replay ? run.buildReplay().results?.native : undefined));
    Iif (result === undefined) {
      await this.showSelect();
      return;
    }
    let replaySlots: ResultReplaySlots | undefined;
    if (courseLog !== undefined && replay) {
      // A course replay shows its course's replay slots and saves into none, as a single replay does.
      replaySlots = this.courseReplaySlots(courseLog, result, undefined, true);
    }
    if (courseLog !== undefined && !replay && active.unkept === true) {
      // A RANDOM MIX run keeps history even though it has no persistent select bar.
      replaySlots = this.courseReplaySlots(courseLog, result, undefined);
      this.replayAutoSave.saveCourse(courseLog);
      this.leaderboard.maybeSubmitCourse(courseLog, run.stages);
    } else if (courseLog !== undefined && !replay) {
      const update = resolveCourseBestRecordUpdate(courseLog, result, courseBestRecordKey(course));
      const kept = this.records.recordCourseResult(update);
      // A cleared GRADE course named after a dan raises the player's dan rank in its key mode.
      this.records.recordDanRank(resolveCourseDanRankUpdate(course, courseLog, result));
      // The run saves into its course's replay slots only when it kept a record, as beatoraja's `CourseResult` does.
      replaySlots = this.courseReplaySlots(
        courseLog,
        result,
        update !== undefined && kept !== undefined ? { play: update.play, previous: kept.previous } : undefined,
      );
      this.replayAutoSave.saveCourse(courseLog);
      // The course is ranked as one run; a practice run has no replay and never reaches these writers.
      this.leaderboard.maybeSubmitCourse(courseLog, run.stages);
    }
    const courseInfo = resolveCourseView(course);
    const histories = courseStageHistories(active);
    // A beatoraja theme shows the course result on its COURSE_RESULT skin (or its result skin).
    if (pickActiveFamilyForScene(this.familyKits.familyDispatchState(), 'result') === 'beatoraja') {
      // The course run read as one play, as on the other families: beatoraja's course result sums the stages and draws
      // every stage's graph joined, each stage as wide as its chart is long.
      const joined = joinCourseStageHistories(
        histories,
        run.stages.map((chartEntry) => createCourseChartRecord(chartEntry).length ?? 0),
      );
      const runResult = buildCourseResultData(course, result, courseLog, joined, {
        playSeconds: run.playSeconds,
        stageHistories: histories,
        practice: run.practice,
        fromReplay: active.replay !== undefined,
      });
      const mounted = await this.showBeatorajaResult(runResult, {
        run: 'course',
        course: {
          info: courseInfo,
          ...(courseLog !== undefined ? { result: { log: courseLog, native: result } } : {}),
        },
        ...(replaySlots !== undefined ? { replaySlots } : {}),
      });
      if (mounted) {
        this.unlockReplayOptions();
        return;
      }
    }
    // LR2 (and the built-in result) shows the last stage's graph.
    const playSeconds = run.playSeconds;
    await this.showResult(
      buildCourseResultData(course, result, courseLog, histories.at(-1), {
        playSeconds,
        practice: run.practice,
        fromReplay: active.replay !== undefined,
      }),
      {
        course: courseInfo,
        ...(courseLog !== undefined ? { courseLog: { log: courseLog, native: result } } : {}),
        ...(replaySlots !== undefined ? { replaySlots } : {}),
      },
    );
  }
}