All files / player-engine/src lane-pms-random.ts

98.7% Statements 153/155
95.83% Branches 69/72
100% Functions 15/15
100% Lines 121/121

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      225x                     6750x     225x 2250x               229x 2061x 229x 229x 908x 1468x 229x                           53x 468x 52x 52x 1145x 1116x 1116x 367x 1116x 137x   52x 52x 52x 1120x 423x 422x 422x 927x 927x 927x 927x   422x 10x 10x   908x     52x 52x 1257x 52x 52x 52x 53x 1145x 1145x         225x 225x 225x   225x                 225x     64x 1x 1x 1x 1x 1x 1x 986409x 362879x 1418x 362879x 362879x 362879x 362879x 362879x 362879x 409112x 362879x 362879x 362879x   623530x 623530x     1x 1x       225x   225x     42x 4x 4x 4x     3435x 38x 38x 18x 18x 18x 3060x 18x 18x   38x                 18x 18x 18x 18x 18x 18x 6531822x 6531822x 6531822x 6531822x 6531822x 6531822x 6531804x 6531804x   38375888x     38375888x 4314496x 4314496x     6531804x   18x         42x 42x 42x 42x 42x 5145x 5145x 5145x 5145x 5145x   42x    
import type { SRandomNote } from './lane-random.ts';
 
// beatoraja 0.8.9 LanePlayableRandomShuffleModifier's ten impossible three-key chords.
const IMPOSSIBLE_CHORDS = [
  [0, 3, 6],
  [0, 3, 7],
  [0, 3, 8],
  [0, 4, 7],
  [0, 4, 8],
  [0, 5, 8],
  [1, 4, 7],
  [1, 4, 8],
  [1, 5, 8],
  [2, 5, 8],
].map((chord) => chord.reduce((mask, lane) => mask | (1 << lane), 0));
 
/** Whether each nine-lane mask of exactly three lanes is one of {@link IMPOSSIBLE_CHORDS}. */
const IMPOSSIBLE_TRIPLE = new Uint8Array(512);
for (const chord of IMPOSSIBLE_CHORDS) IMPOSSIBLE_TRIPLE[chord] = 1;
 
/**
 * The three-lane subsets of `pattern`, as `[a, b, c]` lane triples. Every impossible chord has three lanes and a
 * permutation is a bijection, so a chord's image contains an impossible chord exactly when one of its three-lane
 * subsets maps onto it: checking the subsets is the source's superset test, without building each chord's image.
 */
export function chordTriples(pattern: number): number[][] {
  const lanes: number[] = [];
  for (let lane = 0; lane < 9; lane += 1) if ((pattern & (1 << lane)) !== 0) lanes.push(lane);
  const triples: number[][] = [];
  for (let a = 0; a < lanes.length; a += 1)
    for (let b = a + 1; b < lanes.length; b += 1)
      for (let c = b + 1; c < lanes.length; c += 1) triples.push([lanes[a]!, lanes[b]!, lanes[c]!]);
  return triples;
}
 
/**
 * beatoraja PMS RANDOM_PLAYABLE: choose uniformly among chart-wide permutations
 * without the source's impossible chords, excluding regular and mirror. Seven-
 * key chords, or no valid permutation, fall back to regular/mirror at random.
 * LN tails release before evaluating their timeline, matching the source search.
 */
export function randomizePMSPlayableLanes(
  notes: readonly SRandomNote[],
  lanes: readonly string[],
  random: () => number,
): string[] {
  if (lanes.length !== 9 || new Set(lanes).size !== 9) throw new RangeError('PMS playable RANDOM requires nine lanes.');
  const indexByLane = new Map(lanes.map((lane, index) => [lane, index]));
  const rows = new Map<number, number[]>();
  notes.forEach((note, index) => {
    if (!indexByLane.has(note.channel) || (note.kind ?? 'note') !== 'note') return;
    const row = rows.get(note.timeMs);
    if (row) row.push(index);
    else rows.set(note.timeMs, [index]);
    if (note.endTimeMs !== undefined && note.endTimeMs > note.timeMs && !rows.has(note.endTimeMs))
      rows.set(note.endTimeMs, []);
  });
  const patterns = new Set<number>();
  const held = new Map<number, number>();
  let impossible = false;
  for (const [timeMs, indices] of [...rows].sort(([a], [b]) => a - b)) {
    for (const [lane, endMs] of held) if (endMs <= timeMs) held.delete(lane);
    const chord = new Set(held.keys());
    for (const index of indices) {
      const note = notes[index]!;
      const lane = indexByLane.get(note.channel)!;
      chord.add(lane);
      if (note.endTimeMs !== undefined && note.endTimeMs > timeMs) held.set(lane, note.endTimeMs);
    }
    if (chord.size >= 7) {
      impossible = true;
      break;
    }
    if (chord.size >= 3) patterns.add([...chord].reduce((mask, lane) => mask | (1 << lane), 0));
  }
  // Each pattern as its distinct three-lane subsets, flattened to `a, b, c, a, b, c, …` (see `chordTriples`).
  const tripleMasks = new Set<number>();
  for (const pattern of patterns)
    for (const [a, b, c] of chordTriples(pattern)) tripleMasks.add((1 << a!) | (1 << b!) | (1 << c!));
  const draw = random();
  Iif (!Number.isFinite(draw) || draw < 0 || draw >= 1) throw new RangeError('Lane randomness must be in [0, 1).');
  const permutation = impossible ? undefined : pickPlayablePermutation(tripleMasks, draw);
  return notes.map((note) => {
    const source = indexByLane.get(note.channel);
    return source === undefined ? note.channel : lanes[permutation?.[source] ?? (draw < 0.5 ? source : 8 - source)]!;
  });
}
 
/** The number of permutations Heap's algorithm visits after the initial regular one. */
const VISITED_PERMUTATIONS = 362_879;
const PERMUTATION_BLOCK_SIZE = 256;
const INITIAL_PERMUTATION = [0, 1, 2, 3, 4, 5, 6, 7, 8] as const;
/** The permutation before each block of swaps, so selecting one replays at most one block. */
const PERMUTATION_BLOCKS = new Uint8Array(Math.ceil(VISITED_PERMUTATIONS / PERMUTATION_BLOCK_SIZE) * 9);
 
/**
 * Heap's algorithm in the source order, as its swaps: visit `k` (0 = the first after the regular permutation) swaps
 * positions `HEAP_SWAPS[2k]` and `HEAP_SWAPS[2k + 1]`. Built on first use; with it the search runs one straight loop
 * instead of Heap's counter bookkeeping.
 */
let HEAP_SWAPS: Uint8Array | undefined;
/** The visit ordinal of the mirror permutation, which the source never picks. */
let MIRROR_ORDINAL = -1;
 
function heapSwaps(): Uint8Array {
  if (HEAP_SWAPS) return HEAP_SWAPS;
  const swaps = new Uint8Array(VISITED_PERMUTATIONS * 2);
  const permutation = [...INITIAL_PERMUTATION];
  const counters = new Uint8Array(9);
  let ordinal = 0;
  let index = 0;
  while (index < 9) {
    if (counters[index]! < index) {
      if (ordinal % PERMUTATION_BLOCK_SIZE === 0)
        PERMUTATION_BLOCKS.set(permutation, (ordinal / PERMUTATION_BLOCK_SIZE) * 9);
      const other = index % 2 === 0 ? 0 : counters[index]!;
      const swap = permutation[index]!;
      permutation[index] = permutation[other]!;
      permutation[other] = swap;
      swaps[ordinal * 2] = index;
      swaps[ordinal * 2 + 1] = other;
      if (permutation.every((lane, at) => lane === 8 - at)) MIRROR_ORDINAL = ordinal;
      ordinal += 1;
      counters[index]! += 1;
      index = 0;
    } else {
      counters[index] = 0;
      index += 1;
    }
  }
  HEAP_SWAPS = swaps;
  return swaps;
}
 
/** Cache the last set of chord constraints, independent of chart timing or channel names. */
const VALID_ORDINALS = new Uint32Array(VISITED_PERMUTATIONS);
let lastConstraintKey: string | undefined;
let lastValidCount = 0;
 
function pickPlayablePermutation(tripleMasks: ReadonlySet<number>, draw: number): Uint8Array | undefined {
  if (tripleMasks.size === 0) {
    heapSwaps();
    const rank = Math.floor(draw * (VISITED_PERMUTATIONS - 1));
    return permutationAt(rank < MIRROR_ORDINAL ? rank : rank + 1);
  }
 
  const masks = [...tripleMasks].sort((left, right) => left - right);
  const key = masks.join(',');
  if (key !== lastConstraintKey) {
    const triples = new Uint8Array(masks.length * 3);
    let offset = 0;
    for (const mask of masks)
      for (let lane = 0; lane < 9; lane += 1) if ((mask & (1 << lane)) !== 0) triples[offset++] = lane;
    lastValidCount = searchValidOrdinals(triples);
    lastConstraintKey = key;
  }
  return lastValidCount === 0 ? undefined : permutationAt(VALID_ORDINALS[Math.floor(draw * lastValidCount)]!);
}
 
/**
 * Heap's algorithm in the source order (omitting the initial regular permutation), writing into
 * {@link VALID_ORDINALS} the ordinal of each permutation that is not the mirror and maps none of `triples`
 * (`a, b, c, …`) onto an impossible chord. Returns how many it wrote.
 */
function searchValidOrdinals(triples: Uint8Array): number {
  const swaps = heapSwaps();
  const permutation = new Uint8Array(INITIAL_PERMUTATION);
  const ordinals = VALID_ORDINALS;
  const tripleLength = triples.length;
  let found = 0;
  for (let ordinal = 0; ordinal < VISITED_PERMUTATIONS; ordinal += 1) {
    const index = swaps[ordinal * 2]!;
    const other = swaps[ordinal * 2 + 1]!;
    const swap = permutation[index]!;
    permutation[index] = permutation[other]!;
    permutation[other] = swap;
    if (ordinal === MIRROR_ORDINAL) continue;
    let valid = true;
    for (let at = 0; at < tripleLength; at += 3) {
      const image =
        (1 << permutation[triples[at]!]!) |
        (1 << permutation[triples[at + 1]!]!) |
        (1 << permutation[triples[at + 2]!]!);
      if (IMPOSSIBLE_TRIPLE[image] === 1) {
        valid = false;
        break;
      }
    }
    if (valid) ordinals[found++] = ordinal;
  }
  return found;
}
 
/** The permutation Heap's algorithm visits at `target` (0 = the first after the regular one). */
function permutationAt(target: number): Uint8Array {
  Iif (target < 0 || target >= VISITED_PERMUTATIONS) throw new RangeError(`No permutation at ${target}.`);
  const swaps = heapSwaps();
  const block = Math.floor(target / PERMUTATION_BLOCK_SIZE);
  const permutation = PERMUTATION_BLOCKS.slice(block * 9, (block + 1) * 9);
  for (let ordinal = block * PERMUTATION_BLOCK_SIZE; ordinal <= target; ordinal += 1) {
    const index = swaps[ordinal * 2]!;
    const other = swaps[ordinal * 2 + 1]!;
    const swap = permutation[index]!;
    permutation[index] = permutation[other]!;
    permutation[other] = swap;
  }
  return permutation;
}