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 | 127x 127x 2x 121x 121x 127x 127x 127x 127x 44x 75x 127x 69x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 121x 77x 44x 2x 44x 632x 237x 2x 42x 75x 112x 112x 58x 54x 54x 54x 54x 54x 54x 1750x 152x 152x 1598x 630x 630x 630x 968x 23x 23x 945x 945x 945x 54x 54x 54x 74x 74x 2x 74x 74x 2x 74x 74x 4x 70x 1x 74x 2x 74x 2x 74x 2x 74x 1x 74x 1x 74x 8x 1x 74x 4x 74x 74x 4x 74x 74x 1x 74x 74x 74x 74x 74x 9x 74x 74x 74x 77x 7x 74x 14x 74x 7x 74x 4x 6x 6x 74x 74x 2x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 74x 299x 148x 148x 148x 10x 10x 10x 148x 888x 888x 99x 99x 296x 296x 16x 16x 74x 6x 9x 6x 68x 5x 1x 68x 3x 74x 6x 9x 9x 9x 6x 68x 68x 68x 98x 98x 237x 98x 98x 151x 151x 151x 151x 151x 150x 150x 98x 68x 68x 60x 8x 8x 8x 8x 8x 8x 15x 15x 41x 41x 8x 8x 8x 2x 6x 26x 26x 6x 6x 6x 6x 6x 74x 74x 34x 21x 21x 13x 10x 2x 8x 10x 10x 3x 1x 1x 2x 2x 2x 444x 222x 444x 444x 2x 956x 956x 956x 1771x 1771x 1771x 1x 1770x 956x 956x 3839x 956x 1770x 1770x 1770x 1770x 956x 68x 68x 151x 151x 151x 151x 151x 73x 151x 151x 151x 68x 68x 73x 98x 68x 1054x 1054x 1920x 1920x 1920x 1x 1053x 3992x 3992x 3992x 3992x 1586x 2406x 2406x 1081x 151x 8x 8x 1x 7x 1x 6x 2x 4x 24x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 125x 125x 2x 2x 2x 123x 123x 125x 23x 23x 23x 23x 23x 23x 23x 100x 18x 18x 18x 18x 18x 18x 16x 18x 18x 18x 82x 69x 27x 42x 2x 42x 1x 42x 6x 41x 2x 41x 41x 13x 41x 41x 41x 3x 41x 41x 6x 41x 41x 41x 41x 1x 41x 41x 3x 41x 41x 41x 41x 10x 41x 69x 69x 41x 69x 69x 72x 69x 23x 23x 23x 3x 23x 23x 23x | import {
compareEvents,
resolveGenericBmsonKeyCount,
createBeatResolver,
isLandmineChannel,
isPlayableChannel,
sortEvents,
} from '@be-music/chart-model';
import { parseBMS } from '@be-music/chart-parser/core';
import {
intToBase36,
normalizeChannel,
normalizeObjectKey,
resolveBMSBase,
type BMSObjectLineEntry,
type BMSSourceLineEntry,
type BeMusicEvent,
type BeMusicJSON,
} from '@be-music/chart-source';
import {
gcd,
lcm,
normalizeFractionNumerator,
normalizeNonNegativeInt,
normalizePositiveInt,
} from '@be-music/shared-utils/core';
import { BMS_MINE_SAMPLE_KEY, BMSON_LONG_NOTE_TYPES } from './bmson.ts';
import { areBMSChartsEquivalent, areEventBmsonExtensionsEqual } from './equivalence.ts';
import type { BMSStringifyOptions } from './options.ts';
import { applyIntrinsicWAVGainForBMS } from './wav-gain.ts';
import { convertBmsonBGAToBMS, type ChartExportDiagnosticHandler } from './bga-export.ts';
export function stringifyBMS(json: BeMusicJSON, options: BMSStringifyOptions = {}): string {
json = applyIntrinsicWAVGainForBMS(json);
if (resolveGenericBmsonKeyCount(json.bmson.info.modeHint) !== undefined)
throw new RangeError('Generic bmson layouts cannot be represented by BMS; export bmson or Be-Music JSON.');
assertBmsonKeysFitBMS(json);
const eol = options.eol ?? '\n';
const maxResolution = options.maxResolution;
const skipValidation = options.skipPreservationValidation === true;
const preservedSourceLines =
maxResolution === undefined ? resolvePreservedBMSSourceLinesForOutput(json, skipValidation) : undefined;
if (preservedSourceLines) {
return preservedSourceLines.join(eol);
}
const preservedObjectLines =
maxResolution === undefined ? resolvePreservedObjectLinesForOutput(json, skipValidation) : undefined;
if (!preservedObjectLines) {
json = convertChartForBMSOutput(json, options.onDiagnostic);
}
const lines: string[] = [];
pushBMSSectionComment(lines, 'METADATA');
pushMetadataLines(lines, json);
pushBMSSectionComment(lines, 'EXTENDED HEADER');
pushBMSExtensionLines(lines, json);
pushBMSSectionComment(lines, 'RESOURCES');
pushResourceLines(lines, json);
pushBMSSectionComment(lines, 'MEASURE LENGTH');
pushMeasureLines(lines, json, preservedObjectLines);
pushBMSSectionComment(lines, 'OBJECT DATA');
pushEventLines(lines, json, maxResolution, preservedObjectLines);
pushBMSSectionComment(lines, 'CONTROL FLOW');
pushControlFlowLines(lines, json);
return lines.join(eol);
}
/** BMS object IDs are exactly two characters; truncating bmson keys would alias unrelated resources. */
function assertBmsonKeysFitBMS(json: BeMusicJSON): void {
if (json.sourceFormat !== 'bmson') {
return;
}
const fail = (key: string): never => {
throw new RangeError(
`Cannot export bmson resource key "${key}" to two-character BMS IDs. Keep bmson or Be-Music JSON, or reduce and remap resources before exporting BMS.`,
);
};
for (const table of [
json.resources.wav,
json.resources.bmp,
json.resources.bpm,
json.resources.stop,
json.resources.text,
json.bms.exRank,
json.bms.argb,
json.bms.changeOption,
json.bms.songText,
json.bms.exWAV,
json.bms.exBMP,
json.bms.bga,
json.bms.scroll,
json.bms.speed,
json.bms.swBGA,
]) {
for (const key of Object.keys(table)) {
if (key.length > 2) {
fail(key);
}
}
}
for (const event of json.events) {
Iif (event.value.length > 2) {
fail(event.value);
}
}
}
function resolvePreservedBMSSourceLinesForOutput(json: BeMusicJSON, skipValidation: boolean): string[] | undefined {
const sourceLines = json.preservation.bms.sourceLines;
if (!Array.isArray(sourceLines) || sourceLines.length === 0) {
return undefined;
}
const lines = renderPreservedBMSSourceLines(sourceLines);
Iif (lines.length === 0) {
return undefined;
}
// `skipValidation` halves stringify time on large charts (the re-parse below dominates), but trusts the caller to
// have left the JSON untouched between parse and stringify. See `BMSStringifyOptions.skipPreservationValidation`.
Iif (skipValidation) {
return lines;
}
return doPreservedBMSSourceLinesMatchChart(json, lines) ? lines : undefined;
}
function renderPreservedBMSSourceLines(sourceLines: BMSSourceLineEntry[]): string[] {
const lines: string[] = [];
for (const entry of sourceLines) {
if (entry.kind === 'directive') {
lines.push(entry.value ? `#${entry.command} ${entry.value}` : `#${entry.command}`);
continue;
}
if (entry.kind === 'header') {
// Use the case-preserved `commandRaw` when present so e.g. `#WAV0a` survives the round-trip on a `#BASE 62`
// chart.
const commandText = entry.commandRaw ?? entry.command;
lines.push(entry.value.length > 0 ? `#${commandText} ${entry.value}` : `#${commandText}`);
continue;
}
if (typeof entry.measureLength === 'number' && entry.measureLength > 0) {
lines.push(`#${toMeasure(entry.measure)}${normalizeChannel(entry.channel)}:${formatNumber(entry.measureLength)}`);
continue;
}
const serialized = serializeBMSObjectLineEvents(entry.measure, entry.channel, entry.events);
Eif (serialized) {
lines.push(serialized);
}
}
return lines;
}
function doPreservedBMSSourceLinesMatchChart(json: BeMusicJSON, lines: string[]): boolean {
const reparsed = parseBMS(lines.join('\n'));
return areBMSChartsEquivalent(json, reparsed);
}
function pushMetadataLines(lines: string[], json: BeMusicJSON): void {
lines.push(`#TITLE ${json.metadata.title ?? ''}`);
if (json.metadata.subtitle) {
lines.push(`#SUBTITLE ${json.metadata.subtitle}`);
}
lines.push(`#ARTIST ${json.metadata.artist ?? ''}`);
if (json.metadata.genre) {
lines.push(`#GENRE ${json.metadata.genre}`);
}
lines.push(`#BPM ${formatNumber(json.metadata.bpm)}`);
if (typeof json.metadata.playLevel === 'number') {
lines.push(`#PLAYLEVEL ${formatNumber(json.metadata.playLevel)}`);
} else if (typeof json.metadata.playLevel === 'string' && json.metadata.playLevel.length > 0) {
lines.push(`#PLAYLEVEL ${json.metadata.playLevel}`);
}
if (typeof json.metadata.rank === 'number') {
lines.push(`#RANK ${formatNumber(json.metadata.rank)}`);
}
if (typeof json.metadata.total === 'number') {
lines.push(`#TOTAL ${formatNumber(json.metadata.total)}`);
}
if (typeof json.metadata.difficulty === 'number') {
lines.push(`#DIFFICULTY ${formatNumber(json.metadata.difficulty)}`);
}
if (json.metadata.comment) {
lines.push(`#COMMENT ${json.metadata.comment}`);
}
if (json.metadata.stageFile) {
lines.push(`#STAGEFILE ${json.metadata.stageFile}`);
}
const extras = Object.entries(json.metadata.extras ?? {})
.filter(([command]) => !isDedicatedBMSExtensionCommand(command))
.sort(([left], [right]) => left.localeCompare(right));
for (const [command, value] of extras) {
lines.push(`#${command} ${value}`);
}
}
function pushBMSExtensionLines(lines: string[], json: BeMusicJSON): void {
const base = resolveJSONBase(json);
// `#BASE 62` opts the whole chart into the beatoraja base-62 ID extension, which affects every subsequent
// indexed-header / channel-stream token's case-sensitivity. Emit it FIRST so it takes effect before any `#WAVxx` /
// `#BMPxx` etc. lines below.
if (base === 62) {
lines.push('#BASE 62');
}
Iif (typeof json.bms.preview === 'string' && json.bms.preview.length > 0) {
lines.push(`#PREVIEW ${json.bms.preview}`);
}
if (typeof json.bms.player === 'number') {
lines.push(`#PLAYER ${formatNumber(json.bms.player)}`);
}
Iif (typeof json.bms.pathWAV === 'string' && json.bms.pathWAV.length > 0) {
lines.push(`#PATH_WAV ${json.bms.pathWAV}`);
}
Iif (typeof json.bms.baseBPM === 'number') {
lines.push(`#BASEBPM ${formatNumber(json.bms.baseBPM)}`);
}
for (const stp of json.bms.stp ?? []) {
if (typeof stp === 'string' && stp.length > 0) {
lines.push(`#STP ${stp}`);
}
}
const optionDeclarations = json.bms.optionHeadersInControlFlow
? []
: (json.bms.options ?? (json.bms.option ? [json.bms.option] : []));
for (const option of optionDeclarations) {
Eif (option.length > 0) lines.push(`#OPTION ${option}`);
}
pushIndexedStringLines(lines, 'CHANGEOPTION', json.bms.changeOption, base);
// Charts declare one `#WAVCMD` line per (parameter, slot) pair, so write every line; the legacy `wavCmd` only holds the
// first, and stands in when `wavCmds` is empty.
const wavCmds = (json.bms.wavCmds?.length ?? 0) > 0 ? json.bms.wavCmds : [json.bms.wavCmd];
for (const wavCmd of wavCmds) {
if (typeof wavCmd === 'string' && wavCmd.length > 0) {
lines.push(`#WAVCMD ${wavCmd}`);
}
}
if (typeof json.bms.lnType === 'number') {
lines.push(`#LNTYPE ${formatNumber(json.bms.lnType)}`);
}
if (typeof json.bms.lnMode === 'number') {
lines.push(`#LNMODE ${formatNumber(json.bms.lnMode)}`);
}
if ((json.bms.lnObjs?.length ?? 0) > 0) {
for (const lnObj of json.bms.lnObjs ?? []) {
Eif (typeof lnObj === 'string' && lnObj.length > 0) {
lines.push(`#LNOBJ ${normalizeObjectKey(lnObj, base)}`);
}
}
}
Iif (typeof json.bms.volWAV === 'number') {
lines.push(`#VOLWAV ${formatNumber(json.bms.volWAV)}`);
}
if (typeof json.bms.defExRank === 'number') {
lines.push(`#DEFEXRANK ${formatNumber(json.bms.defExRank)}`);
}
pushIndexedStringLines(lines, 'EXRANK', json.bms.exRank, base);
pushIndexedStringLines(lines, 'ARGB', json.bms.argb, base);
// #WAV and #EXWAV share a slot and the later line wins (#1197): an EXWAV goes here, before the #WAV lines, only when
// no #WAV of its slot is written or a later #WAV redefines it; the rest follow the #WAV lines.
pushIndexedStringLines(lines, 'EXWAV', splitExWAVByWAVOrder(json).beforeWAV, base);
pushIndexedStringLines(lines, 'EXBMP', json.bms.exBMP, base);
pushIndexedStringLines(lines, 'BGA', json.bms.bga, base);
pushIndexedNumberLines(lines, 'SCROLL', json.bms.scroll, base);
pushIndexedNumberLines(lines, 'SPEED', json.bms.speed, base);
Iif (typeof json.bms.poorBGA === 'string' && json.bms.poorBGA.length > 0) {
lines.push(`#POORBGA ${json.bms.poorBGA}`);
}
pushIndexedStringLines(lines, 'SWBGA', json.bms.swBGA, base);
Iif (typeof json.bms.videoFile === 'string' && json.bms.videoFile.length > 0) {
lines.push(`#VIDEOFILE ${json.bms.videoFile}`);
}
Iif (typeof json.bms.midiFile === 'string' && json.bms.midiFile.length > 0) {
lines.push(`#MIDIFILE ${json.bms.midiFile}`);
}
Iif (typeof json.bms.materials === 'string' && json.bms.materials.length > 0) {
lines.push(`#MATERIALS ${json.bms.materials}`);
}
Iif (typeof json.bms.divideProp === 'string' && json.bms.divideProp.length > 0) {
lines.push(`#DIVIDEPROP ${json.bms.divideProp}`);
}
Iif (typeof json.bms.charset === 'string' && json.bms.charset.length > 0) {
lines.push(`#CHARSET ${json.bms.charset}`);
}
}
function pushResourceLines(lines: string[], json: BeMusicJSON): void {
const base = resolveJSONBase(json);
pushIndexedStringLines(lines, 'WAV', json.resources.wav, base);
pushIndexedStringLines(lines, 'EXWAV', splitExWAVByWAVOrder(json).afterWAV, base);
pushIndexedStringLines(lines, 'BMP', json.resources.bmp, base);
pushIndexedNumberLines(lines, 'BPM', json.resources.bpm, base);
pushIndexedNumberLines(lines, 'STOP', json.resources.stop, base);
pushIndexedStringLines(lines, 'TEXT', json.resources.text, base);
// pomu's obsolete name for `#TEXTxx`, written back as the chart had it.
pushIndexedStringLines(lines, 'SONG', json.bms.songText, base);
}
function resolveJSONBase(json: BeMusicJSON): 36 | 62 {
return json.bms.base === 62 ? 62 : 36;
}
/** The `#EXWAVxx` declarations written before the `#WAVxx` lines and after them, so the file order keeps who wins. */
function splitExWAVByWAVOrder(json: BeMusicJSON): {
beforeWAV: Record<string, string>;
afterWAV: Record<string, string>;
} {
const beforeWAV: Record<string, string> = {};
const afterWAV: Record<string, string> = {};
for (const [key, value] of Object.entries(json.bms.exWAV)) {
const wav = json.resources.wav[key];
const exWAVWins = wav !== undefined && wav.length > 0 && json.bms.exWAVOverridden?.includes(key) !== true;
(exWAVWins ? afterWAV : beforeWAV)[key] = value;
}
return { beforeWAV, afterWAV };
}
function pushIndexedStringLines(
lines: string[],
command: string,
values: Record<string, string> | undefined,
base: 36 | 62 = 36,
): void {
const entries = Object.entries(values ?? {}).sort(([left], [right]) => left.localeCompare(right));
for (const [key, value] of entries) {
Eif (value.length > 0) {
lines.push(`#${command}${normalizeObjectKey(key, base)} ${value}`);
}
}
}
function pushIndexedNumberLines(
lines: string[],
command: string,
values: Record<string, number> | undefined,
base: 36 | 62 = 36,
): void {
const entries = Object.entries(values ?? {}).sort(([left], [right]) => left.localeCompare(right));
for (const [key, value] of entries) {
Eif (Number.isFinite(value)) {
lines.push(`#${command}${normalizeObjectKey(key, base)} ${formatNumber(value)}`);
}
}
}
function pushMeasureLines(lines: string[], json: BeMusicJSON, preservedObjectLines?: BMSObjectLineEntry[]): void {
if (preservedObjectLines) {
for (const objectLine of preservedObjectLines) {
Iif (typeof objectLine.measureLength === 'number' && objectLine.measureLength > 0) {
lines.push(`#${toMeasure(objectLine.measure)}02:${formatNumber(objectLine.measureLength)}`);
}
}
return;
}
const measures = [...json.measures]
.filter((measure) => measure.length > 0 && Math.abs(measure.length - 1) > 1e-9)
.sort((left, right) => left.index - right.index);
for (const measure of measures) {
lines.push(`#${toMeasure(measure.index)}02:${formatNumber(measure.length)}`);
}
}
function pushEventLines(
lines: string[],
json: BeMusicJSON,
maxResolution?: number,
preservedObjectLines?: BMSObjectLineEntry[],
): void {
if (preservedObjectLines) {
for (const objectLine of preservedObjectLines) {
const serialized = serializeBMSObjectLineEvents(
objectLine.measure,
objectLine.channel,
objectLine.events,
resolveJSONBase(json),
);
Eif (serialized) {
lines.push(serialized);
}
}
return;
}
const base = resolveJSONBase(json);
const grouped = groupEvents(sortEvents(json.events), base);
for (const group of grouped) {
const { measure, channel, events } = group;
const resolution = chooseResolution(events, maxResolution);
const cells = Array.from({ length: resolution }, () => '00');
const lineOrder = new Map<number, number>();
for (const event of events) {
const { numerator, denominator } = resolveEventFraction(event);
const scaled = Math.round((numerator * resolution) / denominator);
const index = Math.min(resolution - 1, Math.max(0, scaled));
const order = event.bmsLineOrder ?? -1;
if (order >= (lineOrder.get(index) ?? -1)) {
cells[index] = normalizeObjectKey(event.value, base);
if (order >= 0) lineOrder.set(index, order);
}
}
lines.push(`#${toMeasure(measure)}${channel}:${cells.join('')}`);
}
}
function resolvePreservedObjectLinesForOutput(
json: BeMusicJSON,
skipValidation: boolean,
): BMSObjectLineEntry[] | undefined {
const objectLines = json.preservation.bms.objectLines;
if (!Array.isArray(objectLines) || objectLines.length === 0) {
return undefined;
}
Iif (skipValidation) {
return objectLines;
}
return doPreservedObjectLinesMatchChart(json, objectLines) ? objectLines : undefined;
}
function doPreservedObjectLinesMatchChart(json: BeMusicJSON, objectLines: BMSObjectLineEntry[]): boolean {
const flattenedEvents: BeMusicEvent[] = [];
const preservedMeasureLengths = new Map<number, number>();
// Compare values under the chart's authored radix so a base-62 chart's lowercase IDs aren't folded to uppercase
// before the event comparison below — that would falsely trigger a mismatch and force the stringifier to regenerate
// object lines even when the preserved entries are still consistent.
const idBase = resolveBMSBase(json);
for (const objectLine of objectLines) {
Iif (typeof objectLine.measureLength === 'number' && objectLine.measureLength > 0) {
preservedMeasureLengths.set(Math.max(0, Math.floor(objectLine.measure)), objectLine.measureLength);
}
for (const event of objectLine.events) {
Iif (normalizeObjectKey(event.value, idBase) === '00') {
continue;
}
flattenedEvents.push({
measure: Math.max(0, Math.floor(objectLine.measure)),
channel: normalizeChannel(objectLine.channel),
position: event.position,
value: normalizeObjectKey(event.value, idBase),
...(event.bmson ? { bmson: event.bmson } : {}),
});
}
}
const sortedFlattenedEvents = sortEvents(flattenedEvents);
const sortedCurrentEvents = sortEvents(json.events);
if (sortedFlattenedEvents.length !== sortedCurrentEvents.length) {
return false;
}
for (let index = 0; index < sortedCurrentEvents.length; index += 1) {
Iif (compareEvents(sortedFlattenedEvents[index]!, sortedCurrentEvents[index]!) !== 0) {
return false;
}
Iif (!areEventBmsonExtensionsEqual(sortedFlattenedEvents[index]!.bmson, sortedCurrentEvents[index]!.bmson)) {
return false;
}
}
const currentMeasureLengths = new Map<number, number>();
for (const measure of json.measures) {
currentMeasureLengths.set(Math.max(0, Math.floor(measure.index)), measure.length);
}
Iif (preservedMeasureLengths.size !== currentMeasureLengths.size) {
return false;
}
for (const [measure, length] of preservedMeasureLengths) {
if (currentMeasureLengths.get(measure) !== length) {
return false;
}
}
return true;
}
function pushControlFlowLines(lines: string[], json: BeMusicJSON): void {
const base = resolveJSONBase(json);
for (const entry of json.bms.controlFlow) {
if (entry.kind === 'directive') {
lines.push(entry.value ? `#${entry.command} ${entry.value}` : `#${entry.command}`);
continue;
}
if (entry.kind === 'header') {
// This layout writes the top-level headers first, so a branch line that a later top-level line overrides would
// win again on re-parse. It never takes effect, so it is left out.
if (entry.overriddenByLaterHeader === true) {
continue;
}
// Use the case-preserved `commandRaw` when present so e.g. `#WAV0a` survives the round-trip on a `#BASE 62`
// chart.
const commandText = entry.commandRaw ?? entry.command;
lines.push(entry.value.length > 0 ? `#${commandText} ${entry.value}` : `#${commandText}`);
continue;
}
if (typeof entry.measureLength === 'number' && entry.measureLength > 0) {
lines.push(`#${toMeasure(entry.measure)}${normalizeChannel(entry.channel)}:${formatNumber(entry.measureLength)}`);
continue;
}
const serialized = serializeControlFlowObjectEvents(entry.measure, entry.channel, entry.events, base);
Eif (serialized) {
lines.push(serialized);
}
}
}
function pushBMSSectionComment(lines: string[], section: string): void {
if (lines.length > 0 && lines[lines.length - 1] !== '') {
lines.push('');
}
lines.push(`*---------------------- ${section} FIELD`);
lines.push('');
}
function serializeControlFlowObjectEvents(
measure: number,
channel: string,
events: BeMusicEvent[],
base: 36 | 62 = 36,
): string | undefined {
return serializeBMSObjectLineEvents(measure, channel, events, base);
}
function serializeBMSObjectLineEvents(
measure: number,
channel: string,
events: BeMusicEvent[],
base: 36 | 62 = 36,
): string | undefined {
const normalizedChannel = normalizeChannel(channel);
const lineEvents: BeMusicEvent[] = [];
for (const event of sortEvents(events)) {
Iif (event.measure !== measure || normalizeChannel(event.channel) !== normalizedChannel) {
continue;
}
const value = normalizeObjectKey(event.value, base);
if (value === '00') {
continue;
}
lineEvents.push({
...event,
measure,
channel: normalizedChannel,
value,
});
}
Iif (lineEvents.length === 0) {
return undefined;
}
const resolution = chooseResolution(lineEvents);
const cells = Array.from({ length: resolution }, () => '00');
for (const event of lineEvents) {
const { numerator, denominator } = resolveEventFraction(event);
const scaled = Math.round((numerator * resolution) / denominator);
const index = Math.min(resolution - 1, Math.max(0, scaled));
cells[index] = normalizeObjectKey(event.value, base);
}
return `#${toMeasure(measure)}${normalizedChannel}:${cells.join('')}`;
}
interface GroupedEventLine {
measure: number;
channel: string;
events: BeMusicEvent[];
}
function groupEvents(events: BeMusicEvent[], base: 36 | 62 = 36): GroupedEventLine[] {
const groupedByMeasure = new Map<number, Map<string, BeMusicEvent[]>>();
for (const event of events) {
const measure = Math.max(0, Math.floor(event.measure));
const channel = normalizeChannel(event.channel);
const { numerator, denominator } = resolveEventFraction(event);
const groupedByChannel = groupedByMeasure.get(measure) ?? new Map<string, BeMusicEvent[]>();
if (!groupedByMeasure.has(measure)) {
groupedByMeasure.set(measure, groupedByChannel);
}
const slot = groupedByChannel.get(channel) ?? [];
slot.push({
measure,
channel,
position: [numerator, denominator],
value: normalizeObjectKey(event.value, base),
...(event.bmsLineOrder !== undefined ? { bmsLineOrder: event.bmsLineOrder } : {}),
});
groupedByChannel.set(channel, slot);
}
const result: GroupedEventLine[] = [];
for (const [measure, groupedByChannel] of groupedByMeasure) {
for (const [channel, slot] of groupedByChannel) {
result.push({
measure,
channel,
events: slot,
});
}
}
return result;
}
function chooseResolution(events: BeMusicEvent[], maxResolution?: number): number {
let resolution = 1;
for (const event of events) {
const { denominator } = resolveEventFraction(event);
resolution = lcm(resolution, denominator);
if (typeof maxResolution === 'number' && resolution >= maxResolution) {
return maxResolution;
}
}
return Math.max(1, resolution);
}
function resolveEventFraction(event: BeMusicEvent): { numerator: number; denominator: number } {
const denominator = normalizePositiveInt(event.position[1], 1);
const numerator = normalizeFractionNumerator(event.position[0], denominator, 0);
return reduceFraction(numerator, denominator);
}
function reduceFraction(numerator: number, denominator: number): { numerator: number; denominator: number } {
if (numerator <= 0) {
return { numerator: 0, denominator: 1 };
}
const divisor = gcd(numerator, denominator);
return {
numerator: Math.floor(numerator / divisor),
denominator: Math.floor(denominator / divisor),
};
}
function toMeasure(measure: number): string {
return normalizeNonNegativeInt(measure).toString(10).padStart(3, '0').slice(-3);
}
function formatNumber(value: number): string {
return Number.isInteger(value) ? String(value) : value.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
}
function isDedicatedBMSExtensionCommand(command: string): boolean {
const upper = command.toUpperCase();
if (
upper === 'PREVIEW' ||
upper === 'LNTYPE' ||
upper === 'LNMODE' ||
upper === 'LNOBJ' ||
upper === 'VOLWAV' ||
upper === 'DEFEXRANK' ||
upper === 'PLAYER' ||
upper === 'PATH_WAV' ||
upper === 'BASEBPM' ||
upper === 'STP' ||
upper === 'OPTION' ||
upper === 'WAVCMD' ||
upper === 'POORBGA' ||
upper === 'VIDEOFILE' ||
upper === 'MIDIFILE' ||
upper === 'MATERIALS' ||
upper === 'DIVIDEPROP' ||
upper === 'CHARSET'
) {
return true;
}
if (/^EXRANK[0-9A-Z]{2}$/.test(upper) || /^ARGB[0-9A-Z]{2}$/.test(upper)) {
return true;
}
if (
/^CHANGEOPTION[0-9A-Z]{2}$/.test(upper) ||
/^EXWAV[0-9A-Z]{2}$/.test(upper) ||
/^EXBMP[0-9A-Z]{2}$/.test(upper) ||
/^BGA[0-9A-Z]{2}$/.test(upper) ||
/^SCROLL[0-9A-Z]{2}$/.test(upper) ||
/^SPEED[0-9A-Z]{2}$/.test(upper) ||
/^SWBGA[0-9A-Z]{2}$/.test(upper)
) {
return true;
}
return false;
}
/** The largest damage a two-character base-36 mine value (`ZZ`) can carry. */
const MAX_BMS_MINE_DAMAGE = 36 * 36 - 1;
/**
* Rewrites the parts of a chart that BMS spells differently before the canonical BMS output — a no-op for an ordinary
* BMS chart. Mainly for a bmson-sourced chart:
*
* - A long note (`bmson.l > 0` on `1x` / `2x`) becomes a `#LNTYPE 1` pair on `5x` / `6x`: a start and an end object
* carrying the note's own WAV. Unlike `#LNOBJ`, this needs no shared end-object slot, keeps every long note on an
* explicit channel of its own, and pairs only with itself, so a short note just before an end can never be taken
* for its start. `#LNTYPE 1` is written when the chart has no `#LNTYPE`.
* - `#LNMODE` comes from the long notes' type (`t`, else `info.ln_type`) when they all agree, else from `info.ln_type`;
* per-note types that disagree with it cannot be written in BMS and are lost.
* - A mine's object value becomes its damage in base 36 (`bmson.damage`, or the default 0 for a bmson mine
* without one), rounded to an integer and clamped to `01`..`ZZ` — `00` is no object at all, so a 0 damage mine
* becomes `01`. The first mine's sample becomes `#WAV00`, the BMS explosion sound, when the chart has none.
* - bmson `judge_rank` shares `#DEFEXRANK`'s unit, so it is written as `#DEFEXRANK` (when positive) instead of an
* out-of-range `#RANK`.
* - bmson `total` is a percentage of the player's default TOTAL, which depends on the note count and the player, so it
* is not written as an absolute `#TOTAL`; the BMS default applies, which equals bmson's default `100`.
*/
function convertChartForBMSOutput(json: BeMusicJSON, report?: ChartExportDiagnosticHandler): BeMusicJSON {
const isBmsonSource = json.sourceFormat === 'bmson';
const events: BeMusicEvent[] = [];
const longNoteTypes: Array<number | undefined> = [];
let mineSample: string | undefined;
const chartLNType = json.bmson.info.lnType;
const endPositionResolver = createBMSPositionResolver(json);
let changed = false;
// Mines whose damage BMS cannot hold as it is: a base-36 pair is a whole number from 1 to 1295.
let adjustedMines = 0;
let defaultedMines = 0;
// bmson fields BMS has no form for: `up` end keysounds and `c` sound continuations.
let endSounds = 0;
let continuations = 0;
for (const event of json.events) {
const channel = normalizeChannel(event.channel);
if (isBmsonSource && event.bmson?.up === true && isPlayableChannel(channel)) {
endSounds += 1;
changed = true;
continue;
}
if (isBmsonSource && event.bmson?.c === true) continuations += 1;
const length = event.bmson?.l;
if (isPlayableChannel(channel) && typeof length === 'number' && Number.isFinite(length) && length > 0) {
const longNoteChannel = `${channel[0] === '1' ? '5' : '6'}${channel[1]}`;
events.push({ measure: event.measure, position: event.position, channel: longNoteChannel, value: event.value });
events.push({ ...endPositionResolver(event, length), channel: longNoteChannel, value: event.value });
const type = event.bmson?.t;
longNoteTypes.push(typeof type === 'number' && BMSON_LONG_NOTE_TYPES.has(type) ? type : chartLNType);
changed = true;
continue;
}
if (isLandmineChannel(channel)) {
const damage = event.bmson?.damage;
const hasDamage = typeof damage === 'number' && Number.isFinite(damage) && damage >= 0;
Eif (hasDamage || isBmsonSource) {
mineSample ??= json.resources.wav[normalizeObjectKey(event.value, resolveBMSBase(json))];
// bmson's default damage for a mine without one is 0, which BMS cannot hold: it is written as the least, 1.
const value = Math.min(MAX_BMS_MINE_DAMAGE, Math.max(1, Math.round(hasDamage ? damage : 0)));
if (!hasDamage) defaultedMines += 1;
else if (value !== damage) adjustedMines += 1;
events.push({ measure: event.measure, position: event.position, channel, value: intToBase36(value, 2) });
changed = true;
continue;
}
}
events.push(event);
}
if (!changed && !isBmsonSource) {
return json;
}
if (endSounds > 0)
report?.({
code: 'ln-end-sound',
message: `${endSounds} long-note end keysound(s) (up) are left out: BMS has no end sound, so a long note ends silently.`,
});
if (continuations > 0)
report?.({
code: 'sound-continuation',
message: `${continuations} note(s) continue their sound slice (c), which BMS cannot express: each plays its sample from the start.`,
});
if (adjustedMines > 0)
report?.({
code: 'mine-damage',
message: `${adjustedMines} mine(s) have a damage BMS cannot hold; each was rounded to a whole number from 1 to ${MAX_BMS_MINE_DAMAGE} (a damage of 0 becomes 1).`,
});
if (defaultedMines > 0)
report?.({
code: 'mine-damage',
message: `${defaultedMines} mine(s) have no damage, which bmson reads as 0; BMS cannot hold 0, so each was written with the least damage, 1.`,
});
const bms = { ...json.bms };
if (longNoteTypes.length > 0 && bms.lnType === undefined) {
bms.lnType = 1;
}
Eif (bms.lnMode === undefined) {
const uniformType = longNoteTypes.length > 0 && longNoteTypes.every((type) => type === longNoteTypes[0]);
// `#LNMODE` is one mode for the whole chart: long notes of different types all take the chart's.
if (longNoteTypes.length > 0 && !uniformType)
report?.({
code: 'long-note-mode',
message:
'The long notes have different types (LN, CN, HCN), which BMS cannot mark per note; every long note takes the chart-wide mode.',
});
const lnMode = uniformType ? longNoteTypes[0] : chartLNType;
if (typeof lnMode === 'number' && BMSON_LONG_NOTE_TYPES.has(lnMode)) {
bms.lnMode = lnMode;
}
}
const metadata = { ...json.metadata };
Eif (isBmsonSource) {
const judgeRank = json.bmson.info.judgeRank ?? json.metadata.rank;
if (bms.defExRank === undefined && typeof judgeRank === 'number' && Number.isFinite(judgeRank) && judgeRank > 0) {
bms.defExRank = judgeRank;
}
const total = json.bmson.info.total ?? json.metadata.total;
// bmson's default is 100 % of the player's default TOTAL, which is what a BMS chart without `#TOTAL` gets.
if (typeof total === 'number' && Number.isFinite(total) && total !== 100)
report?.({
code: 'total',
message: `bmson total ${total} is a percentage of the player's default TOTAL, which BMS #TOTAL cannot express; no #TOTAL is written and the player's default applies.`,
});
delete metadata.rank;
delete metadata.total;
}
const wav = { ...json.resources.wav };
if (mineSample && !wav[BMS_MINE_SAMPLE_KEY]) {
wav[BMS_MINE_SAMPLE_KEY] = mineSample;
}
// Native bmson BGA becomes BMS image resources and 04 / 07 / 06 objects (#840).
const bga = isBmsonSource ? convertBmsonBGAToBMS(json, report) : undefined;
const bmp = bga ? { ...json.resources.bmp, ...bga.bmp } : json.resources.bmp;
if (bga) events.push(...bga.events);
return { ...json, metadata, bms, resources: { ...json.resources, wav, bmp }, events };
}
/**
* Places the end of a bmson long note: `l` pulses (at the chart's bmson resolution) after `event`, as a measure and an
* exact pulse fraction of that measure, so a long note crossing measures or uneven `lines` ends where it did.
*/
function createBMSPositionResolver(
json: BeMusicJSON,
): (event: BeMusicEvent, pulses: number) => Pick<BeMusicEvent, 'measure' | 'position'> {
const beatResolver = createBeatResolver(json);
const resolution = normalizePositiveInt(json.bmson.info.resolution ?? 240, 240);
const measureStartPulse = (measure: number): number => Math.round(beatResolver.measureToBeat(measure) * resolution);
return (event, pulses) => {
const endPulse = Math.round(beatResolver.eventToBeat(event) * resolution) + Math.round(pulses);
let measure = Math.max(0, Math.floor(event.measure));
while (measureStartPulse(measure + 1) <= endPulse) {
measure += 1;
}
const start = measureStartPulse(measure);
const measurePulses = Math.max(1, measureStartPulse(measure + 1) - start);
return { measure, position: [endPulse - start, measurePulses] };
};
}
|