All files / player-skin-sdk/src chart-stats.ts

89.85% Statements 62/69
79.66% Branches 47/59
100% Functions 10/10
94.73% Lines 54/57

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                                                  122x       14x 14x 13x 13x 13x       13x 13x 13x 13x 13x 13x 13x 13x   13x 13x 68x   68x   13x 13x 13x   14x   14x 14x 14x   13x 13x       13x         13x     122x               13x 13x 13x 2x   11x 11x 11x 13x         2x         4x 4x         4x 4x 4x 3x         4x 4x 4x 4x 4x 4x                       1x 1x                   4x    
import type { BeMusicJSON } from '@be-music/chart-source';
import { isHeldLongNote, resolveChart, resolveChartPlayVariant } from '@be-music/chart-model';
import type { LibraryChart } from './chart.ts';
 
/**
 * What a player wants to know about a chart before starting it, beyond its title and level: how long it runs, the
 * tempo range it travels (soflan), and the gimmicks it carries (long notes, mines, stops).
 */
export interface ChartStats {
  /** Seconds from the chart's start to the last playable note's end. */
  lengthSeconds: number;
  minBPM: number;
  maxBPM: number;
  longNotes: number;
  mines: number;
  /** Whether the chart has STOP sequences. */
  stops: boolean;
  /**
   * The judge rank as players read it: `VERY HARD` … `VERY EASY` for `#RANK 0`–`4`, the `#DEFEXRANK` / bmson
   * `judge_rank` value (`120`, `100` …) when the chart sets one, `NORMAL` when it sets neither (bmson: `100`), and
   * `RANDOM` when `#EXRANKxx` changes it mid-chart.
   */
  judgeRank: string;
}
 
const STATS = new WeakMap<BeMusicJSON, ChartStats>();
 
/** {@link ChartStats} for a song, computed once per chart (the select screen asks every frame). */
export function resolveChartStats(chartEntry: Pick<LibraryChart, 'chart' | 'bpm'>): ChartStats {
  const cached = STATS.get(chartEntry.chart);
  if (cached) return cached;
  const stats = computeChartStats(chartEntry.chart, chartEntry.bpm);
  STATS.set(chartEntry.chart, stats);
  return stats;
}
 
function computeChartStats(chart: BeMusicJSON, fallbackBPM: number | undefined): ChartStats {
  let lengthSeconds = 0;
  let longNotes = 0;
  let mines = 0;
  let minBPM = Number.POSITIVE_INFINITY;
  let maxBPM = 0;
  let stops = false;
  let rankChanges = false;
  try {
    // The song list sees the chart before any `#RANDOM` draw: only its unconditional content counts.
    const resolved = resolveChart(chart, { inferBmsLNTypeWhenMissing: false });
    for (const note of resolved.notes) {
      lengthSeconds = Math.max(lengthSeconds, note.endSeconds ?? note.seconds);
      // A FREE ZONE note's fixed tail is not a long note.
      if (isHeldLongNote(note)) longNotes += 1;
    }
    mines = resolved.mines.length;
    const timing = resolved.timing;
    for (const point of timing.tempoPoints) {
      // Zero / negative tempos are stop-like gimmicks, not a tempo the player reads.
      Iif (!(point.bpm > 0) || !Number.isFinite(point.bpm)) continue;
      // Only tempos in effect before the last note count — a closing tempo change after it never plays.
      Iif (point.seconds > lengthSeconds && minBPM !== Number.POSITIVE_INFINITY) continue;
      minBPM = Math.min(minBPM, point.bpm);
      maxBPM = Math.max(maxBPM, point.bpm);
    }
    stops = timing.stopPoints.some((stop) => stop.seconds > 0 && stop.seconds <= lengthSeconds);
    rankChanges = resolved.judgeRank.changes.length > 0;
  } catch {
    // A chart the timing pass can't read still lists; it just shows no extra facts.
  }
  Iif (minBPM === Number.POSITIVE_INFINITY) {
    const bpm = fallbackBPM !== undefined && fallbackBPM > 0 ? fallbackBPM : 0;
    minBPM = bpm;
    maxBPM = bpm;
  }
  return { lengthSeconds, minBPM, maxBPM, longNotes, mines, stops, judgeRank: judgeRankLabel(chart, rankChanges) };
}
 
const JUDGE_RANK_NAMES = ['VERY HARD', 'HARD', 'NORMAL', 'EASY', 'VERY EASY'] as const;
 
/**
 * {@link ChartStats.judgeRank}. The same rules as the player's song screens (`resolveDisplayedJudgeRankLabel` in
 * `@be-music/player-engine`'s `utils.ts`): a positive `#DEFEXRANK` / bmson `judge_rank` wins, then `#RANK` 0–4 (truncated),
 * then the format's default.
 */
function judgeRankLabel(chart: BeMusicJSON, changes: boolean): string {
  Iif (changes) return 'RANDOM';
  const exRank = chart.sourceFormat === 'bmson' ? chart.bmson.info.judgeRank : chart.bms.defExRank;
  if (typeof exRank === 'number' && Number.isFinite(exRank) && exRank > 0) {
    return Number.isInteger(exRank) && exRank <= 4 ? JUDGE_RANK_NAMES[exRank]! : formatRankValue(exRank);
  }
  Iif (chart.sourceFormat === 'bmson') return '100';
  const rank = chart.metadata.rank;
  const truncated = typeof rank === 'number' && Number.isFinite(rank) ? Math.trunc(rank) : Number.NaN;
  return truncated >= 0 && truncated <= 4 ? JUDGE_RANK_NAMES[truncated]! : 'NORMAL';
}
 
/** `120`, `99.5`: an `#DEFEXRANK` value with up to two decimals and no trailing zeros. */
function formatRankValue(value: number): string {
  return (Math.round(value * 100) / 100).toFixed(2).replace(/(?:\.0+|(\.\d+?)0+)$/, '$1');
}
 
/** `m:ss` play length. */
export function formatChartLength(seconds: number): string {
  const total = Math.max(0, Math.round(Number.isFinite(seconds) ? seconds : 0));
  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
}
 
/** `150`, or `120-240` for a chart whose tempo changes. */
export function formatBPMRange(minBPM: number, maxBPM: number): string {
  const low = Math.round(minBPM);
  const high = Math.round(maxBPM);
  if (high <= 0) return '-';
  return low === high ? String(high) : `${low}-${high}`;
}
 
/** Short gimmick tags for a row: `LN`, `MINE`, `STOP`, and `SOFLAN` when the tempo moves. */
export function resolveChartTags(stats: ChartStats): string[] {
  const tags: string[] = [];
  if (stats.longNotes > 0) tags.push('LN');
  if (Math.round(stats.minBPM) !== Math.round(stats.maxBPM)) tags.push('SOFLAN');
  if (stats.stops) tags.push('STOP');
  if (stats.mines > 0) tags.push('MINE');
  return tags;
}
 
/** The facts a select-list row prints for a song, already formatted (see {@link resolveChartStats}). */
export interface ChartRowFacts {
  notes: string;
  length: string;
  bpm: string;
  tags: string[];
}
 
export function resolveChartRowFacts(chartEntry: Pick<LibraryChart, 'chart' | 'bpm' | 'totalNotes'>): ChartRowFacts {
  const stats = resolveChartStats(chartEntry);
  return {
    notes: String(Math.max(0, chartEntry.totalNotes)),
    length: formatChartLength(stats.lengthSeconds),
    bpm: formatBPMRange(stats.minBPM, stats.maxBPM),
    tags: resolveChartTags(stats),
  };
}
 
/** `'7K KEYS'`-style mode label for a song's play variant. */
export function formatPlayVariantLabel(chartEntry: Pick<LibraryChart, 'chartPath' | 'chart'>): string {
  return `${resolveChartPlayVariant({ chartPath: chartEntry.chartPath, events: chartEntry.chart.events, bms: chartEntry.chart.bms, bmson: chartEntry.chart.bmson, lrx: chartEntry.chart.lrx })} KEYS`;
}