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 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 | 314x 314x 5344x 5800x 5800x 5800x 5800x 5813x 5813x 5812x 74x 804x 435x 74x 214x 369x 369x 5738x 13x 69x 69x 13x 13x 13x 13x 69x 69x 114x 114x 456x 114x 314x 314x 314x 314x 314x 314x 314x 314x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 5811x 191611x 5811x 195546x 195546x 195546x 98221x 97325x 5811x 5811x 5811x 61x 5811x 5811x 5811x 140x 5811x 486x 5811x 900x 5811x 1198x 4613x 1692x 1692x 5811x 87x 589x 61x 26x 5811x 5811x 5811x 123177x 608x 122569x 122569x 122562x 5656x 5656x 116906x 123177x 123177x 123177x 123177x 123177x 23682x 23682x 116906x 5811x 99507x 26373x 122569x 122569x 26373x 26373x 26373x 26373x 122569x 23682x 201357x 201357x 557x 201357x 201357x 2821849x 21347x 23424x 23424x 8107x 508x 8107x 23424x 5913x 2800502x 2936138x 2936138x 474813x 25420x 25420x 1216x 2800502x 1308x 2800502x 2800502x 127x 2800502x 2901x 2821849x 221906x 221906x 221891x 5569x 5141x 5141x 5141x 201357x 2821849x 2800502x 65894x 7213x 65894x 65894x 201357x 10643x 57554x 201357x 53672x 53672x 6421x 6421x 6421x 508x 508x 508x 5913x 5913x 47251x 25420x 25420x 25420x 25420x 25420x 1193x 21831x 5141x 16690x 5141x 11549x 7213x 4336x 127x 127x 127x 124x 124x 124x 124x 4209x 2901x 2901x 2901x 2893x 2893x 2893x 2893x 1308x 1308x 1308x 1302x 1302x 1302x 1302x 1302x 1153x 149x 149x 201357x 2821849x 2638743x 2638743x 115841x 2522902x 2821849x 115828x 2821849x 5653x 201357x 1935x 1935x 1935x 1677x 1236x 1236x 1677x 1673x 24x 1677x 97594x 67587x 67587x 67587x 8868x 8868x 8864x 3770x 8868x 18698x 5368x 13x 5368x 5368x 5368x 5368x 195350x 3018x 7213x 4519x 4519x 7213x 98221x 98221x 98221x 98221x 98221x 98221x 98064x 98064x 98064x 98221x 98064x 242x 15x 227x 115x 112x 242x 98221x 399x 97822x 97594x 97822x 97822x 4362x 93460x 9228x 9228x 9228x 84232x 84232x 84232x 17482x 17482x 66750x 66750x 84232x 32946x 115x 115x 115x 115x 115x 12443x 12443x 12443x 12443x 12443x 12443x 1996x 1289x 12443x 112x 100x 12x 12x 12x 12x 2x 2x 2x 10x 10x 97325x 97325x 97325x 97325x 97171x 97171x 97171x 1x 1x 97170x 97170x 84697x 84697x 12473x 12473x 12473x 12473x 4067x 4067x 8406x 8406x 8406x 12473x 97171x 145x 145x 145x 12328x 195347x 195347x 660x 136x 135x 135x 195490x 195490x 195498x 195498x 195147x 195490x 56x 56x 56x 56x 152x 144x 576x 576x 144x 122x 122x 122x 78x 68x 68x 68x 68x 56x 56x 56x 52x 56x 56x 56x 56x 52x 52x 56x 112x 17482x 17482x 6952x 6952x 6952x 10530x 17482x 10530x 10530x 9810x 9810x 9810x 97822x 97822x 97822x 97822x 97822x 97822x 235514x 235514x 235514x 162509x 162509x 12271x 150238x 150238x 58667x 150238x 162509x 156245x 97822x 4362x 93460x 93460x 156245x 93460x 93460x 62785x 62785x 62785x 6730x 2498x 4232x 276x 6730x 56055x 48716x 7339x 257x 93460x 14678x 7339x 32946x 2128x 2128x 2128x 1920x 1920x 1917x 1510x 1510x 268x 263x 263x 263x 263x 263x 263x 150091x 159997x 159997x 159997x 136577x 94637x 94637x 44342x 50295x 7953x 94637x 94637x 61628x 61628x 31101x 61628x 5533x 5533x 33009x 28255x 28255x 94637x 17286x 8555x 8731x 8731x 94637x 94637x 94637x 99156x 99156x 99039x 99039x 117x 612x 612x 100833x 486x 486x 180x 180x 660x 660x 158974x 158974x 14678x 97966x 97966x 97966x 323983x 323983x 124507x 199476x 97966x | import { AnyKeyRoutes, anyKeyRouteKeys, selectAnyKeyLane, type AnyKeyCandidate } from '../core/any-key.ts';
import { resolvePlugoutScore } from '../ruleset/plugout.ts';
import { resolveAutoScratchSides } from '../core/auto-scratch.ts';
import { resolveScratchChannels } from './scratch-channels.ts';
import { resolve____RankLabel } from '../ruleset/score.ts';
import type { BeMusicReplay, ReplayInputEvent, ReplayRulesetResult } from './format.ts';
import type { ReplayGaugeHistory } from './gauge-histories.ts';
import {
createInputSourceLookup,
endsBackSpinScratch,
hasScratchCounterpart,
inputSourceKey,
isSameInputSource,
releasesScratchHold,
type InputSource,
} from '../core/input-source.ts';
import {
classifyRulesetJudge,
ignoresLateLongNoteHeadBad,
isBackSpinScratch,
noteLateReachUs,
addHCNPassing,
judgeWindowLateReachUs,
longNoteOwesTailMiss,
preferJudgeCandidate,
resolveEffectiveLongNoteMode,
HCNTickCounter,
resolveLNEarlyRelease,
RULESET_JUDGE_NONE,
RulesetGauge,
resolveGaugeEndOnFailure,
selectJudgeWindowSet,
type GaugeJudgeIndex,
type JudgeSelectionCandidate,
type LNJudgeIndex,
type RulesetJudgeIndex,
} from '../ruleset/index.ts';
import {
courseStageCarryCombo,
resolveRulesetConfig,
type JudgeWindowSetUs,
type RulesetId,
type ResolveRulesetOptions,
type RulesetConfig,
type RulesetWindowTables,
} from './rulesets.ts';
export type { RulesetId, BeatorajaJudgeAlgorithm, ResolveRulesetOptions } from './rulesets.ts';
export {
resolveRulesetConfig,
resolveLR2DefaultTotal,
resolveBeatorajaDefaultTotal,
resolve____GaugeUnit,
resolveLR2HardDamageMultiplier,
resolveBeatorajaHardRecoverMultiplier,
} from './rulesets.ts';
export interface SimulateReplayOptions extends ResolveRulesetOptions {
ruleset: RulesetId;
/** Side of a recorded two-player play; defaults to player 1. Player 2 uses its recorded gauge. */
player?: 1 | 2;
/** Overrides the log's `play.endOnFailure`: whether judging stops the moment a survival gauge empties. */
endOnFailure?: boolean;
/**
* Hears every judgment as the simulation scores it, in the order it scores them (`judgment-timeline.ts` builds a
* replay's judgment timeline from them). Observing changes nothing the simulation derives.
*/
onJudgment?: ReplayJudgmentObserver;
/**
* Hears the chart µs of the judgment that first empties the survival gauge mid-play, once (`rejudgeReplay` stops
* the other rulesets there). Observing changes nothing the simulation derives.
*/
onFailure?: (atUs: number) => void;
}
/** A judgment's kind in a {@link ReplayJudgmentEvent}: a scored window, a missed POOR, or an empty POOR. */
export type ReplayJudgmentKind = 'pgreat' | 'great' | 'good' | 'bad' | 'poor' | 'empty-poor';
/** One judgment a replay simulation scored, with the running totals just after it. */
export interface ReplayJudgmentEvent {
/** Chart µs the judgment happened at: the press or release that made it, or the deadline that settled it. */
readonly atUs: number;
readonly judgment: ReplayJudgmentKind;
/** The lane judged; absent for an empty POOR no lane is known for. */
readonly channel?: string;
/** The judged note's head time (µs); absent for an empty POOR, which takes no note. */
readonly noteTimeUs?: number;
/** Whether the note is done with this judgment (a tap, a long note's last judgment); false for a charge head. */
readonly settlesNote: boolean;
/** Note time minus input time (µs) for a timed judgment: positive is early (FAST). */
readonly deltaUs?: number;
readonly combo: number;
readonly maxCombo: number;
readonly exScore: number;
/** The gauge after the judgment, in percent of its maximum. */
readonly gauge: number;
}
/** Hears a replay simulation's judgments ({@link SimulateReplayOptions.onJudgment}). */
export type ReplayJudgmentObserver = (event: ReplayJudgmentEvent) => void;
const JUDGMENT_KINDS: readonly ReplayJudgmentKind[] = ['pgreat', 'great', 'good', 'bad', 'poor', 'empty-poor'];
/** The rulesets `simulateReplay` scores under, in display order. */
export const REPLAY_SIMULATOR_RULESETS: readonly ['lr2', 'beatoraja', '____', 'plugout'] = [
'lr2',
'beatoraja',
'____',
'plugout',
];
/**
* Re-derives one ruleset's judgments / EX-SCORE / combo / gauge from a replay's canonical data (resolved chart +
* raw input stream + play settings). Pure function — never mutates the replay.
*
* The LR2 simulation follows lr2oraja / OpenLR2 semantics, the beatoraja simulation the current beatoraja master,
* and the That-Which-Must-Not-Be-Named simulation the community-measured behavior of recent arcade versions (with documented stand-ins
* where no measurement exists — see `rulesets.ts`).
*/
export function simulateReplay(replay: BeMusicReplay, options: SimulateReplayOptions): ReplayRulesetResult {
return simulateReplayWithRuleset(replay, options.ruleset, options);
}
function simulateReplayWithRuleset(
replay: BeMusicReplay,
ruleset: RulesetId,
options: Omit<SimulateReplayOptions, 'ruleset'>,
): ReplayRulesetResult {
replay = replayForPlayer(replay, options.player);
const config = resolveRulesetConfig(replay, ruleset, options);
const endOnFailure =
options.endOnFailure ??
resolveGaugeEndOnFailure(
replay.play.gaugeAutoShift,
replay.play.endOnFailure === true,
replay.play.course === undefined ? config.gaugeSource : undefined,
);
return new ReplaySimulation(replay, config, endOnFailure, options.onJudgment, options.onFailure).run();
}
function replayForPlayer(replay: BeMusicReplay, player: 1 | 2 | undefined): BeMusicReplay {
const twoPlayer = replay.play.battleMode === 'TWO-PLAYER' || replay.play.battleMode === 'COUPLE';
if (player === 2 && !twoPlayer) throw new RangeError('Player 2 requires a recorded two-player play.');
if (twoPlayer) {
player ??= 1;
const own = (channel: string): boolean => channel.startsWith(String(player));
const notes = replay.chart.notes.filter((note) => own(note.channel));
return {
...replay,
chart: {
...replay.chart,
notes,
noteCount: notes.filter((note) => note.type === 'normal' || note.type === 'long').length,
},
play: { ...replay.play, ...(player === 2 ? { gauge: replay.play.gauge2P ?? replay.play.gauge } : {}) },
inputs: replay.inputs
.map((input) => ({ ...input, channels: input.channels.filter(own) }))
.filter((input) => input.channels.length > 0),
};
}
return replay;
}
/** Internal gauge-history path. With failure stopping disabled, the chosen gauge never changes a judgment. */
export function simulateReplayGaugeSamples(
replay: BeMusicReplay,
ruleset: RulesetId,
gauges: readonly string[],
untilUs: number,
): ReplayGaugeHistory[] {
const played = replayForPlayer(replay, undefined);
const configs = gauges.map((gauge) => resolveRulesetConfig(played, ruleset, { gauge, gaugeAutoShift: 'NONE' }));
const tracks = configs.map(({ gauge, gaugeFallback, gaugeBank }): GaugeTrack => ({
state: new RulesetGauge(gauge, gaugeFallback, gaugeBank),
samples: [],
}));
const first = configs[0];
Eif (first !== undefined) {
new ReplaySimulation(played, first, false, undefined, undefined, { tracks, untilUs }).run();
}
return gauges.map((gauge, index) => {
// The initial marker has always used the full chart, even when the samples are for player 1.
const spec =
played === replay
? configs[index]!.gauge
: resolveRulesetConfig(replay, ruleset, { gauge, gaugeAutoShift: 'NONE' }).gauge;
return {
gauge,
initial: spec.max > 0 ? (spec.initial / spec.max) * 100 : 0,
samples: tracks[index]!.samples,
};
});
}
interface GaugeHistory {
tracks: readonly GaugeTrack[];
untilUs: number;
}
interface GaugeTrack {
state: RulesetGauge;
samples: { atUs: number; gauge: number }[];
}
/** Runs {@link simulateReplay} for each requested ruleset (default: LR2, beatoraja, That-Which-Must-Not-Be-Named). */
export function simulateReplayRulesets(
replay: BeMusicReplay,
rulesets: readonly RulesetId[] = REPLAY_SIMULATOR_RULESETS,
options: ResolveRulesetOptions = {},
): Record<string, ReplayRulesetResult> {
const results: Record<string, ReplayRulesetResult> = {};
for (const ruleset of rulesets) {
results[ruleset] = simulateReplayWithRuleset(replay, ruleset, options);
}
return results;
}
/** At one instant: tails, then auto notes, then misses, then mines (see `advanceTime`). */
const TIMED_EVENT_ORDER = {
'ln-complete': 0,
'hold-deadline': 0,
'release-settle': 0,
'hcn-tick': 0.5,
auto: 1,
miss: 2,
mine: 3,
'mine-settle': 3,
} as const;
// Judgment indices follow beatoraja: 0 PG / 1 GR / 2 GD / 3 BD / 4 missed POOR / 5 empty POOR.
const JUDGE_PGREAT = 0;
const JUDGE_GREAT = 1;
const JUDGE_GOOD = 2;
const JUDGE_BAD = 3;
const JUDGE_MISS_POOR = 4;
const JUDGE_EMPTY_POOR = 5;
/** Selection-time marker: no window matched. Never reaches the gauge. */
const JUDGE_NONE = 6;
/**
* A classification result: a {@link GaugeJudgeIndex} or {@link JUDGE_NONE}. Selection works in this wider space
* because "no window matched" is a real outcome there; only scored judgments reach the gauge.
*/
type JudgeClassification = GaugeJudgeIndex | typeof JUDGE_NONE;
type SimLongStyle = 1 | 2 | 3;
interface SimHCNPassing {
note: SimNote;
endUs: number;
counter: HCNTickCounter;
tailGood: boolean;
/** The lane's next Hell Charge note, judged before this one has passed. */
next?: SimHCNPassing;
}
interface SimNote {
timeUs: number;
endTimeUs?: number;
scratch: boolean;
isLong: boolean;
/** Resolved long-note style for this ruleset (1 LN / 2 CN / 3 HCN). */
longStyle?: SimLongStyle;
judged: boolean;
holding: boolean;
/** AUTO: a charge note's head was cleared; its tail clears at the tail. */
autoHeadDone?: boolean;
/** Miss-sweep deadline (input time past which the head can no longer be judged). */
missDeadlineUs: number;
}
interface SimMine {
timeUs: number;
damage: number;
/** Settled: detonated, or past the crossing, where it no longer can. */
applied: boolean;
}
interface ActiveHold {
note: SimNote;
/** Deferred LN head judge (style 1). */
headJudge?: GaugeJudgeIndex;
headDmUs?: number;
/** That-Which-Must-Not-Be-Named charge heads that BAD/POOR'd skip the tail — such notes never become holds. */
/** Held-past-end deadline for charge tails. */
tailMissDeadlineUs: number;
/**
* A release waiting out the ruleset's long-note release margin: settled with `judge` at `atUs` unless the lane is
* pressed again first, which resumes the hold.
*/
pendingRelease?: { atUs: number; judge: GaugeJudgeIndex; dmUs: number };
/** A back-spin scratch: its tail is judged on a press from another source than {@link headSource} (`endsBackSpinScratch`). */
backSpinScratch?: true;
/** The source that hit the head of a scratch long note (beatoraja's `sckey`), as the engine's judge core keeps it. */
headSource?: InputSource;
}
interface SimLane {
channel: string;
scratch: boolean;
notes: SimNote[];
mines: SimMine[];
sweepCursor: number;
mineCursor: number;
held: boolean;
/**
* The input sources holding the lane down now, by key (`inputKey`). Mines ask whether ANY key on the lane is down, so
* a second key keeps the lane down while the first is released, as the engine's lane history does.
*/
downTokens: Set<string>;
/** The Hell Charge notes passing the lane, in tail order, while their gauge ticks run (see `HCNTickCounter`). */
passing?: SimHCNPassing;
hold?: ActiveHold;
/** Auto-played lane (AUTO mode or AUTO SCRATCH): every note resolves PGREAT on schedule. */
auto: boolean;
autoCursor: number;
}
interface SelectionCandidate {
lane: SimLane;
note: SimNote;
dmUs: number;
/** 0..3 scoreable, 4 pending-in-MS-window, 5 judged-in-MS-window. */
judge: GaugeJudgeIndex;
}
class ReplaySimulation {
private readonly lanes = new Map<string, SimLane>();
/** {@link lanes} in insertion order, for the per-advance sweeps (an array walk instead of a map iterator). */
private readonly laneList: SimLane[] = [];
private readonly counts = [0, 0, 0, 0, 0, 0];
private readonly gauge: RulesetGauge;
private readonly gaugeHistory: GaugeHistory | undefined;
private combo = 0;
private maxCombo = 0;
private minePoor = 0;
/** The course-wide combo and max combo, for a course stage (carried in from the previous stage). */
private readonly course: { combo: number; maxCombo: number } | undefined;
/** Judging stops the moment the survival gauge empties (`play.endOnFailure`). */
private readonly endOnFailure: boolean;
private fast = 0;
private slow = 0;
private exScore = 0;
private lastAdvanceUs = Number.NEGATIVE_INFINITY;
private readonly replay: BeMusicReplay;
private readonly config: RulesetConfig;
/** The scratch lanes of the play mode the log was played in (none in PMS and the keyboard modes). */
private readonly scratchChannels: ReadonlySet<string>;
private readonly observer: ReplayJudgmentObserver | undefined;
/** Where the next judgment happens, for the {@link observer}: its time, and the lane and note it judges. */
private judgeAtUs = 0;
/** Hears where the survival gauge first emptied mid-play ({@link SimulateReplayOptions.onFailure}). */
private readonly onFailure: ((atUs: number) => void) | undefined;
private failed = false;
private judgeLane: SimLane | undefined;
private judgeNote: SimNote | undefined;
/** ANY KEY (`play.anyKey`): the lanes each pressed key was routed to; absent when the play did not use it. */
private readonly anyKeyRoutes: AnyKeyRoutes | undefined;
/** The source each input names (`play.inputSources`). */
private readonly sourceOf: (id: number | undefined) => InputSource | undefined;
constructor(
replay: BeMusicReplay,
config: RulesetConfig,
endOnFailure: boolean,
observer?: ReplayJudgmentObserver,
onFailure?: (atUs: number) => void,
gaugeHistory?: GaugeHistory,
) {
this.onFailure = onFailure;
this.gaugeHistory = gaugeHistory;
this.replay = replay;
this.config = config;
this.endOnFailure = endOnFailure;
this.observer = observer;
this.course = replay.play.course === undefined ? undefined : courseStageCarryCombo(replay.play.course);
this.scratchChannels = resolveScratchChannels(replay.chart.laneMode);
this.gauge =
gaugeHistory?.tracks[0]?.state ?? new RulesetGauge(config.gauge, config.gaugeFallback, config.gaugeBank);
this.anyKeyRoutes = replay.play.anyKey === true && replay.play.mode !== 'auto' ? new AnyKeyRoutes() : undefined;
this.sourceOf = createInputSourceLookup(replay.play.inputSources);
this.buildLanes();
}
run(): ReplayRulesetResult {
const reversalUs = this.replay.chart.reversalTimeUs;
const activationUs = this.replay.chart.reversalActivationUs ?? reversalUs;
const inputs = [...this.replay.inputs].sort((left, right) => left.timeUs - right.timeUs || left.seq - right.seq);
for (const input of inputs) {
this.advanceTime(input.timeUs);
// LR2 negative-BPM reversal (#134): past the reversal R presses and releases are judged on the mirrored clock
// t' = 2R - now (OpenLR2 `LR2f.cpp:12624,12931`), exactly as the engine does. `advanceTime` stays clamped to R,
// so nothing past it is ever swept into a miss.
const judged =
activationUs !== undefined && input.timeUs > activationUs
? { ...input, timeUs: 2 * activationUs - input.timeUs }
: input;
if (input.action === 'down') {
// The engine's mine press leg is dead past the reversal too (`processLandminePassage`).
this.handleDown(judged, reversalUs === undefined || input.timeUs <= reversalUs);
} else {
this.handleUp(judged);
}
}
// ESC stops at the recorded instant. Older aborted replays did not apply the reversal exit rule.
const abortedAtUs = this.replay.play.aborted === true ? this.replay.play.abortedAtUs : undefined;
this.advanceTime(abortedAtUs ?? Number.POSITIVE_INFINITY);
if (
reversalUs !== undefined &&
(abortedAtUs === undefined || (this.replay.play.exitedReversal === true && abortedAtUs >= reversalUs)) &&
!this.closed() &&
this.hasOutstandingNotes()
) {
// LR2 zeroes HP when a play ends with notes unjudged (OpenLR2 `LR2f.cpp:12980-12982`): a reversed run that
// leaves notes past the reversal behind — open holds included — is always FAILED.
this.gauge.drainToZero();
}
const result: ReplayRulesetResult = {
ruleset: this.config.id,
judge: {
pgreat: this.counts[JUDGE_PGREAT]!,
great: this.counts[JUDGE_GREAT]!,
good: this.counts[JUDGE_GOOD]!,
bad: this.counts[JUDGE_BAD]!,
poor: this.counts[JUDGE_MISS_POOR]!,
emptyPoor: this.counts[JUDGE_EMPTY_POOR]!,
},
fast: this.fast,
slow: this.slow,
exScore: this.exScore,
noteCount: this.config.noteCount,
maxCombo: this.maxCombo,
djLevel: resolve____RankLabel(this.exScore, this.config.noteCount),
gauge: {
type: this.gauge.spec.id,
...(this.config.gaugeSource !== this.config.rulesetId ? { source: this.config.gaugeSource } : {}),
...(this.gauge.values ? { values: this.gauge.values } : {}),
final:
this.gauge.spec.max === 100
? this.gauge.value
: this.gauge.spec.max > 0
? (this.gauge.value / this.gauge.spec.max) * 100
: 0,
cleared: this.gauge.cleared(),
},
};
if (this.minePoor > 0) result.minePoor = this.minePoor;
if (this.config.comboBreaksOnEmptyPoor && this.counts[JUDGE_EMPTY_POOR]! > 0) {
result.fullCombo = this.config.noteCount > 0 && this.combo === this.config.noteCount;
}
if (this.gauge.failedMidPlay) {
result.gauge.failedMidPlay = true;
}
if (this.course !== undefined) {
result.course = { combo: this.course.combo, maxCombo: this.course.maxCombo };
}
if (this.config.plugoutScore === true) {
result.score = resolvePlugoutScore(
{ pgreat: this.counts[JUDGE_PGREAT]!, great: this.counts[JUDGE_GREAT]!, good: this.counts[JUDGE_GOOD]! },
this.config.noteCount,
);
} else if (this.config.moneyScore) {
const notes = Math.max(1, this.config.noteCount);
result.score = Math.floor(
((4 * this.counts[JUDGE_PGREAT]! + 2 * this.counts[JUDGE_GREAT]! + this.counts[JUDGE_GOOD]!) * 50000) / notes,
);
}
return result;
}
private hasOutstandingNotes(): boolean {
for (const lane of this.laneList) {
if (lane.notes.some((note) => !note.judged)) {
return true;
}
}
return false;
}
private buildLanes(): void {
const autoPlay = this.replay.play.mode === 'auto';
const autoScratch = resolveAutoScratchSides(this.replay.play);
for (const note of this.replay.chart.notes) {
if (note.type === 'invisible' || note.type === 'freezone') {
continue;
}
const lane = this.laneFor(note.channel, autoPlay, autoScratch);
// plugout's AUTO SCRATCH only sounds its notes: they are neither judged nor counted.
if (this.config.autoScratchUnjudged === true && lane.auto && !autoPlay && note.type !== 'mine') continue;
if (note.type === 'mine') {
lane.mines.push({ timeUs: note.timeUs, damage: note.damage ?? 0, applied: false });
continue;
}
const isLong =
note.type === 'long' && typeof note.endTimeUs === 'number' && note.endTimeUs > note.timeUs ? true : false;
const longStyle = isLong ? this.resolveLongStyle(note.lnMode ?? this.replay.chart.lnMode) : undefined;
const windows = this.config.windowsAt(note.timeUs);
const noteWindows = selectJudgeWindowSet(windows, { scratch: lane.scratch });
const simNote: SimNote = {
timeUs: note.timeUs,
scratch: lane.scratch,
isLong,
judged: false,
holding: false,
missDeadlineUs: note.timeUs + noteLateReachUs(this.config, noteWindows, longStyle),
};
if (isLong) {
simNote.endTimeUs = note.endTimeUs;
simNote.longStyle = longStyle;
}
lane.notes.push(simNote);
}
for (const lane of this.laneList) {
lane.notes.sort((left, right) => left.timeUs - right.timeUs);
lane.mines.sort((left, right) => left.timeUs - right.timeUs);
}
}
private laneFor(
channel: string,
autoPlay: boolean,
autoScratch: ReturnType<typeof resolveAutoScratchSides>,
): SimLane {
let lane = this.lanes.get(channel);
if (!lane) {
const scratch = this.scratchChannels.has(channel);
lane = {
channel,
scratch,
notes: [],
mines: [],
sweepCursor: 0,
mineCursor: 0,
held: false,
downTokens: new Set(),
auto:
autoPlay || (scratch && (channel.startsWith('2') ? autoScratch.autoScratch2P : autoScratch.autoScratch1P)),
autoCursor: 0,
};
this.lanes.set(channel, lane);
this.laneList.push(lane);
}
return lane;
}
private resolveLongStyle(chartMode: SimLongStyle): SimLongStyle {
return resolveEffectiveLongNoteMode(this.config.longNoteStyle, chartMode);
}
// ---- time advancement --------------------------------------------------------------------------------------
private advanceTime(untilUs: number): void {
const reversalUs = this.replay.chart.reversalTimeUs;
if (reversalUs !== undefined && untilUs > reversalUs) {
// The LR2 event pump froze at the reversal and the mirrored judge clock never passes it: misses, mines, hold
// deadlines, and auto judgements past it never happen.
untilUs = reversalUs;
}
interface TimedEvent {
timeUs: number;
kind: 'ln-complete' | 'hold-deadline' | 'release-settle' | 'hcn-tick' | 'auto' | 'miss' | 'mine' | 'mine-settle';
lane: SimLane;
note?: SimNote;
mine?: SimMine;
gain?: boolean;
}
const events: TimedEvent[] = [];
for (const lane of this.laneList) {
if (lane.auto) {
for (let index = lane.autoCursor; index < lane.notes.length; index += 1) {
const note = lane.notes[index]!;
if (note.timeUs >= untilUs) break;
// LN-style longs score once at the tail; a charge note scores its head at the head and its tail at the tail
// (beatoraja's autoplay); a tap at its time.
if (note.isLong && note.longStyle !== 1 && !note.autoHeadDone) {
events.push({ timeUs: note.timeUs, kind: 'auto', lane, note });
}
const autoAt = note.isLong ? note.endTimeUs! : note.timeUs;
if (autoAt >= untilUs) continue;
events.push({ timeUs: autoAt, kind: 'auto', lane, note });
}
} else {
for (let index = lane.sweepCursor; index < lane.notes.length; index += 1) {
const note = lane.notes[index]!;
// Deadlines are not monotonic along a lane (an LR2 LN head reaches only its GOOD leg), so the scan runs on
// note times and tests each deadline.
if (note.timeUs >= untilUs) break;
if (!note.judged && !note.holding && note.missDeadlineUs < untilUs) {
events.push({ timeUs: note.missDeadlineUs, kind: 'miss', lane, note });
// No input falls inside this span, so a missed Hell Charge head starts ticking at its deadline.
if (note.isLong && note.longStyle === 3 && note.missDeadlineUs >= this.lastAdvanceUs) {
this.startHCNPassing(lane, note, note.missDeadlineUs);
}
}
}
if (lane.hold && lane.hold.tailMissDeadlineUs < untilUs) {
events.push({ timeUs: lane.hold.tailMissDeadlineUs, kind: 'hold-deadline', lane, note: lane.hold.note });
}
const pending = lane.hold?.pendingRelease;
if (lane.hold && pending && pending.atUs < untilUs) {
events.push({ timeUs: pending.atUs, kind: 'release-settle', lane, note: lane.hold.note });
}
if (lane.hold && lane.hold.note.longStyle === 1 && lane.hold.note.endTimeUs! < untilUs) {
// An LN held to its tail confirms its deferred head judgment there, in time order with everything else.
events.push({ timeUs: lane.hold.note.endTimeUs!, kind: 'ln-complete', lane, note: lane.hold.note });
}
}
for (let index = lane.mineCursor; index < lane.mines.length; index += 1) {
const mine = lane.mines[index]!;
// Mines at or behind the reversal are frozen with the pump: not even LR2's early GREAT reach detonates them.
if (reversalUs !== undefined && mine.timeUs >= reversalUs) break;
if (mine.timeUs >= untilUs) break;
if (mine.applied) continue;
// Each point is visited once: in the advance whose span [lastAdvanceUs, untilUs) holds it.
Eif (mine.timeUs >= this.lastAdvanceUs) {
events.push({ timeUs: mine.timeUs, kind: 'mine', lane, mine });
events.push({ timeUs: mine.timeUs, kind: 'mine-settle', lane, mine });
}
}
}
for (const lane of this.laneList) {
if (lane.auto) continue;
for (let passing = lane.passing; passing !== undefined; passing = passing.next) {
passing.counter.advance(Math.min(untilUs, passing.endUs), (gain, atUs) =>
events.push({ timeUs: atUs, kind: 'hcn-tick', lane, gain }),
);
lane.passing = passing.endUs >= untilUs ? passing : passing.next;
if (passing.endUs >= untilUs) break;
}
}
// One instant settles tails first, then auto notes, then misses, then mines, each in channel order — the order the
// engine's judge core settles them in.
if (events.length > 1)
events.sort(
(left, right) =>
left.timeUs - right.timeUs ||
TIMED_EVENT_ORDER[left.kind] - TIMED_EVENT_ORDER[right.kind] ||
(left.lane.channel < right.lane.channel ? -1 : left.lane.channel > right.lane.channel ? 1 : 0),
);
for (const event of events) {
this.judgingAt(event.timeUs, event.lane, event.note);
if (event.kind === 'auto') {
const note = event.note!;
Iif (note.judged) continue;
if (note.isLong && note.longStyle !== 1 && !note.autoHeadDone) {
note.autoHeadDone = true;
this.applyJudge(JUDGE_PGREAT, undefined);
continue;
}
note.judged = true;
this.applyJudge(JUDGE_PGREAT, undefined);
} else if (event.kind === 'miss') {
const note = event.note!;
Iif (note.judged || note.holding) continue;
note.judged = true;
this.applyJudge(JUDGE_MISS_POOR, undefined);
if (longNoteOwesTailMiss(this.config, note.isLong ? note.longStyle : undefined)) {
// beatoraja: a missed CN/HCN head also POORs the tail. That-Which-Must-Not-Be-Named (headBadSkipsTail) skips it.
this.applyJudge(JUDGE_MISS_POOR, undefined);
}
} else if (event.kind === 'mine') {
// Held as it crosses the line (every ruleset).
if (event.lane.downTokens.size > 0) this.detonateMine(event.mine!);
} else if (event.kind === 'mine-settle') {
event.mine!.applied = true;
} else if (event.kind === 'hcn-tick') {
this.applyHCNTick(event.gain!);
} else if (event.kind === 'release-settle') {
const lane = event.lane;
const hold = lane.hold;
if (!hold || hold.note !== event.note || !hold.pendingRelease) continue;
lane.hold = undefined;
hold.note.holding = false;
hold.note.judged = true;
this.applyJudge(hold.pendingRelease.judge, hold.pendingRelease.dmUs);
} else if (event.kind === 'ln-complete') {
const lane = event.lane;
const hold = lane.hold;
if (!hold || hold.note !== event.note) continue;
lane.hold = undefined;
hold.note.holding = false;
hold.note.judged = true;
this.applyJudge(hold.headJudge ?? JUDGE_BAD, hold.headDmUs);
} else {
// Charge tail held past its late window — the tail resolves as a missed POOR (beatoraja / That-Which-Must-Not-Be-Named);
// under plugout a key's is a BAD, and a scratch's a PGREAT already at its end (`heldChargeTail`).
const lane = event.lane;
const hold = lane.hold;
if (!hold || hold.note !== event.note) continue;
lane.hold = undefined;
hold.note.holding = false;
hold.note.judged = true;
const heldTail = this.config.heldChargeTail;
if (heldTail === undefined) {
this.applyJudge(JUDGE_MISS_POOR, undefined);
} else {
this.judgingAt(event.timeUs, lane, hold.note);
this.applyJudge(hold.note.scratch ? JUDGE_PGREAT : JUDGE_BAD, hold.note.endTimeUs! - event.timeUs);
}
}
}
// Advance sweep cursors past settled notes.
for (const lane of this.laneList) {
while (lane.sweepCursor < lane.notes.length) {
const note = lane.notes[lane.sweepCursor]!;
if (note.judged || (note.missDeadlineUs < untilUs && !note.holding)) {
lane.sweepCursor += 1;
} else {
break;
}
}
while (lane.autoCursor < lane.notes.length && lane.notes[lane.autoCursor]!.judged) {
lane.autoCursor += 1;
}
while (lane.mineCursor < lane.mines.length && lane.mines[lane.mineCursor]!.applied) {
lane.mineCursor += 1;
}
}
this.lastAdvanceUs = untilUs;
}
private detonateMine(mine: SimMine): void {
Iif (mine.applied) return;
mine.applied = true;
if (this.closed()) return;
// Applied even at 0 damage, as the engine does: the raw path still settles a gauge sitting on its floor.
if (this.config.mineTrigger === 'press-ahead-or-hold') {
this.counts[JUDGE_MISS_POOR]! += 1;
this.minePoor += 1;
}
if (this.gaugeHistory === undefined) {
this.gauge.applyRawDelta(-mine.damage);
} else {
for (const track of this.gaugeHistory.tracks) track.state.applyRawDelta(-mine.damage);
}
this.noteFailure();
}
/** LR2beta3's strict ahead-only GREAT reach, which That-Which-Must-Not-Be-Named imports on its own GREAT window. */
private detonateMinesOnPress(lanes: readonly SimLane[], timeUs: number): void {
if (this.config.mineTrigger === 'hold') return;
const reversalUs = this.replay.chart.reversalTimeUs;
for (const lane of lanes) {
for (let index = lane.mineCursor; index < lane.mines.length; index += 1) {
const mine = lane.mines[index]!;
if (reversalUs !== undefined && mine.timeUs >= reversalUs) break;
// Mines further ahead than any GREAT reach cannot be hit.
if (mine.timeUs - timeUs > 1_000_000) break;
// Read the window at the press, including a dynamic LR2 rank.
const hit = mine.timeUs >= timeUs && mine.timeUs - timeUs < this.config.windowsAt(timeUs).note.judges[1][1];
if (!mine.applied && hit) this.detonateMine(mine);
}
}
}
/**
* Starts the gauge ticks of a Hell Charge note whose head was judged at `judgedUs` (pressed, or missed at its
* deadline), as the engine does: from the later of the head and that instant until the tail passes.
*/
private startHCNPassing(lane: SimLane, note: SimNote, judgedUs: number): void {
if (lane.auto || !note.isLong || note.longStyle !== 3) return;
for (let passing = lane.passing; passing !== undefined; passing = passing.next) {
Iif (passing.note === note) return;
}
const startUs = Math.max(note.timeUs, judgedUs);
const counter = new HCNTickCounter(startUs);
counter.setGaining(lane.downTokens.size > 0, startUs, () => undefined);
lane.passing = addHCNPassing(lane.passing, { note, endUs: note.endTimeUs!, counter, tailGood: false }, startUs);
}
/** Re-reads whether a lane's passing Hell Charge note gains: a key on it is down, or its tail went well. */
private setHCNGaining(lane: SimLane, atUs: number): void {
for (let passing = lane.passing; passing !== undefined; passing = passing.next) {
passing.counter.setGaining(passing.tailGood || lane.downTokens.size > 0, Math.min(atUs, passing.endUs), (gain) =>
this.applyHCNTick(gain),
);
}
}
private applyHCNTick(gain: boolean): void {
if (this.closed()) return;
const tick = this.config.hcnTick;
this.applyGaugeJudge(
(gain ? tick.heldJudge : tick.releasedJudge) as GaugeJudgeIndex,
gain ? tick.heldRate : tick.releasedRate,
);
this.noteFailure();
}
// ---- input handling ----------------------------------------------------------------------------------------
private handleDown(input: ReplayInputEvent, minePressLegLive: boolean): void {
const timeUs = input.timeUs;
this.judgeAtUs = timeUs;
const windows = this.config.windowsAt(timeUs);
const source = this.sourceOf(input.source);
const pressed = this.anyKeyRoutes ? this.routeAnyKeyPress(input, windows) : this.resolveInputLanes(input);
for (const lane of pressed) {
lane.held = true;
lane.downTokens.add(this.inputKey(input));
this.setHCNGaining(lane, timeUs);
}
// Pressing a lane whose release is waiting out the margin resumes its hold: that press judges nothing else. A lane
// whose long note is held (pressed by another key bound to it) judges no other note either: its current note is
// the long note, and the ruleset says what the press does instead.
const lanes = pressed.filter((lane) => {
if (lane.hold === undefined) return true;
if (lane.hold.pendingRelease !== undefined) {
lane.hold.pendingRelease = undefined;
} else if (lane.hold.backSpinScratch === true && endsBackSpinScratch(lane.hold.headSource, source)) {
this.judgeBackSpinScratchTail(lane, lane.hold, timeUs);
} else {
this.applyPressDuringLongNote(lane, lane.hold, timeUs);
}
return false;
});
if (lanes.length === 0) {
return;
}
if (minePressLegLive) {
// Every pressed lane's key goes down, whatever the press then judges.
this.detonateMinesOnPress(pressed, timeUs);
}
const selected = this.selectCandidate(lanes, timeUs, windows);
if (!selected) {
return;
}
if (selected.judge >= JUDGE_MISS_POOR) {
// Empty POOR — the note is never consumed.
this.judgingAt(timeUs, selected.lane, undefined);
this.applyJudge(JUDGE_EMPTY_POOR, undefined);
return;
}
const { note, lane, dmUs } = selected;
this.judgingAt(timeUs, lane, note);
if (note.isLong) {
this.startLongNote(lane, note, selected.judge, dmUs, source);
this.startHCNPassing(lane, note, timeUs);
} else {
note.judged = true;
this.applyJudge(selected.judge, dmUs);
}
if (this.config.multiBad) {
// Only scoreable judgments (PGREAT..BAD) consume a note, so the judge is a real window index here.
this.applyLR2RejudgeChain(lane, timeUs, windows, note, selected.judge as RulesetJudgeIndex);
}
}
/** A back-spin scratch's tail, judged on the reverse spin's timing against the long-scratch-end windows. */
private judgeBackSpinScratchTail(lane: SimLane, hold: ActiveHold, timeUs: number): void {
const note = hold.note;
const endWindows = selectJudgeWindowSet(this.config.windowsAt(timeUs), {
scratch: note.scratch,
longNoteEnd: true,
});
const dmUs = note.endTimeUs! - timeUs;
const endJudge = classifyJudge(dmUs, endWindows);
this.settleChargeTail(lane, note, timeUs, endJudge === JUDGE_NONE ? JUDGE_MISS_POOR : endJudge, dmUs);
}
/** Settles a charge tail at `timeUs` with `judge`: a released CN / HCN, or a back-spin scratch spun back. */
private settleChargeTail(lane: SimLane, note: SimNote, timeUs: number, judge: GaugeJudgeIndex, dmUs: number): void {
lane.hold = undefined;
note.holding = false;
note.judged = true;
this.judgingAt(timeUs, lane, note);
this.applyJudge(judge, dmUs);
for (let passing = lane.passing; passing !== undefined; passing = passing.next) {
if (passing.note === note && judge <= JUDGE_GOOD) {
// A Hell Charge tail released at GOOD or better keeps its lane gaining until the tail passes.
passing.tailGood = true;
}
}
this.setHCNGaining(lane, timeUs);
}
/** The ruleset's {@link RulesetConfig.pressDuringLongNote}: LR2 re-judges the LN head or charges an empty POOR. */
private applyPressDuringLongNote(lane: SimLane, hold: ActiveHold, timeUs: number): void {
if (this.config.pressDuringLongNote === 'ignore') {
return;
}
Eif (hold.note.longStyle === 1) {
const dmUs = hold.note.timeUs - timeUs;
const judge = classifyJudge(dmUs, selectJudgeWindowSet(this.config.windowsAt(timeUs), { scratch: lane.scratch }));
if (judge !== JUDGE_NONE) {
hold.headJudge = judge;
hold.headDmUs = dmUs;
return;
}
}
this.judgingAt(timeUs, lane, undefined);
this.applyJudge(JUDGE_EMPTY_POOR, undefined);
}
private handleUp(input: ReplayInputEvent): void {
const timeUs = input.timeUs;
this.judgeAtUs = timeUs;
const source = this.sourceOf(input.source);
for (const lane of this.anyKeyRoutes ? this.releaseAnyKey(input) : this.resolveInputLanes(input)) {
lane.downTokens.delete(this.inputKey(input));
const hold = lane.hold;
if (
hold !== undefined &&
hold.note.longStyle === 1 &&
hold.headSource !== undefined &&
!releasesScratchHold(hold.headSource, source)
) {
// beatoraja: a scratch LN is let go only by the key that hit its head; another key's release is ignored.
this.setHCNGaining(lane, timeUs);
continue;
}
lane.held = false;
if (!hold || (hold.backSpinScratch === true && !this.endsBackSpinScratchOnRelease(hold, source, timeUs))) {
// A back-spin scratch is not settled by a release (but for beatoraja's early POOR release of its head's source).
this.setHCNGaining(lane, timeUs);
continue;
}
const note = hold.note;
const endWindows = selectJudgeWindowSet(this.config.windowsAt(timeUs), {
scratch: note.scratch,
longNoteEnd: true,
});
const dmUs = note.endTimeUs! - timeUs;
let released: { judge: GaugeJudgeIndex; dmUs: number };
if (note.longStyle === 1) {
// LN: the ruleset decides how a release before the tail combines with the deferred head judgment.
const headJudge = hold.headJudge ?? JUDGE_BAD;
released = resolveLNEarlyRelease(
this.config,
{
judge: (headJudge > JUDGE_MISS_POOR ? JUDGE_MISS_POOR : headJudge) as LNJudgeIndex,
dmUs: hold.headDmUs ?? 0,
},
dmUs,
endWindows,
);
} else {
// CN / HCN tail: judged by the release timing; early releases beyond the windows are POOR (BAD under plugout,
// `heldChargeTail.earlyRelease`).
const endJudge = classifyJudge(dmUs, endWindows);
const outside = this.config.heldChargeTail !== undefined && dmUs > 0 ? JUDGE_BAD : JUDGE_MISS_POOR;
released = { judge: endJudge === JUDGE_NONE ? outside : endJudge, dmUs };
}
const marginUs = note.scratch
? this.config.longNoteReleaseMarginUs.scratch
: this.config.longNoteReleaseMarginUs.note;
if (marginUs > 0 && released.judge >= JUDGE_BAD && released.dmUs > 0) {
// beatoraja: a release that would score BAD or worse before the tail waits out the margin (`releasetime`).
hold.pendingRelease = { atUs: timeUs + marginUs, ...released };
this.setHCNGaining(lane, timeUs);
continue;
}
this.settleChargeTail(lane, note, timeUs, released.judge, released.dmUs);
}
}
/**
* The key an input holds a lane by: its source's key, as the engine's judge core keys lane holds and ANY KEY routes,
* or its id when the table does not hold it.
*/
private inputKey(input: ReplayInputEvent): string {
const source = this.sourceOf(input.source);
return source === undefined ? `#${input.source}` : inputSourceKey(source);
}
/**
* beatoraja's "BSS途中離し": 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. As the engine's judge core (`endsBackSpinScratchOnRelease`).
*/
private endsBackSpinScratchOnRelease(hold: ActiveHold, source: InputSource | undefined, timeUs: number): boolean {
if (!this.config.scratchHoldsBySource || !hasScratchCounterpart(hold.headSource)) return false;
if (!isSameInputSource(hold.headSource, source)) return false;
const endWindows = selectJudgeWindowSet(this.config.windowsAt(timeUs), {
scratch: hold.note.scratch,
longNoteEnd: true,
});
return classifyJudge(hold.note.endTimeUs! - timeUs, endWindows) === JUDGE_NONE;
}
private resolveInputLanes(input: ReplayInputEvent): SimLane[] {
const lanes: SimLane[] = [];
for (const channel of input.channels) {
const lane = this.lanes.get(channel);
if (lane && !lane.auto) {
lanes.push(lane);
}
}
return lanes;
}
/**
* The lanes an ANY KEY press goes to, as the engine's judge core routes it (`resolveAnyKeyPressChannels`): the lane of
* the nearest unjudged note it reaches on any lane but an auto-played one or one whose long note is held, or the
* keys' own lanes when it reaches none. Its keys hold the lane until they come up.
*/
private routeAnyKeyPress(input: ReplayInputEvent, windows: RulesetWindowTables): SimLane[] {
const own = this.resolveInputLanes(input);
const timeUs = input.timeUs;
const candidates: AnyKeyCandidate[] = [];
for (const lane of this.laneList) {
if (lane.auto || lane.hold !== undefined) continue;
const set = selectJudgeWindowSet(windows, { scratch: lane.scratch });
// The widest legs of the four windows: nothing guarantees the tables are monotonic.
const scanLate = Math.min(...set.judges.map((window) => window[0]));
const scanEarly = Math.max(...set.judges.map((window) => window[1]));
for (let index = firstNoteInReach(lane.notes, timeUs, scanLate); index < lane.notes.length; index += 1) {
const note = lane.notes[index]!;
const dmUs = note.timeUs - timeUs;
if (dmUs > scanEarly) break;
if (note.judged || note.holding) continue;
const judge = classifyJudge(dmUs, set);
Iif (judge === JUDGE_NONE) continue;
Iif (ignoresLateLongNoteHeadBad(this.config, judge, dmUs < 0, note.isLong ? (note.longStyle ?? 1) : undefined))
continue;
candidates.push({ channel: lane.channel, noteTimeUs: note.timeUs, dmUs });
}
}
const routed = selectAnyKeyLane(candidates);
const lanes = routed === undefined ? own : [this.lanes.get(routed)!];
this.anyKeyRoutes!.route(
anyKeyRouteKeys([this.inputKey(input)], this.ownChannels(input)),
lanes.map((lane) => lane.channel),
);
return lanes;
}
/** The lanes an ANY KEY release lets go: those its keys were routed to, or its own lanes for keys never routed. */
private releaseAnyKey(input: ReplayInputEvent): SimLane[] {
const own = this.ownChannels(input);
const lanes: SimLane[] = [];
for (const channel of this.anyKeyRoutes!.release(anyKeyRouteKeys([this.inputKey(input)], own), own)) {
const lane = this.lanes.get(channel);
Eif (lane && !lane.auto) lanes.push(lane);
}
return lanes;
}
/** The input's own lanes without the auto-played ones, as the engine hands them to its judge core. */
private ownChannels(input: ReplayInputEvent): string[] {
return input.channels.filter((channel) => this.lanes.get(channel)?.auto !== true);
}
private startLongNote(
lane: SimLane,
note: SimNote,
judge: GaugeJudgeIndex,
dmUs: number,
source: InputSource | undefined,
): void {
const style = note.longStyle ?? 1;
if (style === 1) {
note.holding = true;
lane.hold = {
note,
headJudge: judge,
headDmUs: dmUs,
tailMissDeadlineUs: Number.POSITIVE_INFINITY,
// beatoraja: a scratch LN remembers the key that hit its head (the engine's `headSource`).
...(this.config.scratchHoldsBySource && source !== undefined && lane.scratch ? { headSource: source } : {}),
};
return;
}
// Charge styles score the head immediately. That-Which-Must-Not-Be-Named: a BAD head cancels the tail judgment
// entirely, so the head settles the note.
const skipsTail = this.config.headBadSkipsTail && judge >= JUDGE_BAD;
if (skipsTail) note.judged = true;
this.applyJudge(judge, dmUs);
if (skipsTail) return;
note.holding = true;
// The tail's late window as it stands at the tail, like a note's miss deadline at the note.
const endWindows = selectJudgeWindowSet(this.config.windowsAt(note.endTimeUs!), {
scratch: note.scratch,
longNoteEnd: true,
});
lane.hold = {
note,
// plugout settles a scratch held to its end at the end itself (`heldChargeTail`).
tailMissDeadlineUs:
this.config.heldChargeTail !== undefined && note.scratch
? note.endTimeUs!
: note.endTimeUs! + judgeWindowLateReachUs(endWindows),
// plugout has no back-spin scratch: a release ends a scratch charge like a key's.
...(this.config.heldChargeTail === undefined && isBackSpinScratch(style, lane.scratch)
? { backSpinScratch: true as const, ...(source !== undefined ? { headSource: source } : {}) }
: {}),
};
}
private selectCandidate(
lanes: readonly SimLane[],
timeUs: number,
windows: RulesetWindowTables,
): SelectionCandidate | undefined {
const candidates: SelectionCandidate[] = [];
for (const lane of lanes) {
const set = selectJudgeWindowSet(windows, { scratch: lane.scratch });
const scanLate = Math.min(set.judges[JUDGE_BAD]![0], set.ms?.[0] ?? 0);
const scanEarly = Math.max(set.judges[JUDGE_BAD]![1], set.ms?.[1] ?? 0);
for (let index = firstNoteInReach(lane.notes, timeUs, scanLate); index < lane.notes.length; index += 1) {
const note = lane.notes[index]!;
const dmUs = note.timeUs - timeUs;
if (dmUs > scanEarly) break;
Iif (note.holding) continue;
let judge: JudgeClassification;
if (note.judged) {
judge = set.ms && dmUs >= set.ms[0] && dmUs <= set.ms[1] ? JUDGE_EMPTY_POOR : JUDGE_NONE;
} else {
judge = classifyJudge(dmUs, set);
if (judge === JUDGE_NONE && set.ms && dmUs >= set.ms[0] && dmUs <= set.ms[1]) {
judge = JUDGE_MISS_POOR;
}
Iif (
ignoresLateLongNoteHeadBad(this.config, judge, dmUs < 0, note.isLong ? (note.longStyle ?? 1) : undefined)
) {
// LR2: long-note heads have no late BAD — the press falls through.
judge = JUDGE_NONE;
}
}
if (judge === JUDGE_NONE) continue;
candidates.push({ lane, note, dmUs, judge });
}
}
if (candidates.length === 0) {
return undefined;
}
candidates.sort((left, right) => left.note.timeUs - right.note.timeUs);
let best: SelectionCandidate | undefined;
for (const candidate of candidates) {
if (!best) {
best = candidate;
continue;
}
const bestScoreable = best.judge < JUDGE_MISS_POOR;
const candScoreable = candidate.judge < JUDGE_MISS_POOR;
if (!bestScoreable) {
if (candScoreable) {
best = candidate;
} else if (Math.abs(candidate.dmUs) < Math.abs(best.dmUs)) {
best = candidate;
}
continue;
}
if (!candScoreable) {
continue;
}
if (this.shouldSwitchCandidate(best, candidate, timeUs, windows)) {
best = candidate;
}
}
return best;
}
private shouldSwitchCandidate(
best: SelectionCandidate,
candidate: SelectionCandidate,
timeUs: number,
windows: RulesetWindowTables,
): boolean {
const toSelection = (entry: SelectionCandidate): JudgeSelectionCandidate => ({
noteTimeUs: entry.note.timeUs,
dmUs: entry.dmUs,
// Only scoreable candidates reach this comparison, so the classification is a real judge index.
judge: entry.judge as RulesetJudgeIndex,
windows: windowSetFor(entry, windows),
});
return preferJudgeCandidate(this.config.selection, toSelection(best), toSelection(candidate), timeUs);
}
/** LR2's forward tap chain: every BAD reuses this press for the next tap, until a non-BAD stops it. */
private applyLR2RejudgeChain(
lane: SimLane,
timeUs: number,
windows: RulesetWindowTables,
consumed: SimNote,
consumedJudge: RulesetJudgeIndex,
): void {
if (consumedJudge !== JUDGE_BAD || consumed.isLong || this.closed()) return;
const set = selectJudgeWindowSet(windows, { scratch: lane.scratch });
const bad = set.judges[JUDGE_BAD]!;
for (let index = lane.notes.indexOf(consumed) + 1; index < lane.notes.length; index += 1) {
const note = lane.notes[index]!;
if (note.judged || note.holding) continue;
if (note.isLong) break;
const deltaUs = note.timeUs - timeUs;
if (deltaUs < bad[0] || deltaUs > bad[1]) break;
if (this.config.multiBadAheadUs !== undefined && deltaUs >= this.config.multiBadAheadUs) break;
const judge = classifyRulesetJudge(deltaUs, set);
Iif (judge === RULESET_JUDGE_NONE || judge > JUDGE_BAD) break;
note.judged = true;
this.judgingAt(timeUs, lane, note);
this.applyJudge(judge, deltaUs);
if (judge !== JUDGE_BAD || this.closed()) break;
}
}
/**
* Judging has stopped: the survival gauge emptied in a play that ends on failure. Nothing after the judgment that
* emptied it counts, as in the engine (`isJudgingClosed`).
*/
private closed(): boolean {
return this.endOnFailure && this.gauge.failedMidPlay;
}
/** Where the next judgment happens, for the {@link observer}. */
private judgingAt(atUs: number, lane: SimLane | undefined, note: SimNote | undefined): void {
this.judgeAtUs = atUs;
this.judgeLane = lane;
this.judgeNote = note;
}
private applyJudge(judgeIndex: GaugeJudgeIndex, dmUs: number | undefined): void {
if (this.closed()) return;
this.counts[judgeIndex]! += 1;
if (judgeIndex === JUDGE_PGREAT) {
this.exScore += 2;
} else if (judgeIndex === JUDGE_GREAT) {
this.exScore += 1;
}
const course = this.course;
if (judgeIndex <= JUDGE_GOOD) {
this.combo += 1;
if (this.combo > this.maxCombo) {
this.maxCombo = this.combo;
}
if (course !== undefined) {
course.combo += 1;
course.maxCombo = Math.max(course.maxCombo, course.combo);
}
} else if (
judgeIndex === JUDGE_BAD ||
judgeIndex === JUDGE_MISS_POOR ||
(judgeIndex === JUDGE_EMPTY_POOR && this.config.comboBreaksOnEmptyPoor)
) {
this.combo = 0;
if (course !== undefined) course.combo = 0;
}
if (dmUs !== undefined && (judgeIndex === JUDGE_GREAT || judgeIndex === JUDGE_GOOD)) {
// A delta of exactly 0 is neither, as in the engine (it is always inside PGREAT, so this is only consistency).
if (dmUs > 0) {
this.fast += 1;
} else Eif (dmUs < 0) {
this.slow += 1;
}
}
this.applyGaugeJudge(judgeIndex, 1, this.judgeAtUs);
this.noteFailure();
if (this.observer !== undefined) this.notifyJudgment(judgeIndex, dmUs);
}
private applyGaugeJudge(judge: GaugeJudgeIndex, rate: number, atUs?: number): void {
const history = this.gaugeHistory;
if (history === undefined) {
this.gauge.applyJudge(judge, rate);
return;
}
for (const { state, samples } of history.tracks) {
state.applyJudge(judge, rate);
// Mine damage and HCN ticks change the gauge, but only scored judgments add a sample.
if (atUs !== undefined && atUs <= history.untilUs) samples.push({ atUs, gauge: gaugePercent(state) });
}
}
/** Tells {@link onFailure} where the survival gauge first emptied mid-play. */
private noteFailure(): void {
if (this.failed || !this.gauge.failedMidPlay) return;
this.failed = true;
this.onFailure?.(this.judgeAtUs);
}
private notifyJudgment(judgeIndex: GaugeJudgeIndex, dmUs: number | undefined): void {
const note = judgeIndex === JUDGE_EMPTY_POOR ? undefined : this.judgeNote;
this.observer!({
atUs: this.judgeAtUs,
judgment: JUDGMENT_KINDS[judgeIndex]!,
...(this.judgeLane !== undefined ? { channel: this.judgeLane.channel } : {}),
...(note !== undefined ? { noteTimeUs: note.timeUs } : {}),
settlesNote: note?.judged === true,
...(dmUs !== undefined ? { deltaUs: dmUs } : {}),
combo: this.combo,
maxCombo: this.maxCombo,
exScore: this.exScore,
gauge: gaugePercent(this.gauge),
});
}
}
function gaugePercent(gauge: RulesetGauge): number {
const max = gauge.spec.max;
return max === 100 ? gauge.value : max > 0 ? (gauge.value / max) * 100 : 0;
}
function classifyJudge(dmUs: number, set: JudgeWindowSetUs): JudgeClassification {
const judge = classifyRulesetJudge(dmUs, set);
return judge === RULESET_JUDGE_NONE ? JUDGE_NONE : judge;
}
function windowSetFor(candidate: SelectionCandidate, windows: RulesetWindowTables): JudgeWindowSetUs {
return selectJudgeWindowSet(windows, { scratch: candidate.lane.scratch });
}
/** Play-mode layout per leading key count, for lane-mode strings that are not a layout label (`'7keys'`, `'14K'`). */
/**
* Index of a lane's first note a press at `timeUs` can reach: the first whose `timeUs - pressUs` is not below `lateUs`
* (the window's late edge, negative). A lane's notes are sorted by time, so a binary search finds it where a walk from
* the lane's start would cost every note already passed, on every press.
*/
function firstNoteInReach(notes: readonly SimNote[], pressUs: number, lateUs: number): number {
let low = 0;
let high = notes.length;
while (low < high) {
const middle = (low + high) >>> 1;
if (notes[middle]!.timeUs - pressUs < lateUs) {
low = middle + 1;
} else {
high = middle;
}
}
return low;
}
|