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 | 924x 924x 3182x 3182x 3182x 109170x 109170x 109170x 109170x 109170x 109170x 109170x 109170x 109170x 3182x 3182x 104615x 104615x 708x 708x 3561x 3561x 74x 74x 212x 212x 212x 212x 1908x 212x 339x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 2x 2x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 7x 4x 7x 5x 3502x 3503x 3503x 3503x 3503x 7x 5x 27x 7x 6x 3502x 3502x 3502x 3502x 3502x 3x 3502x 11x 11x 11x 3502x 8x 3502x 3503x 3503x 3503x 3503x 142x 3503x 3503x 130177x 6255x 3502x 3502x 3502x 3503x 3503x 3503x 3503x 3502x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 3503x 130136x 3503x 14x 3019x 3019x 3019x 3019x 3019x 3019x 3019x 130231x 63538x 66693x 66693x 66693x 66690x 3x 3x 3569x 3569x 3569x 137292x 22060x 22060x 3569x 130468x 3569x 6263x 3569x 561x 3569x 22060x 32132x 3569x 3569x 50x 3569x 41x 3569x 130468x 8x 8x 2x 2x 1x 1x 7x | import {
addLR2LongNotes,
addLR2Mines,
addLR2Notes,
applyLR2Loudness,
clampLR2ManiaRate,
createLR2ManiaLocator,
hasLR2ManiaChart,
resolveLR2ManiaEndSeconds,
resolveLR2ManiaSides,
type LR2ManiaChartChanges,
type LR2ManiaChartRates,
} from './lr2-mania-chart.ts';
import { createBeatorajaLaneRandom, type LaneRandomSource } from '../lane-random-source.ts';
import { getPlayModeLayouts, type ChartNotesOption } from '@be-music/chart-model';
import {
chartNotesCopies,
chartNotesDoubles,
copyChartNotes,
doubleChartNotes,
resolveChartNotesOption,
} from './chart-notes-options.ts';
import { doubleNanasiChartNotes } from './nanasi-notes-double.ts';
import { withChartOverrides } from './resolved-chart-overrides.ts';
import { duplicateBattleChart } from './battle-chart.ts';
import {
applyPracticeRange,
createPracticeLoopPreviewNotes,
resolvePracticeLoopShift,
resolvePracticePlayWindow,
resolvePracticeRange,
} from './practice.ts';
import { isDuplicatedBattleMode, resolveEffectiveBattleMode } from './battle-mode.ts';
import { convertLR2SPToDPChart } from './lr2-sp-to-dp-chart.ts';
import type { EffectiveBattleMode } from './battle-mode.ts';
import { convertLR2ExtraChart } from './lr2-extra-chart.ts';
import type { LR2ExtraLevel } from './lr2-extra-lanes.ts';
import { addExtraNotes, clampExtraNoteDepth } from './extra-note-modifier.ts';
import { prepareMineModifier, type MineModifier } from './mine-modifier.ts';
import {
addScrollChanges,
addSoftLanding,
isSoftLanding,
removeScrollChanges,
type ScrollModifier,
} from './scroll-modifier.ts';
import { addLongNotes, clampLongNoteRate, removeLongNoteTails, type LongNoteModifier } from './long-note-modifier.ts';
import { throwIfAborted } from '@be-music/shared-utils/core';
import {
buildChartTextTimeline,
resolveChart,
resolveLRXPlayEndSeconds,
type ResolvedChart,
} from '@be-music/chart-model';
import { normalizeChannel, type BeMusicJSON } from '@be-music/chart-source';
import { type GrooveGaugeJudgmentKind } from './groove-gauge.ts';
import {
GAUGE_JUDGE_BAD,
GAUGE_JUDGE_EMPTY_POOR,
GAUGE_JUDGE_GOOD,
GAUGE_JUDGE_GREAT,
GAUGE_JUDGE_MISS_POOR,
GAUGE_JUDGE_PGREAT,
RulesetGauge,
type GaugeJudgeIndex,
type RulesetConfig,
} from '../ruleset/index.ts';
import { type PlayerGaugeSummary, type PlayerUISignalBus } from './ui-signal-bus.ts';
import type { CreatePlayerUIRuntimeContext, PlayerOptions, PlayerSummary, PlayerUIRuntime } from './engine-types.ts';
import {
toTimedInvisibleNote,
toTimedPlayableNote,
type TimedLandmineNote,
type TimedPlayableNote,
} from '../playable-notes.ts';
import {
appendFreeZoneInputChannels,
type ChannelLike,
createInputTokenToChannelsMap,
createLaneBindings,
type LaneKeyOverrides,
resolveLaneDisplayMode,
type LaneBinding,
} from './lane-layout.ts';
import { DEFAULT_IMAGE_RESIZE_ALGORITHM } from '../image-resize-algorithm.ts';
import { type PlayerStateSignals } from '../state-signals.ts';
import { DEFAULT_TUI_NOTE_HEIGHT } from './ui-options.ts';
/**
* Browser-safe default for `audioBaseDir`. Browsers don't have `process.cwd()`, so a bare reference there
* `ReferenceError`s the moment any web caller leaves `audioBaseDir` undefined. Falls back to `'.'` (the
* conventional CWD shorthand). The asset-resolution path below then joins `'.'` against the chart-relative
* resource paths, which yields the same string the browser caller would have passed; the actual asset bytes
* land via the asset-source closure inside the host (drag-dropped File handles), not via Node fs reads, so the
* `baseDir` field is essentially a label here.
*/
export function resolveDefaultBaseDir(): string {
const proc = (globalThis as { process?: { cwd?: () => string } }).process;
return proc?.cwd?.() ?? '.';
}
export interface PreparedPlaybackChartData {
scrollModifierApplied?: ScrollModifier;
scrollSection?: number;
scrollRate?: number;
scrollModifierTimeline?: import('@be-music/chart-model').ScrollTimelinePoint[];
/** Whether the selected modifier actually changed BPM, STOP or SCROLL; separate from the selected option. */
scrollModifierChanged?: boolean;
notes: TimedPlayableNote[];
laneSoundNotes: TimedPlayableNote[];
landmineNotes: TimedLandmineNote[];
sevenToNinePattern?: import('./seven-to-nine.ts').SevenToNinePattern;
sevenToNineType?: import('./seven-to-nine.ts').SevenToNineType;
sevenToNineThresholdBPM?: number;
sevenToNineApplied?: boolean;
battleMode?: EffectiveBattleMode;
dBattleScratch?: boolean;
/** beatoraja PRACTICE: the range played and the note counts before `PracticeModifier`. */
practiceStartSeconds?: number;
/** Where a PRACTICE play starts: a bar before the range's at least (`resolvePracticePlayWindow`'s first start). */
practicePlayStartSeconds?: number;
/** Where a looping PRACTICE play goes back to: the head of the rest bars before the range, or the range itself. */
practiceLoopStartSeconds?: number;
practiceEndSeconds?: number;
practiceSourceNotes?: import('../ruleset/facts.ts').RulesetNoteCounts;
practiceChangedObjectCount?: number;
battleSourceVariant?: import('@be-music/chart-model').ChartPlayVariant;
battleTempo?: number;
battleAssist1P?: boolean;
battleAssist2P?: boolean;
battleChangedObjectCount?: number;
battleDroppedObjectCount?: number;
/** The chart's NOTES conversion that took effect (#932), and the objects it added. */
chartNotes?: ChartNotesOption;
chartNotesChangedObjectCount?: number;
/** LR2's mania chart generators as applied: the rates, the seed they drew from and what each changed. */
lr2Mania?: PreparedLR2Mania;
lr2ExtraMode?: boolean;
lr2ExtraLevel?: LR2ExtraLevel;
lr2ExtraEffectiveLevel?: LR2ExtraLevel;
lr2ExtraConvertedObjectCount?: number;
lr2ExtraTempo?: number;
extraNoteDepth?: number;
extraNoteScratch?: boolean;
extraNoteChangeCount?: number;
longNoteModifierApplied?: LongNoteModifier;
longNoteModifierRate?: number;
longNoteModifierChangeCount?: number;
/** Number of mines actually changed; selection alone does not imply a source assist. */
mineModifierChangeCount?: number;
mineModifierApplied?: MineModifier;
invisibleNotes: TimedPlayableNote[];
renderNotes: TimedPlayableNote[];
totalSeconds: number;
/**
* `totalSeconds` is the chart's own end (an LRX chart's, `resolveLRXPlayEndSeconds`): option text, BGA and audio
* running longer do not extend it.
*/
fixedEnd?: true;
laneBindings: LaneBinding[];
laneDisplayMode: string;
activeFreeZoneChannels: ReadonlySet<string>;
scorableNotes: TimedPlayableNote[];
inputTokenToChannels: ReadonlyMap<string, readonly string[]>;
/**
* Duplicate notes that lost their lane and position to a note in `notes` but carry a different keysound (see
* `extractTimedNotes`). Manual play sounds them as background audio. Omitted means none.
*/
shadowedNotes?: TimedPlayableNote[];
/** The resolved chart the notes were prepared from (`resolveChart`): its tempo map, triggers and chart facts. */
resolvedChart: ResolvedChart;
}
export interface InitializedPlayerUIRuntime {
uiRuntime: PlayerUIRuntime | undefined;
totalSeconds: number;
uiEnabled: boolean;
activeStateSignals: PlayerStateSignals | undefined;
}
export function createInitialPlayerSummary(
ruleset: RulesetConfig,
totalNotes: number,
): {
summary: PlayerSummary;
applyGaugeJudge: (judge: GrooveGaugeJudgmentKind) => void;
applyGaugeDelta: (delta: number) => void;
applyGaugeTick: (judge: GaugeJudgeIndex, rate: number) => void;
/** Empties the gauge for good (LR2's `HP = 0` on leaving a reversed play with notes outstanding). */
drainGaugeToZero: () => void;
/** Puts the summary and the gauge back to the play's start, in place (a seek rebuilds the play from there). */
reset: () => void;
} {
let gauge = new RulesetGauge(ruleset.gauge, ruleset.gaugeFallback, ruleset.gaugeBank);
const gaugeSummary: PlayerGaugeSummary = {
current: gauge.value,
max: gauge.spec.max,
clearThreshold: gauge.spec.border,
initial: gauge.spec.initial,
effectiveTotal: ruleset.effectiveTotal,
cleared: gauge.cleared(),
// Ruleset-scoped gauge id (`GROOVE` / `NORMAL` / `HARD` / `EX-HARD` / …) so consumers can label the run's
// clear lamp without inferring from the threshold, which collides between line-ups.
type: gauge.spec.id,
...(ruleset.gaugeSource !== ruleset.rulesetId ? { source: ruleset.gaugeSource } : {}),
survival: gauge.spec.survival,
failedMidPlay: gauge.failedMidPlay,
...(gauge.values ? { values: gauge.values } : {}),
};
const syncGaugeSummary = (): void => {
if (gauge.values) gaugeSummary.values = gauge.values;
gaugeSummary.type = gauge.spec.id;
gaugeSummary.max = gauge.spec.max;
gaugeSummary.clearThreshold = gauge.spec.border;
gaugeSummary.initial = gauge.spec.initial;
gaugeSummary.survival = gauge.spec.survival;
gaugeSummary.current = gauge.value;
gaugeSummary.cleared = gauge.cleared();
gaugeSummary.failedMidPlay = gauge.failedMidPlay;
};
const summary: PlayerSummary = {
total: totalNotes,
perfect: 0,
fast: 0,
slow: 0,
great: 0,
good: 0,
bad: 0,
poor: 0,
emptyPoor: 0,
exScore: 0,
score: 0,
combo: 0,
maxCombo: 0,
gauge: gaugeSummary,
};
return {
summary,
applyGaugeJudge: (judge: GrooveGaugeJudgmentKind): void => {
gauge.applyJudge(GROOVE_GAUGE_JUDGE_TO_RULESET_INDEX[judge]);
syncGaugeSummary();
},
applyGaugeDelta: (delta: number): void => {
// Raw deltas (mine damage) bypass the per-judge table, the guts softening, and the TOTAL modifier — every
// ruleset specifies mine damage directly as a gauge percentage — but still kill a survival gauge that bottoms out.
gauge.applyRawDelta(delta);
syncGaugeSummary();
},
applyGaugeTick: (judge: GaugeJudgeIndex, rate: number): void => {
gauge.applyJudge(judge, rate);
syncGaugeSummary();
},
drainGaugeToZero: (): void => {
gauge.drainToZero();
syncGaugeSummary();
},
reset: (): void => {
gauge = new RulesetGauge(ruleset.gauge, ruleset.gaugeFallback, ruleset.gaugeBank);
syncGaugeSummary();
delete summary.minePoor;
for (const key of ['perfect', 'fast', 'slow', 'great', 'good', 'bad', 'poor', 'emptyPoor', 'exScore'] as const) {
summary[key] = 0;
}
summary.score = 0;
},
};
}
/** Engine judge kinds mapped onto the ruleset gauge tables' beatoraja-ordered indices. */
const GROOVE_GAUGE_JUDGE_TO_RULESET_INDEX: Record<GrooveGaugeJudgmentKind, GaugeJudgeIndex> = {
PERFECT: GAUGE_JUDGE_PGREAT,
GREAT: GAUGE_JUDGE_GREAT,
GOOD: GAUGE_JUDGE_GOOD,
BAD: GAUGE_JUDGE_BAD,
POOR: GAUGE_JUDGE_MISS_POOR,
EMPTY_POOR: GAUGE_JUDGE_EMPTY_POOR,
};
/**
* Prepares a play from a resolved chart (`resolveChart` in `@be-music/chart-model`): fresh mutable note arrays for the engine
* and the renderer, the lane bindings for the chart's play variant, and the scorable notes (FREE ZONE columns the
* layout does not bind are left out).
*/
export function preparePlaybackChart(
resolved: ResolvedChart,
options: Pick<
PlayerOptions,
| 'laneModeExtension'
| 'longNoteModifier'
| 'battleMode'
| 'dBattleScratch'
| 'practice'
| 'judgeRuleset'
| 'autoScratch'
| 'autoScratch1P'
| 'autoScratch2P'
| 'lr2ExtraMode'
| 'lr2ExtraLevel'
| 'lr2Mania'
| 'course'
| 'speed'
| 'extraNoteDepth'
| 'extraNoteScratch'
| 'longNoteRate'
| 'longNoteModifierPlacements'
| 'mineModifier'
| 'mineModifierPlacements'
| 'scrollModifier'
| 'scrollSection'
| 'scrollRate'
| 'scrollModifierTimeline'
> & {
/**
* The chart's NOTES conversion (#932), from its gameplay program (a replay's recorded one). It replaces the player's
* battle conversion when it copies the chart, and is narrowed to what can take effect (`resolveChartNotesOption`).
*/
chartNotes?: ChartNotesOption;
/** Whether `chartNotes` comes from a version 1 / 2 gameplay program, which keeps Be-Music's earlier readings. */
chartNotesLegacy?: boolean;
/** The player's own lane keys (`LaneModeOptions.laneKeys`). */
laneKeys?: LaneKeyOverrides;
/**
* LR2 two-player BATTLE (`TWO-PLAYER`) with the same lane option on both sides: LR2 copies the arranged 1P lanes to
* 2P, mines included (OpenLR2 `LR2f.cpp` L27473-L27492), so 2P gets the mines too. With different options LR2
* copies only the note cells at load time (L26244) and 2P gets none.
*/
twoPlayerMines?: boolean;
} = {},
auxiliaryPlaybackEndSeconds = 0,
random?: () => number,
): PreparedPlaybackChartData {
const lr2ExtraMode = options.lr2ExtraMode === true && options.course === undefined;
const lr2Extra = lr2ExtraMode
? convertLR2ExtraChart(resolved, { level: options.lr2ExtraLevel ?? 0, tempo: options.speed })
: undefined;
resolved = lr2Extra?.chart ?? resolved;
const battleSourceVariant = resolved.playVariant;
const chartNotesLegacy = options.chartNotesLegacy === true;
const chartNotes = resolveChartNotesOption(
options.chartNotes,
{ playVariant: battleSourceVariant, course: options.course !== undefined },
chartNotesLegacy,
);
// A chart that copies itself onto the 2P side decides the double-play chart, in place of the player's conversion.
const battleMode = chartNotesCopies(chartNotes)
? 'OFF'
: resolveEffectiveBattleMode(
options.battleMode ?? 'OFF',
options.judgeRuleset ?? 'lr2',
battleSourceVariant,
options.course !== undefined,
resolved.sourceFormat === 'bms' ? resolved.source.bms.player : undefined,
);
if (battleMode === 'COUPLE' && (resolved.playVariant === '5' || resolved.playVariant === '7')) {
const playVariant = resolved.playVariant === '5' ? '10' : '14';
resolved = withChartOverrides(resolved, { playVariant, layouts: getPlayModeLayouts(playVariant) });
}
const battleAssist1P = options.autoScratch1P ?? options.autoScratch ?? false;
const battleAssist2P = options.autoScratch2P ?? options.autoScratch ?? false;
const battle =
battleMode === 'SP-TO-DP'
? convertLR2SPToDPChart(resolved, {
tempo: options.speed,
assist1P: battleAssist1P,
assist2P: battleAssist2P,
})
: undefined;
resolved = battle?.chart ?? resolved;
const scrollAddition =
options.scrollModifier === 'ADD'
? addScrollChanges(resolved, {
section: options.scrollSection,
rate: options.scrollRate,
timeline: options.scrollModifierTimeline,
random,
})
: undefined;
const softLanding = isSoftLanding(options.scrollModifier)
? addSoftLanding(resolved, {
level: options.scrollModifier === 'SOFTLANDING-1' ? 1 : 2,
timeline: options.scrollModifierTimeline,
random,
})
: undefined;
const scrollResult =
scrollAddition ?? softLanding ?? (options.scrollModifier === 'REMOVE' ? removeScrollChanges(resolved) : undefined);
resolved = scrollResult?.chart ?? resolved;
let playVariant = resolved.playVariant;
const notes = resolved.notes.map(toTimedPlayableNote);
// LR2's mania chart generators (#1110-#1113), outside courses and PRACTICE as LR2 skips them in a course. One seeded
// source feeds all four, so the recorded seed rebuilds the chart.
const maniaRates = options.lr2Mania;
const maniaSides =
hasLR2ManiaChart(maniaRates) && options.course === undefined && options.practice === undefined
? resolveLR2ManiaSides(resolved, options.laneModeExtension)
: [];
const mania = maniaSides.length > 0 ? startLR2Mania(maniaRates!, random) : undefined;
if (mania !== undefined) {
if (mania.rates.addNotes > 0)
mania.changes.addNotes = addLR2Notes(notes, resolved.mines, maniaSides, mania.rates.addNotes, mania.random);
if (mania.rates.loudness > 0)
mania.changes.loudness = applyLR2Loudness(notes, resolved.mines, maniaSides, mania.rates.loudness, mania.random);
}
const longMode = options.longNoteModifier ?? 'OFF';
const longChanges =
longMode === 'ADD_LN' || longMode === 'ADD_CN' || longMode === 'ADD_HCN' || longMode === 'ADD_ALL'
? addLongNotes(resolved, notes, longMode, {
rate: options.longNoteRate,
random,
laneModeExtension: options.laneModeExtension,
placements: options.longNoteModifierPlacements,
})
: removeLongNoteTails(notes, longMode, resolved.lnMode);
// Invisible 3x/4x objects are not score targets, but they do update the lane's current keysound in manual play.
// They are always prepared, independently of the debug overlay option, so audio never depends on rendering settings.
const mineResult = prepareMineModifier(resolved, options.mineModifier ?? 'OFF', {
notes,
laneModeExtension: options.laneModeExtension,
random,
placements: options.mineModifierPlacements,
});
const landmineNotes = mineResult.mines;
if (mania !== undefined) {
if (mania.rates.addLongNotes > 0)
mania.changes.addLongNotes = addLR2LongNotes(
notes,
landmineNotes,
maniaSides,
mania.rates.addLongNotes,
mania.random,
resolveLR2ManiaEndSeconds(resolved, notes),
(seconds) => createLR2ManiaLocator(resolved)(seconds).beat,
);
if (mania.rates.addMines > 0)
mania.changes.addMines = addLR2Mines(
notes,
landmineNotes,
maniaSides,
mania.rates.addMines,
mania.random,
createLR2ManiaLocator(resolved),
);
}
const extraResult = addExtraNotes(resolved, notes, landmineNotes, {
depth: options.extraNoteDepth,
scratch: options.extraNoteScratch,
laneModeExtension: options.laneModeExtension,
});
resolved = extraResult.chart;
const invisibleNotes = resolved.invisibleNotes.map(toTimedInvisibleNote);
// The chart's NOTES conversion, after the note and mine modifiers and before the battle conversion it replaces.
// nanasigroove copies the chart first and doubles the double-play chart; the version 1 / 2 reading doubles first (so a
// doubled partner avoids an added mine).
let chartNotesChangedObjectCount = 0;
if (chartNotesLegacy && chartNotesDoubles(chartNotes))
chartNotesChangedObjectCount += doubleChartNotes(notes, landmineNotes, resolved.playVariant);
if (chartNotesCopies(chartNotes)) {
const copied = copyChartNotes(resolved, notes, landmineNotes, invisibleNotes, chartNotesLegacy);
resolved = copied.chart;
chartNotesChangedObjectCount += copied.changedObjectCount;
}
if (!chartNotesLegacy && chartNotesDoubles(chartNotes))
chartNotesChangedObjectCount += doubleNanasiChartNotes(notes, invisibleNotes, resolved.playVariant);
const dBattleScratch = battleMode === 'D-BATTLE' && options.dBattleScratch === true;
const duplicateBattle = isDuplicatedBattleMode(battleMode, battleSourceVariant)
? duplicateBattleChart(resolved, notes, landmineNotes, invisibleNotes, {
// LR2 copies only 1x/3x/5x cells (D-BATTLE, BATTLE); That-Which-Must-Not-Be-Named gives both players one chart.
duplicateMines: !(
battleMode === 'D-BATTLE' ||
(battleMode === 'TWO-PLAYER' && options.judgeRuleset !== '____' && options.twoPlayerMines !== true)
),
backgroundScratch: battleMode === 'BATTLE-AS' || (battleMode === 'D-BATTLE' && !dBattleScratch),
backgroundMineSample: battleMode === 'D-BATTLE',
})
: undefined;
resolved = duplicateBattle?.chart ?? resolved;
playVariant = resolved.playVariant;
// Leave one chart second to present the final selection, even after the last playable note.
const lastTextCue = buildChartTextTimeline(resolved.source, resolved.timing)
.cues.filter((cue) => cue.seconds <= (resolved.reversal?.seconds ?? Infinity))
.at(-1);
const lastTextSeconds = lastTextCue === undefined ? 0 : lastTextCue.seconds + 1;
let totalSeconds = Math.max(resolved.lastNoteSeconds, auxiliaryPlaybackEndSeconds, lastTextSeconds);
for (const note of notes) totalSeconds = Math.max(totalSeconds, note.endSeconds ?? note.seconds);
for (const mine of landmineNotes) totalSeconds = Math.max(totalSeconds, mine.seconds);
// An LRX chart plays for as long as plugout plays it: to its end-of-song note, else 3 s past its last sound note,
// whatever still sounds or shows then. A note still to be judged keeps the play going (`play-loop.ts`).
const lrxEndSeconds = resolveLRXPlayEndSeconds(resolved);
if (lrxEndSeconds !== undefined) totalSeconds = lrxEndSeconds;
const practiceRange =
options.practice !== undefined
? resolvePracticeRange(
options.practice,
Math.floor(Math.max(totalSeconds, resolved.sampleTriggers.at(-1)?.seconds ?? 0) * 1000),
)
: undefined;
const practice = practiceRange
? applyPracticeRange(resolved, notes, landmineNotes, practiceRange, options.practice?.carriedLongNotes === true)
: undefined;
resolved = practice?.chart ?? resolved;
// A practice play runs from the head of the bar before its range to the head of the bar after it (#954).
const practiceWindow =
practiceRange && options.practice
? resolvePracticePlayWindow(resolved, options.practice, practiceRange, practice?.carriedFromMs)
: undefined;
if (practiceWindow) totalSeconds = practiceWindow.endSeconds;
const fixedEnd = lrxEndSeconds !== undefined && practiceWindow === undefined;
const laneSoundNotes = [...notes, ...invisibleNotes].sort(compareLaneSoundNotes);
// A seamless PRACTICE loop draws the next round's notes past the range's end, so they come down the lane (#949).
const loopShift =
practiceWindow && options.practice
? resolvePracticeLoopShift(resolved, options.practice, practiceWindow)
: undefined;
const renderNotes = loopShift ? [...notes, ...createPracticeLoopPreviewNotes(notes, loopShift)] : notes;
const channels = collectUniqueNoteChannels(notes, landmineNotes, invisibleNotes);
const laneModeOptions = {
player: resolved.source.bms.player,
chartExtension: options.laneModeExtension,
playVariant,
laneKeys: options.laneKeys,
};
const laneBindings = createLaneBindings(channels, laneModeOptions);
const inputTokenToChannels = createInputTokenToChannelsMap(laneBindings);
appendFreeZoneInputChannels(inputTokenToChannels, laneBindings, channels);
const laneDisplayMode = resolveLaneDisplayMode(channels, laneModeOptions);
const activeFreeZoneChannels = resolveActiveFreeZoneChannels(channels, laneBindings);
const scorableNotes = notes.filter((note) => !isActiveFreeZoneChannel(note.channel, activeFreeZoneChannels));
return {
...(chartNotes !== undefined ? { chartNotes, chartNotesChangedObjectCount } : {}),
...(options.battleMode !== undefined
? {
battleMode,
battleSourceVariant,
battleTempo: options.speed ?? 1,
battleAssist1P,
battleAssist2P,
battleChangedObjectCount: duplicateBattle?.changedObjectCount ?? battle?.changedObjectCount ?? 0,
battleDroppedObjectCount: battle?.droppedObjectCount ?? 0,
...(battleMode === 'D-BATTLE' ? { dBattleScratch } : {}),
}
: {}),
...(practiceRange && practice
? {
practicePlayStartSeconds: practiceWindow?.firstStartSeconds ?? 0,
practiceLoopStartSeconds: practiceWindow?.startSeconds ?? 0,
practiceStartSeconds: practiceRange.startMs / 1000,
practiceEndSeconds: practiceRange.endMs / 1000,
practiceSourceNotes: practice.sourceNotes,
practiceChangedObjectCount: practice.changedObjectCount,
}
: {}),
...(mania !== undefined ? { lr2Mania: { ...mania.rates, seed: mania.seed, changes: mania.changes } } : {}),
...(options.lr2ExtraMode !== undefined
? {
lr2ExtraMode,
lr2ExtraLevel: options.lr2ExtraLevel ?? 0,
lr2ExtraEffectiveLevel: lr2Extra?.level ?? options.lr2ExtraLevel ?? 0,
lr2ExtraConvertedObjectCount: lr2Extra?.changes ?? 0,
lr2ExtraTempo: options.speed ?? 1,
}
: {}),
...(options.extraNoteDepth !== undefined || options.extraNoteScratch !== undefined
? {
extraNoteDepth: clampExtraNoteDepth(options.extraNoteDepth ?? 0),
extraNoteScratch: options.extraNoteScratch ?? false,
extraNoteChangeCount: extraResult.changes,
}
: {}),
notes,
...(options.longNoteModifier !== undefined
? {
longNoteModifierApplied: longMode,
longNoteModifierChangeCount: longChanges,
longNoteModifierRate: clampLongNoteRate(options.longNoteRate ?? 1),
}
: {}),
laneSoundNotes,
landmineNotes,
...(options.mineModifier !== undefined
? { mineModifierChangeCount: mineResult.changes, mineModifierApplied: options.mineModifier }
: {}),
invisibleNotes,
renderNotes,
totalSeconds,
...(fixedEnd ? { fixedEnd } : {}),
laneBindings,
laneDisplayMode,
activeFreeZoneChannels,
scorableNotes,
inputTokenToChannels,
shadowedNotes: resolved.shadowedNotes.map(toTimedPlayableNote),
resolvedChart: resolved,
...(scrollAddition
? {
scrollSection: scrollAddition.section,
scrollRate: scrollAddition.rate,
scrollModifierTimeline: scrollAddition.timeline,
}
: {}),
...(softLanding ? { scrollModifierTimeline: softLanding.timeline } : {}),
...(options.scrollModifier !== undefined
? { scrollModifierApplied: options.scrollModifier, scrollModifierChanged: scrollResult?.changed ?? false }
: {}),
};
}
/**
* Resolves `resolvedJSON` (a chart without control flow) with `resolveChart` and prepares it with
* {@link preparePlaybackChart}. The play variant is the host-declared one, else the shared `resolveChartPlayVariant`
* rule over the chart's events and `laneModeExtension`.
*/
export function preparePlaybackChartData(
resolvedJSON: BeMusicJSON,
options: Pick<PlayerOptions, 'showInvisibleNotes' | 'laneModeExtension' | 'playVariant'>,
inferBmsLNTypeWhenMissing: boolean,
auxiliaryPlaybackEndSeconds: number,
): PreparedPlaybackChartData {
return preparePlaybackChart(
resolveChart(resolvedJSON, {
chartPath: options.laneModeExtension,
playVariant: options.playVariant,
inferBmsLNTypeWhenMissing,
}),
options,
auxiliaryPlaybackEndSeconds,
);
}
export async function initializePlayerUIRuntime({
options,
resolvedJSON,
mode,
laneDisplayMode,
laneBindings,
speed,
judgeWindowMs,
highSpeed,
randomPatternSummary,
stateSignals,
uiSignals,
totalSeconds,
fixedEnd = false,
onLoadProgress,
}: {
options: PlayerOptions;
resolvedJSON: BeMusicJSON;
mode: CreatePlayerUIRuntimeContext['mode'];
laneDisplayMode: string;
laneBindings: LaneBinding[];
speed: number;
judgeWindowMs: number;
highSpeed: number;
randomPatternSummary: string | undefined;
stateSignals: PlayerStateSignals;
uiSignals: PlayerUISignalBus;
totalSeconds: number;
/** `totalSeconds` is the chart's own end, which a longer BGA does not extend. */
fixedEnd?: boolean;
onLoadProgress: (ratio: number, message: string, detail?: string) => void;
}): Promise<InitializedPlayerUIRuntime> {
throwIfAborted(options.signal);
onLoadProgress(0.18, 'Preparing BGA...');
const uiRuntime = await options.createUIRuntime?.({
json: resolvedJSON,
mode,
laneDisplayMode,
laneBindings,
speed,
uiFPS: options.uiFPS,
tuiVisibleNotesLimit: options.tuiVisibleNotesLimit,
tuiNoteHeight: options.tuiNoteHeight ?? DEFAULT_TUI_NOTE_HEIGHT,
judgeWindowMs,
highSpeed,
imageResizeAlgorithm: options.imageResizeAlgorithm ?? DEFAULT_IMAGE_RESIZE_ALGORITHM,
videoBGAStreaming: options.videoBGAStreaming,
keyBoundBGACues: options.keyBoundBGACues,
bmsonBGACues: options.bmsonBGACues,
showLaneChannels: Boolean(options.debugActiveAudio),
randomPatternSummary,
stateSignals,
uiSignals,
baseDir: options.audioBaseDir ?? resolveDefaultBaseDir(),
loadSignal: options.signal,
onBGALoadProgress: (progress) => {
onLoadProgress(0.18 + progress.ratio * 0.12, 'Preparing BGA...', progress.detail);
},
});
throwIfAborted(options.signal);
const updatedTotalSeconds = fixedEnd ? totalSeconds : Math.max(totalSeconds, uiRuntime?.playbackEndSeconds ?? 0);
const uiEnabled = Boolean(uiRuntime?.tuiEnabled);
return {
uiRuntime,
totalSeconds: updatedTotalSeconds,
uiEnabled,
activeStateSignals: uiEnabled ? stateSignals : undefined,
};
}
function compareLaneSoundNotes(left: TimedPlayableNote, right: TimedPlayableNote): number {
if (left.seconds !== right.seconds) {
return left.seconds - right.seconds;
}
const leftSourceChannel = normalizeChannel(left.event.channel);
const rightSourceChannel = normalizeChannel(right.event.channel);
if (leftSourceChannel !== rightSourceChannel) {
return leftSourceChannel < rightSourceChannel ? -1 : 1;
}
Iif (left.event.value !== right.event.value) {
return left.event.value < right.event.value ? -1 : 1;
}
return 0;
}
export function collectUniqueNoteChannels(
notes: readonly ChannelLike[],
landmineNotes: readonly ChannelLike[],
invisibleNotes: readonly ChannelLike[],
): string[] {
const seen = new Set<string>();
const channels: string[] = [];
const collect = (channel: string): void => {
if (!seen.has(channel)) {
seen.add(channel);
channels.push(channel);
}
};
for (const note of notes) {
collect(note.channel);
}
for (const landmine of landmineNotes) {
collect(landmine.channel);
}
for (const invisible of invisibleNotes) {
collect(invisible.channel);
}
return channels;
}
export function resolveActiveFreeZoneChannels(
channels: ReadonlyArray<string>,
laneBindings: ReadonlyArray<LaneBinding>,
): ReadonlySet<string> {
const existingChannels = new Set(channels.map((channel) => normalizeChannel(channel)));
const boundChannels = new Set(laneBindings.map((binding) => normalizeChannel(binding.channel)));
const activeFreeZoneChannels = new Set<string>();
if (existingChannels.has('17') && boundChannels.has('16') && !boundChannels.has('17')) {
activeFreeZoneChannels.add('17');
}
if (existingChannels.has('27') && boundChannels.has('26') && !boundChannels.has('27')) {
activeFreeZoneChannels.add('27');
}
return activeFreeZoneChannels;
}
export function isActiveFreeZoneChannel(channel: string, activeFreeZoneChannels: ReadonlySet<string>): boolean {
return activeFreeZoneChannels.has(normalizeChannel(channel));
}
/** LR2's mania chart generators as a prepared chart applied them. */
export interface PreparedLR2Mania extends Required<LR2ManiaChartRates> {
/** The seed every draw came from; with the rates it rebuilds the chart. */
seed: string;
changes: LR2ManiaChartChanges;
}
/** The generators' clamped rates and their one seeded source: the recorded seed, or a fresh one drawn from `random`. */
function startLR2Mania(
rates: LR2ManiaChartRates & { seed?: string },
random: (() => number) | undefined,
): { rates: Required<LR2ManiaChartRates>; seed: string; random: LaneRandomSource; changes: LR2ManiaChartChanges } {
let seed = rates.seed;
if (seed === undefined) {
const draw = random?.();
if (draw === undefined || !Number.isFinite(draw) || draw < 0 || draw >= 1)
throw new RangeError("LR2's mania chart options require supplied randomness in [0, 1) or a recorded seed.");
seed = String(Math.floor(draw * 16_777_216));
}
return {
rates: {
addNotes: clampLR2ManiaRate(rates.addNotes),
loudness: clampLR2ManiaRate(rates.loudness),
addLongNotes: clampLR2ManiaRate(rates.addLongNotes),
addMines: clampLR2ManiaRate(rates.addMines),
},
seed,
random: createBeatorajaLaneRandom(seed),
changes: { addNotes: 0, loudness: 0, addLongNotes: 0, addMines: 0 },
};
}
|