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 | 28x 10x 1x 1x 10x 10x 10x 10x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 21x 21x 21x 1x 20x 20x 20x 20x 12x 12x 12x 12x 20x 17x 17x 1x 1x 1x 1x 1x 1x 1x 16x 16x 19x 21x 21x 19x 4x 4x 1x 1x 1x 1x 1x 3x 3x 2x 2x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 12x 12x 12x 10x 28x 21x 21x 21x 21x 21x 21x 10x 63x 2x 2x | import {
Application,
type ApplicationOptions,
Container,
DOMAdapter,
RendererType,
UPDATE_PRIORITY,
WebGPURenderer,
} from 'pixi.js';
import type { SceneIdentity } from './family-kit.ts';
import { logger } from '../logger.ts';
import { createMaxLimitsGPU } from './webgpu-limits.ts';
import { disableTransientAttachments } from './webgpu-transient.ts';
import { retainReleasedTextTextures } from '../stage/text-texture-retention.ts';
import { registerBeatorajaBlendModes } from './beatoraja-blend-modes.ts';
const log = logger('scene-host');
/**
* A single PixiJS scene that lives inside a {@link PixiSceneHost}. Each scene owns a `root` Container and builds its
* scene graph under it; the host puts that root on the shared `app.stage` while the scene is active and takes it off
* when another one takes over. Scenes never add themselves to the stage.
*
* Lifecycle, driven by {@link PixiSceneHost.setScene}:
*
* - `enter(host)` runs each time the scene becomes the active one, before the host puts `root` on the stage. The first
* entry builds the scene graph and wires input and ticker work; a later one (a scene kept alive across others, as
* the select screen is across a play) resumes what `exit()` paused and restarts the screen's entrance.
* - `exit()` runs when another scene takes over or the stage is cleared, before the host takes `root` off the stage.
* The scene stops its ticker work, its input and the sound it plays as a screen (BGM, previews, jingles); heavy GPU
* resources stay so it can be entered again. It is a no-op on a scene that is not active or already disposed.
* - `dispose()` is the permanent cleanup, from any state; the host's owner calls it once the scene is no longer
* wanted. A disposed scene is never entered again.
*
* Scenes do **not** call `Application.destroy()` — that's the host's job, and only at process / page shutdown. This is
* the central idea behind the multi-scene refactor: keeping a single Application (and therefore a single WebGL context)
* alive across the whole session avoids Pixi v8's module-shared `batchPool` race that bit us when two `Application`
* instances ran side-by-side.
*/
export interface PixiScene {
/**
* Container the host attaches to its `app.stage` when this scene is active. Scenes build their own scene graph as
* children of this `root`.
*/
readonly root: Container;
/**
* Which screen the scene is and which skin family draws it, fixed for the scene's lifetime. Hosts read the scene
* showing through it ({@link PixiSceneHost.getCurrentScene}).
*/
readonly identity: SceneIdentity;
enter(host: PixiSceneHost): Promise<void> | void;
exit(): Promise<void> | void;
dispose(): void;
/**
* Optional capture descriptor for the screenshot pipeline. Returns the SKIN's coordinate-
* space root container (= the contents are at native skin pixel coordinates, BEFORE the
* fit-to-stage scale) plus the skin's authored width / height. The host's screenshot
* helper temporarily resets the container's transform to identity, calls `extract.canvas`
* with a `frame: {0, 0, width, height}` rectangle, then restores the transform so the
* live view's scale isn't affected. Scenes that don't author a fixed skin canvas (or that
* don't want to be screenshot-capturable) leave the method undefined and the helper falls
* back to capturing the entire stage at its visible (window) size.
*/
getStageInfo?(): { container: Container; width: number; height: number };
/**
* `false` while the scene draws nothing on the Pixi canvas (its screens are all DOM). The canvas is in the page only
* while the active scene draws on it. Absent means `true`.
*/
readonly drawsOnCanvas?: boolean;
}
export interface PixiSceneHostMountOptions {
/** Native skin screens mount here; defaults to the Canvas container. */
domContainer?: HTMLElement;
/**
* Optional override for the underlying `Application.init` options. The host fills in opinionated defaults (no
* antialias, nearest sampling, devicePixelRatio resolution, transparent BG) that match the LR2 pixel-art aesthetic;
* pass an override to swap any subset for a specific deployment.
*/
appOptions?: Partial<ApplicationOptions>;
/**
* The render resolution to ask for (canvas pixels per CSS pixel), capped at the display's `devicePixelRatio`. Lower
* trades sharpness for fill-rate on GPUs that cannot keep up at full density. `?resolution=` in the URL overrides it;
* without either the display's own ratio is used. Change it later with {@link PixiSceneHost.setResolution}.
*/
resolution?: number;
/**
* The renderer to ask for; WebGL 2 when not given. `?renderer=` in the URL overrides it. Read once, when the host
* mounts.
*/
renderer?: RendererPreference;
}
/**
* Owns the single PixiJS `Application` (and therefore the single WebGL context) for the whole player session. Scenes
* are attached via {@link setScene}; only one scene is "active" (visible + receiving ticker callbacks via its own
* scope) at a time.
*
* Why this exists: PixiJS v8 keeps a module-level `batchPool` that's destroyed when **any** `Application.destroy()` is
* called with the `releaseGlobalResources` flag (which the boolean `app.destroy(true, ...)` shorthand sets implicitly).
* With two `Application`s alive at once, tearing one of them down nulls out shared `Batch` instances that the other
* app's renderer then crashes on at `_DefaultBatcher.break`. Funnelling everything through one `Application` instance
* dodges that landmine entirely — and matches the official "use a single Application for the lifetime of your app"
* guidance in the PixiJS docs.
*/
export class PixiSceneHost {
/** The shared `Application`. Scenes read `host.app` for the ticker, screen size, canvas, etc. */
public readonly app: Application = new Application();
private domLayer: HTMLElement | undefined;
private domParent: HTMLElement | undefined;
private previousPosition: string | undefined;
/** Where the canvas goes back while it is out of the page (see {@link PixiScene.drawsOnCanvas}). */
private canvasSlot: { parent: HTMLElement; next: Node | null } | undefined;
private canvasContainer: HTMLElement | undefined;
/** Resizes the canvas when the container changes size without a window `resize`. */
private containerObserver: ResizeObserver | undefined;
/**
* The element the host was mounted in. The canvas is in it only while the active scene draws on it, so listen here
* for input meant for the whole stage.
*/
public get container(): HTMLElement {
Iif (!this.canvasContainer) throw new Error('Mount the scene host before reading its container');
return this.canvasContainer;
}
/** The host-owned native layer. DOM screens are siblings of the Canvas, outside the Pixi scene graph. */
public get domRoot(): HTMLElement {
if (!this.domParent) throw new Error('Mount the scene host before attaching a DOM skin');
if (!this.domLayer) {
const parent = this.domParent;
if (parent.ownerDocument.defaultView?.getComputedStyle(parent).position === 'static') {
this.previousPosition = parent.style.position;
parent.style.position = 'relative';
}
this.domLayer = parent.ownerDocument.createElement('div');
this.domLayer.setAttribute('data-be-music-dom', '');
Object.assign(this.domLayer.style, { position: 'absolute', inset: '0', pointerEvents: 'none', zIndex: '1' });
parent.append(this.domLayer);
}
return this.domLayer;
}
/** The currently-active scene, or `undefined` between transitions. */
private current: PixiScene | undefined;
/**
* Orientation of the design stage the active scene is drawing on: `'portrait'` while a Be-Music Skin draws on its
* portrait stage, `'landscape'` otherwise (and for themes). Scenes report it every frame via
* {@link setStageOrientation}; hosts read it to decide whether to ask a phone held upright to rotate.
*/
private orientation: 'landscape' | 'portrait' = 'landscape';
/** Set after the first `mount` so re-mount calls are a no-op. */
private mounted = false;
/** Set when {@link dispose} runs so subsequent calls short-circuit. */
private disposed = false;
/**
* Serializes in-flight `setScene` calls. Without it a fast-double-toggle (e.g. ESC-then-immediate-song-pick) could
* interleave a new scene's `enter()` with a previous scene's `exit()`, leaving both attached to the stage.
*/
private transitionLock: Promise<void> = Promise.resolve();
public async mount(container: HTMLElement, options?: PixiSceneHostMountOptions): Promise<void> {
Iif (this.mounted) {
return;
}
this.mounted = true;
// Renderer preference: the player's pick, WebGL 2 by default (see `resolveRendererPreference`); `?renderer=webgl`
// or `?renderer=webgpu` in the URL overrides it for A/B testing. PixiJS falls back to WebGL 2 when the browser has
// no WebGPU — `app.renderer.type` logged below confirms which path actually came up.
const preference = resolveRendererPreference(undefined, options?.renderer);
// Raise the WebGPU device's texture dimensions to the adapter's maximum (see `webgpu-limits.ts`), on the
// devices Pixi creates itself so it can still recover the stage from a lost device.
Iif (preference === 'webgpu') useMaxLimitsGPU();
await this.app.init({
preference,
backgroundAlpha: 0,
resizeTo: container,
// No `useBackBuffer`: with `backgroundAlpha: 0` it blacked out every sprite on some hardware. Pixi's advanced
// blend modes need it on WebGL, so beatoraja's code 3 (subtract) draws as normal there; codes 4 and 9 are plain blend states
// (`registerBeatorajaBlendModes`) and need no back buffer.
// LR2 skins and BGA frames are pixel-art; bilinear filtering and MSAA blur them visibly. Combined with
// `roundPixels: true` and per-texture nearest sampling on each loaded asset, this gives a fully-crisp
// pixel-art-style render.
antialias: false,
autoDensity: true,
// Render at the display's full devicePixelRatio so vector chrome and text land on real device pixels. (This
// used to be capped at 2× to save fill-rate on 3× displays, but the built-in skins' vector shapes and text then
// rendered visibly soft there.) `options.resolution` or `?resolution=` lowers it, trading that sharpness for
// fill-rate on slow GPUs.
resolution: resolveRenderResolution(globalThis.devicePixelRatio || 1, undefined, options?.resolution),
roundPixels: true,
// Force the discrete GPU on hybrid systems (every modern laptop with switchable graphics). Rhythm-game
// input-to-display latency is critical, and the integrated-GPU path adds variable frame-time on top of the
// base 60 Hz tick. The `'high-performance'` hint makes the browser request the dGPU at context creation,
// which on macOS / Windows pins the renderer to the powerful adapter for the rest of the session. Pixi v8
// forwards this option to both the WebGPU and WebGL2 backends.
powerPreference: 'high-performance',
// Keep Pixi's texture GC as a safety net, not an in-song metronome. Scene teardown explicitly destroys BGA and
// skin resources, so a frequent full cache walk buys little during gameplay and can show up as a rare frame-time
// spike on texture-heavy skins/charts. A slower sweep still catches abandoned resources in long app sessions.
gcMaxUnusedTime: 120_000,
gcFrequency: 60_000,
...options?.appOptions,
});
registerBeatorajaBlendModes(this.app.renderer);
// Safari's WebGPU crashes on the transient MSAA textures Pixi makes on Apple GPUs (see `webgpu-transient.ts`).
Iif (this.app.renderer instanceof WebGPURenderer) disableTransientAttachments(this.app.renderer);
// A HUD's changing digits come back to strings rasterized moments ago; keep those textures instead of rasterizing
// them again (slow on Safari above all). The renderer's teardown returns them with the rest.
retainReleasedTextTextures((this.app.renderer as unknown as { canvasText?: object }).canvasText);
// Surface the actual renderer type — the `preference` field is a *hint*, and the real backend may differ if WebGPU
// init failed silently or if the override flag was used.
log.info('renderer ready', {
requested: preference,
actual: rendererTypeLabel(this.app.renderer.type),
});
this.app.canvas.tabIndex = 0;
this.app.canvas.setAttribute('aria-label', 'Be-Music stage');
// Compositor isolation. `contain: content` (= `layout paint style`) tells the browser the canvas's visual
// contents can't affect — and aren't affected by — anything outside its box. The compositor can then skip
// walking siblings / ancestors when the canvas repaints (= every frame), trimming a few hundred μs of
// main-thread work per repaint on dense pages. We deliberately omit the `size` containment that the stricter
// `strict` value would add — Pixi sets `<canvas>` width/height explicitly via `resizeTo`, but `contain: size`
// ignores intrinsic content size during layout, which can interact poorly with the host's ResizeObserver
// path on some browsers. `pointer-events` is intentionally left at `auto` so Pixi's hit-testing
// (song-select buttons, Options dialog, result-screen actions) keeps working.
this.app.canvas.style.contain = 'content';
// `resizeTo` follows only the window's `resize` event. The container also changes size on its own (the page's
// layout settles after the first chart is loaded, a side panel opens), and a canvas left at its old size draws the
// skin into part of the stage and picks the wrong stage orientation.
const View = container.ownerDocument?.defaultView;
if (View?.ResizeObserver) {
this.containerObserver = new View.ResizeObserver(() => this.app.queueResize());
this.containerObserver.observe(container);
}
this.app.stage.label = 'host/stage';
// The canvas goes in once a scene that draws on it becomes active (`placeCanvas`).
this.canvasContainer = container;
this.canvasSlot = { parent: container, next: null };
this.domParent = options?.domContainer ?? container;
}
/**
* Replaces the active scene: the previous one exits and its root leaves the stage, then the next one enters and its
* root goes on the stage. `undefined` clears the stage. Transitions run one at a time, in call order. The previous
* scene is only exited, never disposed — its owner disposes it, or keeps it to enter again later. Awaitable so
* callers can chain follow-up work (loading a song, etc.) once the new scene's `enter()` has resolved. Idempotent —
* passing the already-active scene returns immediately.
*/
public setScene(scene: PixiScene | undefined): Promise<void> {
const next = (async () => {
await this.transitionLock;
if (this.disposed || this.current === scene) {
return;
}
const previous = this.current;
this.current = scene;
// Until the next scene reports its stage (themes never do), it is a landscape one.
this.orientation = 'landscape';
if (previous) {
try {
await previous.exit();
} catch (error) {
log.warn('previous scene.exit threw', error);
}
Eif (previous.root.parent === this.app.stage) {
this.app.stage.removeChild(previous.root);
}
}
if (scene && !this.disposed) {
try {
await scene.enter(this);
} catch (error) {
log.warn('next scene.enter threw', error);
Iif (scene.root.parent === this.app.stage) {
this.app.stage.removeChild(scene.root);
}
Eif (this.current === scene) {
this.current = undefined;
}
try {
scene.dispose();
} catch (disposeError) {
log.warn('failed scene.dispose threw after enter failure', disposeError);
}
throw error;
}
Eif (!this.disposed) {
this.app.stage.addChild(scene.root);
}
}
Eif (!this.disposed) this.placeCanvas(scene !== undefined && scene.drawsOnCanvas !== false);
})();
this.transitionLock = next.catch(() => undefined);
return next;
}
/**
* Runs `callback` on every tick after the stage has been rendered (Pixi renders at `UPDATE_PRIORITY.LOW`; this hooks
* in at `UTILITY`, below it) and returns the unregister function. Used by the gameplay recorder to read each frame
* while it is still in the canvas.
*/
public onAfterRender(callback: () => void): () => void {
const ticker = this.app.ticker;
ticker.add(callback, undefined, UPDATE_PRIORITY.UTILITY);
return () => {
ticker.remove(callback);
};
}
/**
* Puts the canvas in the page when `placed`, or takes it out. A play calls this when it swaps a DOM family for a
* canvas one, or the other way, without changing scenes.
*/
public syncCanvas(placed: boolean): void {
this.placeCanvas(placed);
}
/** Puts the canvas in the page, or takes it out while the active scene draws only on DOM. */
private placeCanvas(placed: boolean): void {
// Before `mount` there is no canvas yet.
if (!this.domParent) return;
const canvas = this.app.canvas;
if (placed) {
const slot = this.canvasSlot;
Iif (!slot) return;
this.canvasSlot = undefined;
slot.parent.insertBefore(canvas, slot.next?.parentNode === slot.parent ? slot.next : null);
return;
}
const parent = canvas.parentElement;
if (this.canvasSlot || !parent) return;
this.canvasSlot = { parent, next: canvas.nextSibling };
canvas.remove();
}
/** Called by the active scene with the orientation of the stage it draws on (see {@link getStageOrientation}). */
public setStageOrientation(orientation: 'landscape' | 'portrait'): void {
this.orientation = orientation;
}
/** The orientation of the stage the active scene draws on; `'landscape'` until it reports one. */
public getStageOrientation(): 'landscape' | 'portrait' {
return this.orientation;
}
/**
* The active scene: the one the latest transition switched to (from the moment that transition starts), or
* `undefined` when the stage is clear. Its {@link PixiScene.identity} says what is showing.
*/
public getCurrentScene(): PixiScene | undefined {
return this.current;
}
/**
* Renders at `resolution` canvas pixels per CSS pixel from the next frame, capped at the display's
* `devicePixelRatio` and no lower than 0.5. Scenes size their surfaces from the renderer every frame, so they follow.
* Returns the resolution applied.
*/
public setResolution(resolution: number): number {
const applied = clampRenderResolution(globalThis.devicePixelRatio || 1, resolution);
const renderer = this.app.renderer;
if (renderer && renderer.resolution !== applied) {
// `resize` (rather than the `resolution` setter) keeps the canvas's CSS size while its pixel size changes.
renderer.resize(this.app.screen.width, this.app.screen.height, applied);
}
return applied;
}
public isDisposed(): boolean {
return this.disposed;
}
public dispose(): void {
Iif (this.disposed) {
return;
}
this.disposed = true;
Iif (this.current) {
try {
this.current.dispose();
} catch (error) {
log.warn('scene.dispose threw', error);
}
this.current = undefined;
}
this.containerObserver?.disconnect();
this.containerObserver = undefined;
this.domLayer?.remove();
this.domLayer = undefined;
Iif (this.domParent && this.previousPosition !== undefined && this.domParent.style.position === 'relative') {
this.domParent.style.position = this.previousPosition;
}
this.domParent = undefined;
try {
// With only ONE Application owned by the process, releasing the module-shared `batchPool` here is safe — no other
// live Application can be tripped up by the cleared pool. (See the class doc-block above for the
// multi-Application landmine we used to hit.)
this.app.destroy({ removeView: true, releaseGlobalResources: true }, { children: true });
} catch (error) {
log.warn('app.destroy threw', error);
}
}
}
/**
* Points Pixi's `navigator.gpu` at {@link createMaxLimitsGPU}, once per page. Pixi reads the navigator through its
* DOM adapter for every adapter and device it requests, including the one that replaces a lost device.
*/
function useMaxLimitsGPU(): void {
const navGPU = (globalThis.navigator as { gpu?: GPU } | undefined)?.gpu;
if (navGPU === undefined || maxLimitsGPUInstalled) return;
maxLimitsGPUInstalled = true;
const pixiNavigator = { userAgent: globalThis.navigator.userAgent, gpu: createMaxLimitsGPU(navGPU) };
DOMAdapter.set({ ...DOMAdapter.get(), getNavigator: () => pixiNavigator });
}
let maxLimitsGPUInstalled = false;
/** The renderer the host asks Pixi for: WebGL 2, or WebGPU. */
export type RendererPreference = 'webgl' | 'webgpu';
/**
* The PixiJS `preference` for the stage: `?renderer=webgl` or `?renderer=webgpu` in `window.location.search` when
* given (exact values only; anything else is ignored), else `requested` (the player's pick), else WebGL 2. WebGL 2 is
* the default because on a laptop's integrated GPU the WebGPU path drew Synesthesia at 1920 × 1080 at about 80 fps
* against 135 fps with WebGL 2; WebGPU stays one setting away.
*
* Exported for testability — callers should normally let {@link PixiSceneHost.mount} resolve this internally.
*/
export function resolveRendererPreference(rawSearch?: string, requested?: RendererPreference): RendererPreference {
const search =
rawSearch ??
(typeof globalThis !== 'undefined' && typeof globalThis.location !== 'undefined' ? globalThis.location.search : '');
const flag = search ? new URLSearchParams(search).get('renderer') : null;
if (flag === 'webgl' || flag === 'webgpu') return flag;
return requested ?? 'webgl';
}
/** Lowest render resolution `?resolution=` may ask for. */
const MIN_RENDER_RESOLUTION = 0.5;
/**
* The render resolution (canvas pixels per CSS pixel) for a display of `devicePixelRatio`: `?resolution=<number>` (e.g.
* `1` or `1.5`) from `window.location.search` when given, else `requested`, else the display's own ratio. Either one
* is capped at the display's ratio and goes no lower than 0.5; anything that isn't a positive number is ignored. Every
* surface follows the renderer's resolution, so this sets the pixel count the GPU fills each frame.
*/
export function resolveRenderResolution(devicePixelRatio: number, rawSearch?: string, requested?: number): number {
const search =
rawSearch ??
(typeof globalThis !== 'undefined' && typeof globalThis.location !== 'undefined' ? globalThis.location.search : '');
const raw = search ? new URLSearchParams(search).get('resolution') : null;
const fromURL = raw === null || raw.trim() === '' ? Number.NaN : Number(raw);
return clampRenderResolution(devicePixelRatio, isPositive(fromURL) ? fromURL : requested);
}
/** `requested` held between 0.5 and the display's ratio; the display's ratio when `requested` isn't a positive number. */
function clampRenderResolution(devicePixelRatio: number, requested: number | undefined): number {
const native = isPositive(devicePixelRatio) ? devicePixelRatio : 1;
if (!isPositive(requested)) return native;
return Math.min(native, Math.max(MIN_RENDER_RESOLUTION, requested));
}
function isPositive(value: number | undefined): value is number {
return value !== undefined && Number.isFinite(value) && value > 0;
}
/**
* Maps a PixiJS `RendererType` enum value to a human-readable label for the post-init console log. Falls back to the
* numeric tag if the enum gets a new variant we haven't accounted for.
*/
function rendererTypeLabel(type: RendererType): string {
switch (type) {
case RendererType.WEBGL:
return 'webgl';
case RendererType.WEBGPU:
return 'webgpu';
case RendererType.CANVAS:
return 'canvas';
case RendererType.BOTH:
return 'both';
default:
return `unknown(${String(type)})`;
}
}
|