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 | 46x 5x 5x 5x 5x 5x 5x 3x 3x 3x 3x 3x 5x 3x 3x 3x 3x 3x 5x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 56x 56x 56x 56x 56x 56x 56x 23x 23x 23x 56x 52x 52x 20x 20x 22x 22x 22x 32x 56x | import type { CreatePlayerUIRuntimeContext, PlayerUIRuntime } from '@be-music/player-engine';
import type {
PlayerJudgeComboSignalState,
PlayerStateSignals,
PlayerUICommand,
PlayerUIFramePayload,
PlayerUISignalBus,
} from '@be-music/player-engine/signals';
import { logger } from '../logger.ts';
const log = logger('web-ui-runtime');
/**
* Surface the {@link createWebUIRuntime} adapter exposes to the host gameplay view. The host wires these callbacks
* to its Pixi rendering pipeline; the engine's UI signal bus is the *only* state source the runtime consults, so
* the host stays purely declarative.
*
* Both callbacks are optional — a host that doesn't need a particular hook can omit it. The runtime swallows
* exceptions thrown from the callbacks so a Pixi-side bug doesn't break the engine's main loop.
*/
export interface WebUIRuntimeCallbacks {
/**
* Fired on every `uiSignals.publishFrame()` (typically once per engine tick). Receives the current frame snapshot
* — `currentBeat` / `currentSeconds` / `summary` / `notes` etc. The host should re-render the score panel, lane
* bars, and any other state-driven chrome from this single source.
*/
onFrame?: (frame: Readonly<PlayerUIFramePayload>) => void;
/**
* Fired for every `uiSignals.pushCommand()` event. Currently the engine emits:
* - `flash-lane` — judged note's lane should pulse (manual judge / auto judge).
* - `hold-lane-until-beat` — LN start: keep the lane laser lit until the chart reaches `beat`.
* - `press-lane` / `release-lane` — manual key press / release on this lane.
* - `trigger-poor-bga` — POOR BGA window started (the host typically draws `#xxx06` until `clear-poor-bga`).
* - `clear-poor-bga` — POOR BGA window ended (next note hit, or the timeout elapsed).
* - `long-note-start` / `long-note-end` — a long note's hold began (with the mode it plays in) / finished
* (`complete` or `dropped`).
* - `hell-charge` — a hell charge note passing the judgement line started gaining or draining the gauge, or passed.
*
* The host should switch on `command.kind` and apply the matching visual effect.
*/
onCommand?: (command: PlayerUICommand) => void;
/**
* Fired once when the engine calls `start()` (after the BGA preload promise resolved). Useful for the host to
* reveal its scene graph at the same moment chart playback begins.
*/
onStart?: () => void;
/**
* Fired when the engine calls `stop()` (graceful end-of-chart, ESC abort, restart). The host typically tears down
* any per-chart subscriptions here; full disposal happens in `dispose`.
*/
onStop?: () => void;
/**
* Final teardown. The runtime invokes the host's onDispose AFTER detaching its own listeners, so the host can
* destroy Pixi resources knowing no further frame callbacks will arrive.
*/
onDispose?: () => void;
/**
* Fired when `triggerPoor(seconds)` is called by the engine (e.g. at chart end, when a no-judge POOR fires from
* outside the regular judge path). Most hosts can route this to the same handler as the `trigger-poor-bga`
* command since they ultimately mean the same UI event.
*/
onPoorTriggered?: (seconds: number) => void;
/** Fired when `clearPoor()` is called. Mirror of {@link onPoorTriggered}. */
onPoorCleared?: () => void;
/**
* Fired whenever the engine publishes a fresh judge / combo state through {@link PlayerStateSignals}. The state
* carries the judge kind (`'PERFECT'` / `'GREAT'` / ... — see `PlayerJudgeComboSignalState`), the running combo,
* and the lane channel that produced the verdict. Hosts use this to drive the LR2 NOWJUDGE plate timer and the
* combo readout on the play skin.
*/
onJudgeCombo?: (state: Readonly<PlayerJudgeComboSignalState>) => void;
/**
* Fired once when the runtime is constructed, handing the engine's signal buses back to the host. Hosts that
* already drive their own per-frame loop (rAF in the gameplay view) can use this to call
* {@link drainWebUISignals} from inside that loop, sharing one event-drain pass with their other Pixi work
* instead of spinning up an independent alien-signals subscription. The runtime still fires `onFrame` /
* `onCommand` / `onJudgeCombo` if the host doesn't poll — the two modes are interchangeable; pick whichever
* matches the host's render scheduling.
*/
onSignalsReady?: (signals: { uiSignals: PlayerUISignalBus; stateSignals?: PlayerStateSignals }) => void;
}
/**
* Construction-time inputs for {@link createWebUIRuntime}. The host supplies the engine's signal buses alongside
* its callbacks; the runtime sets up the subscription lifecycle.
*/
export interface WebUIRuntimeOptions extends WebUIRuntimeCallbacks {
uiSignals: PlayerUISignalBus;
/**
* Optional `PlayerStateSignals` bus. The engine emits judge / combo / pause / hi-speed updates through this
* channel separately from `uiSignals`; the runtime drains it inside {@link drainWebUISignals} so a single
* per-frame poll catches both surfaces.
*/
stateSignals?: PlayerStateSignals;
/** Total seconds of playback the engine reports — surfaced through `playbackEndSeconds`. */
playbackEndSeconds?: number;
}
/**
* Web-side adapter for the engine's `PlayerUIRuntime` contract. Subscribes to `uiSignals`'s frameTick / commandTick
* during `start()`, drains the queues into the host's callbacks, and detaches on `stop()` / `dispose()`. The
* runtime is intentionally thin — it just wires Pixi rendering up to the engine's existing event surface so the
* Web view doesn't need to mirror the engine's internal state.
*
* `tuiEnabled` is hard-wired to `false` because the web runtime never claims to be a TUI; this signals the engine
* that it should still emit per-frame log output (the engine's "no-TUI" branch) for diagnostics.
*/
export function createWebUIRuntime(options: WebUIRuntimeOptions): PlayerUIRuntime {
const { uiSignals } = options;
// Fire the signals-ready hook synchronously during construction so a host that prefers per-frame polling has
// the bus references in hand by the time the engine flips runtime.start().
try {
options.onSignalsReady?.({ uiSignals, stateSignals: options.stateSignals });
} catch (error) {
log.warn('onSignalsReady callback threw', error);
}
let frameUnsub: (() => void) | undefined;
let commandUnsub: (() => void) | undefined;
let lastFrameTick = -1;
let lastCommandTick = -1;
const flushFrame = (): void => {
const tick = uiSignals.frameTick();
Iif (tick === lastFrameTick) return;
lastFrameTick = tick;
try {
options.onFrame?.(uiSignals.getFrame());
} catch (error) {
log.warn('onFrame callback threw', error);
}
};
const flushCommands = (): void => {
const tick = uiSignals.commandTick();
Iif (tick === lastCommandTick) return;
lastCommandTick = tick;
const commands = uiSignals.drainCommands();
for (const command of commands) {
try {
options.onCommand?.(command);
} catch (error) {
log.warn('onCommand callback threw', { command, error });
}
}
};
return {
// The engine reads `tuiEnabled` as the universal "is some UI subscribed" gate, not as "is the TUI
// specifically running" — `flash-lane` / `press-lane` / `release-lane` / `hold-lane-until-beat` /
// `trigger-poor-bga` / `clear-poor-bga` UI commands AND every `stateSignals.publishJudgeCombo` call are
// gated behind it (see `bootstrap.ts:activeStateSignals = uiEnabled ? stateSignals : undefined`). Reporting
// `false` would silence every visual / score event the gameplay view relies on. The Web has a UI just like
// the TUI does (Pixi instead of ANSI), so it's `true`.
tuiEnabled: true,
playbackEndSeconds: options.playbackEndSeconds,
start: (): void => {
// alien-signals' WritableSignal can be subscribed by reading inside an effect, but for our minimal "drain on
// tick" model a polling subscription is simpler and avoids reactive-graph dependency leaks. We poll on every
// signal change by reading `tick()` inside a getter — the host's host-side rAF loop already ticks every
// frame and will call into us via `onFrame` / `onCommand` indirectly. For Phase 3 we simply expose the
// detach hooks; Phase 4 wires the actual rAF subscription.
flushFrame();
flushCommands();
try {
options.onStart?.();
} catch (error) {
log.warn('onStart callback threw', error);
}
},
stop: (): void => {
frameUnsub?.();
commandUnsub?.();
frameUnsub = undefined;
commandUnsub = undefined;
try {
options.onStop?.();
} catch (error) {
log.warn('onStop callback threw', error);
}
},
dispose: (): void => {
frameUnsub?.();
commandUnsub?.();
frameUnsub = undefined;
commandUnsub = undefined;
try {
options.onDispose?.();
} catch (error) {
log.warn('onDispose callback threw', error);
}
},
triggerPoor: (seconds: number): void => {
try {
options.onPoorTriggered?.(seconds);
} catch (error) {
log.warn('onPoorTriggered callback threw', error);
}
},
clearPoor: (): void => {
try {
options.onPoorCleared?.();
} catch (error) {
log.warn('onPoorCleared callback threw', error);
}
},
};
}
/**
* Helper to drain frame / command updates from the engine's `uiSignals` (and, when supplied, the matching
* `stateSignals` judge/combo channel). The web host's rAF loop calls this once per frame so the engine's UI
* events arrive at the host without an alien-signals reactive subscription (which would otherwise complicate
* dispose ordering).
*
* The drainer keeps a per-call latched tick so a stateSignals' judge-combo update only fires `onJudgeCombo` once
* even if the host polls multiple times per engine tick. Pass `lastJudgeComboTick` from your previous call (or
* `0` on the first poll) and persist the returned tick value back for the next frame.
*
* Returns `true` when at least one event drained — useful for the host to skip Pixi work when the engine produced
* nothing new this frame.
*/
export function drainWebUISignals(
uiSignals: PlayerUISignalBus,
callbacks: WebUIRuntimeCallbacks,
options: { stateSignals?: PlayerStateSignals; lastJudgeComboTick?: number } = {},
): { drained: boolean; lastJudgeComboTick: number } {
let drained = false;
let nextJudgeComboTick = options.lastJudgeComboTick ?? 0;
try {
callbacks.onFrame?.(uiSignals.getFrame());
drained = true;
} catch (error) {
log.warn('onFrame drain threw', error);
}
const commands = uiSignals.drainCommands();
for (const command of commands) {
try {
callbacks.onCommand?.(command);
drained = true;
} catch (error) {
log.warn('onCommand drain threw', { command, error });
}
}
if (options.stateSignals) {
// Drain the per-publish queue rather than reading the latched single state. A simultaneous-press AUTO
// PLAY chord resolves several `publishJudgeCombo` calls inside the same engine tick, and the previous
// `getJudgeCombo()` peek only saw the LAST publish (the others got overwritten on the latch) — so only
// the right-most lane's bomb / FC update fired. The queue preserves every publish in publish order, so
// the host can fan out one bomb sprite per chord note. We still update `lastJudgeComboTick` for callers
// that want a "did anything change?" hint, but the queue is the source of truth for the actual fan-out.
const drainedCombos = options.stateSignals.drainPendingJudgeCombos();
if (drainedCombos.length > 0) {
nextJudgeComboTick = options.stateSignals.judgeComboTick();
for (const combo of drainedCombos) {
try {
callbacks.onJudgeCombo?.(combo);
drained = true;
} catch (error) {
log.warn('onJudgeCombo drain threw', error);
}
}
} else {
// No publishes since last drain — keep the tick latch in sync (it should already match, this is just
// defensive against external code mutating the tick signal directly).
nextJudgeComboTick = options.stateSignals.judgeComboTick();
}
}
return { drained, lastJudgeComboTick: nextJudgeComboTick };
}
/**
* Convenience factory matching `PlayerOptions.createUIRuntime`. Closes over the host's callbacks so a caller can
* pass `{ createUIRuntime: createWebUIRuntimeFactory({ onFrame, onCommand, ... }) }` directly to `manualPlay` /
* `autoPlay`.
*/
export function createWebUIRuntimeFactory(
callbacks: WebUIRuntimeCallbacks,
): (context: CreatePlayerUIRuntimeContext) => Promise<PlayerUIRuntime> {
return async (context) =>
createWebUIRuntime({
...callbacks,
uiSignals: context.uiSignals,
stateSignals: context.stateSignals,
});
}
|