All files / player-browser/src/skin/be-music binding.ts

45.88% Statements 106/231
43.18% Branches 57/132
37.25% Functions 19/51
47.39% Lines 100/211

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                                                                                            32x     32x     32x 32x 32x                 32x       7x       32x                       53x                       2x           2x 2x             2x 2x 2x       2x       2x 2x                 8x         4x     4x 4x                                   2x   2x 2x 2x         2x 2x       4x               4x 4x 4x   4x               4x 4x 4x               4x 4x       4x 2x                       2x         2x   2x 2x           2x 2x   2x                   2x                                                           4x 4x 4x 4x 4x 4x 4x 4x                                 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                           6x 6x 6x 6x 6x 6x 6x 6x 6x                                   6x 4x 4x   4x 4x 4x   4x                 7x       24x       1x               1x                                   3x     7x 7x 7x 6x   6x 6x 2x 2x   1x   2x   4x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
import { CanvasSource, Container, RenderTexture, Sprite, Texture, TextureSource, type Renderer } from 'pixi.js';
import { getDesignPixelRatio, resolveCanvasPixelRatio } from '../../stage/viewport.ts';
import { ChildPool } from '../../stage/pixi-utils.ts';
import {
  resolveBeMusicSkinSettings,
  resolveBeMusicStage,
  resolveStageOrientation,
  wideStage,
} from '@be-music/player-skin-sdk';
import { logger } from '../../logger.ts';
import { PIXI_HOST_TARGET, rendersOnPixiHost, type PixiHostTarget } from '../../skins/pixi-kit/host-render.ts';
import { resolveHoldTops } from './hold-top.ts';
import type {
  BeMusicBGAFrame,
  BeMusicBomb,
  BeMusicDecideFrame,
  BeMusicGameplayFrame,
  BeMusicGameplayLayout,
  BeMusicGameplayRuntime,
  BeMusicGuideLabelStyle,
  BeMusicLaneCoverStyle,
  BeMusicLaneFrame,
  BeMusicLongNote,
  BeMusicMine,
  BeMusicNote,
  BeMusicResultFrame,
  BeMusicMeasureLine,
  BeMusicSelectFrame,
  BeMusicSkin,
  BeMusicSkinSettingValues,
  BeMusicChartImageLookup,
  BeMusicChartBestRecord,
  BeMusicCourseBestRecord,
  BeMusicDanRank,
  BeMusicStage,
  BeMusicSurface,
  BeMusicSurfaceContextMap,
} from './types.ts';
 
/**
 * The player's side of a Be-Music Skin: each screen gets a canvas sized to the screen pixels the stage covers, the skin
 * draws it with whatever it likes, and the canvas is shown in the Pixi scene as one texture. Skins never see Pixi —
 * except Pixi-kit skins, which draw through the player's own renderer into the texture (see `PIXI_HOST_RENDER`),
 * so the frame stays on the GPU.
 */
 
const log = logger('be-music-skin');
 
/** Hosts that hand no song images report every image as unavailable. */
const NO_SONG_IMAGE: BeMusicChartImageLookup = () => undefined;
 
/** Hosts that keep no play records report every song as never played. */
const NO_SONG_RECORD = (): BeMusicChartBestRecord | undefined => undefined;
const NO_COURSE_RECORD = (): BeMusicCourseBestRecord | undefined => undefined;
const NO_DAN_RANKS = (): readonly BeMusicDanRank[] => [];
 
/**
 * The player's stored values for a skin's settings, keyed by setting id, as a host persisted them. Bindings check them
 * against the skin's schema with `resolveBeMusicSkinSettings` before a skin sees them.
 */
export type BeMusicStoredSkinSettings = Readonly<Record<string, unknown>>;
 
/** How long the decide screen shows when the skin doesn't say (`BeMusicDecideSkin.durationMs`). */
const DEFAULT_DECIDE_DURATION_MS = 2000;
 
/** How long `skin`'s decide screen shows before the play starts: its `decide.durationMs`, 2000 ms by default. */
export function resolveBeMusicDecideDurationMs(skin: BeMusicSkin): number {
  return Math.max(0, skin.decide?.durationMs ?? DEFAULT_DECIDE_DURATION_MS);
}
 
/** Largest canvas edge a surface allocates, whatever the window size. */
const MAX_CANVAS_EDGE = 4096;
 
/**
 * The design canvas `skin` draws on: its landscape stage (the 16:9 `wideStage` unless it declares another), or — given
 * the `screen` it is shown on — its portrait stage when the screen is upright and the skin has one (see
 * `resolveBeMusicStage`; `chart` keeps gameplay on the landscape stage for play modes too wide for portrait).
 */
export function resolveBeMusicSkinStage(
  skin: BeMusicSkin,
  screen?: { width: number; height: number },
  chart?: Parameters<typeof resolveBeMusicStage>[2],
): BeMusicStage {
  return screen ? resolveBeMusicStage(skin, screen, chart) : (skin.stage ?? wideStage);
}
 
/** The size of the stage a surface draws one frame on. */
type SurfaceSize = { width: number; height: number };
 
/**
 * One canvas + the texture showing it, sized to the screen pixels the stage covers (dot by dot). For a skin that draws
 * through the player's renderer the texture is a render texture the skin renders into, and the canvas only identifies
 * the surface (it never gets a context).
 */
class SkinSurface {
  private readonly canvas = document.createElement('canvas');
  private readonly source: TextureSource;
  readonly texture: Texture;
  /** The player's renderer when the skin draws through it; `undefined` when the skin draws on the canvas. */
  private readonly hostRenderer: Renderer | undefined;
  private context: BeMusicSurfaceContextMap[keyof BeMusicSurfaceContextMap] | undefined;
  private state: 'new' | 'pending' | 'ready' | 'failed' | 'destroyed' = 'new';
  private pixelRatio = 1;
  private readonly skin: BeMusicSkin;
  /** The stage size of the frame being drawn; follows the screen when the host switches between the skin's stages. */
  private stage: SurfaceSize;
 
  /** `renderer` is the player's; a Pixi-kit skin draws through it instead of on the canvas. */
  constructor(skin: BeMusicSkin, renderer: Renderer | undefined) {
    this.skin = skin;
    this.stage = resolveBeMusicSkinStage(skin);
    this.hostRenderer = renderer !== undefined && rendersOnPixiHost(skin) ? renderer : undefined;
    // Nearest sampling: the canvas is sized to the screen pixels it covers, so it is shown dot by dot, never filtered.
    // Dynamic: sprites showing the texture follow its size when the stage changes (a rotation between the skin's
    // landscape and portrait stages).
    if (this.hostRenderer) {
      // Not multisampled: on an integrated GPU a 4x multisampled target over the built-in skins' additive particles cost
      // a quarter of the frame. Pixi-kit skins draw their sub-pixel points grown to a pixel and faded by area instead
      // (see `pointLayerFor`), so they keep their light without the samples.
      this.source = new TextureSource({ scaleMode: 'nearest', antialias: false, autoGenerateMipmaps: false });
      this.texture = new RenderTexture({ source: this.source, dynamic: true });
    } else E{
      this.source = new CanvasSource({ resource: this.canvas, scaleMode: 'nearest' });
      this.texture = new Texture({ source: this.source, dynamic: true });
    }
  }
 
  /** Whether the skin draws through the player's renderer, so a frame must be drawn outside the player's render. */
  get rendersOnHost(): boolean {
    return this.hostRenderer !== undefined;
  }
 
  /** Runs `paint` on the surface (once it is set up) sized to the stage `size`, and uploads the result. */
  draw(size: SurfaceSize, paint: (surface: BeMusicSurface) => void): void {
    Iif (size.width !== this.stage.width || size.height !== this.stage.height) {
      this.stage = { width: size.width, height: size.height };
    }
    this.resize();
    Eif (!this.ensureContext() || this.state !== 'ready') return;
    const surface = this.surface();
    if (this.skin.context === '2d') {
      const ctx = surface.context as CanvasRenderingContext2D;
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
    }
    try {
      paint(surface);
    } catch (error) {
      log.warn(`"${this.skin.id}": draw failed`, error);
    }
    // A render texture already holds the frame; a canvas is uploaded.
    if (!this.hostRenderer) this.source.update();
  }
 
  destroy(): void {
    Iif (this.state === 'destroyed') return;
    // Only a surface the skin set up is handed back to it.
    Eif (this.state === 'ready' || this.state === 'pending') {
      try {
        this.skin.teardown?.(this.surface());
      } catch (error) {
        log.warn(`"${this.skin.id}": teardown failed`, error);
      }
    }
    this.state = 'destroyed';
    this.texture.destroy(true);
  }
 
  private surface(): BeMusicSurface {
    const surface: BeMusicSurface = {
      canvas: this.canvas,
      context: this.context!,
      width: this.stage.width,
      height: this.stage.height,
      orientation: resolveStageOrientation(this.stage),
      pixelRatio: this.pixelRatio,
    };
    Eif (this.hostRenderer) {
      const target: PixiHostTarget = { renderer: this.hostRenderer, texture: this.texture };
      Object.defineProperty(surface, PIXI_HOST_TARGET, { value: target });
    }
    return surface;
  }
 
  /**
   * Sizes the canvas to the device pixels the stage covers on screen (viewport scale × devicePixelRatio), so one canvas
   * pixel is one screen pixel. Capped at {@link MAX_CANVAS_EDGE} on the long side.
   */
  private resize(): void {
    const { width, height } = this.stage;
    const ratio = resolveCanvasPixelRatio(width, height, getDesignPixelRatio(), MAX_CANVAS_EDGE);
    Iif (
      ratio === this.pixelRatio &&
      this.canvas.width > 0 &&
      this.source.width === width &&
      this.source.height === height
    ) {
      return;
    }
    this.pixelRatio = ratio;
    this.source.resize(width, height, ratio);
  }
 
  private ensureContext(): boolean {
    if (this.state === 'new') {
      Eif (this.hostRenderer) return this.setup();
      const context = this.canvas.getContext(this.skin.context, this.skin.contextAttributes) as
        | BeMusicSurfaceContextMap[keyof BeMusicSurfaceContextMap]
        | null;
      if (!context) {
        log.warn(`"${this.skin.id}": the browser offers no "${this.skin.context}" canvas context`);
        this.state = 'failed';
        return false;
      }
      this.context = context;
      return this.setup();
    }
    return this.state !== 'failed' && this.state !== 'destroyed';
  }
 
  /** Hands the surface to the skin's `setup`; the surface is ready once it returns (or its promise resolves). */
  private setup(): boolean {
    this.state = 'pending';
    let setup: void | Promise<void>;
    try {
      setup = this.skin.setup?.(this.surface());
    } catch (error) {
      log.warn(`"${this.skin.id}": setup failed`, error);
      this.state = 'failed';
      return false;
    }
    if (setup instanceof Promise) {
      setup.then(
        () => {
          Iif (this.state === 'pending') this.state = 'ready';
        },
        (error: unknown) => {
          log.warn(`"${this.skin.id}": setup failed`, error);
          if (this.state === 'pending') this.state = 'failed';
        },
      );
    } else E{
      this.state = 'ready';
    }
    return true;
  }
}
 
/**
 * Gameplay for one scene: the scene reports lanes, notes, long notes, and hit effects as it walks them, and
 * {@link renderChrome} places the skin's canvas, which is drawn once — with everything collected — when Pixi renders,
 * or, for a skin drawing through the player's renderer, when the scene calls {@link flush}.
 */
export class BeMusicGameplayBinding {
  readonly bombDurationMs: number;
  /** Whether the skin draws mines from the frame; when false the scene draws them itself. */
  readonly drawsMines: boolean;
  /** Whether the skin draws the lane covers from `runtime.laneCovers`; when false the scene draws them itself. */
  readonly drawsLaneCover: boolean;
  /** How the scene draws the BPM GUIDE labels over the skin, when the skin gives a look (`gameplay.guideLabel`). */
  readonly guideLabelStyle: BeMusicGuideLabelStyle | undefined;
  /** How the scene paints its lane covers for the skin, when the skin gives a look (`gameplay.laneCover`). */
  readonly laneCoverStyle: BeMusicLaneCoverStyle | undefined;
  /** Whether the skin draws measure lines from the frame; when false the scene draws them itself. */
  readonly drawsMeasureLines: boolean;
  /** Whether the skin composites the BGA from the frame; when false the scene shows it behind the skin. */
  readonly drawsBGA: boolean;
  private readonly skin: BeMusicSkin;
  private settings: BeMusicSkinSettingValues;
  private readonly chartImage: BeMusicChartImageLookup;
  /** `undefined` when the skin's DOM screen draws the playfield ({@link drawPlayfield}). */
  private readonly surface: SkinSurface | undefined;
  private readonly drawPlayfield: ((frame: BeMusicGameplayFrame) => void) | undefined;
  private frame: BeMusicGameplayFrame | undefined;
  private lanes: BeMusicLaneFrame[] = [];
  private notes: BeMusicNote[] = [];
  private longNotes: BeMusicLongNote[] = [];
  private mines: BeMusicMine[] = [];
  private bombs: BeMusicBomb[] = [];
  private measureLines: BeMusicMeasureLine[] = [];
  private frameNumber = 0;
  private drawnFrame = -1;
 
  /**
   * `chartImage` resolves the song's images for `frame.chartImage`; without one every image reads as unavailable.
   * `settings` are the player's stored values for the skin's settings; without them the skin draws with its defaults.
   * `renderer` is the player's Pixi renderer: a Pixi-kit skin draws through it.
   * `drawPlayfield` receives every frame instead of a Canvas surface when the skin sets `gameplay.drawsOnDOM`.
   */
  constructor(
    skin: BeMusicSkin,
    options: {
      chartImage?: BeMusicChartImageLookup;
      settings?: BeMusicStoredSkinSettings;
      renderer?: Renderer;
      drawPlayfield?: (frame: BeMusicGameplayFrame) => void;
    } = {},
  ) {
    this.skin = skin;
    this.drawPlayfield = skin.gameplay.drawsOnDOM === true ? options.drawPlayfield : undefined;
    this.surface = this.drawPlayfield ? undefined : new SkinSurface(skin, options.renderer);
    this.chartImage = options.chartImage ?? NO_SONG_IMAGE;
    this.bombDurationMs = skin.gameplay.bombDurationMs ?? 300;
    this.drawsMines = skin.gameplay.drawsMines === true;
    this.drawsLaneCover = skin.gameplay.drawsLaneCover === true;
    this.guideLabelStyle = skin.gameplay.guideLabel;
    this.laneCoverStyle = skin.gameplay.laneCover;
    this.drawsMeasureLines = skin.gameplay.drawsMeasureLines === true;
    this.drawsBGA = skin.gameplay.drawsBGA === true;
    this.settings = resolveBeMusicSkinSettings(skin, options.settings);
  }
 
  /** Replaces the player's values for the skin's settings; the next frame draws with them. */
  setSettings(stored: BeMusicStoredSkinSettings | undefined): void {
    this.settings = resolveBeMusicSkinSettings(this.skin, stored);
  }
 
  /** Starts a frame and shows the skin's canvas in `layerPool` (the scene's chrome layer, above the BGA). */
  renderChrome(context: {
    layerPool: ChildPool;
    runtime: BeMusicGameplayRuntime;
    layout: BeMusicGameplayLayout;
  }): void {
    const { runtime, layout } = context;
    this.frameNumber += 1;
    this.lanes = [];
    this.notes = [];
    this.longNotes = [];
    this.mines = [];
    this.bombs = [];
    this.measureLines = [];
    this.frame = {
      nowMs: runtime.nowMs ?? 0,
      runtime,
      layout,
      lanes: this.lanes,
      notes: this.notes,
      longNotes: this.longNotes,
      mines: this.mines,
      bombs: this.bombs,
      measureLines: this.measureLines,
      // Filled by `setBGA` for a skin that sets `drawsBGA`.
      bga: undefined,
      beatPhase: runtime.beatPhase ?? 0,
      effects: runtime.effects ?? 'full',
      audio: runtime.audio,
      settings: this.settings,
      chartImage: this.chartImage,
    };
    if (!this.surface) return;
    const sprite = context.layerPool.acquireSprite();
    sprite.texture = this.surface.texture;
    // The texture's size is in design pixels already (its source carries the pixel ratio as its resolution).
    sprite.position.set(0, 0);
    sprite.scale.set(1);
    sprite.roundPixels = true;
    // A skin drawing through the player's renderer can't render inside the player's render; the scene flushes it.
    sprite.onRender = this.surface.rendersOnHost ? null : this.drawFrame;
  }
 
  /**
   * Draws the frame collected since {@link renderChrome} when the skin draws through the player's renderer or on its DOM
   * screen; call it once the frame is collected, before the player renders. A no-op for a canvas skin, which draws when
   * its sprite renders.
   */
  flush(): void {
    Eif (!this.surface || this.surface.rendersOnHost) this.drawFrame();
  }
 
  addLanes(lanes: readonly BeMusicLaneFrame[]): void {
    for (const lane of lanes) this.lanes.push({ ...lane });
  }
 
  addNote(note: BeMusicNote): void {
    this.notes.push(note);
  }
 
  addLongNote(note: BeMusicLongNote): void {
    this.longNotes.push(note);
  }
 
  addMine(mine: BeMusicMine): void {
    this.mines.push(mine);
  }
 
  /** Collected only for a skin that sets `drawsMeasureLines`; the scene draws its own lines otherwise. */
  addMeasureLine(line: BeMusicMeasureLine): void {
    this.measureLines.push(line);
  }
 
  addBombs(bombs: readonly BeMusicBomb[]): void {
    for (const bomb of bombs) this.bombs.push({ ...bomb });
  }
 
  /** The BGA layers showing this frame; handed over only for a skin that sets `drawsBGA`. */
  setBGA(bga: BeMusicBGAFrame | undefined): void {
    if (this.frame && this.drawsBGA) this.frame.bga = bga;
  }
 
  dispose(): void {
    this.surface?.destroy();
  }
 
  private readonly drawFrame = (): void => {
    const frame = this.frame;
    if (!frame || this.drawnFrame === this.frameNumber) return;
    this.drawnFrame = this.frameNumber;
    // The lanes were collected before the notes; now both are in, each held lane learns where its note ends.
    resolveHoldTops(frame.lanes, frame.longNotes);
    if (!this.surface) {
      try {
        this.drawPlayfield?.(frame);
      } catch (error) {
        log.warn(`"${this.skin.id}": DOM playfield draw failed`, error);
      }
      return;
    }
    this.surface.draw(frame.layout.stage, (surface) => this.skin.gameplay.draw(surface, frame));
  };
}
 
/**
 * The select frame the scene hands over; the binding adds `revision`, `audio`, `hit`, and the skin-facing extras
 * (`pointer`, `chartBestRecord`, `chartImage`, `settings`).
 */
export type BeMusicSelectSceneFrame = Omit<
  BeMusicSelectFrame,
  | 'revision'
  | 'audio'
  | 'hit'
  | 'pointer'
  | 'chartBestRecord'
  | 'courseBestRecord'
  | 'danRanks'
  | 'chartImage'
  | 'settings'
  | 'listScroll'
>;
 
/**
 * Select for one scene: {@link render} records the latest state when the scene's input changes, and {@link tick} draws
 * the skin every frame with it. Hit areas the skin declares become transparent pointer targets in {@link frontLayer}.
 */
export class BeMusicSelectBinding {
  readonly outroMs: number;
  /** Shows the skin's canvas, behind the scene's list layer. */
  readonly backLayer: Container = new Container();
  /** Holds the hit areas, in front of everything. */
  readonly frontLayer: Container = new Container();
  private readonly skin: BeMusicSkin;
  private readonly surface: SkinSurface;
  private readonly hitPool: ChildPool;
  private settings: BeMusicSkinSettingValues;
  private readonly chartBestRecord: BeMusicSelectFrame['chartBestRecord'];
  private readonly courseBestRecord: NonNullable<BeMusicSelectFrame['courseBestRecord']>;
  private readonly danRanks: () => readonly BeMusicDanRank[];
  private readonly chartImage: BeMusicChartImageLookup;
  /** `frame.listScroll`: how far the list is pulled past its resting place, in design pixels (see `setListScroll`). */
  private listScroll = 0;
  /** The pointer in design pixels, replaced (not mutated) when it moves so a skin may keep last frame's. */
  private pointer: BeMusicSelectFrame['pointer'] = undefined;
  private frame: BeMusicSelectSceneFrame | undefined;
  private revision = 0;
  /**
   * Where the skin's search box was on the last drawn frame, in design pixels: the hit area it bound to
   * `actions.activateSearch`. Undefined when the skin has none. The host lays its text field over it.
   */
  searchFieldRect: { x: number; y: number; width: number; height: number; fontSize?: number } | undefined;
 
  /**
   * `resolveChartBestRecord` looks up the player's best record on a song for `frame.chartBestRecord`; without one every song
   * reads as never played; `resolveCourseBestRecord` does the same for a course bar (`frame.courseBestRecord`), and `resolveDanRanks` gives the player's dan ranks (`frame.danRanks`, none without it). `chartImage` resolves song images for `frame.chartImage` (call {@link invalidate} when one
   * arrives); without one every image reads as unavailable. `settings` are the player's stored values for the skin's
   * settings; without them the skin draws with its defaults.
   * `renderer` is the player's Pixi renderer: a Pixi-kit skin draws through it.
   */
  constructor(
    skin: BeMusicSkin,
    options: {
      resolveChartBestRecord?: BeMusicSelectFrame['chartBestRecord'];
      resolveCourseBestRecord?: BeMusicSelectFrame['courseBestRecord'];
      resolveDanRanks?: () => readonly BeMusicDanRank[];
      chartImage?: BeMusicChartImageLookup;
      settings?: BeMusicStoredSkinSettings;
      renderer?: Renderer;
    } = {},
  ) {
    this.skin = skin;
    this.surface = new SkinSurface(skin, options.renderer);
    this.outroMs = skin.select.outroMs ?? 0;
    this.chartBestRecord = options.resolveChartBestRecord ?? NO_SONG_RECORD;
    this.courseBestRecord = options.resolveCourseBestRecord ?? NO_COURSE_RECORD;
    this.danRanks = options.resolveDanRanks ?? NO_DAN_RANKS;
    this.chartImage = options.chartImage ?? NO_SONG_IMAGE;
    this.settings = resolveBeMusicSkinSettings(skin, options.settings);
    this.backLayer.addChild(new Sprite({ texture: this.surface.texture, roundPixels: true }));
    this.hitPool = new ChildPool(this.frontLayer);
  }
 
  /** Records the select state after an input-driven change. Drawing happens in {@link tick}. */
  render(frame: BeMusicSelectSceneFrame): void {
    this.frame = frame;
    this.revision += 1;
  }
 
  /**
   * Replaces the player's values for the skin's settings and moves `frame.revision`, so a skin that caches its layout
   * per revision redraws with them on the next {@link tick}.
   */
  setSettings(stored: BeMusicStoredSkinSettings | undefined): void {
    this.settings = resolveBeMusicSkinSettings(this.skin, stored);
    this.revision += 1;
  }
 
  /** Moves `frame.revision` without a state change, e.g. when a song image the skin asked for has loaded. */
  invalidate(): void {
    this.revision += 1;
  }
 
  /**
   * Records where the pointer is, in the stage's design pixels, or `undefined` when it is off the stage. Read by the
   * next {@link tick} as `frame.pointer` and by `frame.hit`'s hover test.
   */
  setPointer(x: number | undefined, y: number | undefined): void {
    if (x === undefined || y === undefined) {
      this.pointer = undefined;
    } else if (this.pointer?.x !== x || this.pointer.y !== y) {
      this.pointer = { x, y };
    }
  }
 
  /**
   * Records how far the list is pulled past its resting place (design pixels, positive toward later entries), read by
   * the next {@link tick} as `frame.listScroll`. Changes every frame of a drag without moving `frame.revision`.
   */
  setListScroll(value: number): void {
    this.listScroll = value;
  }
 
  /** Draws the skin with the latest state, the current time, and what is playing. */
  tick(
    nowMs: number,
    focusedChart: BeMusicSelectFrame['focusedChart'],
    launchAt: number | undefined,
    audio: BeMusicSelectFrame['audio'],
  ): void {
    const base = this.frame;
    if (!base) return;
    const pool = this.hitPool;
    pool.begin();
    const pointer = this.pointer;
    let searchFieldRect: BeMusicSelectBinding['searchFieldRect'];
    const frame: BeMusicSelectFrame = {
      ...base,
      nowMs,
      focusedChart,
      launchAt,
      audio,
      revision: this.revision,
      listScroll: this.listScroll,
      pointer,
      chartBestRecord: this.chartBestRecord,
      courseBestRecord: this.courseBestRecord,
      danRanks: this.danRanks(),
      chartImage: this.chartImage,
      settings: this.settings,
      hit: (x, y, w, h, action, cursor = 'pointer') => {
        const area = pool.acquireGraphics();
        area.rect(x, y, w, h).fill({ color: 0xffffff, alpha: 0.001 });
        area.eventMode = 'static';
        area.cursor = cursor;
        area.removeAllListeners('pointerdown');
        area.on('pointerdown', (event) => {
          // The shell uses unhandled mouse presses on the canvas for background fullscreen gestures.
          if (event.pointerType === 'mouse' && event.button === 0) event.preventDefault();
          action();
        });
        if (action === base.actions.activateSearch) {
          const fontSize =
            base.designHeight > base.designWidth
              ? (this.skin.select.portraitSearchTextSize ?? this.skin.select.searchTextSize)
              : this.skin.select.searchTextSize;
          searchFieldRect = { x, y, width: w, height: h, ...(fontSize !== undefined ? { fontSize } : {}) };
        }
        return pointer !== undefined && pointer.x >= x && pointer.x < x + w && pointer.y >= y && pointer.y < y + h;
      },
    };
    try {
      this.surface.draw({ width: frame.designWidth, height: frame.designHeight }, (surface) =>
        this.skin.select.draw(surface, frame),
      );
    } finally {
      pool.end();
      this.searchFieldRect = searchFieldRect;
    }
  }
 
  dispose(): void {
    this.hitPool.destroy();
    this.backLayer.destroy({ children: true });
    this.frontLayer.destroy({ children: true });
    this.surface.destroy();
  }
}
 
/** The result frame the scene hands over; the binding adds `chartImage` and `settings`. */
export type BeMusicResultSceneFrame = Omit<BeMusicResultFrame, 'chartImage' | 'settings'>;
 
/** Result for one scene: draws the skin every frame onto a canvas shown by {@link view}. */
export class BeMusicResultBinding {
  /** Persistent container showing the skin's canvas; the scene mounts it once. */
  readonly view: Container = new Container();
  private readonly skin: BeMusicSkin;
  private readonly surface: SkinSurface;
  private settings: BeMusicSkinSettingValues;
  private readonly chartImage: BeMusicChartImageLookup;
 
  /**
   * `chartImage` resolves song images for `frame.chartImage`; without one every image reads as unavailable. `settings`
   * are the player's stored values for the skin's settings; without them the skin draws with its defaults.
   * `renderer` is the player's Pixi renderer: a Pixi-kit skin draws through it.
   */
  constructor(
    skin: BeMusicSkin,
    options: { chartImage?: BeMusicChartImageLookup; settings?: BeMusicStoredSkinSettings; renderer?: Renderer } = {},
  ) {
    this.skin = skin;
    this.surface = new SkinSurface(skin, options.renderer);
    this.settings = resolveBeMusicSkinSettings(skin, options.settings);
    this.chartImage = options.chartImage ?? NO_SONG_IMAGE;
    this.view.addChild(new Sprite({ texture: this.surface.texture, roundPixels: true }));
  }
 
  /** Replaces the player's values for the skin's settings; the next frame draws with them. */
  setSettings(stored: BeMusicStoredSkinSettings | undefined): void {
    this.settings = resolveBeMusicSkinSettings(this.skin, stored);
  }
 
  render(sceneFrame: BeMusicResultSceneFrame): void {
    const frame: BeMusicResultFrame = { ...sceneFrame, chartImage: this.chartImage, settings: this.settings };
    this.surface.draw({ width: frame.designWidth, height: frame.designHeight }, (surface) =>
      this.skin.result.draw(surface, frame),
    );
  }
 
  dispose(): void {
    this.view.destroy({ children: true });
    this.surface.destroy();
  }
}
 
/** The decide frame the scene hands over; the binding adds `chartImage` and `settings`. */
export type BeMusicDecideSceneFrame = Omit<BeMusicDecideFrame, 'chartImage' | 'settings'>;
 
/** Decide for one scene: draws the skin's `decide` every frame onto a canvas shown by {@link view}. */
export class BeMusicDecideBinding {
  /** Persistent container showing the skin's canvas; the scene mounts it once. */
  readonly view: Container = new Container();
  private readonly skin: BeMusicSkin;
  private readonly surface: SkinSurface;
  private settings: BeMusicSkinSettingValues;
  private readonly chartImage: BeMusicChartImageLookup;
 
  /**
   * `chartImage` resolves song images for `frame.chartImage`; without one every image reads as unavailable. `settings`
   * are the player's stored values for the skin's settings; without them the skin draws with its defaults.
   * `renderer` is the player's Pixi renderer: a Pixi-kit skin draws through it.
   */
  constructor(
    skin: BeMusicSkin,
    options: { chartImage?: BeMusicChartImageLookup; settings?: BeMusicStoredSkinSettings; renderer?: Renderer } = {},
  ) {
    this.skin = skin;
    this.surface = new SkinSurface(skin, options.renderer);
    this.settings = resolveBeMusicSkinSettings(skin, options.settings);
    this.chartImage = options.chartImage ?? NO_SONG_IMAGE;
    this.view.addChild(new Sprite({ texture: this.surface.texture, roundPixels: true }));
  }
 
  /** Replaces the player's values for the skin's settings; the next frame draws with them. */
  setSettings(stored: BeMusicStoredSkinSettings | undefined): void {
    this.settings = resolveBeMusicSkinSettings(this.skin, stored);
  }
 
  /** Draws one frame; a no-op for a skin without a decide screen. */
  render(sceneFrame: BeMusicDecideSceneFrame): void {
    const decide = this.skin.decide;
    if (!decide) return;
    const frame: BeMusicDecideFrame = { ...sceneFrame, chartImage: this.chartImage, settings: this.settings };
    this.surface.draw({ width: frame.designWidth, height: frame.designHeight }, (surface) =>
      decide.draw(surface, frame),
    );
  }
 
  dispose(): void {
    this.view.destroy({ children: true });
    this.surface.destroy();
  }
}