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 | 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x 324x | import type { WebAudioSessionSlicePlayback } from '../../runtime/web-audio-session.ts';
import type { BGAOpacityTimelines } from '@be-music/chart-model';
/**
* The state of a play the play session works on, apart from what draws it: the chart and its notes, the audio graph,
* the engine's handles, the play state (gauge, score, judgements, hi-speed and covers), the lane effects, the BGA's
* timelines and textures, the pause and the exit timeline. The modules of the play session (`session/play/*`) and the
* shared playfield read and write it through their own context interfaces; the play views keep their layers apart
* (`PlayLayers`).
*/
import type { BGACameraFeed } from '../../media/bga-camera.ts';
import type { LRXBGACompositor } from '../../media/lrx-bga-compositor.ts';
import type { Texture } from 'pixi.js';
import type { PreparedPlaybackChartData, PlayerSummary } from '@be-music/player-engine';
import { createEmptyScore, type LongNoteStyle, type ScoreSummary } from '@be-music/player-engine/ruleset';
import type { SecondPlayerState } from './play-state.ts';
import type {
PlayerInputSignalBus,
PlayerStateSignals,
PlayerGaugeSummary,
PlayerUIFramePayload,
PlayerUISignalBus,
} from '@be-music/player-engine/signals';
import type { ScrollDistanceMapperLike, TimedPlayableNote } from '@be-music/player-engine/display';
import type { BeMusicReplay, ReplayViewCoalescer } from '@be-music/player-engine/replay';
import {
createPlayState,
DEFAULT_HISPEED,
HiSpeedTransition,
type LaneCover,
type LaneCoverState,
type LibraryChart,
type ReplayViewCursor,
type PlayState,
} from '@be-music/player-scene-model';
import type { BrowserAssetSource } from '../../collection/types.ts';
import type {
AudioBusChannel,
AudioBusHandle,
CompressorMode,
CompressorParams,
TunableCompressor,
} from '../../runtime/audio-bus.ts';
import type { GameplayRecorder } from '../../recording/gameplay-recorder.ts';
import type { PlayTempoRange } from './tempo-range.ts';
import type { PlayChartContext } from './play-chart.ts';
import { PlayPresentation } from './play-presentation.ts';
import { createPlaceholderGaugeState } from './placeholder-gauge.ts';
import type { NonstopStageMixer } from '../../runtime/nonstop-audio.ts';
import type { PixiSceneHost } from '../../host/scene-host.ts';
import type { AudioAnalyzer } from '../../runtime/audio-analysis.ts';
import type { WebAudioSession } from '../../runtime/web-audio-session.ts';
import type { PlayAudioHandle } from '../../runtime/audio-service.ts';
import type { BeMusicEvent, BeMusicJSON } from '@be-music/chart-source';
import type {
RandomDraws,
ResolvedChart,
TimedSampleTrigger,
TimingResolver,
ChartPlayVariant,
} from '@be-music/chart-model';
import type { BGACue, NonstopStageBGATimeline } from '../../chart/bga-timeline.ts';
import type { BPMGuideEvent } from '../../chart/bpm-guide.ts';
import type { BeMusicJudgeWindows } from '@be-music/player-skin-sdk';
import type { RuntimeMineNote, RuntimeNote } from '../../view/shared/playfield/context.ts';
import type { GhostPresentation } from './ghost/ghost.ts';
import { createAudioClockSmoother } from './play-clock.ts';
import type { PlayfieldLaneRect } from '../../view/types.ts';
export class PlaySessionState extends PlayPresentation {
/**
* The host that owns the underlying `Application`. Set by {@link prepare} or {@link enter}, whichever runs first;
* before that, accessing `this.app` throws. See `PixiSceneHost` for the single-Application architecture rationale.
*/
host: PixiSceneHost | undefined;
chart: LibraryChart | undefined;
source: BrowserAssetSource | undefined;
/**
* The chart's `#RANDOM` / `#IF` control flow resolved for THIS play session. `song.chart` is the raw parsed JSON
* (kept for metadata stability), but every gameplay-time consumer — note extraction, timing resolver, sample
* triggers, BGA timeline, measure walk — reads `resolvedChart` so the rolled random branches actually take effect.
* Without this step BMS charts using `#RANDOM` / `#SETRANDOM` / `#SWITCH` either omit every conditional section or
* include them all (depending on parser default), neither of which matches LR2 behavior.
*/
resolvedChart: BeMusicJSON | undefined;
/**
* The Resolved layer of {@link resolvedChart} (`resolveChart`): its notes, tempo map, triggers, SCROLL / SPEED
* keyframes, bar lines and BGA cues are what this scene and the engine play.
*/
resolvedPlayChart: ResolvedChart | undefined;
/** The `#RANDOM` / `#SWITCH` draws {@link resolvedChart} was resolved with; handed to the engine with it. */
randomDraws: RandomDraws | undefined;
randomSeeds: { p1?: string; p2?: string } = {};
/** The chart's own gameplay options and the lane / mine selection they leave (#844); set by `prepareChart`. */
chartPlay: PlayChartContext['chartPlay'] = undefined;
/**
* `seconds → beat` resolver that properly accounts for `#STOP` windows. During a STOP, this returns the same beat
* across the window's duration so the playfield freezes in place. Without it the previous hand-rolled `currentBeat`
* extrapolation would scroll notes through STOP zones at the prevailing BPM, breaking many BMS arrangements that lean
* on STOP for visual emphasis.
*/
beatAtSeconds: ((seconds: number) => number) | undefined;
/**
* Distance integrator that consumes `#SCROLL` and `#SPEED` events. Note Y positions are computed as `lane.bottom -
* distanceBetween(currentBeat, note.beat) * pixelsPerBeat` instead of `(note.beat - currentBeat) * pixelsPerBeat`,
* so: - `#SCROLL,2` doubles the local scroll rate (notes pass twice as fast), - `#SCROLL,-1` reverses the scroll
* direction (notes scroll backwards through the playfield), and - `#SPEED` lerps the visual speed between control
* points. Falls back to plain beat-difference math when no scroll/speed events are present.
*/
scrollMapper: ScrollDistanceMapperLike | undefined;
/** Beats of the chart's lane timelines, for the last timeline beatoraja's rules draw past the lane top. */
laneTimelineBeats: Float64Array = new Float64Array(0);
/**
* Engine's `preparePlaybackChartData` result, computed once during {@link prepareChart} and forwarded to the
* shared engine via `engineOptions.preparedChart`. Holds the canonical `notes` / `landmineNotes` /
* `invisibleNotes` arrays the renderer points at (`this.notes` / `this.mineNotes` / `this.invisibleNotes`
* are the same instances), so any mutation the engine performs on a note's `judged` flag is automatically
* visible to the renderer with no separate sync step. `undefined` until the song has been prepared.
*/
preparedChart: PreparedPlaybackChartData | undefined;
notes: RuntimeNote[] = [];
/** The notes the lanes draw (`PlayfieldRuntime.drawNotes`). */
drawNotes: RuntimeNote[] = [];
/**
* Landmine notes (channels D1-D9 / E1-E9). Sorted by `seconds` for the same binary-search-by-time access pattern the
* playable-note judge loop uses. Hit-test runs in `judge()` BEFORE the playable-note check so a press that lands
* inside the BAD window of both a mine and a regular note prefers the mine — matches LR2 behavior where the mine
* explodes first.
*/
mineNotes: RuntimeMineNote[] = [];
/**
* Invisible / keysound notes (BMS channels `3x` / `4x`). Held separately from {@link notes} because they don't
* participate in scoring or judgement — they exist purely so a press on the matching lane fires the per-note `#WAV`
* sample. The extractor already remaps `3x → 1x` / `4x → 2x` so each entry's `channel` lines up with the playable
* lane it shares.
*
* Always populated so {@link PlaySessionOptions.showInvisibleNotes} can toggle during play. The overlay is a debug
* visualization, not gameplay state. The renderer paints a thin green bar per entry so the chart author's hidden keysound layout is
* legible alongside the regular note stream.
*/
invisibleNotes: TimedPlayableNote[] = [];
maxLongNoteBeatSpan = 0;
chartLastNoteEndSeconds = 0;
chartDurationSeconds = 0;
laneChannels: string[] = [];
/**
* Cached `resolveChartPlayVariant` result for the loaded chart. Used to pick the right per-variant theme layout (LR2
* `play_<variant>` skin, keymode op 160..164), and to switch lane-channel detection to the PMS layout (`17` is a lane
* note, `22..25` are 1P-side lanes) instead of the default That-Which-Must-Not-Be-Named layout. Defaults to `'7'` before any chart is loaded so the existing
* 7K-flavored fallbacks keep behaving as before for skinless / pre-prepare code paths.
*/
chartPlayVariant: ChartPlayVariant = '7';
/** The play variant of the chart a battle mode converted, as LR2's key-mode ops read it. */
battleSourceVariant: ChartPlayVariant | undefined = undefined;
laneX: Map<string, PlayfieldLaneRect> = new Map();
/**
* `playClock()` value captured at `start()`. Theme animations (LR2 timer 0/40/41 — scene-start / READY / play-start)
* anchor here so the intro slide-ins, scratch turntable rotation, and similar visuals play from the
* moment the gameplay view appears, not from the moment notes begin scrolling.
*/
sceneStartTime = 0;
/** Intro length scheduled by `start()` (theme `#PLAYSTART` or the fallback), for chrome count-ins. */
scheduledIntroMs = 0;
startTime = 0;
/**
* True while the chart's assets are still loading: from {@link prepare} until audio is decoded and the BGA preload
* (which may be transcoding video) has settled. Skins show it as NOW LOADING on the lanes.
*/
assetsLoading = false;
/** Estimated preparation progress, from 0 to 1, while assets load. */
loadProgress = 0;
/**
* Between {@link enter} and {@link exit}: the input listeners are attached, and a {@link prepare} running meanwhile
* shows the playfield (in its loading state) instead of loading off stage.
*/
entered = false;
/**
* `audioContext.currentTime` when the play-start gate opened (0 before): the chart's clock until the engine's first
* frame, and what tells the BGA videos the chart has started. From then on the frames drive the chart's clock
* (`PlaySession.currentSeconds`).
*/
audioContextStartTime = 0;
/**
* The audio clock as the playfield draws it: `currentTime` without its render-callback steps
* (`createAudioClockSmoother`), so the notes move by the frame's own time each frame.
*/
readonly drawClock = createAudioClockSmoother();
/** The stage fades and FIT rates of a stitched NONSTOP chart (`options.nonstop`). */
nonstopMixer: NonstopStageMixer | undefined;
paused = false;
pauseTime = 0;
pauseTotal = 0;
/**
* Idempotency / re-entrancy guard for {@link dispose}. ESC → `onExit` → `showSelect` → `dispose` is fine on a single
* press, but a quick double-tap (or a chart-end `setTimeout` racing the keypress) used to fire `dispose` twice and
* crash on the second pass when `app` was already torn down. Now the second call short-circuits immediately.
*/
disposed = false;
audioContext: AudioContext | undefined;
/**
* Audio routing handle. Owns two stable mixers (`keyMixer` for player-input keysounds, `bgmMixer` for auto-triggered
* BGM) plus the per-bus and master compressor stages. Sample sources connect to the appropriate mixer; the bus's
* `setMode` method swaps the downstream wiring without disturbing those source- side connections.
*
* See `audio-bus.ts` for the architecture and per-mode topology.
*/
audioBus: AudioBusHandle | undefined;
/** Analyser tapped off the bus output; feeds audio-reactive Be-Music Skins. */
audioAnalyzer: AudioAnalyzer | undefined;
/** The play's graph as the host's audio service opened it (`options.audio`); undefined when the play made its own. */
playAudio: PlayAudioHandle | undefined;
/**
* Most-recently-applied compressor mode. Distinct from the bus's `mode` getter so we can decide what to flip back to
* when `setAudioCompressor(true)` re-enables compression after a temporary `'off'` (we restore whatever
* `audioCompressorMode` the constructor / URL flag selected).
*/
audioCompressorMode: CompressorMode = 'split';
/** Compressor tuning overrides, seeded from the options and kept across audio-bus rebuilds. */
audioCompressorParams: Partial<Record<TunableCompressor, Partial<CompressorParams>>> = {};
/** User keysound / BGM bus volumes, seeded from the options and kept across audio-bus rebuilds. */
audioVolumes: Record<AudioBusChannel, number> = { key: 1, bgm: 1 };
/**
* Active recorder (canvas video + audio bus tap → WebM blob) when the host has started a recording session via {@link
* startRecording}. `undefined` while idle. We hold the instance across the play session so `stopRecording` /
* `dispose` can finalize cleanly even if the chart ends mid- recording.
*/
recorder: GameplayRecorder | undefined;
/**
* Web Audio session built in {@link prepareAudio} once `decodedSamples` and `wavCmdVolumeMultipliers` are
* populated. Owns every sample-playback path the view used to manage in-tree (player keysound triggers, BGM
* scheduled triggers, landmine explosion, bmson `c=true` continuation, `#WAVCMD` per-slot gain, dynamic
* `#xxx97` / `#xxx98` volume changes). The view simply forwards `event` payloads to it; the session decides
* routing (`keyMixer` / `bgmMixer`), gain splicing, and lifecycle (`stopChannel` for engine-driven LN early
* release in Phase 4b-ii). Stays `undefined` until `prepareAudio` finishes — every call site guards.
*/
webAudioSession: WebAudioSession | undefined;
/**
* Promise returned by {@link runEngineDriver} once the shared-engine play loop is in flight. `undefined` while
* the driver hasn't started yet (engine launches at the same chart-start moment the LR2 PLAYSTART gate fires)
* and after `dispose` triggers a clean abort. Used here only as a "have we already launched" guard so a
* re-entered `start()` (defensive) doesn't kick off a second engine in parallel.
*/
sharedEnginePromise: Promise<unknown> | undefined;
/**
* Forwarded into the engine via `PlayerOptions.signal`. Aborted from {@link dispose} so the engine's
* `throwIfAborted` checks unwind cleanly instead of leaving the playback loop running on a torn-down audio bus.
*/
sharedEngineAbortController: AbortController | undefined;
/**
* Holds the engine's play open past the chart's end (`holdAfterChart`), so keys keep lighting the lanes through the
* result delay and the fade-out; aborted when the outro is over, which lets the play end and hand over its summary.
*/
chartEndHold: AbortController | undefined;
/** Set while the outro waits for the held play to end: receives its final summary. */
onHeldPlayEnded: ((summary: Readonly<PlayerSummary>) => void) | undefined;
/**
* Latch for the engine's `stateSignals.judgeComboTick`. {@link drainWebUISignals} compares the current tick
* value against this latch on every poll and only fires the host's `onJudgeCombo` callback when a fresh
* judge / combo update has landed since the last drain.
*/
sharedEngineLastJudgeComboTick = 0;
/** Bus references handed back from the engine via `onSignalsReady`. Drained per-frame from {@link tick}. */
sharedEngineSignals: { uiSignals: PlayerUISignalBus; stateSignals?: PlayerStateSignals } | undefined;
/**
* Engine-side `inputSignals` bus captured during the input runtime's `onReady` hook. The view's own
* \`togglePause\` (Space-key handler + visibility/blur auto-pause) pushes \`{ kind: 'toggle-pause' }\` here so
* the engine's playback clock pauses in lock-step with the view's \`paused\` flag — without the propagation,
* the engine would keep advancing chart-time during the pause and fast-forward a burst of judges the moment
* the view resumed.
*/
sharedEngineInputSignals: PlayerInputSignalBus | undefined;
/**
* The interrupt the view sent the shared engine (ESC / F5 / teardown), once sent. The engine only reads its abort
* signal at launch, so a play left mid-chart must be interrupted through its input bus: that ends the engine's loop
* and, for ESC, records the replay as given up (`play.aborted`), which {@link waitForReplay} hands the host.
*/
sharedEngineInterrupt: 'escape' | 'restart' | undefined;
/** True once the shared engine settled the chart (every note judged) and holds the play open for the outro. */
sharedEngineChartSettled = false;
/** The lanes the view's touch fingers hold (touch play, the view's `lane` intents), in the order they went down. */
readonly touchLanesHeld: Set<string> = new Set<string>();
/**
* How many times the play has lifted every finger off the touch lanes (each pause): the view forgets the fingers
* down before the latest lift, so they press nothing until they touch down again.
*/
touchLiftCount = 0;
/** Input token a touch on each lane channel presses, from the chart's lane bindings (built on the first touch). */
touchTokenByChannel: Map<string, string> | undefined;
/**
* The engine's latest UI frame (its chart time and beat, the clock it holds at, the chart's length, its summary and
* gauge), as drained into the play state; `undefined` before the engine's first frame. The chart's clock runs on from
* it (`PlaySession.currentSeconds`); a view that draws the engine's own clock (the beatoraja play view) reads it.
*/
engineFrame: Readonly<PlayerUIFramePayload> | undefined;
/** The seek generation of the engine's last `seek` command (0 before the first): older frames are stale. */
/** The skin opened PLAY START, even if engine preparation has not delivered its input bus yet. */
engineStartRequested = false;
seekGeneration = 0;
practice = false;
/** The seeks asked for and not yet applied (`seekPlay`): each resolves once the engine applies its seek or a later one. */
readonly seekWaiters: Array<{ seconds: number; resolve: () => void }> = [];
decodedSamples: Map<string, AudioBuffer> = new Map<string, AudioBuffer>();
/**
* Per-`#WAVxx` slot volume multipliers from `#WAVCMD 01 xx vv` lines, expressed as 0..1 linear gain. Built once per
* chart by {@link prepareChart} via the shared `collectChartVolumeMultipliers` helper, looked up on every
* `playSample` / `playSampleByKey` so a slot with no `#WAVCMD` directive returns `undefined` and the fast path (no
* extra GainNode) takes over.
*
* Pitch / loop bytes (`pp = 00` / `02`) are intentionally NOT collected here: they require sample-graph rewiring
* (playbackRate, loopStart / loopEnd) which the current pipeline doesn't surface yet — see the spec audit. Volume is
* the dominant in-the-wild use of `#WAVCMD`, so this already covers the common case.
*/
wavCmdVolumeMultipliers: Map<string, number> = new Map<string, number>();
/** `#BGAxx` sub-region slot → its authored `dx dy` on the 256x256 BGA canvas. */
readonly bgaSubRegionOrigins: Map<string, { x: number; y: number }> = new Map<string, { x: number; y: number }>();
/**
* bmson per-event slice playback map. For bmson charts `@be-music/chart-model`'s `createBmsonSamplePlaybackMap`
* precomputes which portion of each `sound_channels[]` WAV a given note is supposed to play — `offsetSeconds` is the
* seek-into-file position, `durationSeconds` (when set) caps how long the slice should run. Built once per chart in
* `prepareChart`; the `WebAudioSession` looks each note's event up here and calls `node.start(when, offset, duration)`
* accordingly so the sliced-WAV authoring intent is preserved.
*
* Stays `undefined` for charts other than bmson and LRX: each note plays its entire WAV from t=0.
*/
bmsonSlicePlayback: Map<BeMusicEvent, WebAudioSessionSlicePlayback> | undefined;
autoSampleTriggers: TimedSampleTrigger[] = [];
/**
* The engine's judgment counts and scores, as the readouts show them: under LR2 the POOR counter folds the empty POORs
* in (`resolveDisplayedPoor`).
*/
score: ScoreSummary = createEmptyScore(0);
/**
* The play as every screen reads it (`@be-music/player-scene-model`): the gauge and EX score with their graphs, the combo,
* max combo and course combo, the timed judgments with their early / late counts, and the view (the hi-speed with
* HS-FIX, the lane covers). Fed through `reducePlayState` from the engine's frames, judgments and commands and from
* the player's hi-speed changes; the result is read off it (`playResultFromPlayState`).
*/
playState: PlayState = createPlayState();
/** The 2P player of a two-player play; the session's own score and play state are the 1P player's. */
secondPlayer: SecondPlayerState | undefined = undefined;
/**
* Replay assembled by the shared engine right before its play promise settles (`onReplayRecorded`). Snapshotted
* into {@link getResultData} so the result host can offer it as a download.
*/
replay: BeMusicReplay | undefined;
/** Callers of {@link waitForReplay} waiting for the engine to record the play. */
readonly replayWaiters: Array<(replay: BeMusicReplay) => void> = [];
/**
* How the engine's ruleset plays long notes and its judge windows (ms), from `onRulesetResolved` at engine launch.
* The windows are the ones in force when the chart starts: an LR2 mid-chart `#EXRANKxx` change narrows or widens
* the engine's windows from then on, but is not reflected here.
*/
longNoteStyle: LongNoteStyle | undefined;
judgeWindows: BeMusicJudgeWindows | undefined;
/** The chart's BPM range, worked out once per {@link prepareChart}. */
chartBPMRange: PlayTempoRange | undefined;
/**
* Scratch lanes the engine plays itself under auto-scratch (empty when it is off), resolved per {@link prepareChart}.
* See {@link isAutoplayedChannel}.
*/
autoScratchChannels: ReadonlySet<string> = new Set();
/**
* The lane covers as drawn ({@link resolveLaneCover} of the play state's covers), handed to skins as
* `runtime.laneCovers`; rebuilt only when the play state's covers change.
*/
drawnLaneCovers:
| { covers: readonly LaneCoverState[]; manualSudden: boolean; lineLift: number; drawn: LaneCover[] }
| undefined;
/** Folds the live view into the recorded replay's view changes ({@link updateReplayView}); unset in a replay. */
replayViewCoalescer: ReplayViewCoalescer | undefined;
/** A replay's recorded view along the playhead ({@link updateReplayView}). */
replayViewCursor: ReplayViewCursor | undefined;
chartEndTimeout: number | undefined;
chartEndGate: ((seconds: number) => void) | undefined;
/** Starts the outro's fade-out at once (`PlayEngineContext.chartEndFade`). */
chartEndFade: (() => void) | undefined;
/**
* `setTimeout` handles for the scene-exit sequence (fade-out → close, LR2 timers 2 / 3). Cleared on dispose so the
* deferred host callback can't fire onto a torn-down view.
*/
exitFadeOutHandle: number | undefined;
exitCloseHandle: number | undefined;
/** `playClock()` at which the exit fade-out began; drives {@link applyExitFadeAlpha}. */
exitFadeStartedAt: number | undefined;
/** The picture fade the running exit sequence uses: the theme's fade-out, a failed play's hold on a theme without a close time, or 0. */
exitFadeOutMs = 0;
/**
* Intro / scene-stage timers that gate the load-end / play-start stages (and theme stages such as LR2
* `#STARTINPUT`). These are independent from
* input flash timers and can otherwise retain a disposed gameplay scene until their delay elapses.
*/
readonly sceneStageTimeouts: Set<number> = new Set<number>();
/**
* True once {@link beginExitSequence} starts the exit (the fade-out, or a failed play's stop) before the host
* callback. Re-entry is suppressed so a frantic second ESC press while the fade is animating doesn't leak a second
* callback or restart the timeline.
*/
exiting = false;
/**
* Mirror of the engine's gauge state, refreshed from every `summary.gauge` frame. The gauge model itself
* (per-judge deltas, TOTAL scaling, guts softening, clear rule) lives entirely in the active ruleset — this view
* only renders what the engine reports, so LR2 / beatoraja / That-Which-Must-Not-Be-Named differences need no change here. The placeholder
* below is what renders between scene construction and the first frame.
*/
gaugeState: PlayerGaugeSummary = createPlaceholderGaugeState();
/**
* FAST / SLOW counts. Incremented on every GREAT or GOOD judgement — PERFECT is "on time" so it doesn't count,
* BAD/POOR break combo and aren't tracked here. Mirrors `applyFastSlow` in `packages/player-engine`'s judge core
* (`core/judge-core-score.ts`). Reset per play in `prepareChart`.
*/
fastCount = 0;
slowCount = 0;
/**
* The scroll factor notes, bar lines and long notes are positioned with: it glides to each new drawn hi-speed (the
* play state's `view.hiSpeed.drawn`) over `HISPEED_TRANSITION_MS` (wall clock) instead of jumping, while the HUD /
* readouts show the new target at once. Visual only — judging never reads it.
*/
readonly scrollHiSpeed: HiSpeedTransition = new HiSpeedTransition(DEFAULT_HISPEED);
/**
* BPM-aware seconds → beat resolver, prepared once per song. Used by `renderNotes` to position scrolling notes
* correctly across `#BPM` change events; the previous hand-rolled `beatAtSeconds` only saw the initial BPM, which
* made notes drift through tempo transitions.
*/
timingResolver: TimingResolver | undefined;
/** The chart's BPM GUIDE labels (`collectBPMGuideEvents`), prepared with the timing. */
bpmGuideEvents: readonly BPMGuideEvent[] = [];
/**
* Per-layer BGA cue lists, sorted by chart-time seconds. Each cue's `bmpKey` is the resource key our texture cache is
* keyed by (BMS id like "01" for BMS charts, header.name like "base.png" for bmson). `bmpKey === undefined` is the
* "clear / hide" command (BMS `00`).
*/
/** A stitched NONSTOP chart's base / layer cues split by stage (`options.nonstop`). */
nonstopBGATimelines: NonstopStageBGATimeline[] | undefined;
bgaTimeline: { base: BGACue[]; layer: BGACue[]; layer2?: BGACue[]; poor: BGACue[]; opacity?: BGAOpacityTimelines } = {
base: [],
layer: [],
poor: [],
};
/**
* BMP-resource → decoded `Texture` cache for the **base** + **POOR** tracks. Loaded lazily during `prepareBGA()` so
* the playfield can start displaying samples while background images keep streaming in. Black pixels are preserved
* (this is the bottommost BGA layer).
*/
bgaTextures: Map<string, Texture> = new Map<string, Texture>();
/**
* BMP-resource → decoded `Texture` cache for the **layer** track (`#BMP` channels 07 and 0A). Decoded separately from
* {@link bgaTextures} with a chroma-key that turns pure-black pixels transparent — mirrors the BMS BGA "layer"
* convention used by `packages/player-terminal/src/bga-frame.ts` so the foreground composites cleanly over the base track.
* Even when the same BMP id appears on both tracks we keep two textures because `chroma-key` is destructive.
*/
bgaLayerTextures: Map<string, Texture> = new Map<string, Texture>();
/**
* BMP-key → `<video>` element for video BGA cues (`.mp4` / `.webm` / etc.). `renderBGA` seeks + plays these on cue
* transitions; `dispose` revokes their object URLs.
*
* Stored separately from {@link bgaTextures} only because the sync logic needs the underlying media element — the
* texture itself is also added to `bgaTextures` / `bgaLayerTextures` so the existing renderer paths pick it up
* unchanged.
*/
bgaVideos: Map<string, { video: HTMLVideoElement; objectURL: string }> = new Map<
string,
{ video: HTMLVideoElement; objectURL: string }
>();
/**
* Tracks active BGA videos and the chart-time each cue was seeded at. Single charts use plane slots; NONSTOP
* slots include the stage-owned BMP key so both sides of a crossfade remain active. We use this to
* detect cue transitions in `renderBGA` (start the new cue's video, pause the previous one) and to compute the
* `currentTime` offset relative to the cue's start seconds.
*/
bgaActiveVideos: Record<string, { key: string; cueSeconds: number } | undefined> = {};
/**
* BMS spec — when the chart omits `#POORBGA` and provides `#BMP00`, the BMP00 image acts as the implicit POOR
* placeholder until an explicit `#xxx06` POOR cue takes over. Set during {@link prepareChart} so the renderer can
* paint BMP00 on a miss before any authored POOR event fires; left `undefined` when the chart already authors a
* proper POOR track or doesn't ship a BMP00 fallback. Mirrors the TUI BGA renderer's `poorFallbackKey` plumbing.
*/
poorBGAMode: 0 | 1 | 2 = 0;
poorBGAFallbackKey: string | undefined;
/**
* Chart-time after which the BMP00 POOR fallback yields to the explicit POOR timeline. Equal to the first authored
* POOR cue's `seconds` (or `Infinity` when no POOR cues exist). The renderer compares the chart playhead against this
* so a chart that authors POOR mid-song falls back to BMP00 only during the pre-roll.
*/
poorBGAFallbackUntilSeconds: number = Number.POSITIVE_INFINITY;
/** Whether the chart actually carries any BGA events (drives LR2 op 170/171). */
hasBGA = false;
/**
* The camera the BGA frame shows in place of the chart's BGA, set by the scene (`PlayScene.setBGACamera`). The scene
* owns it and disposes it.
*/
bgaCamera: BGACameraFeed | undefined = undefined;
/** An LRX chart's composited BGA (plugout's transforms and layers 203 / 204), made once its images are loaded. */
lrxBGA: LRXBGACompositor | undefined = undefined;
/** True iff we paused because the tab/window backgrounded itself. */
autoPaused = false;
/**
* Whether `visibilitychange` / `blur` / `pagehide` should auto-pause gameplay. Seeded from `options.autoPauseOnBlur`
* (default `false`). The host can flip it at runtime via {@link setAutoPauseOnBlur} — useful for a Tweakpane toggle
* that lets the user opt into the LR2-desktop-style "pause when I Cmd-Tab away" behavior.
*/
autoPauseOnBlur = false;
/** Last sampled `document.hidden`, used by the polling safety net. */
lastHidden = false;
/** Last sampled `document.hasFocus()`, used by the polling safety net. */
lastFocus = true;
/** `setInterval` handle for the visibility/focus poll loop. */
visibilityPollHandle: number | undefined;
/**
* Resolves when {@link prepareBGA} has loaded every BGA texture. Set in {@link prepare} (without `await`) so the PLAY
* scene can be revealed immediately and the LR2 LOADING phase keeps painting while a long-running ffmpeg.wasm video
* transcode finishes in the background. {@link start} gates the LOAD END timer / chart-start scheduling on this
* promise so the chart itself doesn't begin until the BGA is actually ready.
*/
bgaReadyPromise: Promise<void> | undefined;
/**
* Resolves once the samples have decoded and {@link bgaReadyPromise} has: what {@link start} gates the chart on. A
* play already on the stage when it loads decodes through its intro, so this can still be pending when it starts.
*/
assetsReadyPromise: Promise<void> | undefined;
/** True once the samples have decoded and the engine may be built on them. */
samplesDecoded = false;
/**
* The replay ghost shown beside the play (`ghost/ghost.ts`), once its replay is read and placed; absent without one.
* It only draws, through the frames the scene session hands the view.
*/
ghost: GhostPresentation | undefined;
/**
* Latches at the moment the engine's `manualPlay` / `autoPlay` Promise resolves so the `onChartFinished` /
* `onExit` callback fires at most once. {@link handleSharedEngineChartFinished} is the only writer.
*/
chartEnded = false;
}
|