All files / player-engine/src/core judge-core-press.ts

94.69% Statements 250/264
92.69% Branches 203/219
100% Functions 21/21
95.96% Lines 238/248

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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695                                                                                                                                      86895x         913107x                             86895x 86895x 86895x 86895x 86895x 913107x 913107x 82018x   831089x 747615x     83474x 83474x 83474x 2337x     81137x     913107x         81137x                                     86835x 86835x         86835x     504691x   81066x       74322x 74322x       86835x 86835x 86835x                         60x 60x 60x 60x     72x   71x   60x 60x                             25709x 2050x 2050x 2050x 2050x       34136x 34136x 5124x 5124x   29012x 1892x 1485x 1485x 1485x 262x 262x 262x 262x 262x 262x 262x   262x 262x 262x                   12624x 12624x 12624x 345x   12279x 12279x     12279x 12279x 22213x 22213x 2252x   19961x 19961x 9096x       3528x         146x     131x                                         86887x 86887x   86887x                   86887x 86894x       86887x         86887x 86894x 86696x   198x 15x 15x   198x           86887x 86894x   86887x 86887x   86887x 86894x           86887x     86887x   198x     86887x 183x 183x 132x   51x       86887x       198x     86887x 198x   86689x   86689x 12624x         12624x               12624x 11032x 11033x   11032x     12624x   3528x   9096x 9096x     74065x 74065x     74065x 74065x 74065x 74065x 74074x 74065x 74065x 74065x 74065x 16206x 16206x                 16206x   16206x 16206x       16206x         16206x 16206x   9338x 9338x 9338x   718x 718x 718x 718x 718x 718x   8620x                     9338x 9338x 9338x 8620x   6868x 6868x                       6868x 6868x 6868x 6868x             57859x 57859x   57859x             57859x                             132x 132x                 132x         132x 132x                           51x 51x 39x   12x 12x 12x 12x 12x 2x 2x     10x                 9106x 9106x 3920x   5186x 5186x 5186x   568x 568x   5186x 5186x 5186x 5116x                     5186x                   86445x 86445x                     86445x 86445x 86445x 86449x 86449x 86449x 86449x               1x   86448x 86448x 86111x   86448x     472x 4x 4x 4x   472x   85976x 11627x 11627x 11627x     11627x 11627x     86445x 11486x                               472x 472x 44x 43x 43x       43x               11627x 11627x 11627x 11627x 11627x 11627x 11222x   405x 405x   405x         11627x 11627x    
import { breakTrackedCombo } from './scoring.ts';
import { notePlugoutLaneJudged, notePlugoutLaneReleased, resolvePlugoutLaneSound } from './plugout-lane-sound.ts';
import { findFirstIndexNumberAtOrAfter } from '@be-music/shared-utils/core';
import { findLaneSoundCandidate, lowerBoundBySeconds } from '../judging.ts';
import type { TimedPlayableNote } from '../playable-notes.ts';
import { classifyRulesetJudge, RULESET_JUDGE_NONE, type RulesetJudgeIndex } from '../ruleset/judge.ts';
import { ignoresLateLongNoteHeadBad, isBackSpinScratch, isChargeLongNoteMode } from '../ruleset/long-note.ts';
import { preferJudgeCandidate, type JudgeSelectionCandidate } from '../ruleset/selection.ts';
import { selectAnyKeyLane, type AnyKeyCandidate } from './any-key.ts';
import {
  isLongPlayableNote,
  judgeDeltaUs,
  RULESET_JUDGE_KINDS,
  resolveLongNoteEarlyReleaseJudge,
  resolveManualTimedJudge,
  resolveRulesetLongNoteMode,
  toUILongNoteMode,
} from './judge-rules.ts';
import {
  advanceJudgeState,
  detonateLandminesOnPress,
  finalizeActiveLongNote,
  laneHoldHistory,
  processLandminePassage,
  setHCNGaining,
  startHCNPassing,
} from './judge-core-advance.ts';
import { recordLaneDown, recordLaneUp } from './lane-hold.ts';
import type { ScratchSpin } from './scratch-spin.ts';
import {
  endsBackSpinScratch,
  hasScratchCounterpart,
  isSameInputSource,
  releasesScratchHold,
  type InputSource,
} from './input-source.ts';
import {
  applyGaugeJudge,
  applyResolvedManualJudge,
  judgeWindowsFor,
  markScorableJudged,
  maxJudgeEarlyReachSeconds,
  maxJudgeReachSeconds,
  setCombo,
  toJudgeClock,
  toJudgeUs,
  isJudgingClosed,
} from './judge-core-score.ts';
import {
  type ActiveLongNoteState,
  type JudgeCoreEffectSink,
  type JudgeCoreInput,
  type JudgeCoreState,
} from './judge-core-types.ts';
 
/**
 * Judgment-core input handling: which note a press resolves against, multi-BAD, empty POOR and
 * releases.
 */
 
// ---- presses --------------------------------------------------------------------------------------------------
 
/**
 * The first note a press scan visits: one microsecond wider than the reach, since the windows are compared in whole
 * microseconds (`judgeDeltaUs`) while note times are float seconds. A note just outside is rejected by its windows.
 */
function scanStartIndex(notes: readonly TimedPlayableNote[], nowSec: number, reachSeconds: number): number {
  return lowerBoundBySeconds(notes, nowSec - reachSeconds - 1e-6);
}
 
/** True once a scan has passed every note a press at `inputTimeUs` can reach, compared in whole microseconds. */
function isBeyondScanReach(note: TimedPlayableNote, inputTimeUs: number, reachSeconds: number): boolean {
  return toJudgeUs(note.seconds) - inputTimeUs > Math.round(reachSeconds * 1e6);
}
 
/**
 * Visits each unjudged note a press at `nowSec` reaches on a lane `accepts` takes, in ascending time order, with the
 * judgment it would get. Reachability is per note: the note's own lane (key vs scratch) and its own chart time (the
 * `#EXRANKxx` rank in force there) pick its window set, and both legs are checked separately. A note inside the coarse
 * scan radius but outside its own windows is not visited, nor an LR2 long-note head a late press would BAD.
 */
function forEachReachableNote(
  state: JudgeCoreState,
  nowSec: number,
  accepts: (channel: string) => boolean,
  visit: (note: TimedPlayableNote, selection: JudgeSelectionCandidate) => void,
): void {
  const { config } = state;
  const { ruleset, scorableNotes } = config;
  const reachSeconds = maxJudgeReachSeconds(config, nowSec);
  const inputTimeUs = Math.round(nowSec * 1e6);
  for (let index = scanStartIndex(scorableNotes, nowSec, reachSeconds); index < scorableNotes.length; index += 1) {
    const note = scorableNotes[index]!;
    if (isBeyondScanReach(note, inputTimeUs, reachSeconds)) {
      break;
    }
    if (note.judged || !accepts(note.channel)) {
      continue;
    }
    // The windows in force at the press, as LR2 reads its judge widths (`#EXRANK` can change them mid-chart).
    const windows = judgeWindowsFor(config, note.channel, nowSec);
    const judge = classifyRulesetJudge(judgeDeltaUs(note.seconds, nowSec), windows);
    if (judge === RULESET_JUDGE_NONE) {
      continue;
    }
    const playedMode =
      typeof note.endSeconds === 'number' && note.endSeconds > note.seconds
        ? resolveRulesetLongNoteMode(ruleset.longNoteStyle, note)
        : undefined;
    Iif (ignoresLateLongNoteHeadBad(ruleset, judge, note.seconds < nowSec, playedMode)) {
      // LR2: a long-note head has no LATE bad — the press falls through to whatever else is in reach. The mode is the
      // one the ruleset plays, not the chart's `#LNMODE`: LR2 plays a `#LNMODE 2` note as a plain LN too.
      continue;
    }
    visit(note, {
      noteTimeUs: Math.round(note.seconds * 1e6),
      dmUs: judgeDeltaUs(note.seconds, nowSec),
      judge,
      windows,
    });
  }
}
 
/**
 * The note a press resolves against, chosen by the ruleset's own selection algorithm among the notes it reaches
 * ({@link forEachReachableNote}). With none, the press falls through to the lane keysound / empty-POOR path instead of
 * consuming a note as a POOR.
 */
function selectPressCandidate(
  state: JudgeCoreState,
  nowSec: number,
  candidateChannels: ReadonlySet<string>,
): { note: TimedPlayableNote; judge: RulesetJudgeIndex } | undefined {
  const { ruleset } = state.config;
  const inputTimeUs = Math.round(nowSec * 1e6);
  let bestNote: TimedPlayableNote | undefined;
  let bestSelection: JudgeSelectionCandidate | undefined;
  // `scorableNotes` is sorted by time, so the scan visits candidates in the ascending order the selection algorithms
  // assume (`lowest` keeps the first, the others may displace it).
  forEachReachableNote(
    state,
    nowSec,
    (channel) => candidateChannels.has(channel),
    (note, selection) => {
      if (
        bestSelection === undefined ||
        preferJudgeCandidate(ruleset.selection, bestSelection, selection, inputTimeUs)
      ) {
        bestNote = note;
        bestSelection = selection;
      }
    },
  );
  const note = bestNote as TimedPlayableNote | undefined;
  const selection = bestSelection as JudgeSelectionCandidate | undefined;
  return note === undefined || selection === undefined ? undefined : { note, judge: selection.judge };
}
 
/**
 * The lanes an ANY KEY press on `channels` at chart second `nowSec` goes to (#751): the lane of the nearest unjudged
 * note it reaches on any lane but an auto-played one or one whose long note is still held ({@link selectAnyKeyLane}),
 * or the keys' own lanes when it reaches none. Reads the state only.
 */
export function resolveAnyKeyPressChannels(
  state: JudgeCoreState,
  channels: ReadonlySet<string>,
  nowSec: number,
): ReadonlySet<string> {
  const { config } = state;
  const autoChannels = config.autoScratch ? (config.autoScratchChannels ?? config.scratchChannels) : undefined;
  const candidates: AnyKeyCandidate[] = [];
  forEachReachableNote(
    state,
    toJudgeClock(config, nowSec),
    (channel) => !state.activeLongNotes.has(channel) && autoChannels?.has(channel) !== true,
    (note, selection) =>
      candidates.push({ channel: note.channel, noteTimeUs: selection.noteTimeUs, dmUs: selection.dmUs }),
  );
  const lane = selectAnyKeyLane(candidates);
  return lane === undefined ? channels : new Set([lane]);
}
 
/**
 * LR2 ProcSinglenote reuses a BAD press for the next tap on that lane, judging its own delta. A non-BAD,
 * a long note or a note outside BAD reach stops the forward chain. Effect times retain the true clock past reversal.
 */
function applyLR2RejudgeChain(
  state: JudgeCoreState,
  nowSec: number,
  consumed: TimedPlayableNote,
  consumedJudge: RulesetJudgeIndex,
  atSeconds: number,
  emit: JudgeCoreEffectSink,
): void {
  if (consumedJudge !== 3 || isLongPlayableNote(consumed) || isJudgingClosed(state)) return;
  const { config } = state;
  let passedConsumed = false;
  for (
    let index = lowerBoundBySeconds(config.scorableNotes, consumed.seconds);
    index < config.scorableNotes.length;
    index += 1
  ) {
    const note = config.scorableNotes[index]!;
    if (!passedConsumed) {
      passedConsumed = note === consumed;
      continue;
    }
    if (note.judged || note.channel !== consumed.channel) continue;
    if (isLongPlayableNote(note)) break;
    const windows = judgeWindowsFor(config, note.channel, nowSec);
    const deltaUs = judgeDeltaUs(note.seconds, nowSec);
    if (deltaUs < windows.judges[3][0] || deltaUs > windows.judges[3][1]) break;
    Iif (config.ruleset.multiBadAheadUs !== undefined && deltaUs >= config.ruleset.multiBadAheadUs) break;
    Iif (!markScorableJudged(state, note)) break;
    const judge = resolveManualTimedJudge((nowSec - note.seconds) * 1000, windows);
    emit({ kind: 'ui', command: { kind: 'flash-lane', channel: note.channel } });
    for (const event of note.soundEvents ?? [note.event])
      emit({ kind: 'sound', source: 'manual-note', event, seconds: atSeconds, channel: note.channel });
    Iif (note.chainSounds)
      emit({ kind: 'chain-sounds', sounds: note.chainSounds, seconds: atSeconds, channel: note.channel });
    notePlugoutLaneJudged(state, note.channel, note);
    applyResolvedManualJudge(state, note.channel, judge, atSeconds, emit);
    if (judge.kind !== 'BAD' || isJudgingClosed(state)) break;
  }
}
 
/**
 * Is there a note near enough on any pressed lane for a note-less press to charge an empty POOR? The reach is the
 * ruleset's own miss (`ms`) window, which is not symmetric: LR2's is early-only, beatoraja's reaches 500 ms early and
 * 150 ms late. Both neighbours of the press are tested, since the late side matters where the ruleset has one.
 */
function hasEmptyPoorReferenceNote(state: JudgeCoreState, channels: ReadonlySet<string>, nowSec: number): boolean {
  for (const channel of channels) {
    const noteTimes = state.scorableNoteSecondsByChannel.get(channel);
    if (!noteTimes) {
      continue;
    }
    const missWindow = judgeWindowsFor(state.config, channel, nowSec).ms;
    Iif (!missWindow) {
      continue;
    }
    const index = findFirstIndexNumberAtOrAfter(noteTimes, nowSec);
    for (const neighbour of [index - 1, index]) {
      const noteSeconds = noteTimes[neighbour];
      if (noteSeconds === undefined) {
        continue;
      }
      const dmUs = judgeDeltaUs(noteSeconds, nowSec);
      if (dmUs >= missWindow[0] && dmUs <= missWindow[1]) {
        return true;
      }
    }
  }
  return false;
}
 
/** Whether a press on `channels` at chart second `nowSec` has a note in reach to judge. Reads the state only. */
export function hasPressCandidate(state: JudgeCoreState, channels: ReadonlySet<string>, nowSec: number): boolean {
  return selectPressCandidate(state, toJudgeClock(state.config, nowSec), channels) !== undefined;
}
 
const NO_CHANNELS: readonly string[] = [];
 
/**
 * A press on `candidateChannels`. `recordedChannels` are the lanes the replay records for it: the keys' own lanes, which
 * differ from the lanes judged only when ANY KEY routed the press. `tokens` are the keys the lanes are held by (the
 * source's key, when there is one). `source` is the physical input the press came from (`input-source.ts`): a scratch
 * long note remembers the source that hit its head. `spin` is the way a scratch press turned the turntable, for
 * display, and `code` the physical input the replay records.
 */
export function handleLanePress(
  state: JudgeCoreState,
  candidateChannels: ReadonlySet<string>,
  tokens: readonly string[],
  nowMs: number,
  nowSec: number,
  emit: JudgeCoreEffectSink,
  recordedChannels: ReadonlySet<string> = candidateChannels,
  source?: InputSource,
  spin?: ScratchSpin,
  code?: string,
): void {
  const { config } = state;
  const { ruleset } = config;
  // Replay press event — recorded BEFORE any judging so the log stays a raw input replay.
  emit({
    kind: 'record-input',
    action: 'down',
    seconds: nowSec,
    source,
    channels: recordedChannels,
    ...(spin !== undefined ? { spin } : {}),
    ...(code !== undefined ? { code } : {}),
  });
 
  for (const mappedChannel of candidateChannels) {
    emit({ kind: 'ui', command: { kind: 'flash-lane', channel: mappedChannel } });
  }
 
  // A press on a lane whose long note is still unresolved is part of that long note: it judges no other note there.
  let pressesLongNote = false;
  // Lanes whose long note was let go and is waiting out the ruleset's release margin: pressing again resumes the hold,
  // so the press judges nothing else on them (beatoraja's re-press, `releasetime` reset).
  // Allocated only on a re-press: most presses hold no long note.
  let resumedChannels: Set<string> | undefined;
  for (const channel of candidateChannels) {
    if (!state.activeLongNotes.has(channel)) {
      continue;
    }
    if (state.longHoldReleaseSeconds.delete(channel)) {
      state.longNoteSettleMs.delete(channel);
      (resumedChannels ??= new Set<string>()).add(channel);
    }
    pressesLongNote = true;
  }
 
  // Record the press before settling any crossings. LR2 also accepts an early GREAT press, the Be-Music AC
  // extension accepts a press on either side within PGREAT, and beatoraja only checks the held key at crossing.
  // Detonation never consumes the press, so regular note judgment still runs.
  for (const channel of candidateChannels) {
    recordLaneDown(laneHoldHistory(state, channel), tokens, nowMs);
  }
  processLandminePassage(state, nowSec, nowMs, emit);
  detonateLandminesOnPress(state, candidateChannels, nowSec, emit);
  // A key going down on a lane with a passing Hell Charge note makes it gain.
  for (const channel of candidateChannels) {
    setHCNGaining(state, channel, toJudgeUs(nowSec), emit);
  }
 
  // Past an LR2 negative-BPM reversal the press is judged on the mirrored clock (#134; see `toJudgeClock`): note
  // selection, timing deltas, windows, the lane keysound and the empty-POOR reach all read `judgeSec`, while the
  // judgments, logs, gauge history and UI cues keep the true `nowSec`.
  const judgeSec = toJudgeClock(config, nowSec);
  // A lane whose long note is held is pressed again by another key bound to it: its current note is the long note, so
  // the press never judges another note there; the ruleset says what it does instead.
  const heldLongNoteChannels = pressesLongNote
    ? [...candidateChannels].filter(
        (channel) => state.activeLongNotes.has(channel) && resumedChannels?.has(channel) !== true,
      )
    : NO_CHANNELS;
  for (const channel of heldLongNoteChannels) {
    const hold = state.activeLongNotes.get(channel)!;
    if (hold.backSpinScratch === true && endsBackSpinScratch(hold.headSource, source)) {
      judgeBackSpinScratchTail(state, channel, judgeSec, nowSec, emit);
    } else {
      applyPressDuringLongNote(state, channel, judgeSec, nowSec, emit);
    }
  }
  const judgedChannels =
    resumedChannels === undefined && heldLongNoteChannels.length === 0
      ? candidateChannels
      : new Set(
          [...candidateChannels].filter(
            (channel) => resumedChannels?.has(channel) !== true && !heldLongNoteChannels.includes(channel),
          ),
        );
  if (judgedChannels.size === 0) {
    return;
  }
  const selected = selectPressCandidate(state, judgeSec, judgedChannels);
 
  if (!selected) {
    Iif (pressesLongNote) {
      // The press is part of a long note's sustain, not a phantom press.
      return;
    }
    const fallback =
      state.plugoutLaneSounds !== undefined
        ? resolvePlugoutLaneSound(state, judgedChannels, judgeSec)
        : findLaneSoundCandidate(
            config.laneSoundNotes,
            judgedChannels,
            judgeSec,
            maxJudgeEarlyReachSeconds(config, judgeSec),
          );
    if (fallback) {
      for (const event of fallback.soundEvents ?? [fallback.event])
        emit({ kind: 'sound', source: 'lane-fallback', event, seconds: nowSec, channel: fallback.channel });
      // plugout plays the chain after any press that sounds the note, an empty one included (0x43bcd0).
      Iif (fallback.chainSounds)
        emit({ kind: 'chain-sounds', sounds: fallback.chainSounds, seconds: nowSec, channel: fallback.channel });
    }
    if (!hasEmptyPoorReferenceNote(state, judgedChannels, judgeSec)) {
      // No note in the ruleset's miss window — the press is harmless: only the lane keysound plays.
      return;
    }
    chargeEmptyPoor(state, nowSec, emit);
    return;
  }
 
  const candidate = selected.note;
  Iif (!markScorableJudged(state, candidate)) {
    return;
  }
  const channel = candidate.channel;
  const signedDeltaMs = (judgeSec - candidate.seconds) * 1000;
  emit({ kind: 'ui', command: { kind: 'flash-lane', channel } });
  for (const event of candidate.soundEvents ?? [candidate.event])
    emit({ kind: 'sound', source: 'manual-note', event, seconds: nowSec, channel });
  if (candidate.chainSounds) emit({ kind: 'chain-sounds', sounds: candidate.chainSounds, seconds: nowSec, channel });
  notePlugoutLaneJudged(state, channel, candidate);
  const endSeconds = candidate.endSeconds;
  if (typeof endSeconds === 'number' && Number.isFinite(endSeconds) && endSeconds > candidate.seconds) {
    const longNoteMode = resolveRulesetLongNoteMode(ruleset.longNoteStyle, candidate);
    emit({
      kind: 'long-note',
      seconds: nowSec,
      channel,
      state: 'start',
      mode: longNoteMode === 2 || longNoteMode === 3 ? longNoteMode : 1,
      event: candidate.event,
      endSeconds,
    });
    candidate.visibleUntilBeat = candidate.endBeat;
    // Light the renderer's LN-hold timer on the head; the matching `release-lane` comes when the note resolves.
    Eif (longNoteMode !== undefined) {
      emit({
        kind: 'ui',
        command: { kind: 'hold-lane-until-beat', channel, beat: candidate.endBeat ?? candidate.beat },
      });
      emit({
        kind: 'ui',
        command: { kind: 'long-note-start', channel, beat: candidate.beat, mode: toUILongNoteMode(longNoteMode) },
      });
    }
    const headJudge = resolveManualTimedJudge(signedDeltaMs, judgeWindowsFor(config, channel, judgeSec));
    if (longNoteMode !== undefined && isChargeLongNoteMode(longNoteMode)) {
      // Charge modes score the head right here — it is a judgment of its own, not half of a deferred one.
      applyResolvedManualJudge(state, channel, headJudge, nowSec, emit, true);
      startHCNPassing(state, candidate, toJudgeUs(nowSec), emit);
      if (ruleset.headBadSkipsTail && (headJudge.kind === 'BAD' || headJudge.kind === 'POOR')) {
        // That-Which-Must-Not-Be-Named: a broken charge-note head cancels the tail; the note is finished with a single judgment.
        state.activeLongNotes.delete(channel);
        state.longNoteSettleMs.delete(channel);
        emit({ kind: 'ui', command: { kind: 'long-note-end', channel, outcome: 'dropped' } });
        emit({ kind: 'ui', command: { kind: 'release-lane', channel } });
        Iif (ruleset.multiBad) applyLR2RejudgeChain(state, judgeSec, candidate, selected.judge, nowSec, emit);
        return;
      }
      state.activeLongNotes.set(channel, {
        endSeconds,
        note: candidate,
        mode: longNoteMode,
        headJudge,
        headScored: true,
        audioStopped: false,
        ...(ruleset.heldChargeTail === undefined && isBackSpinScratch(longNoteMode, config.scratchChannels.has(channel))
          ? { backSpinScratch: true as const, ...(source !== undefined ? { headSource: source } : {}) }
          : {}),
      });
      state.longNoteSettleMs.delete(channel);
      state.longHoldReleaseSeconds.delete(channel);
      if (ruleset.multiBad) applyLR2RejudgeChain(state, judgeSec, candidate, selected.judge, nowSec, emit);
      return;
    }
    Eif (longNoteMode === 1) {
      state.activeLongNotes.set(channel, {
        endSeconds,
        note: candidate,
        mode: 1,
        headJudge,
        headScored: false,
        audioStopped: false,
        // beatoraja: a scratch LN remembers the key that hit its head, and only that key's release lets it go.
        ...(ruleset.scratchHoldsBySource && source !== undefined && config.scratchChannels.has(channel)
          ? { headSource: source }
          : {}),
      });
      state.longNoteSettleMs.delete(channel);
      state.longHoldReleaseSeconds.delete(channel);
      if (ruleset.multiBad) applyLR2RejudgeChain(state, judgeSec, candidate, selected.judge, nowSec, emit);
      return;
    }
    state.activeLongNotes.delete(channel);
    state.longNoteSettleMs.delete(channel);
    if (ruleset.multiBad) applyLR2RejudgeChain(state, judgeSec, candidate, selected.judge, nowSec, emit);
    return;
  }
  state.activeLongNotes.delete(channel);
  state.longNoteSettleMs.delete(channel);
 
  applyResolvedManualJudge(
    state,
    channel,
    resolveManualTimedJudge(signedDeltaMs, judgeWindowsFor(config, channel, judgeSec)),
    nowSec,
    emit,
  );
  if (ruleset.multiBad) applyLR2RejudgeChain(state, judgeSec, candidate, selected.judge, nowSec, emit);
}
 
/**
 * A back-spin scratch's tail, judged on the press that spun the turntable the other way (beatoraja's "BSS終端処理"): the
 * press's timing against the tail's long-scratch-end windows, POOR outside them. It settles at once — no release
 * margin — and plays the tail's keysound like a released charge tail.
 */
function judgeBackSpinScratchTail(
  state: JudgeCoreState,
  channel: string,
  judgeSec: number,
  nowSec: number,
  emit: JudgeCoreEffectSink,
): void {
  const hold = state.activeLongNotes.get(channel)!;
  emit({
    kind: 'long-note',
    seconds: nowSec,
    channel,
    state: 'complete',
    mode: hold.mode,
    event: hold.note.event,
    endSeconds: hold.endSeconds,
  });
  const tail = resolveManualTimedJudge(
    (judgeSec - hold.endSeconds) * 1000,
    judgeWindowsFor(state.config, channel, judgeSec, true),
  );
  // The tail resolves on this press as a charge tail does on its release.
  state.longHoldReleaseSeconds.set(channel, nowSec);
  finalizeActiveLongNote(state, channel, tail, nowSec, emit);
}
 
/**
 * A press on a lane whose long note is held, by the ruleset's {@link PressDuringLongNoteRule}: LR2 judges the LN's head
 * again when the press is within its BAD window and charges an empty POOR otherwise; beatoraja and That-Which-Must-Not-Be-Named ignore it.
 */
function applyPressDuringLongNote(
  state: JudgeCoreState,
  channel: string,
  judgeSec: number,
  nowSec: number,
  emit: JudgeCoreEffectSink,
): void {
  const { config } = state;
  if (config.ruleset.pressDuringLongNote === 'ignore') {
    return;
  }
  const hold = state.activeLongNotes.get(channel)!;
  Eif (hold.mode === 1 && !hold.headScored) {
    const dmUs = judgeDeltaUs(hold.note.seconds, judgeSec);
    const judge = classifyRulesetJudge(dmUs, judgeWindowsFor(config, channel, judgeSec));
    if (judge !== RULESET_JUDGE_NONE) {
      hold.headJudge = { kind: RULESET_JUDGE_KINDS[judge], signedDeltaMs: -dmUs / 1000 };
      return;
    }
  }
  chargeEmptyPoor(state, nowSec, emit);
}
 
/**
 * Empty POOR (空POOR): a phantom press near a note but outside every judgable window. It costs gauge and fires the POOR
 * cue without consuming the note, so it never reaches EX-SCORE. Repeatable per note (LR2's `MissCondition.ALWAYS`).
 * Whether it breaks the combo is the ruleset's call.
 */
function chargeEmptyPoor(state: JudgeCoreState, nowSec: number, emit: JudgeCoreEffectSink): void {
  const { ruleset } = state.config;
  if (isJudgingClosed(state)) {
    return;
  }
  state.summary.emptyPoor += 1;
  applyGaugeJudge(state, nowSec, 'EMPTY_POOR', emit, 'empty-poor');
  if (ruleset.comboBreaksOnEmptyPoor) {
    // The score tracker keeps the combo the max combo is measured on, so it breaks too.
    breakTrackedCombo(state.scoreTracker);
    setCombo(state, nowSec, 0, 'judge', emit, 'POOR');
  }
  emit({ kind: 'record-empty-poor' });
  emit({ kind: 'poor-bga', action: 'trigger', seconds: nowSec });
  if (!state.config.omitTraceEffects) {
    emit({
      kind: 'trace',
      name: 'judge',
      seconds: nowSec,
      fields: [
        ['result', 'EMPTY_POOR'],
        ['reason', 'empty-poor'],
      ],
    });
  }
  // The UI maps this back to the LR2 `'poor'` skin slot (NOWJUDGE 0/1 share one kind in our model).
  emit({ kind: 'judge-combo', judge: 'POOR', combo: state.combo, poor: 'empty' });
}
 
/** A release of `input.channels`; `recordedChannels` are the lanes the replay records (see {@link handleLanePress}). */
export function handleLaneRelease(
  state: JudgeCoreState,
  input: Extract<JudgeCoreInput, { kind: 'release' }>,
  emit: JudgeCoreEffectSink,
  recordedChannels: ReadonlySet<string> = input.channels,
): void {
  Eif (recordedChannels.size > 0) {
    emit({
      kind: 'record-input',
      action: 'up',
      seconds: input.recordSec,
      source: input.source,
      channels: recordedChannels,
      ...(input.inferred === true ? { inferred: true } : {}),
      ...(input.code !== undefined ? { code: input.code } : {}),
    });
  }
  // The release's own instant (a live driver drains it later than it happened; the replay records the instant).
  const releaseMs = input.nowMs - (input.nowSec - input.recordSec) * state.config.judgeMsPerChartSecond;
  let settleNow = false;
  for (const channel of input.channels) {
    recordLaneUp(laneHoldHistory(state, channel), input.tokens, releaseMs);
    setHCNGaining(state, channel, toJudgeUs(input.nowSec), emit);
    const hold = state.activeLongNotes.get(channel);
    if (
      hold !== undefined &&
      hold.mode === 1 &&
      hold.headSource !== undefined &&
      !releasesScratchHold(hold.headSource, input.source)
    ) {
      // beatoraja: a scratch LN is let go only by the key that hit its head; another key's release is ignored, and the
      // lane stays held.
      continue;
    }
    state.heldChannels.delete(channel);
    if (input.inferred !== true) {
      emit({ kind: 'ui', command: { kind: 'release-lane', channel } });
    }
    if (hold?.backSpinScratch === true) {
      // A back-spin scratch is not settled by a release, except, under beatoraja, a release of the head's own source
      // that would judge POOR ("BSS途中離し"): its tail is then judged at once.
      if (endsBackSpinScratchOnRelease(state, channel, hold, input)) {
        state.longHoldReleaseSeconds.set(channel, input.nowSec);
        state.longNoteSettleMs.set(channel, Number.NEGATIVE_INFINITY);
        settleNow = true;
      }
      continue;
    }
    if (hold !== undefined) {
      notePlugoutLaneReleased(state, channel);
      state.longHoldReleaseSeconds.set(channel, input.nowSec);
      const marginMs = resolveLongNoteReleaseMarginMs(state, channel, input.nowSec);
      // A release settles its long note at once, unless the ruleset lets a BAD-or-worse early release wait out a
      // margin in which the lane can be pressed again (beatoraja's `longnoteMargin`).
      state.longNoteSettleMs.set(channel, marginMs > 0 ? input.nowMs + marginMs : Number.NEGATIVE_INFINITY);
      settleNow ||= marginMs === 0;
    }
  }
  if (settleNow) {
    advanceJudgeState(state, input.nowSec, input.nowMs, emit);
  }
}
 
/**
 * beatoraja's "BSS途中離し" (`JudgeManager` L494-L511): under a ruleset that keys scratch holds by source, releasing the
 * source that hit a back-spin scratch's head ends it when the release would judge POOR against the long-scratch-end
 * windows (too early for any of them). Any other release, and every release of a hold that plays the lenient
 * single-source rule (`hasScratchCounterpart`), is ignored.
 */
function endsBackSpinScratchOnRelease(
  state: JudgeCoreState,
  channel: string,
  hold: ActiveLongNoteState,
  input: Extract<JudgeCoreInput, { kind: 'release' }>,
): boolean {
  const { config } = state;
  if (!config.ruleset.scratchHoldsBySource || !hasScratchCounterpart(hold.headSource)) return false;
  if (!isSameInputSource(hold.headSource, input.source)) return false;
  const judgeSec = toJudgeClock(config, input.nowSec);
  const tail = resolveManualTimedJudge(
    (judgeSec - hold.endSeconds) * 1000,
    judgeWindowsFor(config, channel, judgeSec, true),
  );
  return tail.kind === 'POOR';
}
 
/**
 * How long (ms on the judge's clock) a long note released at `nowSec` waits before it settles: the ruleset's release
 * margin when the release would score an early BAD or worse before the tail (`JudgeManager` L509, L537), 0 otherwise.
 */
function resolveLongNoteReleaseMarginMs(state: JudgeCoreState, channel: string, nowSec: number): number {
  const { config } = state;
  const hold = state.activeLongNotes.get(channel)!;
  const margins = config.ruleset.longNoteReleaseMarginUs;
  const marginUs = config.scratchChannels.has(channel) ? margins.scratch : margins.note;
  const judgeSec = toJudgeClock(config, nowSec);
  if (marginUs === 0 || judgeSec >= hold.endSeconds) {
    return 0;
  }
  const releaseDeltaMs = (judgeSec - hold.endSeconds) * 1000;
  const endWindows = judgeWindowsFor(config, channel, judgeSec, true);
  const judge =
    hold.mode === 1
      ? resolveLongNoteEarlyReleaseJudge(config.ruleset, hold.headJudge, releaseDeltaMs, endWindows)
      : resolveManualTimedJudge(releaseDeltaMs, endWindows);
  // beatoraja waits only when the judgment is BAD or worse AND its timing is early (`judge >= 3 && dmtime > 0`); an
  // LN's timing is the head's when the head was further off than the release, so a late head settles at once.
  const waits = (judge.kind === 'BAD' || judge.kind === 'POOR') && judge.signedDeltaMs < 0;
  return waits ? (marginUs / 1e6) * config.judgeMsPerChartSecond : 0;
}