All files / player-browser/src/view/built-in play-chrome.ts

89.36% Statements 126/141
77.14% Branches 135/175
82.35% Functions 14/17
92.18% Lines 118/128

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                                                                                                                      31x     33x                                   31x   31x                                                                           4x               12x 12x 12x 9x   3x 3x 12x 1x 12x             35x 35x 35x                 15x   20x               20x                 20x       8x 8x 8x 8x   28x 8x     8x       8x 16x 8x   8x   8x                 8x     8x 8x 8x 8x 8x 8x 8x 8x 8x 8x     8x                                                                                               28x                                                                                       31x                     8x 8x 5x 3x 3x   2x 2x 4x 4x 3x 3x   2x               13x         10x 10x 10x         10x 10x 4x 4x 4x 4x 4x 4x   4x                                                             12x 3x 12x 12x   12x     12x 3x 3x 3x 3x 24x 24x         3x       3x   3x         2x 2x       2x   2x 2x 2x 2x       2x 2x                 10x 10x 10x               4x   6x                 6x               6x                                             6x 6x 6x 6x 6x 6x 6x 6x 6x 6x             6x 2x   4x     6x 6x                                                      
import { fitVideoBGARect } from './bga-layout.ts';
import { pickActiveBGACue } from '../../chart/bga-timeline.ts';
/**
 * The built-in play screen's chrome inputs (`BuiltInPlayView`): the lane geometry of the built-in playfield for the
 * loaded chart and the stage, and the runtime the skinless chrome (`skinlessChromeRenderer`, or a Be-Music Skin's
 * `gameplay.renderChrome`) draws from each frame.
 *
 * The functions read the scene's state through {@link LaneGeometryContext} and {@link PlayChromeContext}; the scene
 * passes itself.
 */
 
import type { ChartPlayVariant } from '@be-music/chart-model';
import { resolve____RankLabel } from '@be-music/player-engine/ruleset';
import { resolveNonstopSongInfoState, type NonstopSongInfo } from '@be-music/player-engine/course';
import {
  formatJudgeDetail,
  resolveGameplayLaneGeometry,
  resolveGameplayLayout,
  resolveCabinetLayout,
  type BeMusicJudgeDetail,
  type GameplayLayoutMode,
} from '@be-music/player-skin-sdk';
import type { PlayOptions } from '@be-music/player-scene-model';
import { formatGaugeLabel, recentJudgeTimings, resolveGreenNumber } from '@be-music/player-scene-model';
import type { AudioFeatures } from '../../runtime/audio-analysis.ts';
import type { PlaySessionOptions } from '../../session/play/play-options.ts';
import type { Container } from 'pixi.js';
import type { ChildPool } from '../../stage/pixi-utils.ts';
import type { BeMusicGameplayBinding } from '../../skin/be-music/binding.ts';
import type { PlayfieldRuntime } from '../shared/playfield/context.ts';
import type {
  BeMusicGameplayLayout,
  BeMusicGameplayRuntime,
  BeMusicSecondPlayerRuntime,
  BeMusicJudgmentState,
  BeMusicStage,
} from '../../skin/be-music/types.ts';
import type { PlayFrame, PlayfieldBGATarget, PlayfieldStage } from '../types.ts';
import { DESIGN_HEIGHT, DESIGN_WIDTH } from '../../stage/design.ts';
import { BGA } from '../shared/play-constants.ts';
import { resolveKeyBeamAlpha } from '../shared/playfield/key-beam.ts';
 
/** One side's recent judgement state for skinless chrome renderers (the Be-Music Skin type). */
export type SkinlessGameplayJudgeState = BeMusicJudgmentState;
 
/** Live gameplay values a skinless chrome renderer can paint (the Be-Music Skin type). */
export type SkinlessGameplayChromeRuntime = BeMusicGameplayRuntime;
 
export interface SkinlessGameplayChromeRenderContext {
  layer: Container;
  overlayLayer: Container;
  layerPool: ChildPool;
  overlayLayerPool: ChildPool;
  runtime: SkinlessGameplayChromeRuntime;
}
 
export type SkinlessGameplayChromeRenderer = (context: SkinlessGameplayChromeRenderContext) => void;
 
/** Default-family BGA rect: the fixed {@link BGA} square, drawn opaque and untinted. */
const DEFAULT_BGA_TARGET: PlayfieldBGATarget = createDefaultBGATarget(BGA);
 
function createDefaultBGATarget(rect: { x: number; y: number; w: number; h: number }): PlayfieldBGATarget {
  return {
    x: rect.x,
    y: rect.y,
    w: rect.w,
    h: rect.h,
    noBase: false,
    noLayer: false,
    noPoor: false,
    preserveVideoAspect: true,
    applyToSprite: (sprite) => {
      sprite.alpha = 1;
      sprite.tint = 0xffffff;
      sprite.blendMode = 'normal';
    },
  };
}
 
/** The LR2-compatible 640x480 canvas. */
export const LEGACY_STAGE_SIZE: PlayfieldStage = { width: DESIGN_WIDTH, height: DESIGN_HEIGHT };
/** The 640x480 stage with the fixed default-family BGA square, for skins that declare no stage of their own. */
const LEGACY_STAGE: BeMusicStage = { ...LEGACY_STAGE_SIZE, resolveBGARect: () => ({ ...BGA }) };
 
/** What {@link resolveLaneGeometry} lays the lanes out from, and its cache: a play view's members of these names. */
export interface LaneGeometryContext {
  readonly play: PlayfieldRuntime;
  readonly layoutMode: GameplayLayoutMode;
  readonly beMusicStage: BeMusicStage | undefined;
  laneGeometryCache:
    | {
        laneChannels: readonly string[];
        laneCount: number;
        twoPlayer: boolean;
        playVariant: unknown;
        layoutMode: unknown;
        stage: BeMusicStage | undefined;
        geometry: ReturnType<typeof resolveGameplayLaneGeometry>;
      }
    | undefined;
}
 
/** What the skinless chrome's runtime is made from each frame: a play view's members of these names. */
export interface PlayChromeContext {
  readonly play: PlayfieldRuntime;
  readonly options: Readonly<
    Pick<PlaySessionOptions, 'autoPlay' | 'beMusicEffects' | 'judgeTimingAutoAdjust' | 'nonstop' | 'practiceRange'>
  >;
  readonly audioFrame: AudioFeatures | undefined;
  /** The frame being drawn, for what it carries beside the play: the best record, the course and the player. */
  readonly playFrame?: Pick<PlayFrame, 'scoreTargets' | 'course' | 'playerName' | 'playOptions' | 'progress'>;
}
 
type SongInfoRuntime = Pick<
  SkinlessGameplayChromeRuntime,
  'chartTitle' | 'chartArtist' | 'chartGenre' | 'songInfoFade'
>;
 
/** A NONSTOP stage's song as the runtime names it; a stage without a title keeps the stitched chart's (the course's). */
function stageSongInfo(info: NonstopSongInfo | undefined, fallbackTitle: string | undefined): SongInfoRuntime {
  return { chartTitle: info?.title ?? fallbackTitle, chartArtist: info?.artist, chartGenre: info?.genre };
}
 
/**
 * The song info the chrome shows at `seconds`: the chart's, or in a stitched NONSTOP play the stage being played's,
 * crossfading from the previous stage's as each stage's window starts (`resolveNonstopSongInfoState`).
 */
export function resolveSongInfoRuntime(ctx: PlayChromeContext, seconds: number): SongInfoRuntime {
  const chart = ctx.play.chart;
  const stages = ctx.options.nonstop?.stages;
  if (stages === undefined || stages.length === 0) {
    return { chartTitle: chart?.title, chartArtist: chart?.artist, chartGenre: chart?.genre };
  }
  const state = resolveNonstopSongInfoState(stages, seconds);
  const current = stageSongInfo(stages[state.stage]?.songInfo, chart?.title);
  if (state.previous === undefined) return current;
  const { songInfoFade: _fade, ...previous } = stageSongInfo(stages[state.previous]?.songInfo, chart?.title);
  return { ...current, songInfoFade: { ...previous, progress: state.progress } };
}
 
/** Lane rects, playfield bounds, and judgement line of the built-in playfield for the loaded chart. */
export function resolveLaneGeometry(ctx: LaneGeometryContext): ReturnType<typeof resolveGameplayLaneGeometry> {
  // Asked several times a frame (lanes, BGA, notes); it changes only with its inputs, so it is kept until one does. The
  // stage is one of the skin's own stage objects, so a rotation that switches stages shows up as a new one.
  const stage = ctx.beMusicStage;
  const cached = ctx.laneGeometryCache;
  if (
    cached !== undefined &&
    cached.laneChannels === ctx.play.laneChannels &&
    cached.laneCount === ctx.play.laneChannels.length &&
    cached.playVariant === ctx.play.chartPlayVariant &&
    cached.layoutMode === ctx.layoutMode &&
    cached.twoPlayer === (ctx.play.secondPlayer !== undefined) &&
    cached.stage === stage
  ) {
    return cached.geometry;
  }
  const geometry = resolveGameplayLaneGeometry(
    ctx.play.laneChannels,
    ctx.play.laneChannels.length,
    ctx.play.chartPlayVariant,
    ctx.layoutMode,
    stage,
    ctx.play.secondPlayer !== undefined,
  );
  ctx.laneGeometryCache = {
    laneChannels: ctx.play.laneChannels,
    laneCount: ctx.play.laneChannels.length,
    twoPlayer: ctx.play.secondPlayer !== undefined,
    playVariant: ctx.play.chartPlayVariant,
    layoutMode: ctx.layoutMode,
    stage,
    geometry,
  };
  return geometry;
}
 
export function resolveSkinlessGameplayChromeRuntime(ctx: PlayChromeContext): SkinlessGameplayChromeRuntime {
  const total = ctx.play.score.total > 0 ? ctx.play.score.total : 0;
  const play = ctx.play.playState;
  const seconds = ctx.play.currentSeconds();
  const chartLengthSeconds = ctx.play.resolveChartDurationSeconds();
  const usesPlayer2 =
    ctx.play.chartPlayVariant !== '9' && ctx.play.laneChannels.some((channel) => channel.startsWith('2'));
  const judgeSides: SkinlessGameplayJudgeState[] = [];
  // A chart's HIDJUDGE (#931) hides the judgment display as LR2's SILENT does.
  const hidesJudge =
    ctx.options.judgeTimingAutoAdjust === 'LR2-SILENT' ||
    ctx.play.engineFrame?.chartOptions?.crazyJudge === 'HIDJUDGE' ||
    // The player's own switch (AC 34's 判定文字の表示位置, OFF).
    ctx.playFrame?.playOptions.judgeDisplay === 'OFF';
  for (const side of ['1P', '2P'] as const) {
    if (side === '2P' && !usesPlayer2) {
      continue;
    }
    const state = ctx.play.judgeSideState[side];
    // LR2's SILENT automatic judge timing shows no judgment or combo.
    Iif (state.judge && seconds <= state.until && !hidesJudge) {
      judgeSides.push({
        side,
        judge: state.judge,
        combo: state.combo,
        details: resolveJudgeDetails(ctx.playFrame?.playOptions, state.timings, seconds),
      });
    }
  }
  const currentBeat = ctx.play.currentBeat(seconds);
  // The BPM readout freezes at the reversal value (LR2's frozen pump holds |BPM| there) instead of following the
  // mirrored scroll back through earlier tempo points — see `nowBPM`.
  const bpm = ctx.play.nowBPM(seconds) ?? ctx.play.chart?.bpm;
  const laneCovers = ctx.play.resolveLaneCovers();
  const visibleMs = ctx.play.resolveVisibleMs(laneCovers[0], bpm, ctx.play.scrollMapper?.rateAt?.(currentBeat) ?? 1);
  const frame = ctx.playFrame;
  const best = frame?.scoreTargets?.bestEXScore;
  const target = frame?.scoreTargets?.targetEXScore;
  const targetPace = frame?.scoreTargets?.targetPaceEXScore;
  const targetLabel = frame?.scoreTargets?.targetLabel;
  const nowMs = ctx.play.playClock();
  const songInfo = resolveSongInfoRuntime(ctx, seconds);
  // One literal with every field, absent ones `undefined`: the skins read this object every frame, and conditional
  // spreads would hand them a different hidden class from frame to frame (megamorphic reads) and allocate the pieces.
  return {
    bestEXScore: best !== undefined && best > 0 ? best : undefined,
    targetEXScore: target !== undefined && target > 0 ? target : undefined,
    targetPaceEXScore: target !== undefined && target > 0 ? targetPace : undefined,
    targetLabel,
    course: frame?.course,
    playerName: frame?.playerName,
    random1P: frame?.playOptions.random1P,
    tempo: ctx.play.tempo,
    chartTitle: songInfo.chartTitle,
    chartArtist: songInfo.chartArtist,
    chartGenre: songInfo.chartGenre,
    songInfoFade: songInfo.songInfoFade,
    // The scroll above runs on the chart's tempo; a NONSTOP readout shows the stage's own BPM — see `displayBPM`.
    bpm: ctx.play.displayBPM(seconds) ?? bpm,
    // The player's hi-speed, as the select panel and the host show it (HS-FIX scales only the scroll).
    hiSpeed: play.view.hiSpeed.player,
    floatingHiSpeed: play.view.hiSpeed.floating ? true : undefined,
    score: ctx.play.score.score,
    exScore: ctx.play.score.exScore,
    exScoreMax: total * 2,
    combo: play.combo,
    maxCombo: play.maxCombo,
    perfect: ctx.play.score.perfect,
    great: ctx.play.score.great,
    good: ctx.play.score.good,
    bad: ctx.play.score.bad,
    poor: ctx.play.score.poor,
    gauge: ctx.play.gaugeState.current,
    clearThreshold: ctx.play.gaugeState.clearThreshold,
    laneCount: ctx.play.laneChannels.length,
    laneChannels: ctx.play.laneChannels,
    playVariant: ctx.play.chartPlayVariant,
    lastJudge: seconds <= ctx.play.lastJudgeUntil && !hidesJudge ? ctx.play.lastJudge : undefined,
    judgeSides,
    rank: total <= 0 ? undefined : resolve____RankLabel(ctx.play.score.exScore, total),
    secondPlayer: ctx.play.secondPlayer !== undefined ? secondPlayerRuntime(ctx.play.secondPlayer) : undefined,
    autoplay: ctx.options.autoPlay === true,
    practice: ctx.play.practice === true || ctx.options.practiceRange !== undefined,
    // The camera fills the BGA frame even on a chart without a BGA.
    hasBGA: ctx.play.hasBGA || ctx.play.bgaCamera !== undefined || ctx.play.lrxBGA !== undefined,
    nowMs,
    progressRatio: chartLengthSeconds > 0 ? Math.max(0, Math.min(1, seconds / chartLengthSeconds)) : 0,
    // The beat this frame already worked out for the same `seconds`.
    beatPhase: currentBeat - Math.floor(currentBeat),
    chartBeat: currentBeat,
    scratchInputs: Object.fromEntries(ctx.play.scratchInputs ?? []),
    keyBeams: Object.fromEntries(
      ctx.play.laneChannels.map((channel) => [channel, resolveKeyBeamAlpha(ctx.play, channel, 120, nowMs)]),
    ),
    ghostSide: ctx.play.ghostSide || undefined,
    rulesetLabel: ctx.play.resolveJudgeRuleset(),
    gaugeLabel: formatGaugeLabel(ctx.play.gaugeState.type) ?? 'GROOVE',
    gaugeSurvival: ctx.play.gaugeState.survival === true,
    fast: ctx.play.fastCount,
    slow: ctx.play.slowCount,
    totalNotes: total,
    // While assets load the count-in waits: the skin shows NOW LOADING instead.
    chartMs: ctx.play.assetsLoading ? undefined : ctx.play.resolveChartMs(),
    loading: ctx.play.assetsLoading,
    loadingProgress: ctx.playFrame?.progress,
    judgeAtMs: ctx.play.lastJudgeAt,
    impulseAtMs: ctx.play.lastImpulseAt,
    impulseKind: ctx.play.lastImpulseKind,
    effects: ctx.options.beMusicEffects ?? 'full',
    audio: ctx.audioFrame,
    chart: ctx.play.chart,
    lastJudgeDeltaMs: play.lastJudgeDeltaMs,
    judgeTimings: recentJudgeTimings(play),
    hidesJudgeCounts: ctx.playFrame?.playOptions.judgeCounts === false,
    minBPM: ctx.play.chartBPMRange?.minBPM,
    maxBPM: ctx.play.chartBPMRange?.maxBPM,
    mainBPM: ctx.play.chartBPMRange?.mainBPM,
    songLengthMs: ctx.play.chart ? chartLengthSeconds * 1000 : undefined,
    // Clamped to the length so the remaining time never runs negative through the audio tail.
    songElapsedMs: ctx.play.chart ? Math.min(seconds, chartLengthSeconds) * 1000 : undefined,
    failedAtMs: ctx.play.playMoments.failedAtMs,
    allNotesDoneAtMs: ctx.play.playMoments.allNotesDoneAtMs,
    outroAtMs: ctx.play.playMoments.outroAtMs,
    gaugeRiseAtMs: ctx.play.playMoments.gaugeRiseAtMs,
    gaugeMaxAtMs: ctx.play.playMoments.gaugeMaxAtMs,
    // The play state's own arrays, shared by reference: skins are told not to mutate them.
    scoreHistory: play.scoreHistory,
    gaugeHistory: play.gaugeHistory,
    judgeWindows: ctx.play.judgeWindows,
    laneCovers,
    visibleMs,
    greenNumber: visibleMs === undefined ? undefined : resolveGreenNumber(visibleMs),
  };
}
 
/** No judge detail: one array for every judgment that shows none. */
const NO_JUDGE_DETAILS: readonly BeMusicJudgeDetail[] = [];
 
/**
 * The judge detail a side's plate shows at chart time `seconds`: the timing of the judgment on the plate, or, with
 * the keys and the scratch apart, the last timing of each that is still showing. None when the option is off.
 */
export function resolveJudgeDetails(
  options: Pick<PlayOptions, 'judgeDetail' | 'judgeDetailSplit'> | undefined,
  timings: PlayfieldRuntime['judgeSideState']['1P']['timings'],
  seconds: number,
): readonly BeMusicJudgeDetail[] {
  const mode = options?.judgeDetail ?? 'OFF';
  if (mode === 'OFF' || timings === undefined) return NO_JUDGE_DETAILS;
  if (!options?.judgeDetailSplit) {
    const detail = timings.last && formatJudgeDetail(mode, timings.last.judge, timings.last.deltaMs);
    return detail ? [detail] : NO_JUDGE_DETAILS;
  }
  const details: BeMusicJudgeDetail[] = [];
  for (const lane of ['scratch', 'keys'] as const) {
    const timing = timings[lane];
    if (timing === undefined || seconds > timing.until) continue;
    const detail = formatJudgeDetail(mode, timing.judge, timing.deltaMs);
    Eif (detail) details.push({ ...detail, lane });
  }
  return details.length > 0 ? details : NO_JUDGE_DETAILS;
}
 
/**
 * The judgment position option in stage pixels: `position` percent of the lanes' height, from their top to the judge
 * line. Positive is down the lanes.
 */
export function resolveJudgeOffsetY(position: number, top: number, judgementY: number): number {
  return Math.round(((judgementY - top) * position) / 100);
}
 
/** Keep the base layout/BGA fixed and publish each side's actual line for the skin's chrome. */
function withLiftLines(ctx: BeMusicLayoutContext, layout: BeMusicGameplayLayout): BeMusicGameplayLayout {
  const bga = resolveVideoBGA(ctx, layout.bga, resolveLaneGeometry(ctx));
  if (bga !== layout.bga) layout = { ...layout, bga };
  const judgeOffsetY = resolveJudgeOffsetY(
    ctx.playFrame?.playOptions.judgePosition ?? 0,
    layout.playfield.top,
    layout.playfield.judgementY,
  );
  Iif (judgeOffsetY !== 0) layout = { ...layout, playfield: { ...layout.playfield, judgeOffsetY } };
  if (!ctx.drawsLift) return layout;
  const sides = { ...layout.playfield.sides };
  for (const cover of ctx.play.resolveLaneCovers()) {
    const bounds = sides[cover.side];
    Iif (!bounds) continue;
    const judgementY = layout.playfield.judgementY - (layout.playfield.judgementY - layout.playfield.top) * cover.lift;
    sides[cover.side] = { ...bounds, judgementY };
  }
  return { ...layout, playfield: { ...layout.playfield, sides } };
}
 
/** What the built-in BGA rect is worked out from: a play view's members of these names. */
export interface BGATargetsContext extends LaneGeometryContext {
  stageBGATarget: PlayfieldBGATarget | undefined;
}
 
/** What the Be-Music chrome's layout is worked out from, and its cache: a play view's members of these names. */
export interface BeMusicLayoutContext extends LaneGeometryContext {
  readonly drawsLift?: boolean;
  /** The frame being drawn, for its judgment position. */
  readonly playFrame?: PlayChromeContext['playFrame'];
  beMusicLayout:
    | {
        twoPlayer: boolean;
        layoutMode: GameplayLayoutMode;
        channels: readonly string[];
        variant: ChartPlayVariant | undefined;
        stage: BeMusicStage;
        layout: BeMusicGameplayLayout;
      }
    | undefined;
}
 
/** Resizes only opted-in built-in monitors; external skins retain their authored rectangles. */
function resolveVideoBGA(
  ctx: LaneGeometryContext,
  rect: BeMusicGameplayLayout['bga'],
  geometry: ReturnType<typeof resolveLaneGeometry>,
): BeMusicGameplayLayout['bga'] {
  if (!rect || !ctx.beMusicStage?.fitBGAVideoAspect || !ctx.play.bgaVideos?.size) return rect;
  const cues = ctx.play.bgaTimeline?.base ?? [];
  const cue = pickActiveBGACue(cues, ctx.play.currentSeconds()) ?? cues[0];
  const key = cue?.bmpKey;
  const handle =
    key === undefined
      ? undefined
      : (ctx.play.bgaVideos.get(String.fromCharCode(0) + 'base:' + key) ?? ctx.play.bgaVideos.get(key));
  Iif (!handle) return rect;
  let maxWidth = rect.w;
  Eif (geometry.orientation === 'landscape' && geometry.mode === 'standard') {
    const sides: BeMusicGameplayLayout['playfield']['sides'] = {};
    for (const lane of geometry.lanes) {
      const before = sides[lane.side];
      sides[lane.side] = {
        left: Math.min(before?.left ?? lane.x, lane.x),
        right: Math.max(before?.right ?? lane.x + lane.w, lane.x + lane.w),
      };
    }
    const cabinet = resolveCabinetLayout({
      playfield: { ...geometry, sides, centerX: (geometry.left + geometry.right) / 2 },
      twoPlayer: geometry.twoPlayer,
    });
    maxWidth = geometry.twoPlayer ? cabinet.judge.w : cabinet.players.w;
  }
  return fitVideoBGARect(rect, handle.video.videoWidth, handle.video.videoHeight, maxWidth);
}
 
/** The built-in BGA rect (`PlayfieldSkin.bgaTargets` of the built-in view). */
export function collectBGATargets(ctx: BGATargetsContext, out: PlayfieldBGATarget[]): void {
  const stage = ctx.beMusicStage;
  Iif (!stage) {
    out.push(DEFAULT_BGA_TARGET);
    return;
  }
  const geometry = resolveLaneGeometry(ctx);
  // The landscape touch layout gives the BGA's room to the lanes.
  Iif (geometry.mode === 'touch' && geometry.orientation === 'landscape') return;
  const rect = resolveVideoBGA(ctx, stage.resolveBGARect(geometry.right, geometry.left, geometry.twoPlayer), geometry)!;
  const cached = ctx.stageBGATarget;
  Iif (cached && cached.x === rect.x && cached.y === rect.y && cached.w === rect.w && cached.h === rect.h) {
    out.push(cached);
    return;
  }
  ctx.stageBGATarget = createDefaultBGATarget(rect);
  out.push(ctx.stageBGATarget);
}
 
/**
 * The gameplay layout handed to the Be-Music Skin's chrome: stage, lanes, playfield bounds, judgement line, and BGA
 * rect. Lane geometry only changes with the chart and the stage, so it is rebuilt when the lane channels, the play
 * variant, or the stage (a rotation) change.
 */
export function resolveBeMusicLayout(ctx: BeMusicLayoutContext): BeMusicGameplayLayout {
  const stage = ctx.beMusicStage ?? LEGACY_STAGE;
  const cached = ctx.beMusicLayout;
  if (
    cached &&
    cached.channels === ctx.play.laneChannels &&
    cached.layoutMode === ctx.layoutMode &&
    cached.variant === ctx.play.chartPlayVariant &&
    cached.twoPlayer === (ctx.play.secondPlayer !== undefined) &&
    cached.stage === stage
  ) {
    return withLiftLines(ctx, cached.layout);
  }
  const layout = resolveGameplayLayout(
    {
      laneChannels: ctx.play.laneChannels,
      playVariant: ctx.play.chartPlayVariant,
      layoutMode: ctx.layoutMode,
      twoPlayer: ctx.play.secondPlayer !== undefined,
    },
    stage,
  );
  ctx.beMusicLayout = {
    twoPlayer: ctx.play.secondPlayer !== undefined,
    layoutMode: ctx.layoutMode,
    channels: ctx.play.laneChannels,
    variant: ctx.play.chartPlayVariant,
    stage,
    layout,
  };
  return withLiftLines(ctx, layout);
}
 
/** What {@link renderBuiltInChrome} draws into: the chrome layers and pools, the BGA layer and the Be-Music binding. */
export interface BuiltInChromeContext extends PlayChromeContext, BeMusicLayoutContext {
  readonly skinLayer: Container;
  readonly overlayLayer: Container;
  readonly bgaLayer: Container;
  readonly skinLayerPool: ChildPool;
  readonly overlayLayerPool: ChildPool;
  readonly skinBinding: BeMusicGameplayBinding | undefined;
}
 
/**
 * Paints the built-in chrome layers (`skinLayer` / `overlayLayer`) for this frame and resets their transforms together
 * with the BGA layer's: the skinless chrome through a host's `skinlessChromeRenderer`, else the Be-Music Skin's
 * `gameplay.renderChrome`, in raw design coordinates.
 */
export function renderBuiltInChrome(
  ctx: BuiltInChromeContext,
  skinlessChromeRenderer: SkinlessGameplayChromeRenderer | undefined,
  runtime: SkinlessGameplayChromeRuntime = resolveSkinlessGameplayChromeRuntime(ctx),
): void {
  ctx.skinLayerPool.begin();
  ctx.overlayLayerPool.begin();
  try {
    ctx.skinLayer.scale.set(1);
    ctx.skinLayer.position.set(0, 0);
    ctx.overlayLayer.scale.set(1);
    ctx.overlayLayer.position.set(0, 0);
    ctx.bgaLayer.scale.set(1);
    ctx.bgaLayer.position.set(0, 0);
    const context = {
      layer: ctx.skinLayer,
      overlayLayer: ctx.overlayLayer,
      layerPool: ctx.skinLayerPool,
      overlayLayerPool: ctx.overlayLayerPool,
      runtime,
    };
    if (skinlessChromeRenderer) {
      skinlessChromeRenderer(context);
    } else {
      ctx.skinBinding?.renderChrome({ ...context, layout: resolveBeMusicLayout(ctx) });
    }
  } finally {
    ctx.skinLayerPool.end();
    ctx.overlayLayerPool.end();
  }
}
 
/** The 2P player's HUD figures in a two-player play, read off its own play state and scores. */
function secondPlayerRuntime(second: NonNullable<PlayfieldRuntime['secondPlayer']>): BeMusicSecondPlayerRuntime {
  const total = Math.max(0, second.score.total);
  return {
    score: second.score.score,
    exScore: second.score.exScore,
    exScoreMax: total * 2,
    combo: second.playState.combo,
    maxCombo: second.playState.maxCombo,
    perfect: second.score.perfect,
    great: second.score.great,
    good: second.score.good,
    bad: second.score.bad,
    poor: second.score.poor,
    gauge: second.playState.gauge,
    ...(second.gauge !== undefined && second.gauge.max > 0
      ? { clearThreshold: (second.gauge.clearThreshold / second.gauge.max) * 100 }
      : {}),
    gaugeLabel: formatGaugeLabel(second.gauge?.type ?? second.playState.gaugeType) ?? 'GROOVE',
    gaugeSurvival: second.gauge?.survival === true,
    ...(total > 0 ? { rank: resolve____RankLabel(second.score.exScore, total) } : {}),
  };
}