All files / player-browser/src/session/decide decide-session.ts

95.6% Statements 87/91
94.73% Branches 72/76
100% Functions 15/15
100% Lines 70/70

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                                                                                            29x 25x 16x 5x                                                                                             100x 39x         39x               39x   39x 39x 39x 39x     39x     39x 39x 39x             80x         36x 36x 36x 36x 36x 36x 36x 36x         36x 17x 17x 17x       20x 20x 20x       21x 20x 21x 21x   19x 1x 1x   18x 18x 14x 14x       5x 5x       64x 64x 64x 64x 12x   64x   64x 64x                                 64x 64x 61x 61x 36x                 20x 20x 13x 20x         25x 21x         77x 77x 33x 21x 21x 6x      
import { clamp } from '@be-music/shared-utils/core';
/**
 * The decide screen's behaviour, whatever family draws it: the short screen between picking a chart and its play. The
 * session times the screen from its view's skin timing (`DecideView.timing`): input opens after the input delay, the
 * screen moves on to the play by itself after the auto advance, and a leaving screen fades out before the host hears
 * where it goes. Enter, Space or a click continue to the play once input is open; Escape backs out to select at any
 * time, or once input is open when the skin's timing says so (beatoraja's). The screen shows how far the play behind
 * it has loaded: the host's progress, else how much of the auto advance has gone by. The decide jingle plays through
 * the audio service and stops when the screen leaves the stage.
 *
 * The session draws the chart's `#RANDOM` / `#SWITCH` branches once, when it is made ({@link DecideSession.resolved}):
 * the screen's graphs show those branches, and the host hands the same chart and draws to the play, so the play plays
 * what the screen showed.
 */
 
import { resolvePlayChart, type ResolvedPlayChart } from '@be-music/player-engine';
import {
  DEFAULT_PLAY_OPTIONS,
  type CourseView,
  type LibraryChart,
  type PlayOptions,
  type SystemSoundSet,
} from '@be-music/player-scene-model';
import type { AudioService } from '../../runtime/audio-service.ts';
import type { DecideFrame, DecideIntent, SceneLeaving, SceneViewTiming } from '../../view/types.ts';
import type { SceneSession, SessionKeyEvent } from '../session-scene.ts';
import {
  DEFAULT_CONTROL_ACTIONS,
  type ControlActionKeyEvent,
  type ControlActionMap,
} from '../controls/control-actions.ts';
import { controlButtonsOfKey, DEFAULT_CONTROL_BUTTONS } from '../controls/control-buttons.ts';
import { createControlButtonTracker, isStartAndSelectDown } from '../controls/button-tracker.ts';
 
/** What a key press does on the decide screen. */
export type DecideKeyAction = 'continue' | 'cancel';
 
/**
 * Maps a key press to its decide-screen action by the player's keys (`actions`): Enter / Space continue to the play,
 * Escape goes back to select, by default. Auto-repeats are ignored, so the Enter still held from picking the chart
 * doesn't skip the screen.
 */
export function resolveDecideKeyAction(
  event: ControlActionKeyEvent & { readonly repeat: boolean },
  actions: ControlActionMap = DEFAULT_CONTROL_ACTIONS.lr2,
): DecideKeyAction | undefined {
  if (event.repeat) return undefined;
  if (actions.is('decide.cancel', event)) return 'cancel';
  if (actions.is('decide.continue', event)) return 'continue';
  return undefined;
}
 
/** The part of the audio service the decide screen uses. */
export type DecideAudio = Pick<AudioService, 'playJingle' | 'stopOwned'>;
 
/** Where the decide screen leads. */
export interface DecideSessionEvents {
  /** The screen is done (its time is up, or the player went on): start the play. Fired once per entry. */
  continue(): void;
  /** The player backed out: go back to select. Fired once per entry. */
  cancel(): void;
}
 
export interface DecideSessionOptions {
  /** The chart about to be played. */
  readonly chart: LibraryChart;
  /** The course and the stage about to be played, for a course stage. */
  readonly course?: CourseView;
  /** The options the play will run with. Defaults to `DEFAULT_PLAY_OPTIONS`. */
  readonly playOptions?: PlayOptions;
  /** The theme's sounds: the decide jingle is `decideBGM`, none without it. */
  readonly sounds: SystemSoundSet;
  readonly audio: DecideAudio;
  /** When the screen takes input and how it leaves, as the view's skin authors it. */
  readonly timing: SceneViewTiming;
  /**
   * How far the play behind the screen has loaded, 0..1, read every frame; `undefined` while nothing loads. Without it
   * the screen shows how much of its auto advance has gone by.
   */
  readonly progress?: () => number | undefined;
  /** The random source the chart's `#RANDOM` / `#SWITCH` branches are drawn with, in `[0, 1)`. Defaults to `Math.random`. */
  readonly random?: () => number;
  /**
   * The chart already drawn (`resolvePlayChart`), when the host drew its branches before the screen was made, to load
   * the play from the moment the chart was picked: the screen shows those draws instead of drawing its own.
   */
  readonly resolved?: ResolvedPlayChart;
  /** The player's keys for the screen's operations. Defaults to the default keys. */
  readonly actions?: ControlActionMap;
  readonly on: DecideSessionEvents;
}
 
/** Where a leaving decide screen goes. */
type DecideLeavingTo = 'play' | 'select';
 
function clampProgress(value: number | undefined): number | undefined {
  if (value === undefined || !Number.isFinite(value)) return undefined;
  return clamp(value, 0, 1);
}
 
/** The decide screen's session. See the module comment. */
export class DecideSession implements SceneSession<DecideFrame, DecideIntent> {
  public readonly kind = 'decide' as const;
  /**
   * The chart as the play will play it: its `#RANDOM` / `#SWITCH` branches drawn once, when the session was made, with
   * the draws (`resolvePlayChart`). The host hands it to the play (`preResolved`).
   */
  public readonly resolved: ResolvedPlayChart;
  private readonly options: DecideSessionOptions;
  private readonly playOptions: PlayOptions;
  private entered = false;
  /** The control buttons held, for START + SELECT. */
  private readonly buttons = createControlButtonTracker();
  private disposed = false;
  private enteredAtMs = 0;
  private nowMs = 0;
  private leaving: SceneLeaving<DecideLeavingTo> | undefined;
  /** The leaving screen told the host where it goes; nothing more happens until the next entry. */
  private completed = false;
 
  public constructor(options: DecideSessionOptions) {
    this.options = options;
    this.playOptions = options.playOptions ?? DEFAULT_PLAY_OPTIONS;
    this.resolved =
      options.resolved ??
      resolvePlayChart(options.chart.chart, options.random !== undefined ? { random: options.random } : {});
  }
 
  /** On the clock, when input opens. */
  private get inputOpenAtMs(): number {
    return this.enteredAtMs + Math.max(0, this.options.timing.inputDelayMs);
  }
 
  /** Starts the screen's time from `nowMs` and plays the decide jingle. */
  public enter(nowMs: number): void {
    Iif (this.disposed) return;
    this.entered = true;
    this.enteredAtMs = nowMs;
    this.nowMs = nowMs;
    this.leaving = undefined;
    this.completed = false;
    const jingle = this.options.sounds.decideBGM;
    if (jingle !== undefined) void this.options.audio.playJingle(jingle, { owner: this });
  }
 
  /** Stops the screen's time and the jingle. */
  public exit(): void {
    if (!this.entered) return;
    this.entered = false;
    this.buttons.reset();
    this.options.audio.stopOwned(this);
  }
 
  public dispose(): void {
    Iif (this.disposed) return;
    this.exit();
    this.disposed = true;
  }
 
  public handleKey(event: SessionKeyEvent): boolean {
    if (!this.entered) return false;
    const buttons = event.buttons ?? controlButtonsOfKey(event, DEFAULT_CONTROL_BUTTONS);
    const changes = this.buttons.handle({ ...event, buttons });
    if (event.type !== 'down') return false;
    // START and SELECT held together back out, as LR2's and beatoraja's decide screens take them.
    if (changes.some((change) => change.type === 'down') && isStartAndSelectDown(this.buttons)) {
      this.request('cancel', event.timeStamp);
      return true;
    }
    const action = resolveDecideKeyAction({ ...event, buttons }, this.options.actions);
    if (action === undefined) return false;
    this.request(action, event.timeStamp);
    return true;
  }
 
  public dispatch(intent: DecideIntent): void {
    Iif (!this.entered) return;
    this.request(intent.type, this.nowMs);
  }
 
  public frame(nowMs: number): DecideFrame {
    Eif (this.entered) {
      this.nowMs = Math.max(this.nowMs, nowMs);
      const autoAdvanceMs = this.options.timing.autoAdvanceMs;
      if (this.leaving === undefined && autoAdvanceMs !== undefined && nowMs - this.enteredAtMs >= autoAdvanceMs) {
        this.leave('play', nowMs);
      }
      this.completeLeaving(nowMs);
    }
    const progress = this.progressAt(nowMs);
    return {
      clock: { nowMs, enteredAtMs: this.enteredAtMs },
      chart: this.options.chart,
      playChart: this.resolved.chart,
      ...(this.options.course !== undefined ? { course: this.options.course } : {}),
      playOptions: this.playOptions,
      ...(progress !== undefined ? { progress } : {}),
      inputOpenAtMs: this.inputOpenAtMs,
      ...(this.leaving !== undefined ? { leaving: this.leaving } : {}),
    };
  }
 
  /**
   * How far the play behind the screen has loaded at `nowMs`: the host's progress, else how much of the auto advance
   * has gone by; `undefined` with neither.
   */
  private progressAt(nowMs: number): number | undefined {
    const loaded = clampProgress(this.options.progress?.());
    if (loaded !== undefined) return loaded;
    const autoAdvanceMs = this.options.timing.autoAdvanceMs;
    if (autoAdvanceMs === undefined || autoAdvanceMs <= 0) return undefined;
    return clampProgress((nowMs - this.enteredAtMs) / autoAdvanceMs);
  }
 
  /**
   * The player asked to continue or back out at `atMs`: continuing waits for input to open. Backing out does not (LR2
   * lets Escape leave its decide screen before `#STARTINPUT`), unless the skin's timing holds Escape back too
   * (beatoraja's `input` holds back every key).
   */
  private request(action: DecideKeyAction, atMs: number): void {
    const waitsForInput = action === 'continue' || this.options.timing.escapeWaitsForInput === true;
    if (waitsForInput && Math.max(atMs, this.nowMs) < this.inputOpenAtMs) return;
    this.leave(action === 'continue' ? 'play' : 'select', atMs);
    this.completeLeaving(Math.max(atMs, this.nowMs));
  }
 
  /** Starts leaving for `to`, unless the screen is already on its way out. */
  private leave(to: DecideLeavingTo, atMs: number): void {
    if (this.leaving !== undefined) return;
    this.leaving = { to, atMs };
  }
 
  /** Tells the host where the screen goes once its fade-out has run. */
  private completeLeaving(nowMs: number): void {
    const leaving = this.leaving;
    if (leaving === undefined || this.completed) return;
    if (nowMs - leaving.atMs < Math.max(0, this.options.timing.fadeOutMs)) return;
    this.completed = true;
    if (leaving.to === 'play') this.options.on.continue();
    else this.options.on.cancel();
  }
}