All files / player-browser/src/view/beatoraja result-view.ts

63.55% Statements 75/118
57.14% Branches 44/77
40% Functions 18/45
69.6% Lines 71/102

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                                                                                                                29x     29x               28x                           11x                                                 29x       14x                     14x     14x   14x     14x 14x 14x 14x 14x 14x                                                       2x 2x                             1x 1x 1x                       14x 14x 14x 14x 14x 14x 14x       37x 37x 37x       14x 14x 14x 14x 14x               23x 23x 23x 23x 23x 23x 23x 23x     4x     1x                       7x 7x 7x         5x 5x                                                 23x 23x 13x   10x 10x 10x 10x                     23x 23x 2x 2x   23x 23x         23x                             12x 12x       2x 1x 1x         12x           4x      
/**
 * The beatoraja family's result screen: a beatoraja result skin (`header.type` 7, or the course-result skin for a course
 * run) drawn by `BeatorajaPlaySkinView`, its canvas fitted into the window. It reads the result session's `PlayResult`
 * directly through the scene mapping (`resolveBeatorajaResult*` of `@be-music/skin-beatoraja/scene`): the score, the
 * judgments and their timings, the gauge with its border and TOTAL, the rank, verdict and lamp ops, the graphs and the
 * course. The chart's note kinds, BPM graph and `#TOTAL` come from the chart as the play played it
 * (`ResultFrame.playChart`), the chart's own images from its files; beatoraja's scene timers are read off each frame.
 * The session times the screen from the skin's `input` and `fadeout` ({@link resolveBeatorajaResultTiming}). As on
 * beatoraja, the screen takes keys and no mouse clicks; a tap (a touch or a pen) presses on as Enter does, so a device
 * with no keyboard can leave it ({@link resolveBeatorajaResultPointerIntent}).
 */
 
import { buildBaseOpSet, type BeatorajaSkin } from '@be-music/skin-beatoraja';
import {
  beatorajaReplayButtonSlot,
  resolveBeatorajaResultReplayOps,
  resolveBeatorajaGaugePolyline,
  resolveBeatorajaResultGaugePercent,
  resolveBeatorajaResultGaugeState,
  resolveBeatorajaResultGraphValue,
  resolveBeatorajaResultJudgeGraph,
  resolveBeatorajaResultNumber,
  resolveBeatorajaResultOps,
  resolveBeatorajaResultPolyline,
  resolveBeatorajaResultText,
  type BeatorajaNoteBreakdown,
  type BeatorajaResultInput,
} from '@be-music/skin-beatoraja/scene';
import type { BeMusicJSON } from '@be-music/chart-source';
import {
  scrollCourseStages,
  type LibraryChart,
  type PlayResult,
  type ReplaySlotState,
} from '@be-music/player-scene-model';
import { Point, type Container, type Renderer } from 'pixi.js';
import { computeBeatorajaBPMCurve, type BPMCurvePoint } from '../../chart/beatoraja/bpm-curve.ts';
import { computeBeatorajaNoteBreakdown } from '../../chart/beatoraja/note-counts.ts';
import type { BrowserAssetSource } from '../../collection/types.ts';
import type { BeatorajaKit } from '../../host/family-kit.ts';
import { logger } from '../../logger.ts';
import { resolveBeatorajaOptionRef } from './option-refs.ts';
import { BeatorajaPlaySkinView } from './skin-view.ts';
import type { PixiSceneHost } from '../../host/scene-host.ts';
import type { BeatorajaSkinAudio } from '../../skin/beatoraja/audio.ts';
import type { IntentSink, ResultFrame, ResultIntent, ResultView, ResultViewTiming } from '../types.ts';
import {
  BeatorajaSkinStage,
  BeatorajaViewChartImages,
  beatorajaSceneNowMs,
  beatorajaChartTextOf,
  resolveBeatorajaFadeOutMs,
  resolveBeatorajaSceneTimers,
  resolveBeatorajaSkinTimingMs,
} from './scene-frame.ts';
 
const log = logger('result');
 
/** When a beatoraja result screen takes input, for a skin without `input`: the 500 ms of `resultmain.lua`. */
export const BEATORAJA_RESULT_DEFAULT_INPUT_MS = 500;
 
/**
 * The result skin's timing: input opens after its `input` (500 ms without one) and holds back every key until then, as
 * beatoraja's `MusicResult` does; the first press leaves, with no steps to press through, after a fade-out over its
 * `fadeout` (500 ms without one). The screen does not move on by itself.
 */
export function resolveBeatorajaResultTiming(skin: Pick<BeatorajaSkin, 'input' | 'fadeout'>): ResultViewTiming {
  return {
    inputDelayMs: Math.max(0, resolveBeatorajaSkinTimingMs(skin.input, BEATORAJA_RESULT_DEFAULT_INPUT_MS)),
    fadeOutMs: resolveBeatorajaFadeOutMs(skin.fadeout),
    escapeWaitsForInput: true,
    skipsResultSteps: true,
  };
}
 
/**
 * What a pointer pressed on a beatoraja result screen asks for: a tap (a touch or a pen) presses on, as Enter does (the
 * session waits for input to open), so a phone or a tablet can leave the screen; a mouse click asks for nothing, as
 * beatoraja's `MusicResult.input` reads keys only.
 */
export function resolveBeatorajaResultPointerIntent(pointerType: string): ResultIntent | undefined {
  return pointerType === 'touch' || pointerType === 'pen' ? { type: 'continue' } : undefined;
}
 
/** What the result skin reads of one result, worked out once per result ({@link readBeatorajaResult}). */
export interface BeatorajaResultReading {
  readonly result: PlayResult;
  readonly playChart: BeMusicJSON | undefined;
  readonly input: BeatorajaResultInput;
  /** The run's ops (rank, verdict, lamp, judgments, course stage). */
  readonly ops: readonly number[];
  readonly bpmCurve: readonly BPMCurvePoint[];
  /** Every timed judgment, as the timing distribution graph reads them. */
  readonly timings: readonly { deltaMs: number; kind: string }[];
}
 
export interface BeatorajaResultViewOptions {
  /** The chart the result is of, whose images the view loads before its first frame. */
  readonly chart?: Pick<LibraryChart, 'chart' | 'chartPath'>;
  /** Where the chart's files are, for its `#STAGEFILE`, `#BACKBMP` and `#BANNER`; none load without one. */
  readonly source?: BrowserAssetSource;
  /** Where the skin's Lua sounds play (`main_state.audio_*`); they are silent without it. */
  readonly skinSounds?: BeatorajaSkinAudio;
}
 
/** The course stages a beatoraja skin lists at once: strings 150-159 name stages 1-10. */
const BEATORAJA_COURSE_STAGE_ROWS = 10;
 
/** The beatoraja result view. See the module comment. */
export class BeatorajaResultView implements ResultView {
  public readonly family = 'beatoraja' as const;
  public readonly timing: ResultViewTiming;
  private kit: BeatorajaKit;
  private readonly options: BeatorajaResultViewOptions;
  private readonly stage: BeatorajaSkinStage;
  private readonly chartImages: BeatorajaViewChartImages;
  /** What the skin reads of the result being drawn; the skin view's resolvers read it. */
  private reading: BeatorajaResultReading | undefined;
  private baseOps: ReadonlySet<number> | undefined;
  private activeOps: ReadonlySet<number> | undefined;
  /** The replay slots the active ops were lit for. */
  private replaySlotsKey = '';
  private host: PixiSceneHost | undefined;
  private emit: IntentSink<ResultIntent> | undefined;
  private disposed = false;
  /** How long the screen has shown, on its own clock: a long course run's stage list scrolls by it. */
  private sceneMs = 0;
 
  public constructor(kit: BeatorajaKit, options: BeatorajaResultViewOptions = {}) {
    this.kit = kit;
    this.options = options;
    this.chartImages = new BeatorajaViewChartImages(options.chart, options.source);
    const { skin, textures, fonts } = kit.kit;
    this.timing = resolveBeatorajaResultTiming(skin);
    this.stage = new BeatorajaSkinStage(
      new BeatorajaPlaySkinView({
        skin,
        textures,
        resolveRefValue: (ref) =>
          resolveBeatorajaOptionRef(ref, {
            ...(this.reading?.playChart !== undefined ? { chart: this.reading.playChart } : {}),
            ...(this.reading !== undefined ? { lamp: this.reading.result.lamp } : {}),
          }) ?? 0,
        resolveTextContent: (ref) =>
          this.read((input) => resolveBeatorajaResultText(ref, this.withScrolledStages(input))),
        resolveNumberValue: (ref) => this.read((input) => resolveBeatorajaResultNumber(ref, input)),
        resolveFontFamily: fonts !== undefined ? (id) => fonts.family(id) : undefined,
        resolveFontKind: fonts !== undefined ? (id) => fonts.kind(id) : undefined,
        resolveGraphValue: (type) => this.read((input) => resolveBeatorajaResultGraphValue(type, input)),
        resolveGraphPolyline: (type) => this.read((input) => resolveBeatorajaResultPolyline(type, input)),
        resolveGaugePercent: () => this.read((input) => resolveBeatorajaResultGaugePercent(input)),
        resolveJudgeGraphBars: (type) => this.read((input) => resolveBeatorajaResultJudgeGraph(type, input)),
        resolveBPMGraphPoints: () => {
          const curve = this.reading?.bpmCurve;
          return curve !== undefined && curve.length > 0 ? curve : undefined;
        },
        resolveGaugeGraphPoints: () =>
          this.read((input) => resolveBeatorajaGaugePolyline(input.result.gaugeHistory ?? [])),
        resolveTimingDistribution: () => this.reading?.timings,
        chartImageProvider: (id) => this.chartImages.resolve(id),
        // The replay buttons (19, 316-318) save the play into their slot, as beatoraja's result does.
        onButtonAction: (act) => {
          const slot = beatorajaReplayButtonSlot(act);
          if (slot !== undefined) this.emit?.({ type: 'saveReplay', slot });
        },
      }),
    );
  }
 
  public get root(): Container {
    return this.stage.root;
  }
 
  /**
   * Takes the player's settings for the skin; the next frame draws with them. A beatoraja skin is loaded with its
   * options, so another skin needs another view.
   */
  public updateKit(kit: BeatorajaKit): void {
    Eif (kit.kit.skin !== this.kit.kit.skin) {
      log.warn('a result view keeps its skin; ignoring a kit of another skin');
      return;
    }
    this.kit = kit;
    this.baseOps = undefined;
    this.activeOps = undefined;
  }
 
  /**
   * Gets ready to draw on `host`, once the chart's images have loaded (on the first attach), so the first frame shows
   * them, then listens for taps on the canvas. A beatoraja result screen takes no mouse clicks.
   */
  public async attach(host: PixiSceneHost, emit: IntentSink<ResultIntent>): Promise<void> {
    Iif (this.disposed) return;
    await this.chartImages.load();
    Iif (this.disposed) return;
    this.detach();
    this.host = host;
    this.emit = emit;
    host.app.canvas.addEventListener('pointerdown', this.handlePointerDown);
  }
 
  public detach(): void {
    this.host?.app.canvas.removeEventListener('pointerdown', this.handlePointerDown);
    this.host = undefined;
    this.emit = undefined;
  }
 
  public dispose(): void {
    Iif (this.disposed) return;
    this.detach();
    this.disposed = true;
    this.stage.dispose();
    this.chartImages.dispose();
  }
 
  public getStageInfo(): { container: Container; width: number; height: number } {
    return this.stage.getStageInfo();
  }
 
  public draw(frame: ResultFrame): void {
    const host = this.host;
    Iif (host === undefined || this.disposed) return;
    this.stage.fitTo(host);
    const reading = this.readingOf(frame);
    this.sceneMs = beatorajaSceneNowMs(frame.clock);
    const timers = resolveBeatorajaSceneTimers(frame, 'entry', 'result');
    const skinSounds = this.options.skinSounds;
    this.stage.view.update({
      activeOps: this.opsOf(reading, frame.replaySlots),
      // A timer that has not started reads `undefined`, which hides what is gated on it (the fade-out's black overlay).
      getTimerStart: (timerId) => timers.get(timerId),
      // The gauge the play ended on, so `main_state.gauge_type()` and the gauge slab name it (a course's class gauge
      // included) instead of defaulting to NORMAL.
      resolveGaugeState: () => resolveBeatorajaResultGaugeState(reading.input),
      nowMs: beatorajaSceneNowMs(frame.clock),
      audioPlay: skinSounds === undefined ? undefined : (path, volume) => skinSounds.play(path, volume),
      audioLoop: skinSounds === undefined ? undefined : (path, volume) => skinSounds.loop(path, volume),
      audioStop: skinSounds === undefined ? undefined : (path) => skinSounds.stop(path),
    });
  }
 
  /**
   * A tap presses on (the session waits for input to open), unless it lands on one of the skin's buttons, which act on
   * their own; a mouse click does nothing.
   */
  private readonly handlePointerDown = (event: PointerEvent): void => {
    const intent = resolveBeatorajaResultPointerIntent(event.pointerType);
    if (intent !== undefined && !this.isOverButton(event)) this.emit?.(intent);
  };
 
  /** Whether `event` lands on an interactive sprite of the skin (an `act` button), by Pixi's own hit test. */
  private isOverButton(event: PointerEvent): boolean {
    const events = (this.host?.app as { renderer?: Partial<Pick<Renderer, 'events'>> } | undefined)?.renderer?.events;
    Eif (events === undefined) return false;
    const point = new Point();
    events.mapPositionToPoint(point, event.clientX, event.clientY);
    const hit = events.rootBoundary.hitTest(point.x, point.y);
    return hit !== null && hit.eventMode === 'static' && hit.cursor === 'pointer';
  }
 
  /**
   * The result as its stage list shows now: a course run longer than the skin's ten stage rows scrolls through every
   * stage ({@link scrollCourseStages}).
   */
  private withScrolledStages(input: BeatorajaResultInput): BeatorajaResultInput {
    const course = input.result.course;
    if (course === undefined) return input;
    const shown = scrollCourseStages(course, this.sceneMs, BEATORAJA_COURSE_STAGE_ROWS);
    return shown === course ? input : { ...input, result: { ...input.result, course: shown } };
  }
 
  /** Reads the result being drawn through `resolve`; `undefined` before the first frame. */
  private read<T>(resolve: (input: BeatorajaResultInput) => T): T | undefined {
    return this.reading !== undefined ? resolve(this.reading.input) : undefined;
  }
 
  /** What the skin reads of the frame's result, worked out again only for another result or chart. */
  private readingOf(frame: ResultFrame): BeatorajaResultReading {
    const current = this.reading;
    if (current !== undefined && current.result === frame.result && current.playChart === frame.playChart) {
      return current;
    }
    const reading = readBeatorajaResult(frame.result, frame.playChart, this.kit.kit.skin);
    this.reading = reading;
    this.activeOps = undefined;
    return reading;
  }
 
  /**
   * The ops of the player's picks for the skin's options, the run's ops and its replay slots', kept until the result,
   * the kit or a slot changes.
   */
  private opsOf(
    reading: BeatorajaResultReading,
    replaySlots: readonly ReplaySlotState[] | undefined,
  ): ReadonlySet<number> {
    const slotsKey = replaySlots?.join(',') ?? '';
    if (slotsKey !== this.replaySlotsKey) {
      this.replaySlotsKey = slotsKey;
      this.activeOps = undefined;
    }
    this.baseOps ??= buildBaseOpSet(this.kit.kit.skinConfig?.option);
    this.activeOps ??= new Set([
      ...this.baseOps,
      ...reading.ops,
      ...(replaySlots !== undefined ? resolveBeatorajaResultReplayOps(replaySlots) : []),
    ]);
    return this.activeOps;
  }
}
 
/**
 * What a result skin reads of `result` (`BeatorajaResultInput`): the result itself, the chart's `#TOTAL` and note kinds
 * (counted the first time a skin asks) from the chart as played, the chart's song texts and the skin's own; with the
 * run's ops, the BPM graph of the chart as played and the timings as the timing distribution graph reads them.
 */
export function readBeatorajaResult(
  result: PlayResult,
  playChart: BeMusicJSON | undefined,
  skin: Pick<BeatorajaSkin, 'name' | 'author'>,
): BeatorajaResultReading {
  let breakdown: BeatorajaNoteBreakdown | undefined;
  const chartEntry = beatorajaChartTextOf(result.chart);
  const input: BeatorajaResultInput = {
    result,
    ...(playChart?.metadata.total !== undefined ? { chartTotal: playChart.metadata.total } : {}),
    get breakdown(): BeatorajaNoteBreakdown | undefined {
      if (playChart === undefined) return undefined;
      breakdown ??= computeBeatorajaNoteBreakdown(playChart);
      return breakdown;
    },
    ...(chartEntry !== undefined ? { chart: chartEntry } : {}),
    skin: { name: skin.name, author: skin.author },
  };
  return {
    result,
    playChart,
    input,
    ops: resolveBeatorajaResultOps(input),
    bpmCurve: playChart !== undefined ? computeBeatorajaBPMCurve(playChart) : [],
    timings: (result.judgeTimings ?? []).map((timing) => ({ deltaMs: timing.deltaMs, kind: timing.judge })),
  };
}