All files / player-engine/src/core engine-effects.ts

100% Statements 74/74
95.38% Branches 62/65
100% Functions 4/4
100% Lines 68/68

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                                                                                                                                                              3028x 3028x 3028x   3028x 3028x 12x 12x     12x   3028x 1398331x 1398331x 1398331x 667x 667x   1398331x   172728x 172728x                 172728x   5150x 5150x   84641x 84641x   86185x 83257x                   86185x 86185x   1x 1x   8195x 7884x                   8195x 8195x   106949x         106949x   98514x           98514x   32373x               32373x   415937x 15931x   415937x   94496x         94496x   89438x 85860x 42903x   42957x     89438x   103168x 17x 17x 103151x 98x   103168x               103168x 6x 6x   103168x   98452x 98452x   98452x   2104x 1842x   2104x     3028x   116785x 1313x 1313x        
import { resolveBmsonBGAEventInput, type BmsonBGAEventInput } from './bmson-bga.ts';
import { resolveChartTextInput, type ChartTextInput } from './chart-text.ts';
import {
  adjustBeatorajaJudgeTiming,
  createLR2JudgeTimingSamples,
  isLR2JudgeTimingAutoAdjust,
  sampleLR2JudgeTiming,
  settleLR2JudgeTiming,
  type JudgeTimingAutoAdjust,
} from './judge-timing.ts';
import { type PlayerStateSignals } from '../state-signals.ts';
import { formatSeconds } from '../utils.ts';
import { type PlayerUISignalBus } from './ui-signal-bus.ts';
import { type PlaybackStateLogger } from './playback-support.ts';
import { type JudgeCoreEffectSink } from './judge-core.ts';
import { type ReplayRecorder } from '../replay/recorder.ts';
import {
  type NoTUIPlaybackEventTracer,
  writePlayableSampleTriggerEventLog,
  writeRuntimeEventLog,
  writeSampleStopEventLog,
} from './engine-trace.ts';
import { type AudioSession } from './engine-types.ts';
import { type ChainSoundQueue } from './chain-audio.ts';
import { resolveGuideSound } from './guide-sound.ts';
 
/**
 * Maps judge-core effects onto a play's audio session, UI buses, replay and no-TUI trace.
 */
/** What a driver hands {@link createJudgeEffectHandler}: the host side of every judge-core effect. */
interface JudgeEffectHost {
  uiEnabled: boolean;
  onBmsonBGAInput?: (input: BmsonBGAEventInput) => void;
  onChartTextInput?: (input: ChartTextInput) => void;
  onInput?: (input: Extract<Parameters<JudgeCoreEffectSink>[0], { kind: 'record-input' }>) => void;
  /** Where a press's LRX chain notes go to wait for their moment; without it they do not sound. */
  chainSounds?: ChainSoundQueue;
  /**
   * The automatic judge-timing adjustment this play runs (`OFF` for none: AUTO, replays, or a mode the play skips), and
   * the live timing it moves. `currentSeconds` is the chart time an LR2 step is recorded at.
   */
  judgeTiming?: { mode: JudgeTimingAutoAdjust; value: number; currentSeconds?: () => number };
  writeOutput: (text: string) => void;
  wavResources: Readonly<Record<string, string>>;
  idBase: 36 | 62;
  audioSession: AudioSession | undefined;
  playbackStateLogger: PlaybackStateLogger;
  playbackEventTracer: NoTUIPlaybackEventTracer;
  uiSignals: PlayerUISignalBus;
  activeStateSignals: PlayerStateSignals | undefined;
  replayRecorder: ReplayRecorder | undefined;
  publishUIFrame: (seconds: number, beat: number) => void;
  beatAtSeconds: (seconds: number) => number;
}
 
/** The judge-effect sink of one play, with the step LR2's automatic judge timing takes once per judging pass. */
export interface JudgeEffectHandler extends JudgeCoreEffectSink {
  /** Ends a judging pass: LR2's adjustment steps when its window is full (a no-op in any other mode). */
  settleJudgeTiming(): void;
}
 
/**
 * Interprets judge-core effects for one play: audio always, UI cues or the no-TUI trace depending on the mode, and
 * the replay when one is being recorded. Shared by the manual and the auto drivers.
 */
export function createJudgeEffectHandler(host: JudgeEffectHost): JudgeEffectHandler {
  const {
    uiEnabled,
    writeOutput,
    wavResources,
    idBase,
    audioSession,
    playbackStateLogger,
    playbackEventTracer,
    uiSignals,
    activeStateSignals,
    replayRecorder,
    publishUIFrame,
    beatAtSeconds,
  } = host;
  const judgeTiming = host.judgeTiming;
  const judgeTimingMode = judgeTiming?.mode ?? 'OFF';
  // LR2's window starts empty with the play (OpenLR2 leaves the reset at play start undetermined).
  const lr2Samples = isLR2JudgeTimingAutoAdjust(judgeTimingMode) ? createLR2JudgeTimingSamples() : undefined;
  const changeJudgeTiming = (next: number, seconds: number): void => {
    judgeTiming!.value = next;
    replayRecorder?.recordOptionChange(Math.max(0, seconds, judgeTiming!.currentSeconds?.() ?? 0), {
      judgeTimingMs: next,
    });
    uiSignals.pushCommand({ kind: 'judge-timing', value: next });
  };
  const sink: JudgeCoreEffectSink = (effect) => {
    const textInput = host.onChartTextInput ? resolveChartTextInput(effect) : undefined;
    if (textInput) host.onChartTextInput!(textInput);
    if (host.onBmsonBGAInput) {
      const input = resolveBmsonBGAEventInput(effect);
      if (input) host.onBmsonBGAInput(input);
    }
    switch (effect.kind) {
      case 'record-input':
        host.onInput?.(effect);
        replayRecorder?.recordInput(
          effect.action,
          effect.seconds,
          effect.source,
          effect.channels,
          effect.inferred,
          effect.spin,
          effect.code,
        );
        return;
      case 'record-empty-poor':
        replayRecorder?.recordEmptyPoor();
        return;
      case 'input-time':
        playbackEventTracer.flushUntil(effect.seconds);
        return;
      case 'sound':
        if (!uiEnabled) {
          writePlayableSampleTriggerEventLog(
            writeOutput,
            effect.event,
            effect.seconds,
            wavResources,
            effect.source,
            effect.channel,
            idBase,
          );
        }
        audioSession?.triggerEvent?.(effect.event);
        return;
      case 'chain-sounds':
        host.chainSounds?.schedule(effect.seconds, effect.sounds);
        return;
      case 'stop-sound':
        if (!uiEnabled) {
          writeSampleStopEventLog(
            writeOutput,
            effect.channel,
            effect.seconds,
            effect.reason,
            effect.event,
            wavResources,
            idBase,
          );
        }
        audioSession?.stopChannel?.(effect.channel);
        return;
      case 'gauge':
        playbackStateLogger.logGaugeChange(effect.seconds, {
          reason: effect.reason,
          judge: effect.judge,
          delta: effect.delta,
        });
        return;
      case 'combo':
        playbackStateLogger.logComboChange(effect.seconds, {
          value: effect.value,
          reason: effect.reason,
          judge: effect.judge,
          channel: effect.channel,
        });
        return;
      case 'long-note':
        playbackStateLogger.logLongNoteState(effect.seconds, {
          channel: effect.channel,
          state: effect.state,
          mode: effect.mode,
          event: effect.event,
          resources: wavResources,
          endSeconds: effect.endSeconds,
        });
        return;
      case 'ui':
        if (uiEnabled) {
          uiSignals.pushCommand(effect.command);
        }
        return;
      case 'poor-bga':
        uiSignals.pushCommand(
          effect.action === 'trigger'
            ? { kind: 'trigger-poor-bga', seconds: effect.seconds }
            : { kind: 'clear-poor-bga' },
        );
        return;
      case 'poor-trace':
        if (!uiEnabled) {
          if (effect.action === 'trigger') {
            playbackEventTracer.logPoorTriggered(effect.seconds);
          } else {
            playbackEventTracer.logPoorCleared(effect.seconds);
          }
        }
        return;
      case 'judge-combo':
        if (judgeTimingMode === 'BEATORAJA' && effect.seconds !== undefined) {
          const next = adjustBeatorajaJudgeTiming(judgeTiming!.value, effect.judge, effect.signedDeltaMs);
          if (next !== judgeTiming!.value) changeJudgeTiming(next, effect.seconds);
        } else if (lr2Samples !== undefined) {
          sampleLR2JudgeTiming(lr2Samples, effect.judge, effect.signedDeltaMs, effect.longNote === true);
        }
        activeStateSignals?.publishJudgeCombo(
          effect.judge,
          effect.combo,
          effect.channel,
          undefined,
          effect.signedDeltaMs,
        );
        // beatoraja's GUIDE SE: the judgment's sound, from an audio session that has the sound set's.
        if (audioSession?.playGuideSound !== undefined) {
          const guide = resolveGuideSound(effect.judge, effect.poor);
          if (guide !== undefined) audioSession.playGuideSound(guide);
        }
        return;
      case 'trace':
        Eif (!uiEnabled) {
          writeRuntimeEventLog(writeOutput, effect.name, [['time', formatSeconds(effect.seconds)], ...effect.fields]);
        }
        return;
      case 'frame':
        if (uiEnabled) {
          publishUIFrame(effect.seconds, effect.beat ?? beatAtSeconds(effect.seconds));
        }
        return;
    }
  };
  return Object.assign(sink, {
    settleJudgeTiming: () => {
      if (lr2Samples === undefined) return;
      const next = settleLR2JudgeTiming(judgeTiming!.value, lr2Samples);
      if (next !== judgeTiming!.value) changeJudgeTiming(next, 0);
    },
  });
}