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 | 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 21x 126x 21x 21x 21x 26x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 5x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 2x 2x 12x 12x 12x 12x 12x 12x 12x 12x 12x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 13x 13x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 18x 18x 18x 18x 18x 18x 18x 8x 8x 8x 8x 8x 8x 8x 8x 3x 3x 3x 3x 3x 5x 4x 3x 3x 3x 3x 3x 8x 8x 8x 8x 3x 3x 3x 3x 3x 8x 8x 8x 8x 8x 3x 3x 3x 3x 3x 2x 10x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 2x 2x 2x 2x 2x 3x 3x 3x 13x | import { ChartTextOverlay } from '../shared/chart-text.ts';
import type { BGAFeed } from '../../media/bga-camera.ts';
import type { BGAOpacityTimelines } from '@be-music/chart-model';
import { collectBPMGuideEvents, type BPMGuideKinds } from '../../chart/bpm-guide.ts';
import { DisplayAreaInfoOverlay, resolveDisplayAreaLabels } from '../shared/display-area-info.ts';
import { BPMChangeWarningOverlay } from '../shared/bpm-change-warning.ts';
import {
resolveLR2Earthquake,
resolveLR2ManiaVisual,
LR2_SCREEN_HEIGHT,
} from '../shared/playfield/lr2-mania-visual.ts';
import { resolveHiddenNoteChannels } from '../shared/playfield/hidden-note-channels.ts';
import { resolveLaneDim } from '../shared/playfield/lane-brightness.ts';
import { resolveConstantVisibility, resolveWhiteNumber, resolveLaneCover } from '@be-music/player-scene-model';
/**
* The beatoraja family's play screen: a beatoraja play skin (`play_<variant>`) drawn by `BeatorajaPlaySkinView` with the
* play's notes, lane markers and BGA spliced in where the skin authors them (`BeatorajaPlayStage`), its canvas fitted
* into the window. It draws the play session's frames:
*
* - the skin's ops, timers, numbers, texts, graphs and offsets through the bridge ({@link BeatorajaPlayBridge}): the
* frame's `PlayState` and events, the engine's latest frame, resolved by `@be-music/skin-beatoraja/scene`;
* - the notes and markers on the engine's clock at the play state's hi-speed, the BGA from the session's textures;
* - the chart's own images in the skin's synthetic slots (-100 to -102), and the skin's Lua sounds through the audio
* service.
*
* The skin's cover buttons and the mouse wheel come back as cover intents; the cover keys and the hi-speed keys are the
* session's (`PlaySessionOptions.coverKeys`), and the view shows what they set for a moment. The session times the
* play from the view's timing ({@link resolveBeatorajaPlayTiming}): READY follows loading, the chart starts
* after the skin's `playstart` interval, and the play ends over the skin's `fadeout`, or, failed, after its `close`.
*/
import {
buildBaseOpSet,
normalizeBeatorajaNote,
normalizeBeatorajaSliders,
type BeatorajaSkin,
type BeatorajaSkinConfig,
type BeatorajaSkinCustomOffset,
} from '@be-music/skin-beatoraja';
import { withBeatorajaCourseStageOps } from '@be-music/skin-beatoraja/scene';
import type { BeMusicJSON } from '@be-music/chart-source';
import {
createBeatAtSecondsResolverFromTimingResolver,
resolveChartPlayfieldVisual,
type ChartPlayVariant,
} from '@be-music/chart-model';
import type { PlayerGaugeSummary, PlayerUIFrameNote, PlayerUIFramePayload } from '@be-music/player-engine/signals';
import type { ScoreSummary } from '@be-music/player-engine/ruleset';
import type { CourseView, HiSpeedTransition, LibraryChart, PlayState } from '@be-music/player-scene-model';
import type { BeMusicJudgeWindows } from '@be-music/player-skin-sdk';
import { BEATORAJA_HI_SPEED_SCALE } from '@be-music/player-scene-model';
import { Container, Text, type Texture } from 'pixi.js';
import { computeBeatorajaBPMCurve, type BPMCurvePoint } from '../../chart/beatoraja/bpm-curve.ts';
import { flipDPChart } from '../../chart/beatoraja/dp-flip.ts';
import { computeBeatorajaChartMarkers } from '../../chart/beatoraja/markers.ts';
import {
computeBeatorajaChartNoteDistribution,
type BeatorajaChartNoteDistribution,
} from '../../chart/beatoraja/note-distribution.ts';
import type { BrowserAssetSource } from '../../collection/types.ts';
import type { BeatorajaKit } from '../../host/family-kit.ts';
import { logger } from '../../logger.ts';
import type { BGACue, NonstopBGAStage, NonstopStageBGATimeline } from '../../chart/bga-timeline.ts';
import { DESIGN_HEIGHT, DESIGN_WIDTH, KEY_ON_FADE_OUT_MS } from '../../stage/design.ts';
import type { PixiSceneHost } from '../../host/scene-host.ts';
import type { BeatorajaSkinAudio } from '../../skin/beatoraja/audio.ts';
import type { PlayReplayViewScale } from '../../session/play/play-session-theme.ts';
import { playEndingFadeAlpha } from '../shared/play-frame.ts';
import { uploadTextures } from '../shared/texture-upload.ts';
import { TouchLaneInput } from '../shared/touch-lane-input.ts';
import type {
IntentSink,
PlayFrame,
PlayIntent,
PlayView,
PlayViewSetting,
PlayViewTiming,
PlayfieldSkin,
} from '../types.ts';
import { resolveBeatorajaOptionRef } from './option-refs.ts';
import { BeatorajaPlayBridge, type BeatorajaPlayEngineInput } from './play-bridge.ts';
import { BeatorajaPlayStage, type BeatorajaPlayBGA, type BeatorajaPlayChartLayout } from './play-stage.ts';
import { createBeatorajaLaneTimelines, createBeatorajaScrollMapper } from './play/scroll-placement.ts';
import { readJudgeComboMetrics } from './play/skin-metrics.ts';
import { BeatorajaViewChartImages, resolveBeatorajaFadeOutMs } from './scene-frame.ts';
const log = logger('beatoraja-gameplay');
/** @deprecated The legacy fixed lead-in. Play timing now uses the skin's `playstart` (zero when omitted). */
export const BEATORAJA_PLAY_LEAD_IN_MS = 1500;
/** How far the skin's cover buttons move a cover: 5 % of the lane per click (Shift reverses). */
const COVER_BUTTON_STEP = 0.05;
/** The wheel moves SUDDEN+ by 0.5 % of the lane per tick, 2.5 % with Shift. */
const WHEEL_COVER_STEP = 0.005;
const WHEEL_COVER_STEP_SHIFT = 0.025;
/** The view-setting feedback shows fully for 800 ms, then fades over 600 ms. */
const INDICATOR_HOLD_MS = 800;
const INDICATOR_FADE_MS = 600;
/** The skin's buttons that move the covers: `LANECOVER` (330), `LIFT` (331), `HIDDEN` (332). */
const BUTTON_LANECOVER = 330;
const BUTTON_LIFT = 331;
const BUTTON_HIDDEN = 332;
/** The beatoraja scale the replay reads the hi-speed on: a lane is four beats at hi-speed 1. */
const BEATORAJA_REPLAY_VIEW: PlayReplayViewScale = { scale: BEATORAJA_HI_SPEED_SCALE, laneBeats: 4 };
/** The skin's input/loading offsets and its READY interval; omitted beatoraja timings default to zero. */
export function resolveBeatorajaPlayTiming(
skin: Pick<BeatorajaSkin, 'fadeout' | 'close' | 'input' | 'loadstart' | 'loadend' | 'playstart' | 'finishmargin'>,
): PlayViewTiming {
const duration = (value: number | undefined) =>
typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
const loadEndOffsetMs = duration(skin.loadstart) + duration(skin.loadend);
const playStartAfterLoadEndMs = duration(skin.playstart);
return {
inputStartOffsetMs: duration(skin.input),
loadEndOffsetMs,
playStartOffsetMs: loadEndOffsetMs + playStartAfterLoadEndMs,
playStartAfterLoadEndMs,
musicEndDelayMs: 5000,
finishMarginMs: duration(skin.finishmargin),
fadeOutMs: resolveBeatorajaFadeOutMs(skin.fadeout),
closeMs: duration(skin.close),
};
}
/**
* The skin's options as ops (`buildBaseOpSet`), with a course stage's: they pick a destination's `if[]` alternatives
* (beatoraja's per-layout BGA and lane presets) for the whole play.
*/
function resolveSkinConfigOps(
skinConfig: BeatorajaSkinConfig | undefined,
course: CourseView | undefined,
): ReadonlySet<number> {
return withBeatorajaCourseStageOps(buildBaseOpSet(skinConfig?.option), course);
}
/** What the beatoraja play view reads of the running play: the play session's members of these names. */
export interface BeatorajaPlayRuntime {
/** The scratch lanes AUTO SCRATCH plays; empty when it is off. */
readonly autoScratchChannels: ReadonlySet<string>;
readonly chart: LibraryChart | undefined;
/** The chart as the play plays it (its `#RANDOM` branches drawn), before DP FLIP. */
readonly resolvedChart: BeMusicJSON | undefined;
readonly resolvedPlayChart:
| {
readonly timing?: import('@be-music/chart-model').TimingResolver;
readonly reversal?: BeatorajaPlayChartLayout['reversal'];
readonly scroll?: readonly import('@be-music/chart-model').ScrollTimelinePoint[];
readonly speed?: readonly import('@be-music/chart-model').SpeedTimelinePoint[];
}
| undefined;
readonly chartPlayVariant: ChartPlayVariant;
/** The camera the BGA frame shows in place of the chart's BGA (`PlayScene.setBGACamera`). */
readonly bgaCamera?: BGAFeed | undefined;
/** An LRX chart's composited BGA, shown when no camera is. */
readonly lrxBGA?: BGAFeed | undefined;
/** The play's Visual CONSTANT switch and the course's NO_SPEED lock, which decide whether `#SPEED` scrolls. */
readonly options?: { readonly visualConstant?: boolean; readonly hiSpeedLocked?: boolean };
readonly notes: readonly PlayerUIFrameNote[];
/** The notes the lanes draw before the engine's first frame: `notes`, and a seamless PRACTICE loop's next round. */
readonly drawNotes: readonly PlayerUIFrameNote[];
readonly mineNotes: readonly PlayerUIFrameNote[];
readonly invisibleNotes: readonly PlayerUIFrameNote[];
/** The engine's latest frame; `undefined` before its first. */
readonly engineFrame: Readonly<PlayerUIFramePayload> | undefined;
/** The engine's counts as the play started (all 0 but the total), for the intro before its first frame. */
readonly score: ScoreSummary;
readonly gaugeState: PlayerGaugeSummary;
readonly scrollHiSpeed: HiSpeedTransition;
readonly bgaTextures: ReadonlyMap<string, Texture>;
readonly bgaSubRegionOrigins?: ReadonlyMap<string, { x: number; y: number }>;
readonly bgaLayerTextures: ReadonlyMap<string, Texture>;
readonly bgaVideos: ReadonlyMap<string, { video: HTMLVideoElement }>;
readonly poorBGAMode?: 0 | 1 | 2;
readonly bgaTimeline: {
base: BGACue[];
layer: BGACue[];
layer2?: BGACue[];
poor: BGACue[];
opacity?: BGAOpacityTimelines;
};
/** A stitched NONSTOP chart's cues split by stage (`splitNonstopBGATimeline`), for the BGA's crossfade at a seam. */
readonly nonstopBGATimelines: readonly NonstopStageBGATimeline[] | undefined;
readonly assetsLoading: boolean;
readonly exiting: boolean;
readonly exitFadeStartedAt: number | undefined;
readonly exitFadeOutMs: number;
readonly playMoments: { readonly failedAtMs?: number };
/**
* The windows the engine judges the play by (its judge ruleset's, after the debug override), once it has started;
* the timing visualizer's bands show the key lanes' ones.
*/
readonly judgeWindows: BeMusicJudgeWindows | undefined;
readonly disposed: boolean;
playClock(): number;
currentSeconds(): number;
/** True once the play's intro timeline has started. Absent on a stand-in that never starts. */
hasSceneStarted?(): boolean;
isIntroPlaying(): boolean;
resolveChartDurationSeconds(): number;
}
/** What the beatoraja play view draws with besides its kit. */
export interface BeatorajaPlayViewOptions {
/** Show hidden keysound objects as green inspection markers. Off by default. */
readonly showInvisibleNotes?: boolean;
/** Which labels BPM GUIDE shows; beatoraja's BPM and STOP by default. */
readonly bpmGuideKinds?: BPMGuideKinds;
/** The play is AUTO PLAY. */
readonly autoPlay?: boolean;
/** DP FLIP: the chart's sides swap, for the skin's per-side readouts (the notes come flipped from the session). */
readonly dpFlip?: boolean;
/** The course the play is a stage of, with the stage being played. */
readonly course?: CourseView;
/** The stages of a stitched NONSTOP chart (`PlaySessionOptions.nonstop`), whose BGA cross-fades at each seam. */
readonly chartOptionProgram?: import('@be-music/chart-model').ChartOptionProgram;
readonly nonstop?: { readonly stages: readonly (NonstopBGAStage & { readonly backBMP?: string })[] };
/** Where the chart's files are, for its `#STAGEFILE`, `#BACKBMP` and `#BANNER`. */
readonly source?: BrowserAssetSource;
/** Where the skin's Lua sounds play (`main_state.audio_*`); they are silent without it. */
readonly skinSounds?: BeatorajaSkinAudio;
}
/** What the view works out of the chart once it is prepared. */
interface PreparedChart {
readonly chart: BeMusicJSON;
readonly analysis: BeatorajaChartNoteDistribution;
readonly bpmCurve: readonly BPMCurvePoint[];
readonly layout: BeatorajaPlayChartLayout;
}
/** The beatoraja play view. See the module comment. */
export class BeatorajaPlayView implements PlayView {
private readonly displayInfo = new DisplayAreaInfoOverlay();
private readonly bpmChangeWarning = new BPMChangeWarningOverlay();
private readonly chartText = new ChartTextOverlay();
public readonly family = 'beatoraja' as const;
public readonly root: Container = new Container();
public readonly timing: PlayViewTiming;
/** How the view answers the session: the skin's canvas and the beam fade. */
public readonly playfieldSkin: PlayfieldSkin;
/**
* The canvas under the fingers: no touch lanes (the skin owns its lanes and lays none out for the playfield), but a
* finger still keeps the page from scrolling or zooming, as on every play screen.
*/
private readonly touchLanes: TouchLaneInput = new TouchLaneInput({
stage: () => this.playfieldSkin.stage,
lanes: () => [],
liftCount: () => 0,
});
private kit: BeatorajaKit;
private readonly play: BeatorajaPlayRuntime;
private readonly options: BeatorajaPlayViewOptions;
private showInvisibleNotes: boolean;
private bpmGuideKinds: BPMGuideKinds | undefined;
private readonly chartImages: BeatorajaViewChartImages;
private prepared: PreparedChart | undefined;
private bridge: BeatorajaPlayBridge | undefined;
private playOptions: PlayFrame['playOptions'] | undefined;
private stage: BeatorajaPlayStage | undefined;
private host: PixiSceneHost | undefined;
/** The host the play loads on, for the GPU upload of its BGA before the view is attached. */
private uploadHost: PixiSceneHost | undefined;
private emit: IntentSink<PlayIntent> | undefined;
/** READY has been reached: the notes stand at the chart's start until the engine's first frame. */
private loaded = false;
private wasPaused = false;
private state: PlayState | undefined;
private indicator: Text | undefined;
private indicatorShownAt = 0;
private disposed = false;
public constructor(kit: BeatorajaKit, play: BeatorajaPlayRuntime, options: BeatorajaPlayViewOptions = {}) {
this.kit = kit;
this.play = play;
this.options = options;
this.showInvisibleNotes = options.showInvisibleNotes === true;
this.bpmGuideKinds = options.bpmGuideKinds;
this.timing = resolveBeatorajaPlayTiming(kit.kit.skin);
this.chartImages = new BeatorajaViewChartImages(
play.chart,
options.source,
options.nonstop !== undefined
? { stages: options.nonstop.stages, currentSeconds: () => play.currentSeconds() }
: undefined,
);
const skin = kit.kit.skin;
this.playfieldSkin = {
stage: {
width: typeof skin.w === 'number' && skin.w > 0 ? skin.w : DESIGN_WIDTH,
height: typeof skin.h === 'number' && skin.h > 0 ? skin.h : DESIGN_HEIGHT,
},
ownsLanes: true,
laneRect: () => undefined,
noteCell: () => undefined,
measureLines: () => undefined,
bgaTargets: () => {},
bombCell: () => undefined,
bombDurationMs: () => 0,
keyOnFadeMs: () => KEY_ON_FADE_OUT_MS,
};
}
/** Keeps `host` for the GPU upload of what the play loads before the view is attached. */
public prepareOn(host: PixiSceneHost): void {
this.uploadHost = host;
}
/**
* Starts the skin's scene timers from the clock when this view joins a play already running. Those moments were
* delivered to the view it replaces; without them a beatoraja skin stays on its loading frame.
*/
public joinRunningPlay(): void {
const bridge = this.bridge;
if (bridge === undefined || this.play.hasSceneStarted?.() !== true) return;
const now = this.play.playClock();
const chartStarted = !this.play.isIntroPlaying();
const at = chartStarted ? now - Math.max(0, this.play.currentSeconds()) * 1000 : now;
bridge.joinRunning(at, chartStarted);
}
/** Toggles the inspection overlay without restarting the play. */
public setShowInvisibleNotes(enabled: boolean): void {
this.showInvisibleNotes = enabled;
}
/** Changes which labels BPM GUIDE shows, from the next frame. */
public setBPMGuideKinds(kinds: BPMGuideKinds): void {
this.bpmGuideKinds = kinds;
}
/**
* Gets the skin ready for the play once its chart is prepared (the session's `prepareView`): the chart as the play
* plays it (DP FLIP applied for the skin's per-side readouts), its BPM graph, note distribution, markers and scroll,
* the bridge, the skin with the notes and markers, and the chart's own images.
*/
public async prepare(): Promise<void> {
Iif (this.disposed || this.prepared !== undefined) return;
const play = this.play;
const resolved = play.resolvedChart ?? play.chart?.chart;
Iif (resolved === undefined) return;
const chart = this.options.dpFlip === true ? flipDPChart(resolved) : resolved;
const skin = this.kit.kit.skin;
// Visual CONSTANT ignores `#SPEED` (`LaneRenderer`'s `speed` is 1), unless a NO_SPEED course turns it off.
const constant = resolveConstantVisibility({
enabled: play.options?.visualConstant,
noSpeed: play.options?.hiSpeedLocked,
});
const scrollMapper = createBeatorajaScrollMapper(chart, { ignoreSpeed: constant.enabled });
const laneTimelines = scrollMapper !== undefined ? createBeatorajaLaneTimelines(chart) : undefined;
const timeMarkers = normalizeBeatorajaNote(skin.note).time.length > 0;
const resolvedPlay = play.resolvedPlayChart;
const guideEvents = resolvedPlay?.timing
? collectBPMGuideEvents(resolvedPlay.timing, resolvedPlay.scroll, resolvedPlay.speed)
: [];
this.prepared = {
chart,
analysis: computeBeatorajaChartNoteDistribution(chart),
bpmCurve: computeBeatorajaBPMCurve(chart),
layout: {
variant: play.chartPlayVariant,
scrollMapper,
timelineBeats: laneTimelines?.beats,
beatToSeconds: laneTimelines?.beatToSeconds ?? play.resolvedPlayChart?.timing?.beatToSeconds,
beatAtSeconds: play.resolvedPlayChart?.timing
? createBeatAtSecondsResolverFromTimingResolver(play.resolvedPlayChart.timing)
: undefined,
reversal: play.resolvedPlayChart?.reversal,
// One-second time ticks when the skin authors `time[]` markers.
markers: {
...computeBeatorajaChartMarkers(chart, {
timeIntervalSec: timeMarkers ? 1 : undefined,
totalSeconds: undefined,
}),
bpm: guideEvents.filter((event) => event.kind === 'bpm').map((event) => event.beat),
stop: guideEvents.filter((event) => event.kind === 'stop').map((event) => event.beat),
},
guideEvents,
autoPlay: this.options.autoPlay === true,
},
};
this.bridge = this.createBridge(chart);
this.buildStage();
log.info('beatoraja play prepared', {
variant: play.chartPlayVariant,
skin: { w: this.stage?.width, h: this.stage?.height, name: skin.name },
autoPlay: this.options.autoPlay === true,
});
await this.chartImages.load();
}
private createBridge(chart: BeMusicJSON): BeatorajaPlayBridge {
const { skin, skinConfig } = this.kit.kit;
// The LIFT and HIDDEN+ move across the lane's height: the skin's lane cover slider range.
const laneHeight = normalizeBeatorajaSliders((skin as { slider?: unknown }).slider).find(
(s) => s.type === 4,
)?.range;
const bridge = new BeatorajaPlayBridge({
chartPlayVariant: this.play.chartPlayVariant,
baseOps: resolveSkinConfigOps(skinConfig, this.options.course),
autoPlay: this.options.autoPlay === true,
chart,
skinHeaderName: skin.name,
skinHeaderAuthor: skin.author,
directoryLabel: this.play.chart?.directoryLabel,
...(this.options.course !== undefined ? { courseInfo: this.options.course } : {}),
...(laneHeight !== undefined ? { laneHeight } : {}),
judgeComboMetrics: readJudgeComboMetrics(skin),
...(this.options.skinSounds !== undefined ? { skinSounds: this.options.skinSounds } : {}),
});
applyCustomOffsets(bridge, skin.offset, skinConfig?.customOffset);
return bridge;
}
/** Builds the stage for the kit's skin (again, after the player changed its options) and puts it in the root. */
private buildStage(): void {
const prepared = this.prepared;
const bridge = this.bridge;
Iif (prepared === undefined || bridge === undefined) return;
const previous = this.stage;
const kit = this.kit.kit;
const analysis = prepared.analysis;
const stage = new BeatorajaPlayStage(
kit,
resolveSkinConfigOps(kit.skinConfig, this.options.course),
prepared.layout,
{
resolveRefValue: (ref) => {
// The chart as played, its undefined long notes given the player's LN MODE.
const playedChart = this.play.resolvedChart ?? this.play.chart?.chart;
return (
resolveBeatorajaOptionRef(ref, {
...(playedChart !== undefined ? { chart: playedChart } : {}),
...(this.playOptions !== undefined ? { playOptions: this.playOptions } : {}),
}) ?? bridge.resolveRefValue(ref)
);
},
resolveTextContent: (ref) => bridge.resolveTextContent(ref),
resolveNumberValue: (ref) => bridge.resolveNumberValue(ref),
resolveFontFamily: kit.fonts !== undefined ? (id) => kit.fonts!.family(id) : undefined,
resolveFontKind: kit.fonts !== undefined ? (id) => kit.fonts!.kind(id) : undefined,
resolveGraphValue: (type) => bridge.resolveGraphValue(type),
resolveGraphPolyline: (type) => bridge.resolveGraphPolyline(type),
resolveSliderValue: (type) => bridge.resolveSliderValue(type),
resolveGaugePercent: () => bridge.resolveGaugePercent(),
resolveBPMGraphPoints: () => prepared.bpmCurve,
resolveBPMGraphData: () =>
analysis.bpmSegments.length === 0 || analysis.totalMs <= 0
? undefined
: {
segments: analysis.bpmSegments,
mainBPM: analysis.mainBPM,
minBPM: analysis.minBPM,
maxBPM: analysis.maxBPM,
totalMs: analysis.totalMs,
},
resolveJudgeGraphBars: (type) => bridge.resolveJudgeGraphBars(type),
resolveJudgeStateBuckets: (type) => bridge.resolveJudgeStateBuckets(type),
resolveNoteDistribution: () =>
analysis.buckets.length === 0
? undefined
: { buckets: analysis.buckets, maxCount: analysis.maxCount, totalMs: analysis.totalMs },
resolveTimingSamples: () => bridge.resolveTimingSamples(),
resolveTimingJudgeWindows: () => bridge.resolveTimingJudgeWindows(),
// The playhead on `bpmgraph` / `notes-graph`, from the engine's frame; hidden before its first.
resolveCurrentTimeMs: () => {
const seconds = this.play.engineFrame?.currentSeconds;
return seconds !== undefined && Number.isFinite(seconds) ? Math.max(0, seconds * 1000) : undefined;
},
chartImageProvider: (id) => this.chartImages.resolve(id),
onButtonAction: (act, modifiers) => this.handleSkinButton(act, modifiers),
},
);
if (previous !== undefined) {
previous.dispose();
Iif (!this.play.assetsLoading) stage.addBGA(this.bgaOf());
}
this.stage = stage;
this.root.addChildAt(stage.root, 0);
}
/** The session's BGA as the BGA layer draws it: the base track over the base textures, the layer over its own. */
private bgaOf(): BeatorajaPlayBGA {
const play = this.play;
const nonstop = this.options.nonstop;
return {
textures: play.bgaTextures,
subRegionOrigins: play.bgaSubRegionOrigins,
layerTextures: play.bgaLayerTextures,
videos: new Map([...play.bgaVideos].map(([key, { video }]) => [key, video] as const)),
cues: play.bgaTimeline,
poorBGAMode: play.poorBGAMode,
chartOptionProgram: this.options.chartOptionProgram,
...(nonstop !== undefined && play.nonstopBGATimelines !== undefined
? { nonstop: { stages: nonstop.stages, timelines: play.nonstopBGATimelines } }
: {}),
};
}
public attach(host: PixiSceneHost, emit: IntentSink<PlayIntent>): void {
Iif (this.disposed) return;
this.host = host;
this.emit = emit;
Eif (typeof window !== 'undefined') window.addEventListener('wheel', this.handleWheel, { passive: false });
this.touchLanes.attach(host, emit);
Eif (this.stage) this.displayInfo.attachCanvas(this.stage.canvas);
Eif (this.stage) this.bpmChangeWarning.attachCanvas(this.stage.canvas);
}
public detach(): void {
this.displayInfo.detach();
this.bpmChangeWarning.detach();
this.chartText.detach();
this.touchLanes.detach();
if (typeof window !== 'undefined') window.removeEventListener('wheel', this.handleWheel);
this.host = undefined;
this.emit = undefined;
}
public draw(frame: PlayFrame): void {
const stage = this.stage;
const bridge = this.bridge;
const host = this.host;
this.root.visible = frame.shown;
if (!frame.shown) this.displayInfo.hide();
if (!frame.shown) this.bpmChangeWarning.hide();
if (!frame.shown) this.chartText.hide();
if (stage === undefined || bridge === undefined || host === undefined || !frame.shown || this.disposed) return;
stage.fitTo(host);
const play = this.play;
this.state = frame.state;
this.playOptions = frame.playOptions;
for (const event of frame.events) {
if (event.kind === 'load-end') this.loaded = true;
else Iif (event.kind === 'view-setting') this.showViewSetting(event.setting, frame.state);
}
// The BGA goes in once it has loaded (before READY), and its video plays on after a pause.
if (!stage.hasBGA && !play.assetsLoading) stage.addBGA(this.bgaOf());
const paused = frame.stage === 'paused';
Iif (this.wasPaused && !paused) stage.resumeBGA();
this.wasPaused = paused;
const context = bridge.update({
judgeTimingMs: frame.playOptions.judgeTimingMs,
visualConstant: frame.playOptions.visualConstant,
judgeTimingAutoAdjust: frame.playOptions.judgeTimingAutoAdjust,
hideJudgeDisplay: frame.playOptions.judgeDisplay === 'OFF',
chartPlayfield: resolveChartPlayfieldVisual(
play.engineFrame?.chartOptions,
play.engineFrame?.currentSeconds ?? frame.seconds,
),
nowMs: play.playClock(),
hostNowMs: frame.clock.nowMs,
state: frame.state,
...withEngine(this.engineInput()),
...(play.judgeWindows !== undefined ? { judgeWindows: play.judgeWindows } : {}),
events: frame.events,
exiting: play.exiting,
scoreTargets: frame.scoreTargets,
});
// The notes stand at the chart's start from READY until the engine's first frame, as the engine's lead-in held them.
const engineFrame = play.engineFrame;
const clock =
engineFrame ??
(this.loaded
? {
notes: play.drawNotes,
landmineNotes: play.mineNotes,
invisibleNotes: play.invisibleNotes,
currentSeconds: 0,
currentBeat: 0,
}
: undefined);
stage.draw(context, clock, play.scrollHiSpeed.valueAt(performance.now()), bridge, {
tempo: engineFrame?.clock?.tempo ?? 1,
paused,
started: !play.isIntroPlaying(),
showInvisibleNotes: this.showInvisibleNotes,
...((play.bgaCamera ?? play.lrxBGA) !== undefined ? { camera: (play.bgaCamera ?? play.lrxBGA)! } : {}),
bpmGuide: frame.playOptions.bpmGuide,
...(this.bpmGuideKinds !== undefined ? { bpmGuideKinds: this.bpmGuideKinds } : {}),
judgeTimingMs: frame.playOptions.judgeTimingMs,
hiddenNoteChannels: resolveHiddenNoteChannels(frame.playOptions.autoScratchNotes, play.autoScratchChannels),
...(frame.playOptions.showJudgeArea && play.judgeWindows !== undefined ? { judgeArea: play.judgeWindows } : {}),
markProcessedNotes: frame.playOptions.markProcessedNotes,
laneDim: resolveLaneDim(frame.playOptions.laneBrightness),
constant: resolveConstantVisibility({
enabled: frame.playOptions.visualConstant,
durationMs: frame.playOptions.noteDurationMs,
fadeMs: frame.playOptions.constantFadeMs,
noSpeed: frame.state.view.hiSpeed.locked,
}),
});
// A failed play's picture fades with its sound; on a normal end the skin draws its own fade-out.
Iif (play.exiting && play.playMoments.failedAtMs !== undefined && play.exitFadeStartedAt !== undefined) {
stage.canvas.alpha = playEndingFadeAlpha(play.playClock() - play.exitFadeStartedAt, play.exitFadeOutMs);
}
const overlayLanes = stage.getDisplayAreaLanes(context.activeOps, frame.playfield.laneChannels);
this.displayInfo.attachCanvas(stage.canvas);
this.displayInfo.update(
resolveDisplayAreaLabels({
mode: frame.playOptions.displayAreaInfo,
lanes: overlayLanes,
covers: frame.state.view.covers.map(resolveLaneCover),
visibleMs: (cover) =>
resolveWhiteNumber({
laneBeats: 4,
hiSpeed: frame.state.view.hiSpeed.drawn,
sudden: cover.sudden,
bpm: frame.bpm ?? 0,
scrollRate: frame.playfield.scrollMapper?.rateAt?.(frame.playfield.currentBeat(frame.seconds)) ?? 1,
}),
}),
{ width: stage.width, height: stage.height },
host.app.screen,
stage.canvas.alpha,
);
this.chartText.attachCanvas(stage.canvas);
this.chartText.show(frame.chartText ?? '', stage, host.app.screen, stage.canvas.alpha);
// LR2's EARTHQUAKE sways the whole play screen.
const quake = resolveLR2Earthquake(
resolveLR2ManiaVisual(frame.playOptions),
play.playClock(),
host.app.screen.height / LR2_SCREEN_HEIGHT,
);
this.root.position.set(quake.x, quake.y);
this.bpmChangeWarning.attachCanvas(stage.canvas);
this.bpmChangeWarning.show({
enabled: frame.playOptions.bpmChangeWarning,
timing: play.resolvedPlayChart?.timing,
seconds: frame.seconds,
lanes: overlayLanes,
stage: { width: stage.width, height: stage.height },
screen: host.app.screen,
opacity: stage.canvas.alpha,
resolution: host.app.renderer.resolution,
});
this.fadeIndicator();
}
/**
* The engine's frame as the bridge reads it, with the song's length the play state's graphs run over; from READY
* until the engine's first frame, the chart's start with the play's starting score and gauge.
*/
private engineInput(): BeatorajaPlayEngineInput | undefined {
const play = this.play;
const frame = play.engineFrame;
const totalSeconds = play.resolveChartDurationSeconds();
Iif (frame !== undefined) {
return {
currentSeconds: frame.currentSeconds,
currentBeat: frame.currentBeat,
totalSeconds,
...(frame.reversalSeconds !== undefined ? { reversalSeconds: frame.reversalSeconds } : {}),
summary: frame.summary,
hcnLanes: frame.hcnLanes,
judgedNoteCount: frame.judgedNoteCount,
};
}
if (!this.loaded) return undefined;
return { currentSeconds: 0, currentBeat: 0, totalSeconds, summary: { ...play.score, gauge: play.gaugeState } };
}
/** Uploads `textures` to the GPU through the host's renderer, when the view has a host. */
public uploadTextures(textures: Iterable<Texture | undefined>, isCancelled: () => boolean): Promise<void> {
return uploadTextures((this.host ?? this.uploadHost)?.app.renderer, textures, isCancelled);
}
/**
* The beatoraja scale the replay reads the hi-speed on: a lane of four beats. The session takes the visible time at
* the play's main BPM, as on every family's play screen.
*/
public replayView(): PlayReplayViewScale {
return BEATORAJA_REPLAY_VIEW;
}
/**
* Takes the player's new options for the skin: the skin is built again with them (its textures and fonts from the new
* kit) while the play and its bridge carry on, the option ops and the custom offsets replaced. A kit of another skin
* entry is taken the same way.
*/
public updateKit(kit: BeatorajaKit): void {
Iif (this.disposed) return;
this.kit = kit;
const bridge = this.bridge;
Iif (bridge === undefined) return;
bridge.setBaseOps(resolveSkinConfigOps(kit.kit.skinConfig, this.options.course));
applyCustomOffsets(bridge, kit.kit.skin.offset, kit.kit.skinConfig?.customOffset);
this.buildStage();
log.info('beatoraja play skin replaced', {
canvas: { w: this.stage?.width, h: this.stage?.height },
name: kit.kit.skin.name,
});
}
public getStageInfo(): { container: Container; width: number; height: number } {
return this.stage?.getStageInfo() ?? { container: this.root, ...this.playfieldSkin.stage };
}
public dispose(): void {
this.displayInfo.dispose();
this.bpmChangeWarning.dispose();
this.chartText.dispose();
Iif (this.disposed) return;
this.detach();
this.disposed = true;
this.stage?.dispose();
this.stage = undefined;
this.chartImages.dispose();
this.indicator?.destroy();
this.indicator = undefined;
Eif (!this.root.destroyed) this.root.destroy({ children: false });
}
/** A skin's cover button (`LANECOVER` / `LIFT` / `HIDDEN`): a step of the cover, back with Shift. */
private handleSkinButton(act: number, modifiers?: { shift: boolean; ctrl: boolean; alt: boolean }): void {
const emit = this.emit;
if (emit === undefined) return;
const delta = (modifiers?.shift === true ? -1 : 1) * COVER_BUTTON_STEP;
switch (act) {
case BUTTON_LANECOVER:
emit({ type: 'cover', command: { type: 'cover-adjust', part: 'sudden', delta } });
return;
case BUTTON_LIFT:
emit({ type: 'cover', command: { type: 'cover-adjust', part: 'lift', delta } });
return;
case BUTTON_HIDDEN: {
// HIDDEN+ off comes on at one step; on, it steps, going off at nothing. A course's lock holds it.
const state = this.state;
const covers = state?.view.covers ?? [];
if (state?.view.hiSpeed.locked === true) return;
if (covers.some((cover) => cover.hiddenOn)) {
emit({ type: 'cover', command: { type: 'cover-adjust', part: 'hidden', delta } });
} else {
emit({
type: 'cover',
command: {
type: 'cover-set',
covers: covers.map((cover) => ({ side: cover.side, hidden: COVER_BUTTON_STEP, hiddenOn: true })),
},
});
}
return;
}
}
}
/** The mouse wheel moves SUDDEN+: down covers more of the lane, up less; faster with Shift. */
private readonly handleWheel = (event: WheelEvent): void => {
Iif (event.deltaY === 0) return;
event.preventDefault();
const step = event.shiftKey ? WHEEL_COVER_STEP_SHIFT : WHEEL_COVER_STEP;
this.emit?.({
type: 'cover',
command: { type: 'cover-adjust', part: 'sudden', delta: (event.deltaY > 0 ? 1 : -1) * step },
});
};
/** Shows what a key set, for a moment: the lane cover, the LIFT, HIDDEN+ or the hi-speed. */
private showViewSetting(setting: PlayViewSetting, state: PlayState): void {
const cover = state.view.covers.find((entry) => entry.side === '1P') ?? state.view.covers[0];
const percent = (fraction: number | undefined): number => Math.round((fraction ?? 0) * 100);
let text: string;
switch (setting) {
case 'sudden':
text = `Lanecover ${percent(cover?.sudden)}%`;
break;
case 'lift':
text = `Lift ${percent(cover?.lift)}%`;
break;
case 'hidden-toggle':
text = cover?.hiddenOn === true ? `Hidden cover ON (${percent(cover.hidden)}%)` : 'Hidden cover OFF';
break;
case 'hidden':
text = cover?.hiddenOn === true ? `Hidden cover ${percent(cover.hidden)}%` : 'Hidden cover OFF';
break;
case 'hi-speed':
text = `Hi-Speed ×${state.view.hiSpeed.player.toFixed(2)}`;
break;
}
const indicator = this.indicatorNode();
indicator.text = text;
// Placed again each time: the skin's canvas size, in the root's (unscaled) space.
indicator.x = (this.stage?.width ?? 0) / 2;
indicator.y = (this.stage?.height ?? 0) * 0.2;
indicator.alpha = 1;
indicator.visible = true;
this.indicatorShownAt = performance.now();
}
private indicatorNode(): Text {
if (this.indicator === undefined) {
const node = new Text({
text: '',
style: {
fontFamily: 'sans-serif',
fontSize: 28,
fill: 0xffe066,
fontWeight: '700',
stroke: { color: 0x000000, width: 4 },
},
});
node.anchor.set(0.5, 0.5);
node.eventMode = 'none';
this.root.addChild(node);
this.indicator = node;
}
return this.indicator;
}
private fadeIndicator(): void {
const indicator = this.indicator;
Eif (indicator === undefined || !indicator.visible) return;
const elapsed = performance.now() - this.indicatorShownAt;
if (elapsed < INDICATOR_HOLD_MS) indicator.alpha = 1;
else if (elapsed < INDICATOR_HOLD_MS + INDICATOR_FADE_MS) {
indicator.alpha = 1 - (elapsed - INDICATOR_HOLD_MS) / INDICATOR_FADE_MS;
} else indicator.visible = false;
}
}
function withEngine(engine: BeatorajaPlayEngineInput | undefined): { engine?: BeatorajaPlayEngineInput } {
return engine !== undefined ? { engine } : {};
}
/**
* Hands the bridge the player's custom offsets (`BeatorajaSkinConfig.customOffset`) by the skin's offset ids
* (`header.offset[]`): the axes each slot exposes, so a destination that lists the id (`offsets: [50]`) moves.
*/
export function applyCustomOffsets(
bridge: Pick<BeatorajaPlayBridge, 'setOffset'>,
schema: ReadonlyArray<BeatorajaSkinCustomOffset> | undefined,
picks: BeatorajaSkinConfig['customOffset'],
): void {
Eif (schema === undefined || schema.length === 0 || picks === undefined) return;
for (const slot of schema) {
const axes = picks[slot.name];
if (axes === undefined) continue;
const next: Partial<{ x: number; y: number; w: number; h: number; r: number; a: number }> = {};
if (slot.x && axes.x !== undefined) next.x = axes.x;
if (slot.y && axes.y !== undefined) next.y = axes.y;
if (slot.w && axes.w !== undefined) next.w = axes.w;
if (slot.h && axes.h !== undefined) next.h = axes.h;
if (slot.r && axes.r !== undefined) next.r = axes.r;
if (slot.a && axes.a !== undefined) next.a = axes.a;
bridge.setOffset(slot.id, next);
}
}
|