All files / player-browser/src/view/beatoraja play-stage.ts

67.34% Statements 66/98
46.66% Branches 28/60
45.83% Functions 11/24
72.72% Lines 64/88

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                                                                                                                      28x                                                                                                         13x 13x                       13x 13x 13x 13x 13x   13x 13x 13x 13x                         13x                         13x 13x 13x 13x       3x         13x         19x       22x         3x               1x 1x 1x                       1x                 3x                 28x                                                                               3x 3x 3x 3x 3x 3x 3x       3x 2x 2x 3x         3x                       3x     3x 3x 3x 3x   3x 3x 3x   3x                 3x   3x     3x                         3x 3x                                                                                                                                   2x 2x 2x   2x                             13x 13x 13x 13x 13x 13x      
import { isScratch } from '@be-music/player-engine/lanes';
import { renderJudgeArea } from '../shared/judge-area.ts';
import type { KeyBoundBGAFrame, BmsonBGAFrame } from '@be-music/player-engine/display';
import type { BGAFeed } from '../../media/bga-camera.ts';
import type { BGAOpacityTimelines, ChartOptionProgram } from '@be-music/chart-model';
import {
  resolveConstantAlpha,
  resolveNoteDisplaySeconds,
  type ConstantVisibility,
  resolveLaneCover,
  type LaneCoverState,
} from '@be-music/player-scene-model';
/**
 * One beatoraja play skin on the stage: the skin's elements (`BeatorajaPlaySkinView`) with the play's layers spliced in
 * where the skin authored them — the lane markers under the notes at the skin's note anchor, and the BGA at its `bga`
 * destination — on a black backdrop, the skin's canvas fitted into the window. The play view keeps one per skin and
 * builds another when the player's skin options change mid-play; the play and its bridge carry over.
 */
 
import {
  normalizeBeatorajaImages,
  normalizeBeatorajaNote,
  type BeatorajaImageElement,
  type BeatorajaImageId,
} from '@be-music/skin-beatoraja';
import type { TempoReversalPoint, ChartPlayVariant } from '@be-music/chart-model';
import type { ScrollDistanceMapperLike } from '@be-music/player-engine/display';
import { Container, type Texture } from 'pixi.js';
import { ChildPool } from '../../skins/pixi-kit/pools.ts';
import { renderBPMGuide } from '../shared/bpm-guide.ts';
import {
  resolveShownGuideKinds,
  showsAnyGuide,
  type BPMGuideEvent,
  type BPMGuideKind,
  type BPMGuideKinds,
} from '../../chart/bpm-guide.ts';
 
import type { BeatorajaSceneKit } from '../../skin/beatoraja/scene-kit.ts';
import type { BGACue, NonstopBGAStage, NonstopStageBGATimeline } from '../../chart/bga-timeline.ts';
import { BeatorajaPlaySkinView, type BeatorajaPlaySkinViewOptions } from './skin-view.ts';
import type { PixiSceneHost } from '../../host/scene-host.ts';
import type { BeatorajaRenderContext } from '../../skin/beatoraja/render.ts';
import { BeatorajaBGALayer } from './play/bga.ts';
import { resolveChartPlayfieldVisual } from '@be-music/chart-model';
import { applyChartReverse } from '../shared/playfield/chart-note-visual.ts';
import type { BeatorajaMarkerBeats } from '../../chart/beatoraja/markers.ts';
import { BeatorajaMarkerLayer } from './play/markers.ts';
import {
  BeatorajaNoteLayer,
  beatorajaDisplayScrollBeat,
  beatorajaPixelsPerBeat,
  type BeatorajaNoteClock,
} from './play/notes.ts';
import { resolveBeatorajaScrollPlacement } from './play/scroll-placement.ts';
import { computeAuthoredLaneBottomYPixi } from './play/skin-metrics.ts';
import { BeatorajaSkinStage } from './scene-frame.ts';
 
/** The guide kinds whose lines the guide draws itself on a beatoraja skin: the ones its marker images do not cover. */
const GUIDE_LINE_KINDS: ReadonlySet<BPMGuideKind> = new Set(['scroll', 'speed']);
 
/** What the chart gives every skin the play is drawn with: its lanes, scroll, markers. */
export interface BeatorajaPlayChartLayout {
  readonly variant: ChartPlayVariant;
  readonly scrollMapper: ScrollDistanceMapperLike | undefined;
  readonly timelineBeats: ArrayLike<number> | undefined;
  readonly beatToSeconds: ((beat: number) => number) | undefined;
  readonly reversal: TempoReversalPoint | undefined;
  readonly markers: BeatorajaMarkerBeats;
  readonly guideEvents?: readonly BPMGuideEvent[];
  readonly beatAtSeconds?: ((seconds: number) => number) | undefined;
  readonly autoPlay: boolean;
}
 
/**
 * The chart's BGA as the BGA layer draws it: its textures and videos by `#BMPxx` key and its cues, and a stitched NONSTOP
 * chart's stages with each stage's own cues.
 */
export interface BeatorajaPlayBGA {
  readonly subRegionOrigins?: ReadonlyMap<string, { x: number; y: number }>;
  /** Base and POOR track textures (black kept). */
  readonly textures: ReadonlyMap<string, Texture>;
  /** Layer track textures (black keyed out for a BMS chart). */
  readonly layerTextures: ReadonlyMap<string, Texture>;
  readonly videos: ReadonlyMap<string, HTMLVideoElement>;
  readonly poorBGAMode?: 0 | 1 | 2;
  readonly chartOptionProgram?: ChartOptionProgram;
  readonly cues: {
    base: readonly BGACue[];
    layer: readonly BGACue[];
    layer2?: readonly BGACue[];
    poor: readonly BGACue[];
    opacity?: BGAOpacityTimelines;
  };
  readonly nonstop?: {
    readonly stages: readonly NonstopBGAStage[];
    readonly timelines: readonly NonstopStageBGATimeline[];
  };
}
 
/** Where the engine is, as the layers scroll: its notes, chart time and beat. */
export type BeatorajaPlayLayerClock = BeatorajaNoteClock & {
  readonly reversalSeconds?: number;
  readonly keyBoundBGA?: KeyBoundBGAFrame;
  readonly bmsonBGA?: BmsonBGAFrame;
};
 
/** One beatoraja play skin on the stage. See the module comment. */
export class BeatorajaPlayStage {
  private readonly stage: BeatorajaSkinStage;
  private readonly noteLayer: BeatorajaNoteLayer;
  private readonly markerLayer: BeatorajaMarkerLayer;
  private readonly guideLayer = new Container({ label: 'bpm-guide', eventMode: 'none' });
  private readonly guidePool = new ChildPool(this.guideLayer);
  private bgaLayer: BeatorajaBGALayer | undefined;
  private readonly kit: BeatorajaSceneKit;
  private readonly skinConfigOps: ReadonlySet<number>;
  private readonly layout: BeatorajaPlayChartLayout;
 
  public constructor(
    kit: BeatorajaSceneKit,
    skinConfigOps: ReadonlySet<number>,
    layout: BeatorajaPlayChartLayout,
    resolvers: Omit<BeatorajaPlaySkinViewOptions, 'skin' | 'textures' | 'skinConfigOps'>,
  ) {
    this.kit = kit;
    this.skinConfigOps = skinConfigOps;
    this.layout = layout;
    const view = new BeatorajaPlaySkinView({ skin: kit.skin, textures: kit.textures, skinConfigOps, ...resolvers });
    this.stage = new BeatorajaSkinStage(view);
    // The note layer crops each lane's note images out of the skin's `image[]` entries.
    const images = new Map<BeatorajaImageId, BeatorajaImageElement>();
    for (const image of normalizeBeatorajaImages(kit.skin.image)) images.set(image.id, image);
    const noteSection = normalizeBeatorajaNote(kit.skin.note);
    this.noteLayer = new BeatorajaNoteLayer({
      noteSection,
      variant: layout.variant,
      images,
      textures: kit.textures,
      canvasHeight: view.height,
      scrollMapper: layout.scrollMapper,
      timelineBeats: layout.timelineBeats,
      autoplay: layout.autoPlay,
      reversal: layout.reversal,
    });
    // Bar lines sit their authored distance above the lane bottom (`LaneRenderer.java:373`'s `y - hl`), so ModernChic's,
    // authored 12 px up, cross the note heads through their middle.
    this.markerLayer = new BeatorajaMarkerLayer({
      group: noteSection.group,
      bpm: noteSection.bpm,
      stop: noteSection.stop,
      time: noteSection.time,
      images,
      textures: kit.textures,
      canvasHeight: view.height,
      laneAuthoredBottomY: computeAuthoredLaneBottomYPixi(noteSection.dst[0]?.rects ?? [], view.height),
    });
    // At the skin's note anchor, markers under the notes: elements authored after the anchor (the lane cover, the
    // HIDDEN cover, readouts) draw over the falling notes, as beatoraja's z-order has it. `addChildAt` twice at the same
    // index puts the markers first and the notes after them.
    const index = view.noteLayerInsertIndex;
    view.container.addChildAt(this.markerLayer.container, index);
    view.container.addChildAt(this.guideLayer, index + 1);
    view.container.addChildAt(this.noteLayer.container, index + 2);
  }
 
  getDisplayAreaLanes(activeOps: ReadonlySet<number>, channels: readonly string[]) {
    return this.noteLayer.getDisplayAreaLanes(activeOps, channels);
  }
 
  /** The stage's root: the backdrop and the skin's canvas. */
  public get root(): Container {
    return this.stage.root;
  }
 
  /** The skin's canvas size in skin pixels. */
  public get width(): number {
    return this.stage.view.width;
  }
 
  public get height(): number {
    return this.stage.view.height;
  }
 
  /** Whether the BGA layer is in. */
  public get hasBGA(): boolean {
    return this.bgaLayer !== undefined;
  }
 
  /**
   * Puts the BGA layer in, at the skin's `bga` destination (`bgaLayerInsertIndex`): later elements draw over it, so the
   * default skin's full-canvas background does not cover it.
   */
  public addBGA(bga: BeatorajaPlayBGA): void {
    Iif (this.bgaLayer !== undefined) return;
    const view = this.stage.view;
    this.bgaLayer = new BeatorajaBGALayer({
      skin: this.kit.skin,
      subRegionOrigins: bga.subRegionOrigins,
      textures: bga.textures,
      layerTextures: bga.layerTextures,
      videoElements: bga.videos,
      cues: bga.cues,
      poorBGAMode: bga.poorBGAMode,
      nonstop: bga.nonstop,
      chartOptionProgram: bga.chartOptionProgram,
      skinConfigOps: this.skinConfigOps,
    });
    view.container.addChildAt(this.bgaLayer.container, view.bgaLayerInsertIndex);
  }
 
  /** Plays the BGA's current video again after a pause (the play paused every video). */
  public resumeBGA(): void {
    this.bgaLayer?.resume();
  }
 
  public fitTo(host: PixiSceneHost): void {
    this.stage.fitTo(host);
  }
 
  public getStageInfo(): { container: Container; width: number; height: number } {
    return this.stage.getStageInfo();
  }
 
  /** The skin's canvas, which a failed play's fade dims. */
  public get canvas(): Container {
    return this.stage.view.container;
  }
 
  /**
   * Draws one frame: the skin's elements at `context`, then — with the engine's `clock` — the notes and markers at
   * `hiSpeed` and the BGA.
   */
  public draw(
    context: BeatorajaRenderContext,
    clock: BeatorajaPlayLayerClock | undefined,
    hiSpeed: number,
    lanes: {
      isLaneLNHeld(channel: string): boolean;
      isPoorBGAActive(seconds: number): boolean;
      readonly laneCover?: LaneCoverState;
      setLaneHeight?(height: number): void;
    },
    playback: {
      tempo?: number;
      paused?: boolean;
      started?: boolean;
      showInvisibleNotes?: boolean;
      bpmGuide?: boolean;
      /** Which labels BPM GUIDE shows; beatoraja's BPM and STOP by default. */
      bpmGuideKinds?: BPMGuideKinds;
      judgeTimingMs?: number;
      /** Visual CONSTANT: notes, mines, bar lines and BPM guide lines show only near their time. */
      constant?: ConstantVisibility;
      /** Lanes whose notes are not drawn (AUTO SCRATCH with its notes hidden). */
      hiddenNoteChannels?: ReadonlySet<string>;
      /** beatoraja's mark processed note. */
      markProcessedNotes?: boolean;
      /** AC 34's lane brightness as the opacity of the black layer over the lanes. */
      laneDim?: number;
      /** beatoraja's judge area: the windows to draw as bands above the judge line, while the option is on. */
      judgeArea?: Pick<import('@be-music/player-skin-sdk').BeMusicJudgeWindows, 'note' | 'scratch'>;
      /** The camera to show in the BGA frame in place of the chart's BGA. */
      camera?: BGAFeed;
    } = {},
  ): void {
    const view = this.stage.view;
    const guideKinds = resolveShownGuideKinds(playback.bpmGuide, playback.bpmGuideKinds);
    const authored = this.noteLayer.getLaneBounds(context.activeOps, false);
    Iif (authored) lanes.setLaneHeight?.(authored.bottomY - authored.topY);
    this.noteLayer.setLift(lanes.laneCover ? resolveLaneCover(lanes.laneCover).lift : 0);
    view.update(context);
    this.guideLayer.visible =
      clock !== undefined &&
      (showsAnyGuide(guideKinds) || playback.judgeArea !== undefined || (playback.laneDim ?? 0) > 0) &&
      playback.started !== false;
    if (clock === undefined) return;
    const activeOps = context.activeOps;
    const displaySeconds = resolveNoteDisplaySeconds(clock.currentSeconds, playback.judgeTimingMs ?? 0);
    const noteClock = {
      ...clock,
      currentSeconds: displaySeconds,
      currentBeat: this.layout.beatAtSeconds?.(displaySeconds) ?? clock.currentBeat,
    };
    this.noteLayer.update(
      noteClock,
      hiSpeed,
      activeOps,
      (channel) => lanes.isLaneLNHeld(channel),
      playback.showInvisibleNotes,
      playback.constant,
      playback.hiddenNoteChannels,
      playback.markProcessedNotes === true,
    );
    // The markers scroll with the notes' per-beat distance (`rxhs / 4 * hispeed`, `LaneRenderer.java:271-276`) on the
    // lane the active dst block resolves; skin-canvas defaults when no lane matched.
    const laneBounds = this.noteLayer.getLaneBounds(activeOps) ?? { topY: 0, bottomY: view.height };
    // Chart-authored playfield options (#931): REVERSE mirrors the notes and bar lines in the lane area, DARK hides the
    // BGA. The skin's own judgement line, covers and bombs stay where the skin draws them.
    const chartPlayfield = resolveChartPlayfieldVisual(clock.chartOptions, displaySeconds);
    applyChartReverse(this.noteLayer.container, chartPlayfield.reverse, laneBounds.topY, laneBounds.bottomY);
    applyChartReverse(this.markerLayer.container, chartPlayfield.reverse, laneBounds.topY, laneBounds.bottomY);
    const laneHeight = Math.max(0, laneBounds.bottomY - laneBounds.topY);
    // Past an LR2 negative-BPM reversal both layers scroll from the mirrored display beat.
    const currentBeat = beatorajaDisplayScrollBeat(noteClock);
    const pixelsPerBeat = beatorajaPixelsPerBeat(laneHeight, hiSpeed);
    const layout = this.layout;
    // On a chart that scrolls, bar lines follow the notes' `LaneRenderer` window as well as their distance.
    const placement = resolveBeatorajaScrollPlacement({
      currentBeat,
      nowSeconds: noteClock.currentSeconds,
      reversal: clock.reversalActivation,
      mapper: layout.scrollMapper,
      laneBeats: pixelsPerBeat > 0 ? laneHeight / pixelsPerBeat : 0,
      timelineBeats: layout.timelineBeats,
      stageBottomY: view.height,
    });
    const constant = playback.constant;
    const alphaAt =
      constant?.enabled === true
        ? (seconds: number): number => resolveConstantAlpha(seconds, noteClock.currentSeconds, constant)
        : undefined;
    this.markerLayer.update({
      currentBeat,
      distance: layout.scrollMapper ? placement.distance : undefined,
      judgementY: laneBounds.bottomY,
      laneTopY: laneBounds.topY,
      pixelsPerBeat,
      markers: layout.markers,
      bpmGuide: guideKinds.bpm || guideKinds.stop,
      bpmGuideKinds: guideKinds,
      window: placement.window,
      secondsAt: layout.beatToSeconds,
      ...(alphaAt !== undefined ? { alphaAt } : {}),
    });
    this.guidePool.begin();
    Iif (this.guideLayer.visible) {
      const laneRects = this.noteLayer.getDisplayAreaLanes(activeOps, [
        ...new Set(clock.notes.map((note) => note.channel)),
      ]);
      const lanes = ['1P', '2P'].flatMap((side) => {
        const group = laneRects.filter((lane) => lane.side === side);
        if (!group.length) return [];
        const x = Math.min(...group.map((lane) => lane.x));
        return [
          {
            x,
            w: Math.max(...group.map((lane) => lane.x + lane.w)) - x,
            top: laneBounds.topY,
            bottom: laneBounds.bottomY,
          },
        ];
      });
      // The guide layer sits under the notes: the lane dim and the judge area draw there, behind what scrolls.
      const laneDim = playback.laneDim ?? 0;
      const laneAreas =
        playback.judgeArea !== undefined || laneDim > 0
          ? [...new Set(clock.notes.map((note) => note.channel))].flatMap((channel) =>
              this.noteLayer.getDisplayAreaLanes(activeOps, [channel]).map((lane) => ({
                x: lane.x,
                w: lane.w,
                top: lane.top,
                bottom: lane.bottom,
                scratch: isScratch(channel),
              })),
            )
          : [];
      // AC 34's lane brightness: a black layer over each lane.
      if (laneDim > 0) {
        for (const lane of laneAreas) {
          this.guidePool
            .acquireGraphics()
            .rect(lane.x, lane.top, lane.w, lane.bottom - lane.top)
            .fill({ color: 0x000000, alpha: laneDim });
        }
      }
      if (playback.judgeArea !== undefined) {
        const beatAt = layout.beatAtSeconds;
        renderJudgeArea({
          lanes: laneAreas,
          note: playback.judgeArea.note,
          scratch: playback.judgeArea.scratch,
          distanceAt: (ms) =>
            beatAt === undefined ? 0 : placement.distance(beatAt(noteClock.currentSeconds + ms / 1000)) * pixelsPerBeat,
          pool: this.guidePool,
        });
      }
      renderBPMGuide({
        enabled: showsAnyGuide(guideKinds),
        events: layout.guideEvents ?? [],
        window: placement.window,
        distance: placement.distance,
        pixelsPerBeat,
        lanes,
        pool: this.guidePool,
        kinds: guideKinds,
        // The skin's own BPM and STOP lines draw in the marker layer; `#SCROLL` and `#SPEED` have none, so they get the
        // guide's line.
        drawLines: GUIDE_LINE_KINDS,
        ...(alphaAt !== undefined ? { alphaAt } : {}),
      });
    }
    this.guidePool.end();
    Eif (this.bgaLayer !== undefined) this.bgaLayer.container.visible = !chartPlayfield.hideBGA;
    Iif (chartPlayfield.hideBGA) return;
    // The BGA freezes on what showed at a reversal (clamped, not mirrored), as LR2 stops its cues there.
    this.bgaLayer?.update(
      Math.min(clock.currentSeconds, clock.reversalSeconds ?? Number.POSITIVE_INFINITY),
      context,
      lanes.isPoorBGAActive(clock.currentSeconds),
      {
        ...playback,
        seconds: clock.currentSeconds,
        keyBoundBGA: clock.keyBoundBGA,
        bmsonBGA: clock.bmsonBGA,
        bgaMode: clock.chartOptions?.bgaMode,
      },
    );
  }
 
  public dispose(): void {
    this.bgaLayer?.dispose();
    this.bgaLayer = undefined;
    this.noteLayer.dispose();
    this.markerLayer.dispose();
    this.guidePool.destroy();
    this.stage.dispose();
  }
}