All files / player-engine/src/core input-signal-bus.ts

100% Statements 8/8
100% Branches 0/0
100% Functions 3/3
100% Lines 7/7

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                                                                                                                                                                                                                    3098x 3098x   3098x 6236x 6236x     272198x   3098x            
import type { ReplayOptionState } from '../replay/options.ts';
import { signal } from 'alien-signals';
import type { ReplayViewState } from '../replay/view.ts';
import type { HighSpeedControlAction } from './high-speed-control.ts';
import type { ScratchSpin } from './scratch-spin.ts';
import type { InputSource } from './input-source.ts';
 
type WritableSignal<T> = {
  (): T;
  (value: T): void;
};
 
export type PlayerInputCommand =
  /** Opens a play configured with `waitForStart`; repeated commands have no effect. */
  | { kind: 'start' }
  | { kind: 'interrupt'; reason: 'escape' | 'ctrl-c' | 'restart' }
  | { kind: 'toggle-pause' }
  | { kind: 'high-speed'; action: HighSpeedControlAction }
  /**
   * The host's view changed (hi-speed, covers, lift): the engine records it in the replay at the chart time it
   * drains the command. It changes no judgment.
   */
  | { kind: 'view'; change: ReplayViewState }
  /** A source option changed; record it at the next engine tick, independently of score eligibility. */
  | { kind: 'options'; values: ReplayOptionState }
  /**
   * The host changed the play tempo (`PlayerOptions.speed`) during the play: the engine re-anchors its clock at the
   * chart time it drains the command, runs at `tempo` from there on and records the change in the replay. Inputs and
   * judgments stay in chart time.
   */
  | { kind: 'tempo'; tempo: number }
  /**
   * The host moves the play to chart second `seconds` (clamped to the chart). The engine applies the last seek of each
   * drain at its next tick: the judge state becomes the one a play from the start reaches there, the audio follows,
   * chart time re-bases on the play clock (a paused play stays paused), the UI gets a `seek` command and a frame at
   * `seconds` with the next generation, and the play records no replay. During the lead-in it sets where the chart
   * starts. AUTO play and replays rebuild their judgments; manual play starts practice without earlier judgments.
   */
  | { kind: 'seek'; seconds: number }
  | {
      kind: 'lane-input';
      tokens: string[];
      /**
       * The physical input behind the press (`input-source.ts`): a touch zone, a controller button, or one direction of
       * a turntable. Omitted for keys: the engine takes a keyboard source from the first token (each physical key is
       * its own source). The replay records it and beatoraja's scratch rules key a scratch hold by it. Device-identifying
       * data goes only in its `deviceName` (a `Gamepad.id`), which the replay keeps only when the player opted in
       * (`ReplayRecordingOptions.includeDeviceNames`); never put it in the label.
       */
      source?: InputSource;
      /**
       * The way a scratch press turned the turntable, from a controller that reports rotation (a turntable or an analog
       * axis). Omitted for keys: the engine takes a key's spin from the odd-even rule over the scratch lane's keys
       * (`createScratchSpinByToken`). `null` for input with no direction at all (a touch lane). Display only (the
       * turntable's animation): a back-spin scratch is judged on `source`.
       */
      spin?: ScratchSpin | null;
      /**
       * The physical input behind the press, recorded in the replay (`ReplayInputEvent.code`): a keyboard's
       * `KeyboardEvent.code`, or `'touch'`. Omitted by hosts that have none (a terminal).
       */
      code?: string;
      /**
       * Wall-clock-ms snapshot of the physical key press (`performance.timeOrigin + performance.now()`-style,
       * i.e. `Date.now()`-equivalent with sub-ms precision). The runtime adapter (web / node) sets this the
       * moment the OS-level event handler fires; the engine subtracts the wall-clock delta against this when
       * resolving the judge timestamp so a press that lands a few ms before the next 60 Hz tick still resolves
       * at its true timing rather than getting up to ~16 ms of artificial late-bias.
       *
       * The wall-clock domain (NOT raw `performance.now()`) is what makes this safe across `worker_threads`:
       * the TUI runs the input adapter on the main thread and the engine in a worker, and each thread has its
       * own `performance.timeOrigin`, so a raw `performance.now()` snapshot wouldn't survive the cross-thread
       * comparison. Both adapters add `performance.timeOrigin` to whatever event-side timestamp they have so
       * the value is process-shared.
       *
       * Optional — older runtimes / synthetic inputs that don't have a meaningful press time omit it and the
       * engine falls back to drain-time semantics.
       */
      pressedAt?: number;
    }
  /**
   * A control button that is not a lane (START / SELECT) went down or up. The engine only records it in the replay
   * (`ReplayPlay.controlInputs`) at the chart time it drains it; what the host does with the button arrives as its own
   * commands (`view`, `interrupt`, ...).
   */
  | { kind: 'control-input'; button: string; action: 'down' | 'up'; code?: string }
  | {
      kind: 'kitty-state';
      pressTokens: string[];
      repeatTokens: string[];
      releaseTokens: string[];
      /** The physical input behind the event (`lane-input.code`); the replay records it on the release. */
      code?: string;
      /** The input source of the event (`lane-input.source`); omitted for keys, as there. */
      source?: InputSource;
      /** Wall-clock-ms snapshot of the underlying physical event. Same domain as `lane-input.pressedAt`. */
      pressedAt?: number;
    };
 
export interface PlayerInputSignalBus {
  readonly tick: WritableSignal<number>;
  pushCommand: (command: PlayerInputCommand) => void;
  drainCommands: () => PlayerInputCommand[];
}
 
export function createPlayerInputSignalBus(): PlayerInputSignalBus {
  const tick = signal(0);
  const commandQueue: PlayerInputCommand[] = [];
 
  const pushCommand = (command: PlayerInputCommand): void => {
    commandQueue.push(command);
    tick(tick() + 1);
  };
 
  const drainCommands = (): PlayerInputCommand[] => commandQueue.splice(0, commandQueue.length);
 
  return {
    tick,
    pushCommand,
    drainCommands,
  };
}