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 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 | 28x 3x 30x 30x 13x 13x 5x 12x 10x 2x 17x 30x 6x 6x 6x 3x 5x 2x 11x 30x 4x 2x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 152x 10x 10x 23x 9x 9x 23x 23x 23x 4x 3x 1x 1x 1x 4x 10x 2x 2x 4x 3x 3x 3x 27x 27x 27x 27x 27x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 27x 27x 27x 27x 71x 27x 27x 27x 27x 7x 5x 16x 23x 22x 27x 3x 27x 20x 27x 27x 27x 28x 28x 27x 28x 3x 3x 18x 18x 3x | /**
* The host API for the play screen: `createPlayScene(kit, options)` pairs a play session with the view of the kit's
* family and returns the scene to load with `prepare`, show with `PixiSceneHost.setScene` and begin with `start`.
*/
import { BGACameraFeed } from '../media/bga-camera.ts';
import type { GuideSound, ResolvedPlayChart } from '@be-music/player-engine';
import type { BeMusicReplay, ReplayCourseStage } from '@be-music/player-engine/replay';
import { gaugePickType, type RulesetId } from '@be-music/player-engine/ruleset';
import {
DEFAULT_PLAY_OPTIONS,
resolvePlayOptions,
resolvePracticeSelection,
type CourseView,
type LibraryChart,
type PlayOptions,
type PlayResult,
type PracticeRange,
type GuideSoundSlot,
type RankingScoreTarget,
type SystemSound,
type SystemSoundSet,
} from '@be-music/player-scene-model';
import type { Texture } from 'pixi.js';
import type { BrowserAssetSource } from '../collection/types.ts';
import type { GameplayRecorderResult } from '../recording/gameplay-recorder.ts';
import type { RecordingFormat, RecordingQuality } from '../recording/recording-format.ts';
import type { AudioBusChannel, CompressorParams, CompressorStage, TunableCompressor } from '../runtime/audio-bus.ts';
import type { AudioOwner, AudioService } from '../runtime/audio-service.ts';
import type { PlayDisposeOptions, PlaySessionOptions, SkinAdjust } from '../session/play/play-options.ts';
import type { PixiSceneHost } from './scene-host.ts';
import { PlaySceneSession } from '../session/play/play-scene-session.ts';
import { PlaySession } from '../session/play/play-session.ts';
import type { PlayReplayViewScale, PlaySessionTheme } from '../session/play/play-session-theme.ts';
import { SessionScene, type SessionSceneOptions } from '../session/session-scene.ts';
import { logger } from '../logger.ts';
import { BeatorajaPlayView } from '../view/beatoraja/play-view.ts';
import { BuiltInPlayView, LIFT_SKINS } from '../view/built-in/play-view.ts';
import { LR2PlayView } from '../view/lr2/play-view.ts';
import { LR2TextureRetainer } from '../view/lr2/texture-retainer.ts';
import type { PlayFrame, PlayIntent, PlayView, PlayfieldSkin } from '../view/types.ts';
import type { BeatorajaKit, BuiltInKit, LR2PlayKit } from './family-kit.ts';
import type { BPMGuideKinds } from '../chart/bpm-guide.ts';
import { resolveLaneInputTokens } from '../session/play/play-cover-keys.ts';
import { resolveControlScheme } from '../session/controls/control-buttons.ts';
import { keyboardEventToTokens } from '../runtime/web-input-runtime.ts';
const log = logger('gameplay');
/**
* The kits the play scene takes: a Be-Music Skin, an LR2 play skin (with the 9-keys skin for invisible notes), or a
* beatoraja theme's play entry.
*/
export type PlaySceneKit = BuiltInKit | LR2PlayKit | BeatorajaKit;
/**
* How a play runs, apart from its chart, its skin and where it leads: the play options it judges and scrolls with
* (`autoPlay`, the gauge, the lane options, the hi-speed and HS-FIX, the covers), the tempo, the audio mix, the BGA and
* the debug drawing options.
*/
export type PlaySceneSettings = Omit<
PlaySessionOptions,
| 'beMusicEffects'
| 'onExit'
| 'onRestart'
| 'onChartFinished'
| 'onJudgeTimingChange'
| 'onHiSpeedChange'
| 'onSkinAdjustChange'
| 'onTempoChange'
| 'replay'
| 'preResolved'
| 'audio'
| 'course'
| 'courseInfo'
>;
/** The course a play is a stage of: the stage's rules and carried-in state, and the course as a skin shows it. */
export interface PlaySceneCourse {
/** A previous stage sought; the entire course stays practice. */
readonly practice?: boolean;
/** The stage's rules for the engine (`ReplayCourseStage`), with what the previous stage carried in. */
readonly stage: ReplayCourseStage;
/** The course and the stage being played, for the skin. */
readonly view?: CourseView;
}
/** Where a play leads. */
export interface PlaySceneEvents {
/** The chart was played to its end (the ending has run): the result, and the replay the engine recorded. */
finish(result: PlayResult, replay: BeMusicReplay | undefined): void;
/** The player left the play (Escape, the Backspace hold, `requestExit`); its replay follows (`waitForReplay`). */
exit(): void;
/** The player asked to play the chart again (F5). */
restart(): void;
/** The player stepped the hi-speed; on the player's own scale, to remember for the next play. */
hiSpeed?(hiSpeed: number, normalLevel?: number, floating?: boolean): void;
/** The play's tempo changed (a live change, or a replay following its log). */
tempo?(tempo: number): void;
judgeTiming?(judgeTimingMs: number): void;
/** The player moved or scaled the play skin (LR2's 1 / 2 + the arrows), to keep for the next play. */
skinAdjust?(adjust: SkinAdjust): void;
}
export interface PlaySceneOptions extends SessionSceneOptions {
/** The chart to play. */
readonly chart: LibraryChart;
/** Where the chart's files are: its samples, BGA and images. */
readonly source?: BrowserAssetSource;
readonly settings: PlaySceneSettings;
/** Allow manual seeking; the first seek makes the play practice and disables saved results. */
readonly allowSeek?: 'practice';
/**
* The bars a PRACTICE play loops, as chart milliseconds (`chartScoreRangeTimes` of the bars picked on the chart's
* score). Read only when the play options turn PRACTICE on for a single fresh play; without it the whole chart loops.
*/
readonly practiceRange?: PracticeRange;
/** The course stage this play is, if any. */
readonly course?: PlaySceneCourse;
/** A replay to play back instead of the player's input: its recorded setup, arrangement, tempo and view. */
readonly replay?: BeMusicReplay;
/**
* The chart's `#RANDOM` / `#SWITCH` branches as the decide screen drew them (`DecideScene.resolved`), so the play
* plays the branches the screen showed. Without it the play draws its own; a replay plays its log's.
*/
readonly preResolved?: ResolvedPlayChart;
/** The host's audio service: the play opens its own context and bus through it. */
readonly audio: AudioService;
/** Optional theme sounds; `playStop` plays once when the play fails. */
readonly sounds?: SystemSoundSet;
/** The play options as the select screen set them, for the frames a view reads. Defaults to `DEFAULT_PLAY_OPTIONS`. */
readonly playOptions?: PlayOptions;
readonly scoreTargets?: PlayFrame['scoreTargets'];
/**
* The EX score at a ranking target's place (`IR_*` in `PlayOptions.scoreTarget`) on the chart's ranking, or
* `undefined` when the chart has none. Without it a ranking target shows nothing.
*/
readonly rankingTarget?: (target: RankingScoreTarget) => Promise<number | undefined>;
/** The signed-in player's name, which a skin may show beside the chart. */
readonly playerName?: string;
/**
* The host the scene will show on. With it the scene builds its layers as it loads, so the BGA uploads to the GPU
* behind a decide screen instead of on its first cue.
*/
readonly host?: PixiSceneHost;
readonly on: PlaySceneEvents;
}
/** A play's recording of its canvas and mix, as the host's recorder drives it. */
export interface PlaySceneRecording {
/** Starts recording the play in `format` (MP4 · H.264 by default) at `quality` (`standard` by default). */
startRecording(options?: { format?: RecordingFormat; quality?: RecordingQuality }): void;
stopRecording(): Promise<GameplayRecorderResult | undefined>;
isRecording(): boolean;
}
/** The play screen as a scene. */
export interface PlayScene extends SessionScene<PlayFrame, PlayIntent> {
/**
* Loads the play: the chart, its samples (decoded, stretched for a keep-pitch tempo) and the BGA, which goes on
* loading in the background. Touches nothing on the stage, so a decide screen can show meanwhile; run while the
* scene is shown, the playfield draws in its loading state. Reports 0..1 as it goes.
*/
prepare(onProgress?: (progress: number) => void): Promise<void>;
/** Begins the play once it is prepared and shown: the intro, then the chart. Later calls do nothing. */
start(): void;
/** Leaves the play as Escape does: the fade-out, then `on.exit`. */
requestExit(): void;
/** Pauses or resumes the play, as Space does. */
requestTogglePause(): void;
isPaused(): boolean;
/** Whether a lane of the chart takes the key (`code`): a key every screen takes (F4, F6) is the lane's then. */
takesKey(event: { readonly code: string }): boolean;
/**
* Moves an AUTO play or replay to chart second `seconds` (clamped to the chart) and plays on from there, as a preview's seek bar
* does; a paused play stays paused there. The running play seeks — it is not started again — and the promise resolves
* once the play shows the second sought (its frames are of the new seek generation). Manual play requires
* `allowSeek: 'practice'` and the first seek disables result persistence (`PlayFrame.seekable`).
*/
seek(seconds: number): Promise<void>;
/** Changes the play's tempo (pitch mode, not in a replay); whether it was taken. */
setTempo(tempo: number): boolean;
getTempo(): number;
/** Sets the player's hi-speed (HS-FIX applies on top). */
setHiSpeed(hiSpeed: number): void;
/** beatoraja display-clock calibration; never shifts recorded inputs. */
setJudgeTimingMs(judgeTimingMs: number): void;
getHiSpeed(): number;
/** The play's recording. */
readonly recording: PlaySceneRecording;
/** The play as a result so far (the test hook reads it); `undefined` before the chart is loaded. */
progress(): PlayResult | undefined;
/**
* The chart as the play plays it — its `#RANDOM` / `#SWITCH` branches drawn, with the draws — once it is loaded and
* until the scene is disposed: what a result's graphs plot.
*/
readonly resolved: ResolvedPlayChart | undefined;
/** The replay once the engine has recorded it, also after Escape; `undefined` after `timeoutMs` without one. */
waitForReplay(timeoutMs?: number): Promise<BeMusicReplay | undefined>;
/**
* Takes the player's new settings for the kit's skin; the next frame draws with them. The scene keeps its family: a
* kit of another family is ignored. A built-in or LR2 scene keeps its skin too, while a beatoraja scene takes another
* entry's skin (the player's play-skin picker) and rebuilds its stage.
*/
updateKit(kit: PlaySceneKit): void;
/**
* Draws the play with `kit` from the next frame. The chart, judgments and audio stay. A kit this scene already draws
* is handed to {@link updateKit}. Another family's view is disposed; its LR2 textures stay until the play ends, so
* switching back does not decode the same bytes again.
*/
replaceFamily(kit: PlaySceneKit): Promise<void>;
setAudioVolume(channel: AudioBusChannel, volume: number): void;
setAudioCompressor(enabled: boolean): void;
setAudioCompressorMode(mode: 'split' | 'legacy'): void;
setAudioCompressorStageEnabled(stage: CompressorStage, enabled: boolean): void;
setAudioCompressorParams(compressor: TunableCompressor, params: Partial<CompressorParams>): void;
setAutoPauseOnBlur(enabled: boolean): void;
setShowInvisibleNotes(enabled: boolean): void;
/** Which labels BPM GUIDE shows, from the next frame (a viewing preference: no record or replay changes). */
setBPMGuideKinds(kinds: BPMGuideKinds): void;
/**
* Shows `camera.stream` in the BGA frame in place of the chart's BGA, flipped left to right when `camera.mirror` is
* set, or the chart's BGA again with `undefined`. Takes effect from the next frame, during a play too. The scene only
* shows the stream: the caller opens it and stops its tracks.
*/
setBGACamera(camera: BGACamera | undefined): void;
/** Ends the scene; `preserveAudioTail` lets a play that ended ring out before its audio closes. */
dispose(options?: PlayDisposeOptions): void;
}
/** A camera for the BGA frame ({@link PlayScene.setBGACamera}). */
export interface BGACamera {
readonly stream: MediaStream;
readonly mirror: boolean;
}
/** A family's play view, and what the scene and the play session ask of it. */
interface FamilyPlayView {
readonly view: PlayView;
/** How the view's skin answers the shared playfield: its key-beam fade. */
readonly playfieldSkin: PlayfieldSkin;
/** Builds the view's layers on `host` ahead of its first frame, so what the play loads can upload to the GPU. */
prepareOn(host: PixiSceneHost): void;
/** Loads the view's own assets once the chart is prepared (the session theme's `prepareView`). */
prepareView?(): Promise<void>;
/** The scale the view's hi-speed reads on in the replay, when it has its own (the session theme's `replayView`). */
replayView?(): PlayReplayViewScale | undefined;
/** The view draws the LIFT (the session theme's `drawsLift`). */
readonly drawsLift?: boolean;
uploadTextures(textures: Iterable<Texture | undefined>, isCancelled: () => boolean): Promise<void>;
setShowInvisibleNotes(enabled: boolean): void;
setBPMGuideKinds(kinds: BPMGuideKinds): void;
updateKit(kit: PlaySceneKit): void;
}
/**
* The play view of `kit`'s family, drawing `play`. A beatoraja skin's Lua sounds play through the audio service as
* `soundOwner`'s, so they stop as the scene leaves the stage.
*/
/** True when `view` is already drawing `kit`, so {@link PlayScene.updateKit} can take it without a new view. */
function viewDrawsKit(view: FamilyPlayView, kit: PlaySceneKit): boolean {
Eif (view.view.family !== kit.family) return false;
if (kit.family === 'beatoraja') return true;
if (kit.family === 'lr2') return view.view instanceof LR2PlayView && view.view.skin === kit.skin;
return view.view instanceof BuiltInPlayView && view.view.drawsSkin(kit.skin);
}
function createPlayView(
kit: PlaySceneKit,
play: PlaySession,
options: Pick<PlaySceneOptions, 'settings' | 'course' | 'source' | 'audio' | 'replay'>,
soundOwner: AudioOwner,
textures: LR2TextureRetainer,
): FamilyPlayView {
const { settings, course, source } = options;
if (kit.family === 'beatoraja') {
const view = new BeatorajaPlayView(kit, play, {
...(settings.showInvisibleNotes !== undefined ? { showInvisibleNotes: settings.showInvisibleNotes } : {}),
...(settings.bpmGuideKinds !== undefined ? { bpmGuideKinds: settings.bpmGuideKinds } : {}),
...(settings.autoPlay !== undefined ? { autoPlay: settings.autoPlay } : {}),
...(settings.dpFlip !== undefined ? { dpFlip: settings.dpFlip } : {}),
...(course?.view !== undefined ? { course: course.view } : {}),
...(settings.nonstop !== undefined ? { nonstop: settings.nonstop } : {}),
chartOptionProgram: options.replay ? options.replay.chart.chartOptions : settings.nonstop?.chartOptions,
...(source !== undefined ? { source } : {}),
// The skin's Lua sounds play through the audio service, owned by the scene's session (not the play, which owns its
// audio graph: a play that ended keeps ringing out after the scene leaves).
skinSounds: options.audio.skinSounds.owned(soundOwner),
});
return {
view,
playfieldSkin: view.playfieldSkin,
prepareOn: (host) => view.prepareOn(host),
prepareView: () => view.prepare(),
replayView: () => view.replayView(),
drawsLift: true,
uploadTextures: (textures, isCancelled) => view.uploadTextures(textures, isCancelled),
setShowInvisibleNotes: (enabled) => view.setShowInvisibleNotes(enabled),
setBPMGuideKinds: (kinds) => view.setBPMGuideKinds(kinds),
updateKit: (next) => (next.family === 'beatoraja' ? view.updateKit(next) : ignoreKit(next, 'beatoraja')),
};
}
const drawing = {
...(settings.visualConstant !== undefined ? { visualConstant: settings.visualConstant } : {}),
...(settings.noteDurationMs !== undefined ? { noteDurationMs: settings.noteDurationMs } : {}),
...(settings.constantFadeMs !== undefined ? { constantFadeMs: settings.constantFadeMs } : {}),
...(settings.judgeTimingMs !== undefined ? { judgeTimingMs: settings.judgeTimingMs } : {}),
...(settings.bpmGuide !== undefined ? { bpmGuide: settings.bpmGuide } : {}),
...(settings.bpmGuideKinds !== undefined ? { bpmGuideKinds: settings.bpmGuideKinds } : {}),
...(settings.bga !== undefined ? { bga: settings.bga } : {}),
...(settings.autoPlay !== undefined ? { autoPlay: settings.autoPlay } : {}),
...(settings.nonstop !== undefined ? { nonstop: settings.nonstop } : {}),
...(settings.showInvisibleNotes !== undefined ? { showInvisibleNotes: settings.showInvisibleNotes } : {}),
...(source !== undefined ? { source } : {}),
};
if (kit.family === 'lr2') {
const view = new LR2PlayView(kit, play, {
...drawing,
...(settings.bgaSize !== undefined ? { bgaSize: settings.bgaSize } : {}),
...(settings.autoScratch1P !== undefined ? { autoScratch1P: settings.autoScratch1P } : {}),
...(settings.autoScratch2P !== undefined ? { autoScratch2P: settings.autoScratch2P } : {}),
...(settings.scoreGraph !== undefined ? { scoreGraph: settings.scoreGraph } : {}),
...(settings.battleMode !== undefined ? { battleMode: settings.battleMode } : {}),
...(settings.lr2ExtraMode !== undefined ? { lr2ExtraMode: settings.lr2ExtraMode } : {}),
// A view labels the gauge by its type; the source of a qualified pick (`lr2:HARD`) stays with the engine.
...(settings.gauge2P !== undefined ? { gauge2P: gaugePickType(settings.gauge2P) } : {}),
gauge: gaugePickType(play.resolveSelectedGauge()),
courseGauge: course !== undefined,
...(course?.view !== undefined ? { course: course.view } : {}),
...(options.replay !== undefined ? { replay: true } : {}),
});
view.useTextureRetainer(textures);
return {
view,
playfieldSkin: view.playfieldSkin,
prepareOn: (host) => view.prepareOn(host),
prepareView: () => view.prepare(),
uploadTextures: (textures, isCancelled) => view.uploadTextures(textures, isCancelled),
setShowInvisibleNotes: (enabled) => {
view.options.showInvisibleNotes = enabled;
},
setBPMGuideKinds: (kinds) => {
view.options.bpmGuideKinds = kinds;
},
updateKit: (next) => (next.family === 'lr2' ? view.updateKit(next) : ignoreKit(next, 'lr2')),
};
}
const view = new BuiltInPlayView(kit, play, {
...drawing,
...(settings.layoutMode !== undefined ? { layoutMode: settings.layoutMode } : {}),
});
return {
view,
playfieldSkin: view.playfieldSkin,
get drawsLift() {
return view.drawsLift;
},
prepareOn: (host) => view.prepareOn(host),
uploadTextures: (textures, isCancelled) => view.uploadTextures(textures, isCancelled),
setShowInvisibleNotes: (enabled) => {
view.options.showInvisibleNotes = enabled;
},
setBPMGuideKinds: (kinds) => {
view.options.bpmGuideKinds = kinds;
},
updateKit: (next) => (next.family === 'built-in' ? view.updateKit(next) : ignoreKit(next, 'built-in')),
};
}
function ignoreKit(kit: PlaySceneKit, family: PlaySceneKit['family']): void {
log.warn(`a ${family} play scene keeps its family; ignoring a ${kit.family} kit`);
}
interface FamilySlot {
current: FamilyPlayView;
}
class FamilyPlayScene extends SessionScene<PlayFrame, PlayIntent> implements PlayScene {
public readonly recording: PlaySceneRecording;
private readonly playSession: PlaySceneSession;
private readonly familySlot: FamilySlot;
private readonly textures: LR2TextureRetainer;
private readonly audio: AudioService;
private readonly soundOwner: AudioOwner;
private readonly viewOptions: Pick<PlaySceneOptions, 'settings' | 'course' | 'source' | 'audio'>;
private readonly chart: LibraryChart;
private readonly source: BrowserAssetSource | undefined;
private readonly prepareHost: PixiSceneHost | undefined;
/** Family swaps run one at a time. A newer one waits until the view being prepared is in place or discarded. */
private replaceChain: Promise<void> = Promise.resolve();
public constructor(
session: PlaySceneSession,
familySlot: FamilySlot,
facts: {
chart: LibraryChart;
source?: BrowserAssetSource;
host?: PixiSceneHost;
audio: AudioService;
soundOwner: AudioOwner;
viewOptions: Pick<PlaySceneOptions, 'settings' | 'course' | 'source' | 'audio'>;
textures: LR2TextureRetainer;
},
options: SessionSceneOptions,
) {
super(session, familySlot.current.view, options);
this.playSession = session;
this.familySlot = familySlot;
this.textures = facts.textures;
this.audio = facts.audio;
this.soundOwner = facts.soundOwner;
this.viewOptions = facts.viewOptions;
this.chart = facts.chart;
this.source = facts.source;
this.prepareHost = facts.host;
const play = session.play;
this.recording = {
startRecording: (recordingOptions) => play.startRecording(recordingOptions),
stopRecording: () => play.stopRecording(),
isRecording: () => play.isRecording(),
};
}
private get play(): PlaySession {
return this.playSession.play;
}
public override async enter(host: PixiSceneHost): Promise<void> {
// The play's own input listens on the host's canvas from the scene's entry on (`PlaySceneSession.enter`).
this.play.host ??= host;
await super.enter(host);
}
public async prepare(onProgress?: (progress: number) => void): Promise<void> {
if (this.prepareHost !== undefined) {
this.play.host ??= this.prepareHost;
this.familySlot.current.prepareOn(this.prepareHost);
}
onProgress?.(0);
await this.play.load(this.chart, this.source);
onProgress?.(1);
}
public start(): void {
this.play.start();
}
public requestExit(): void {
this.play.requestExit();
}
public requestTogglePause(): void {
this.play.requestTogglePause();
}
public isPaused(): boolean {
return this.play.isPaused();
}
public takesKey(event: { readonly code: string }): boolean {
const tokens = resolveLaneInputTokens(this.play.preparedChart?.laneBindings);
return keyboardEventToTokens(event).some((token) => tokens.has(token));
}
public seek(seconds: number): Promise<void> {
return this.play.seek(seconds);
}
public setTempo(tempo: number): boolean {
return this.play.setTempo(tempo);
}
public getTempo(): number {
return this.play.getTempo();
}
public setJudgeTimingMs(judgeTimingMs: number): void {
this.play.setJudgeTimingMs(judgeTimingMs);
}
public setHiSpeed(hiSpeed: number): void {
this.play.setHiSpeed(hiSpeed);
}
public getHiSpeed(): number {
return this.play.getHiSpeed();
}
public progress(): PlayResult | undefined {
return this.play.getResultData();
}
public get resolved(): ResolvedPlayChart | undefined {
const { resolvedChart, randomDraws } = this.play;
return resolvedChart !== undefined && randomDraws !== undefined ? { chart: resolvedChart, randomDraws } : undefined;
}
public waitForReplay(timeoutMs?: number): Promise<BeMusicReplay | undefined> {
return this.play.waitForReplay(timeoutMs);
}
public updateKit(kit: PlaySceneKit): void {
this.familySlot.current.updateKit(kit);
}
public replaceFamily(kit: PlaySceneKit): Promise<void> {
const run = this.replaceChain.then(() => this.installFamily(kit));
this.replaceChain = run.catch((error) => {
log.warn('play family replace failed', error);
});
return run;
}
public setAudioVolume(channel: AudioBusChannel, volume: number): void {
this.play.setAudioVolume(channel, volume);
}
public setAudioCompressor(enabled: boolean): void {
this.play.setAudioCompressor(enabled);
}
public setAudioCompressorMode(mode: 'split' | 'legacy'): void {
this.play.setAudioCompressorMode(mode);
}
public setAudioCompressorStageEnabled(stage: CompressorStage, enabled: boolean): void {
this.play.setAudioCompressorStageEnabled(stage, enabled);
}
public setAudioCompressorParams(compressor: TunableCompressor, params: Partial<CompressorParams>): void {
this.play.setAudioCompressorParams(compressor, params);
}
public setAutoPauseOnBlur(enabled: boolean): void {
this.play.setAutoPauseOnBlur(enabled);
}
public setShowInvisibleNotes(enabled: boolean): void {
this.familySlot.current.setShowInvisibleNotes(enabled);
}
public setBPMGuideKinds(kinds: BPMGuideKinds): void {
this.familySlot.current.setBPMGuideKinds(kinds);
}
public setBGACamera(camera: BGACamera | undefined): void {
const current = this.play.bgaCamera;
if (camera !== undefined && current?.stream === camera.stream) {
current.mirror = camera.mirror;
return;
}
current?.dispose();
this.play.bgaCamera = camera !== undefined && !this.disposed ? new BGACameraFeed(camera.stream, camera) : undefined;
}
public override dispose(options: PlayDisposeOptions = {}): void {
this.playSession.disposeOptions = options;
this.play.bgaCamera?.dispose();
this.play.bgaCamera = undefined;
super.dispose();
this.textures.destroyAll(this.prepareHost ?? this.play.host);
}
/** Swaps in `kit`'s view. The play session is not rebuilt. */
private async installFamily(kit: PlaySceneKit): Promise<void> {
Iif (this.disposed) return;
const current = this.familySlot.current;
Iif (viewDrawsKit(current, kit)) {
current.updateKit(kit);
this.play.options.coverKeys = kit.family === 'beatoraja';
this.play.options.controlScheme = resolveControlScheme(kit.family, this.play.options.builtInControlScheme);
return;
}
this.audio.stopOwned(this.soundOwner);
const next = createPlayView(kit, this.play, this.viewOptions, this.soundOwner, this.textures);
const host = this.prepareHost ?? this.play.host;
Eif (host !== undefined) next.prepareOn(host);
try {
await next.prepareView?.();
} catch (error) {
this.retire(next);
throw error;
}
Iif (this.disposed) {
this.retire(next);
return;
}
this.familySlot.current = next;
let installed = false;
try {
installed = await this.replaceView(next.view);
} catch (error) {
this.familySlot.current = current;
this.retire(next);
throw error;
}
Iif (!installed) {
this.familySlot.current = current;
this.retire(next);
return;
}
this.play.options.coverKeys = kit.family === 'beatoraja';
this.play.options.controlScheme = resolveControlScheme(kit.family, this.play.options.builtInControlScheme);
if (next.view instanceof LR2PlayView || next.view instanceof BeatorajaPlayView) next.view.joinRunningPlay();
this.retire(current);
}
/** Drops `family`'s scene graph and DOM. LR2 textures go back to {@link textures} instead of being destroyed. */
private retire(family: FamilyPlayView): void {
family.view.dispose();
}
}
/**
* The play screen for `kit`: a play session (the chart, media, engine, input, view settings and ending around one
* `PlayState`) drawn by the kit's family view. Load it with `prepare`, show it with `PixiSceneHost.setScene`, begin it
* with `start`, and dispose it once it is gone (with `preserveAudioTail` after it finished, so its last samples ring
* out).
*/
export function createPlayScene(kit: PlaySceneKit, options: PlaySceneOptions): PlayScene {
const { settings, course, on } = options;
const recordedSpeed =
options.replay !== undefined && (settings.replayView?.hiSpeed ?? true) ? options.replay.play.options : undefined;
const speedProfile = recordedSpeed
? {
...(typeof recordedSpeed.floatingHiSpeed === 'boolean'
? { floatingHiSpeed: recordedSpeed.floatingHiSpeed }
: {}),
...(typeof recordedSpeed.classicHiSpeed === 'boolean' ? { classicHiSpeed: recordedSpeed.classicHiSpeed } : {}),
...(typeof recordedSpeed.normalHiSpeedLevel === 'number'
? { normalHiSpeedLevel: recordedSpeed.normalHiSpeedLevel }
: {}),
}
: {};
const playOptions = resolvePlayOptions({
...(options.playOptions ?? DEFAULT_PLAY_OPTIONS),
...Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== undefined)),
...(settings.initialHiSpeed !== undefined ? { hiSpeed: settings.initialHiSpeed } : {}),
...(settings.gauge !== undefined ? { gauge1P: settings.gauge } : {}),
...speedProfile,
...(options.replay !== undefined &&
((settings.replayView?.covers ?? true) || (settings.replayView?.lift ?? true)) &&
typeof options.replay.play.options?.fixedDisplayArea === 'boolean'
? { fixedDisplayArea: options.replay.play.options.fixedDisplayArea }
: {}),
});
let sceneSession: PlaySceneSession | undefined;
const familySlot: { current?: FamilyPlayView } = {};
const textures = new LR2TextureRetainer();
const viewOptions = {
settings,
...(course !== undefined ? { course } : {}),
...(options.source !== undefined ? { source: options.source } : {}),
audio: options.audio,
};
// The view is made for the play below; the play asks its theme nothing before both exist.
const theme: PlaySessionTheme = {
timing: () => familySlot.current!.view.timing,
pixelsPerBeat: () => familySlot.current?.playfieldSkin.pixelsPerBeat,
moment: (moment) => sceneSession?.queueEvent(moment),
keyOnFadeMs: (channel) => familySlot.current!.playfieldSkin.keyOnFadeMs(channel),
prepareView: () => familySlot.current?.prepareView?.() ?? Promise.resolve(),
uploadTextures: (uploaded) =>
familySlot.current?.uploadTextures(uploaded, () => play.disposed) ?? Promise.resolve(),
replayView: () => familySlot.current?.replayView?.(),
drawsLift: () => familySlot.current?.drawsLift === true,
};
const play = new PlaySession(
{
...settings,
...(kit.family === 'built-in' && LIFT_SKINS.has(kit.skin.id) ? { coverKeys: true } : {}),
controlScheme: resolveControlScheme(kit.family, settings.builtInControlScheme),
...(playOptions.windowHold ? { windowHold: true } : {}),
// beatoraja's GUIDE SE: the sound set's judgment sounds, when the player turned them on.
...(playOptions.guideSE ? { guideSounds: resolveGuideSounds(options.sounds) } : {}),
judgeTimingAutoAdjust: playOptions.judgeTimingAutoAdjust,
...(playOptions.lr2Gambol !== 0 && (settings.judgeRuleset ?? 'lr2') === 'lr2'
? { lr2Gambol: playOptions.lr2Gambol }
: {}),
...(playOptions.customJudge && settings.judgeRuleset === 'beatoraja'
? {
customJudge: {
keyPerfectGreat: playOptions.customJudgeKeyPerfectGreat,
keyGreat: playOptions.customJudgeKeyGreat,
keyGood: playOptions.customJudgeKeyGood,
scratchPerfectGreat: playOptions.customJudgeScratchPerfectGreat,
scratchGreat: playOptions.customJudgeScratchGreat,
scratchGood: playOptions.customJudgeScratchGood,
longNoteMargin: playOptions.customJudgeLongNoteMargin,
},
}
: {}),
hRandomThresholdBPM: playOptions.hRandomThresholdBPM,
mineModifier: playOptions.mineModifier,
crazyJudge: playOptions.crazyJudge,
crazyHellJudge: playOptions.crazyHellJudge,
crazyAddMine: playOptions.crazyAddMine,
crazyNotes: playOptions.crazyNotes,
scrollModifier: playOptions.scrollModifier,
scrollSection: playOptions.scrollSection,
scrollRate: playOptions.scrollRate,
longNoteRate: playOptions.longNoteRate,
sevenToNinePattern: playOptions.sevenToNinePattern,
sevenToNineType: playOptions.sevenToNineType,
battleMode: playOptions.battleMode,
dBattleScratch: playOptions.dBattleScratch,
gauge2P: playOptions.gauge2P,
mRan1P: playOptions.mRan1P,
mRan2P: playOptions.mRan2P,
longNoteMode: playOptions.longNoteMode,
lr2ExtraMode: playOptions.lr2ExtraMode,
lr2ExtraLevel: playOptions.lr2ExtraLevel,
lr2Mania: {
addNotes: playOptions.lr2AddNotes,
loudness: playOptions.lr2Loudness,
addLongNotes: playOptions.lr2AddLongNotes,
addMines: playOptions.lr2AddMines,
},
extraNoteDepth: playOptions.extraNoteDepth,
extraNoteScratch: playOptions.extraNoteScratch,
gaugeAutoShift: playOptions.gaugeAutoShift,
bmsonTotalMode: playOptions.bmsonTotalMode,
bottomShiftableGauge: playOptions.bottomShiftableGauge,
randomSeed1P: playOptions.randomSeed1P,
randomSeed2P: playOptions.randomSeed2P,
randomFixedLane1P: playOptions.randomFixedLane1P,
randomFixedLane2P: playOptions.randomFixedLane2P,
lr2RandomScratch1P: playOptions.lr2RandomScratch1P,
lr2RandomScratch2P: playOptions.lr2RandomScratch2P,
classicHiSpeed: playOptions.classicHiSpeed,
floatingHiSpeed: playOptions.floatingHiSpeed,
fixedDisplayArea: playOptions.fixedDisplayArea,
normalHiSpeedLevel: playOptions.normalHiSpeedLevel,
visualConstant: playOptions.visualConstant,
noteDurationMs: playOptions.noteDurationMs,
lift1P: playOptions.lift1P,
lift2P: playOptions.lift2P,
liftOn1P: playOptions.liftOn1P,
liftOn2P: playOptions.liftOn2P,
constantFadeMs: playOptions.constantFadeMs,
hsFix: playOptions.hsFix,
recordingOptionState: { ...playOptions },
...(options.allowSeek !== undefined ? { allowSeek: options.allowSeek } : {}),
...(kit.family === 'beatoraja' ? BEATORAJA_PLAY_SETTINGS : {}),
...(course !== undefined
? {
course: course.stage,
...(course.view !== undefined ? { courseInfo: course.view } : {}),
...(course.practice === true ? { practice: true } : {}),
}
: {}),
...(options.replay !== undefined ? { replay: options.replay } : {}),
...(options.preResolved !== undefined ? { preResolved: options.preResolved } : {}),
...resolvePracticeSessionOptions(
playOptions,
settings.judgeRuleset,
course === undefined && options.replay === undefined,
options.practiceRange,
),
audio: options.audio,
onExit: () => on.exit(),
onRestart: () => on.restart(),
onChartFinished: (result) => on.finish(result, result.replay),
...(on.judgeTiming !== undefined ? { onJudgeTimingChange: (value: number) => on.judgeTiming?.(value) } : {}),
...(on.hiSpeed !== undefined
? {
onHiSpeedChange: (hiSpeed: number, normalLevel?: number, floating?: boolean) =>
on.hiSpeed?.(hiSpeed, normalLevel, floating),
}
: {}),
...(on.tempo !== undefined ? { onTempoChange: (tempo: number) => on.tempo?.(tempo) } : {}),
...(on.skinAdjust !== undefined ? { onSkinAdjustChange: (adjust: SkinAdjust) => on.skinAdjust?.(adjust) } : {}),
},
theme,
);
sceneSession = new PlaySceneSession(play, {
chart: options.chart,
...(course?.view !== undefined ? { course: course.view } : {}),
playOptions,
...(options.scoreTargets !== undefined ? { scoreTargets: options.scoreTargets } : {}),
...(options.rankingTarget !== undefined ? { rankingTarget: options.rankingTarget } : {}),
...(options.playerName !== undefined ? { playerName: options.playerName } : {}),
audio: options.audio,
...(options.sounds !== undefined ? { sounds: options.sounds } : {}),
// A ghost draws a field of its own (a second playfield, marks over the lanes) only on a built-in family view.
showsGhost: () => familySlot.current?.view.family === 'built-in',
});
// The views draw with the session's settings: the host's, with what the session resolved from them.
viewOptions.settings = play.options;
familySlot.current = createPlayView(kit, play, viewOptions, sceneSession, textures);
return new FamilyPlayScene(
sceneSession,
familySlot as FamilySlot,
{
chart: options.chart,
...(options.source !== undefined ? { source: options.source } : {}),
...(options.host !== undefined ? { host: options.host } : {}),
audio: options.audio,
soundOwner: sceneSession,
viewOptions,
textures,
},
{
// The play listens for its own keys (`play-input.ts`), so the scene listens for none.
keyTarget: options.keyTarget ?? NO_KEYS,
...(options.now !== undefined ? { now: options.now } : {}),
},
);
}
const NO_KEYS = { addEventListener: (): void => {}, removeEventListener: (): void => {} };
/**
* What a beatoraja play runs with over the host's settings: beatoraja's cover keys. The lane options (RANDOM, MIRROR,
* S-RANDOM), HS-FIX and the lane covers it starts with are the host's, as on every family.
*/
const BEATORAJA_PLAY_SETTINGS: Pick<PlaySessionOptions, 'coverKeys'> = {
coverKeys: true,
};
/**
* PRACTICE for a single fresh play, under every judge ruleset (#933): the bars picked and the rules read under the ruleset
* (`resolvePracticeSelection`), a practice play saving nothing, and no chart modifier, as beatoraja applies them only in
* PLAY / AUTOPLAY.
*/
function resolvePracticeSessionOptions(
playOptions: Readonly<PlayOptions>,
ruleset: RulesetId | undefined,
single: boolean,
range: PracticeRange | undefined,
): Partial<PlaySessionOptions> {
Eif (!playOptions.practice || !single) return {};
return {
practice: true,
practiceRange: resolvePracticeSelection(playOptions, ruleset ?? 'lr2', range),
battleMode: 'OFF',
longNoteModifier: 'OFF',
mineModifier: 'OFF',
crazyJudge: 'OFF',
crazyHellJudge: false,
crazyAddMine: false,
crazyNotes: 'OFF',
scrollModifier: 'OFF',
extraNoteDepth: 0,
lr2ExtraMode: false,
};
}
/** beatoraja's name for each guide sound slot, in its judge order. */
const GUIDE_SOUND_NAMES: readonly (readonly [GuideSound, GuideSoundSlot])[] = [
['PG', 'guidePG'],
['GR', 'guideGR'],
['GD', 'guideGD'],
['BD', 'guideBD'],
['PR', 'guidePR'],
['MS', 'guideMS'],
];
/** The guide sound of each judgment a sound set has: its `guidePG` to `guideMS` slots, by beatoraja's judge names. */
export function resolveGuideSounds(sounds: SystemSoundSet | undefined): Partial<Record<GuideSound, SystemSound>> {
const found: Partial<Record<GuideSound, SystemSound>> = {};
for (const [name, slot] of GUIDE_SOUND_NAMES) {
const sound = sounds?.[slot];
if (sound !== undefined) found[name] = sound;
}
return found;
}
|