All files / player-engine/src/replay rejudge.ts

98.68% Statements 75/76
90.82% Branches 99/109
100% Functions 13/13
100% Lines 62/62

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                                                                                                  967x                   4044x   1013x 608x   594x   594x 448x 448x                           4044x     4044x 4029x 3014x 3013x               5x   5x                     693x 15x 15x 693x   693x 1x     15x       5x   15x                       825x 825x 822x 825x 4x 4x                     49x 124x 49x         15x 15x                           128x 312x 128x 293x 293x 1x 1x     127x 128x 33x   94x 94x 93x 93x     5x   5x       5x     88x 93x   3x 3x   1x   1x         2x     128x   128x     128x    
/**
 * Re-judging a replay under a ruleset, with ADR 0019's outcomes: a result that is simulated in full, one that is
 * truncated at the point the played run stopped, or none at all ("not simulated") with the reason.
 *
 * {@link simulateReplay} stays the plain simulator: it judges whatever it is given. These wrappers decide first whether
 * the replay can be judged under the target at all, and never synthesize inputs the played run did not record.
 */
import { resolveGaugeTypes, splitGaugePick, type GaugePick, type GaugeType } from '../ruleset/gauge-type.ts';
import { courseGoesOnAfterGivingUp, isCourseStageFailed } from '../ruleset/course.ts';
import type { RulesetId } from '../ruleset/index.ts';
import { simulateCourseReplay, type BeMusicCourseReplay, type ReplayCourseResult } from './course.ts';
import type { BeMusicReplay, ReplayRulesetResult } from './format.ts';
import { simulateReplay, type SimulateReplayOptions } from './simulate.ts';
 
/**
 * Why a replay is not simulated under a ruleset:
 *
 * - `gauge` — the replay's bare gauge is not one the ruleset defines (`P-ATTACK` under beatoraja, `EX-HARD` under LR2,
 *   `DEATH` under AC outside a course). It is never mapped to a lookalike. A qualified gauge (`lr2:P-ATTACK`) is its
 *   source's under every ruleset, so it is never a reason (#1171).
 * - `custom-judge` — CUSTOM JUDGE stays beatoraja's (#933): it has no reading under another ruleset.
 *
 * Gauge auto-shift is carried under every ruleset, along the target's own gauge ladder (`resolveGaugeShiftLadder`), so
 * it is no reason by itself (#933).
 */
export type ReplayNotSimulatedReason = 'gauge' | 'custom-judge';
 
/** One ruleset's outcome of re-judging a replay (ADR 0019). */
export type ReplayRejudgeOutcome =
  | { status: 'simulated'; result: ReplayRulesetResult }
  | {
      /**
       * The played run stopped where its survival gauge emptied, and this ruleset's gauge would have survived that
       * point: judged up to it ({@link stoppedAtUs}) and no further. Not ranked.
       */
      status: 'truncated';
      result: ReplayRulesetResult;
      stoppedAtUs: number;
    }
  | { status: 'not-simulated'; reason: ReplayNotSimulatedReason };
 
/** One ruleset's outcome of re-judging a course replay; a course is truncated where its played run stopped early. */
export type ReplayCourseRejudgeOutcome =
  | { status: 'simulated'; result: ReplayCourseResult }
  | { status: 'truncated'; result: ReplayCourseResult }
  | { status: 'not-simulated'; reason: ReplayNotSimulatedReason; stage?: number };
 
/** The ruleset a replay was played under (LR2 when the log does not say). */
function playedRuleset(replay: BeMusicReplay): RulesetId {
  return replay.play.judgeRuleset ?? 'lr2';
}
 
/**
 * Whether `ruleset` defines the bare gauge pick `gauge`. A course stage plays the pick on the ruleset's course gauges,
 * which take every pick but the attack gauges outside LR2, EX-HARD or ASSIST EASY under LR2, ASSIST EASY under plugout,
 * and plugout's EX picks anywhere else (`resolveCourseGaugeId`).
 */
function definesGauge(ruleset: RulesetId, pick: GaugePick, courseStage: boolean): boolean {
  // A bare pick on the ruleset's menu, the common case, needs no split.
  if (!courseStage && resolveGaugeTypes(ruleset).includes(pick as GaugeType)) return true;
  // A qualified gauge keeps its source's reading under every ruleset (carried, ADR 0019).
  if (pick.includes(':') && splitGaugePick(pick)?.source !== undefined) return true;
  if (!courseStage) return false;
  // Anything else, a bare pick or no pick at all, reads as it is.
  const gauge = pick as GaugeType;
  // plugout's course gauges take every pick of its own but ASSIST EASY; its EX picks exist nowhere else.
  if (ruleset === 'plugout') return gauge !== 'ASSIST-EASY' && gauge !== 'P-ATTACK' && gauge !== 'G-ATTACK';
  Iif (gauge === 'EX-GROOVE' || gauge === 'EX-EASY' || gauge === 'EX-DEATH') return false;
  return ruleset === 'lr2'
    ? gauge !== 'EX-HARD' && gauge !== 'ASSIST-EASY'
    : gauge !== 'P-ATTACK' && gauge !== 'G-ATTACK';
}
 
/**
 * Why `replay` cannot be judged under `ruleset`, or `undefined` when it can. `player` picks the side of a recorded
 * two-player play, whose gauge it reads.
 */
export function findReplayNotSimulatedReason(
  replay: BeMusicReplay,
  ruleset: RulesetId,
  player: 1 | 2 = 1,
): ReplayNotSimulatedReason | undefined {
  const gauge = player === 2 ? (replay.play.gauge2P ?? replay.play.gauge) : replay.play.gauge;
  // Under the played ruleset too: the engine refuses a bare gauge its ruleset lacks, so only a replay recorded before
  // that (a bare DEATH under That-Which-Must-Not-Be-Named, once played as EX-HARD) fails here, and it is reported.
  if (!definesGauge(ruleset, gauge, replay.play.course !== undefined)) return 'gauge';
  if (ruleset === 'beatoraja') return undefined;
  if (replay.play.customJudge !== undefined) return 'custom-judge';
  return undefined;
}
 
/**
 * The replay cut where judging stopped at `stoppedAtUs`: nothing after it is judged, and no note past it is missed,
 * as for a run given up there.
 */
function stopReplayAt(replay: BeMusicReplay, stoppedAtUs: number): BeMusicReplay {
  return {
    ...replay,
    inputs: replay.inputs.filter((input) => input.timeUs <= stoppedAtUs),
    // Judgments due at the stop itself still count: it was the judgment that emptied the played gauge.
    play: { ...replay.play, aborted: true, abortedAtUs: stoppedAtUs + 1 },
  };
}
 
/**
 * Where the played run stopped because its survival gauge emptied (`play.endOnFailure`), re-judged under its own
 * ruleset; `undefined` when it did not stop early for that.
 */
function findFailureStop(replay: BeMusicReplay, options: Omit<SimulateReplayOptions, 'ruleset'>): number | undefined {
  if (replay.play.endOnFailure !== true || replay.play.aborted === true) return undefined;
  const ruleset = playedRuleset(replay);
  const gaugeKey = options.player === 2 && replay.play.gauge2P !== undefined ? 'gauge2P' : 'gauge';
  const gauge = replay.play[gaugeKey];
  // Older ____ replays used EX-HARD for a bare DEATH pick. Reconstruct their stop on that curve.
  if (ruleset === '____' && replay.play.course === undefined && (gauge === 'DEATH' || gauge === 'DEATH-CORRECTED')) {
    replay = { ...replay, play: { ...replay.play, [gaugeKey]: 'EX-HARD' } };
  }
  let stoppedAtUs: number | undefined;
  simulateReplay(replay, {
    ...options,
    ruleset,
    onJudgment: undefined,
    onFailure: (atUs) => (stoppedAtUs = atUs),
  });
  return stoppedAtUs;
}
 
/**
 * Re-judges `replay` under `options.ruleset` by ADR 0019's declared rules. Under the played ruleset the replay is
 * simulated as recorded, unless it carries a bare gauge the engine now refuses there. Under another ruleset:
 *
 * - a gauge or option the ruleset cannot read makes it `not-simulated` (see {@link ReplayNotSimulatedReason});
 * - a run that stopped where its survival gauge emptied is judged only up to that point, and is `truncated` when this
 *   ruleset's gauge would have survived it.
 */
export function rejudgeReplay(replay: BeMusicReplay, options: SimulateReplayOptions): ReplayRejudgeOutcome {
  const reason = findReplayNotSimulatedReason(replay, options.ruleset, options.player);
  if (reason !== undefined) return { status: 'not-simulated', reason };
  const stoppedAtUs = options.ruleset === playedRuleset(replay) ? undefined : findFailureStop(replay, options);
  if (stoppedAtUs === undefined) return { status: 'simulated', result: simulateReplay(replay, options) };
  const result = simulateReplay(stopReplayAt(replay, stoppedAtUs), options);
  return result.gauge.failedMidPlay === true
    ? { status: 'simulated', result }
    : { status: 'truncated', result, stoppedAtUs };
}
 
/** Runs {@link rejudgeReplay} for each ruleset. */
export function rejudgeReplayRulesets(
  replay: BeMusicReplay,
  rulesets: readonly RulesetId[],
  options: Omit<SimulateReplayOptions, 'ruleset'> = {},
): Record<string, ReplayRejudgeOutcome> {
  const outcomes: Record<string, ReplayRejudgeOutcome> = {};
  for (const ruleset of rulesets) outcomes[ruleset] = rejudgeReplay(replay, { ...options, ruleset });
  return outcomes;
}
 
/** Whether a course result's run ended because a stage failed, by the course rule (`isCourseStageFailed`). */
function endedOnFailedStage(result: ReplayCourseResult): boolean {
  const last = result.stages.at(-1);
  return last !== undefined && isCourseStageFailed(last.ruleset, last.gauge);
}
 
/**
 * Re-judges a course replay under `options.ruleset` by ADR 0019's rules, as {@link rejudgeReplay} does for one play:
 * a stage log the ruleset cannot read makes the run `not-simulated`. A run that the played ruleset ended at a failed
 * stage (its last played stage cut where its gauge emptied, or followed by unreached stages) is `truncated` under a
 * ruleset whose gauge would have carried on, since the stages and notes after that point were never played. So is a
 * run that ended on a stage given up, under a ruleset whose course gauge goes on past one (`courseGoesOnAfterGivingUp`).
 */
export function rejudgeCourseReplay(
  courseLog: BeMusicCourseReplay,
  options: Omit<SimulateReplayOptions, 'course'>,
): ReplayCourseRejudgeOutcome {
  const logs = courseLog.nonstop !== undefined ? [courseLog.nonstop.replay] : [];
  const stageLogs = courseLog.stages.flatMap((entry) => (entry.played ? [entry.replay] : []));
  for (const [index, log] of [...logs, ...stageLogs].entries()) {
    const reason = findReplayNotSimulatedReason(log, options.ruleset, options.player);
    if (reason !== undefined) {
      const stage = index - logs.length;
      return { status: 'not-simulated', reason, ...(stage >= 0 ? { stage } : {}) };
    }
  }
  const lastLog = courseLog.nonstop?.replay ?? stageLogs.at(-1);
  if (lastLog === undefined || options.ruleset === playedRuleset(lastLog)) {
    return { status: 'simulated', result: simulateCourseReplay(courseLog, options) };
  }
  const stoppedAtUs = findFailureStop(lastLog, options);
  if (stoppedAtUs === undefined) {
    const result = simulateCourseReplay(courseLog, options);
    if (courseLog.nonstop === undefined && lastLog.play.aborted === true) {
      // The played run ended on a stage given up. Where this ruleset's course gauge goes on past it (LR2's), the stages
      // after it were never played, so the result stops short of the run this ruleset would have had.
      const givenUp = result.stages.at(-1);
      const goesOn =
        stageLogs.length < courseLog.stages.length &&
        result.stages.length === stageLogs.length &&
        givenUp !== undefined &&
        courseGoesOnAfterGivingUp(givenUp.ruleset, givenUp);
      return goesOn ? { status: 'truncated', result } : { status: 'simulated', result };
    }
    const unreached =
      courseLog.nonstop === undefined && stageLogs.length < courseLog.stages.length && lastLog.play.aborted !== true;
    if (!unreached || endedOnFailedStage(result)) return { status: 'simulated', result };
    // A stage passed here that failed the played run: the stages after it were never played.
    const played = simulateCourseReplay(courseLog, { ...options, ruleset: playedRuleset(lastLog) });
    return endedOnFailedStage(played) ? { status: 'truncated', result } : { status: 'simulated', result };
  }
  const cut = stopReplayAt(lastLog, stoppedAtUs);
  const judged: BeMusicCourseReplay =
    courseLog.nonstop !== undefined
      ? { ...courseLog, nonstop: { ...courseLog.nonstop, replay: cut } }
      : {
          ...courseLog,
          stages: courseLog.stages.map((entry) =>
            entry.played && entry.replay === lastLog ? { played: true, replay: cut } : entry,
          ),
        };
  const result = simulateCourseReplay(judged, options);
  const failed =
    courseLog.nonstop !== undefined
      ? simulateReplay(cut, options).gauge.failedMidPlay === true
      : result.stages.at(-1)?.gauge.failedMidPlay === true;
  return failed ? { status: 'simulated', result } : { status: 'truncated', result };
}