All files / chart-model/src long-notes.ts

96.64% Statements 173/179
83.83% Branches 83/99
100% Functions 18/18
96.61% Lines 171/177

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                                                                                                                60180x 60180x 87x             60093x 60093x 33137x             26956x 26956x   26956x     60180x       3713x                     60199x 89x             60110x   60110x 30247x   60110x 31181x             28929x 28929x 28929x 28929x 28929x 28929x 28929x 28929x   28929x 28929x 755284x 755284x 91506x   663778x 663778x 4931x 4931x     658847x 658847x 658847x 135824x 135824x 118187x 118187x 118187x   135824x 135824x     523023x     28929x                                 28929x 28929x 28929x 755284x 72105x 72105x 72105x 47886x 24219x 19169x 19169x   5050x     28929x             26594x 26594x 26594x   26594x 99316x 99316x 99316x 42267x 42267x 42267x 42267x 42267x   57049x           57049x 57049x     26594x       28929x 28929x 755284x         28929x             60093x     60093x 1036656x   60093x 101037x 101037x 101037x             60093x       28929x 28929x 755284x 755284x 705937x   49347x   28929x       49347x       713125x 713125x 713125x 713125x             362x 362x 362x   362x       556x 1721x 1721x 556x           556x 556x 556x     1165x 1030x 1030x 1030x     135x 135x 135x 135x 135x     135x           135x 135x     556x 556x 556x 556x 556x         362x 425x 425x                     362x               26956x 26887x   69x 55x   14x       14x     14x 14x 33x     18x 18x 5x     15x   28x 28x       9x           376x 376x 1756x 1756x 1186x 1186x   570x   376x       1184x 1076x             108x       108x 108x 108x 108x   108x       691x 691x 691x 691x 691x 294x   397x    
import {
  normalizeChannel,
  normalizeObjectKey,
  resolveBMSBase,
  type BeMusicEvent,
  type BeMusicJSON,
} from '@be-music/chart-source';
import {
  createBeatResolver,
  normalizePositionDenominator,
  normalizePositionNumerator,
  sortEvents,
  type BeatResolver,
} from './beats.ts';
import { isPlayableNormalizedChannel, mapBMSLongNoteNormalizedChannelToPlayable } from './channels.ts';
 
export interface BMSLongNote {
  event: BeMusicEvent;
  sourceChannel: string;
  channel: string;
  beat: number;
  endBeat?: number;
  /**
   * The object the tail is read from: the closing object of an `#LNTYPE 1` pair, or the last object of an `#LNTYPE 2`
   * run, whose tail is one cell after it. Set together with {@link endBeat}.
   */
  endEvent?: BeMusicEvent;
}
 
export interface BMSLongNoteResolution {
  notes: BMSLongNote[];
  suppressedTriggerEvents: Set<BeMusicEvent>;
  /** The `#LNTYPE` the `5x` / `6x` objects were read with: the chart's own, else inferred or 1. */
  lnType: 1 | 2;
}
 
export interface ResolveBMSLongNotesOptions {
  inferLNTypeWhenMissing?: boolean;
}
 
interface ResolvedBMSLongNoteEvent {
  event: BeMusicEvent;
  sourceChannel: string;
  channel: string;
  normalizedValue: string;
}
 
interface NormalizedChartEvent {
  event: BeMusicEvent;
  normalizedChannel: string;
}
 
export function resolveBMSLongNotes(
  json: BeMusicJSON,
  options: ResolveBMSLongNotesOptions = {},
): BMSLongNoteResolution {
  const declaredLNType = json.bms.lnType === 1 || json.bms.lnType === 2 ? json.bms.lnType : 1;
  if (json.sourceFormat !== 'bms') {
    return {
      notes: [],
      suppressedTriggerEvents: new Set(),
      lnType: declaredLNType,
    };
  }
 
  const longNoteEvents = prepareResolvedBMSLongNoteEvents(json.events, resolveBMSBase(json));
  if (longNoteEvents.length === 0) {
    return {
      notes: [],
      suppressedTriggerEvents: new Set(),
      lnType: declaredLNType,
    };
  }
 
  const beatResolver = createBeatResolver(json);
  const lnType = resolveBMSLongNoteType(json, longNoteEvents, options);
  const resolved =
    lnType === 2
      ? resolveBMSLongNotesType2(longNoteEvents, beatResolver)
      : resolveBMSLongNotesType1(longNoteEvents, beatResolver);
  return { ...resolved, lnType };
}
 
export function collectLNOBJEndEvents(json: BeMusicJSON): Set<BeMusicEvent> {
  return resolveLNOBJLongNotes(json).endEvents;
}
 
export interface LNOBJLongNoteResolution {
  startToEndBeat: Map<BeMusicEvent, number>;
  /** The end object each long-note start pairs with (the same pairs as {@link startToEndBeat}). */
  startToEndEvent: Map<BeMusicEvent, BeMusicEvent>;
  endEvents: Set<BeMusicEvent>;
}
 
export function resolveLNOBJLongNotes(json: BeMusicJSON): LNOBJLongNoteResolution {
  if (json.sourceFormat !== 'bms') {
    return {
      startToEndBeat: new Map(),
      startToEndEvent: new Map(),
      endEvents: new Set(),
    };
  }
 
  const idBase = resolveBMSBase(json);
  let lastLNOBJ: string | undefined;
  for (const value of json.bms.lnObjs ?? []) {
    Eif (typeof value === 'string' && value.length > 0) lastLNOBJ = value;
  }
  if (lastLNOBJ === undefined) {
    return {
      startToEndBeat: new Map(),
      startToEndEvent: new Map(),
      endEvents: new Set(),
    };
  }
 
  const lnObjValue = normalizeObjectKey(lastLNOBJ, idBase);
  const beatResolver = createBeatResolver(json);
  const preparedEvents = prepareNormalizedChartEvents(json.events);
  const legacyLongNoteTicks = collectLegacyLongNoteTickKeysFromPreparedEvents(preparedEvents);
  const pendingStartByChannel = new Map<string, { event: BeMusicEvent; beat: number }>();
  const startToEndBeat = new Map<BeMusicEvent, number>();
  const startToEndEvent = new Map<BeMusicEvent, BeMusicEvent>();
  const endEvents = new Set<BeMusicEvent>();
 
  const overwritten = collectOverwrittenBMSObjects(preparedEvents, beatResolver);
  for (const item of preparedEvents) {
    const { event, normalizedChannel } = item;
    if (!isPlayableNormalizedChannel(normalizedChannel) || overwritten.has(event)) {
      continue;
    }
    const tickKey = createEventTickKey(event);
    if (legacyLongNoteTicks.has(`${normalizedChannel}:${tickKey}`)) {
      pendingStartByChannel.delete(normalizedChannel);
      continue;
    }
 
    const beat = beatResolver.eventToBeat(event);
    const normalizedValue = normalizeObjectKey(event.value, idBase);
    if (normalizedValue === lnObjValue) {
      const start = pendingStartByChannel.get(normalizedChannel);
      if (start && beat > start.beat) {
        startToEndBeat.set(start.event, beat);
        startToEndEvent.set(start.event, event);
        endEvents.add(event);
      }
      pendingStartByChannel.delete(normalizedChannel);
      continue;
    }
 
    pendingStartByChannel.set(normalizedChannel, { event, beat });
  }
 
  return {
    startToEndBeat,
    startToEndEvent,
    endEvents,
  };
}
 
/**
 * The playable objects a later line of the same measure and channel overwrites at the same beat (the later nonzero
 * object wins, as cmds and beatoraja read duplicate lines). `#LNOBJ` pairs only the objects that remain, the same ones
 * the notes are chosen from (`selectBMSNormalObjects`), so an overwritten end object cannot end a note nor an
 * overwritten start begin one. IR without line order (`bmsLineOrder`) overwrites nothing, as before line order was kept.
 */
function collectOverwrittenBMSObjects(
  events: readonly NormalizedChartEvent[],
  beatResolver: BeatResolver,
): Set<BeMusicEvent> {
  const overwritten = new Set<BeMusicEvent>();
  const winners = new Map<string, BeMusicEvent>();
  for (const { event, normalizedChannel } of events) {
    if (event.bmsLineOrder === undefined || !isPlayableNormalizedChannel(normalizedChannel)) continue;
    const key = `${normalizedChannel}:${beatResolver.eventToBeat(event)}`;
    const winner = winners.get(key);
    if (winner === undefined) {
      winners.set(key, event);
    } else if (event.bmsLineOrder > winner.bmsLineOrder!) {
      overwritten.add(winner);
      winners.set(key, event);
    } else {
      overwritten.add(event);
    }
  }
  return overwritten;
}
 
function resolveBMSLongNotesType1(
  events: ResolvedBMSLongNoteEvent[],
  beatResolver: BeatResolver,
): Omit<BMSLongNoteResolution, 'lnType'> {
  const notes: BMSLongNote[] = [];
  const suppressedTriggerEvents = new Set<BeMusicEvent>();
  const pendingByChannel = new Map<string, BMSLongNote>();
 
  for (const item of events) {
    const beat = beatResolver.eventToBeat(item.event);
    const pending = pendingByChannel.get(item.sourceChannel);
    if (pending && beat > pending.beat) {
      pending.endBeat = beat;
      pending.endEvent = item.event;
      suppressedTriggerEvents.add(item.event);
      pendingByChannel.delete(item.sourceChannel);
      continue;
    }
    const note: BMSLongNote = {
      event: item.event,
      sourceChannel: item.sourceChannel,
      channel: item.channel,
      beat,
    };
    notes.push(note);
    pendingByChannel.set(item.sourceChannel, note);
  }
 
  return { notes, suppressedTriggerEvents };
}
 
function prepareNormalizedChartEvents(events: ReadonlyArray<BeMusicEvent>): NormalizedChartEvent[] {
  const prepared: NormalizedChartEvent[] = [];
  for (const event of sortEvents(events as BeMusicEvent[])) {
    prepared.push({
      event,
      normalizedChannel: normalizeChannel(event.channel),
    });
  }
  return prepared;
}
 
function prepareResolvedBMSLongNoteEvents(
  events: ReadonlyArray<BeMusicEvent>,
  base: 36 | 62 = 36,
): ResolvedBMSLongNoteEvent[] {
  const prepared: ResolvedBMSLongNoteEvent[] = [];
  // Only the `5x` / `6x` objects are sorted, not the whole chart: the sort is stable, so they come out in the same order
  // as when picked from the sorted chart.
  const longNoteEvents = events.filter(
    (event) => mapBMSLongNoteNormalizedChannelToPlayable(normalizeChannel(event.channel)) !== undefined,
  );
  for (const event of sortEvents(longNoteEvents)) {
    const sourceChannel = normalizeChannel(event.channel);
    const mapped = mapBMSLongNoteNormalizedChannelToPlayable(sourceChannel)!;
    prepared.push({
      event,
      sourceChannel,
      channel: mapped,
      normalizedValue: normalizeObjectKey(event.value, base),
    });
  }
  return prepared;
}
 
function collectLegacyLongNoteTickKeysFromPreparedEvents(events: ReadonlyArray<NormalizedChartEvent>): Set<string> {
  const keys = new Set<string>();
  for (const item of events) {
    const playableChannel = mapBMSLongNoteNormalizedChannelToPlayable(item.normalizedChannel);
    if (!playableChannel) {
      continue;
    }
    keys.add(createNormalizedChannelTickKey(playableChannel, item.event));
  }
  return keys;
}
 
function createNormalizedChannelTickKey(normalizedChannel: string, event: BeMusicEvent): string {
  return `${normalizedChannel}:${createEventTickKey(event)}`;
}
 
function createEventTickKey(event: BeMusicEvent): string {
  const measure = Math.max(0, Math.floor(event.measure));
  const denominator = normalizePositionDenominator(event.position[1]);
  const numerator = normalizePositionNumerator(event.position[0], denominator);
  return `${measure}:${numerator}/${denominator}`;
}
 
function resolveBMSLongNotesType2(
  events: ResolvedBMSLongNoteEvent[],
  beatResolver: BeatResolver,
): Omit<BMSLongNoteResolution, 'lnType'> {
  const notes: BMSLongNote[] = [];
  const suppressedTriggerEvents = new Set<BeMusicEvent>();
  const eventsByChannel = groupResolvedLongNoteEventsBySourceChannel(events);
 
  for (const channelEvents of eventsByChannel.values()) {
    let runNote: BMSLongNote | undefined;
    let previousEvent: BeMusicEvent | undefined;
 
    for (const item of channelEvents) {
      const beat = beatResolver.eventToBeat(item.event);
      if (!runNote) {
        runNote = {
          event: item.event,
          sourceChannel: item.sourceChannel,
          channel: item.channel,
          beat,
        };
        notes.push(runNote);
        previousEvent = item.event;
        continue;
      }
 
      if (previousEvent && isBMSLongNoteType2Continuation(previousEvent, item.event)) {
        suppressedTriggerEvents.add(item.event);
        previousEvent = item.event;
        continue;
      }
 
      Eif (previousEvent) {
        const endBeat = resolveBMSLongNoteType2SegmentEndBeat(previousEvent, beatResolver);
        Eif (endBeat > runNote.beat) {
          runNote.endBeat = endBeat;
          runNote.endEvent = previousEvent;
        }
      }
      runNote = {
        event: item.event,
        sourceChannel: item.sourceChannel,
        channel: item.channel,
        beat,
      };
      notes.push(runNote);
      previousEvent = item.event;
    }
 
    Eif (runNote && previousEvent) {
      const endBeat = resolveBMSLongNoteType2SegmentEndBeat(previousEvent, beatResolver);
      Eif (endBeat > runNote.beat) {
        runNote.endBeat = endBeat;
        runNote.endEvent = previousEvent;
      }
    }
  }
 
  notes.sort((left, right) => {
    Eif (left.beat !== right.beat) {
      return left.beat - right.beat;
    }
    if (left.channel !== right.channel) {
      return left.channel < right.channel ? -1 : 1;
    }
    if (left.event.value !== right.event.value) {
      return left.event.value < right.event.value ? -1 : 1;
    }
    return 0;
  });
 
  return { notes, suppressedTriggerEvents };
}
 
function resolveBMSLongNoteType(
  json: BeMusicJSON,
  events: ResolvedBMSLongNoteEvent[],
  options: ResolveBMSLongNotesOptions,
): 1 | 2 {
  if (json.bms.lnType === 1 || json.bms.lnType === 2) {
    return json.bms.lnType;
  }
  if (options.inferLNTypeWhenMissing !== true) {
    return 1;
  }
  return inferBMSLongNoteType(events);
}
 
function inferBMSLongNoteType(events: ResolvedBMSLongNoteEvent[]): 1 | 2 {
  for (const channelEvents of groupResolvedLongNoteEventsBySourceChannel(events).values()) {
    let previous: BeMusicEvent | undefined;
    let previousValue: string | undefined;
    let continuationCount = 0;
    for (const item of channelEvents) {
      if (previous && previousValue === item.normalizedValue && isBMSLongNoteType2Continuation(previous, item.event)) {
        // A single same-value continuation is ambiguous because legacy LNTYPE=1 charts also use same-value pairs for
        // their start/end markers.
        continuationCount += 1;
        if (continuationCount >= 2) {
          return 2;
        }
      } else {
        continuationCount = 0;
      }
      previous = item.event;
      previousValue = item.normalizedValue;
    }
  }
 
  return 1;
}
 
function groupResolvedLongNoteEventsBySourceChannel(
  events: ReadonlyArray<ResolvedBMSLongNoteEvent>,
): Map<string, ResolvedBMSLongNoteEvent[]> {
  const grouped = new Map<string, ResolvedBMSLongNoteEvent[]>();
  for (const item of events) {
    const bucket = grouped.get(item.sourceChannel);
    if (bucket) {
      bucket.push(item);
      continue;
    }
    grouped.set(item.sourceChannel, [item]);
  }
  return grouped;
}
 
function isBMSLongNoteType2Continuation(previous: BeMusicEvent, current: BeMusicEvent): boolean {
  if (current.measure === previous.measure) {
    return (
      current.position[1] === previous.position[1] &&
      normalizePositionNumerator(current.position[0], normalizePositionDenominator(current.position[1])) ===
        normalizePositionNumerator(previous.position[0], normalizePositionDenominator(previous.position[1])) + 1
    );
  }
 
  Iif (current.measure !== previous.measure + 1) {
    return false;
  }
 
  const previousDenominator = normalizePositionDenominator(previous.position[1]);
  const previousNumerator = normalizePositionNumerator(previous.position[0], previousDenominator);
  const currentDenominator = normalizePositionDenominator(current.position[1]);
  const currentNumerator = normalizePositionNumerator(current.position[0], currentDenominator);
 
  return previousNumerator + 1 === previousDenominator && currentNumerator === 0;
}
 
function resolveBMSLongNoteType2SegmentEndBeat(event: BeMusicEvent, beatResolver: BeatResolver): number {
  const measure = Math.max(0, Math.floor(event.measure));
  const denominator = normalizePositionDenominator(event.position[1]);
  const numerator = normalizePositionNumerator(event.position[0], denominator);
  const nextNumerator = numerator + 1;
  if (nextNumerator >= denominator) {
    return beatResolver.measureToBeat(measure + 1, 0);
  }
  return beatResolver.measureToBeat(measure, nextNumerator / denominator);
}