All files / src/components/music/piano helpers.ts

85.23% Statements 127/149
71.01% Branches 49/69
95.24% Functions 20/21
83.58% Lines 112/134

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 3761x                     1x       1x 1x 1x 1x   1x 3x       1x 3x   1x 3x         3x                 1x       4x   4x 8x 2x     8x       1x       1x   1x 2x   2x       2x         2x 2x       2x       1x       1x 1x   1x 2x       2x       2x   2x 2x         1x     1x                                                           1x       3x 3x       6x 2x       1x     1x         3x 8x   8x             8x 1x 1x   1x 1x         2x     1x                         3x       3x 3x       3x 3x     3x 3x 2x       3x         3x 1x       3x 3x                       3x 3x                     3x       1x           6x           1x 3x     74x     72x                     1x       4x 1x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 8x 8x 5x 5x   8x 5x 5x   8x     3x       1x 9x   1x 6x           1x         4x   4x           4x             1x           3x   3x                          
import {
  PIANO_ROLL_CELL_SIZE,
  TOTAL_NOTES,
  TRACKER_PATTERN_LENGTH,
} from "consts";
import {
  DutyInstrument,
  NoiseInstrument,
  PatternCell,
  WaveInstrument,
} from "shared/lib/uge/types";
import clamp from "shared/lib/helpers/clamp";
 
type ChannelInstrument = DutyInstrument | WaveInstrument | NoiseInstrument;
 
const SET_VOLUME_EFFECT = 12;
const NOTE_CUT_EFFECT = 14;
const SET_SPEED_EFFECT = 15;
const TIMER_HZ = 64;
 
const isInstrumentAudible = (instrument: ChannelInstrument) =>
  "volume" in instrument
    ? instrument.volume > 0
    : instrument.initialVolume > 0 || instrument.volumeSweepChange > 0;
 
const getInstrumentLengthSeconds = (instrument: ChannelInstrument) =>
  instrument.length !== null ? instrument.length / 256 : null;
 
const getInstrumentFadeOutSeconds = (instrument: ChannelInstrument) => {
  if (
    "volume" in instrument ||
    instrument.initialVolume <= 0 ||
    instrument.volumeSweepChange >= 0
  ) {
    return null;
  }
 
  return (
    (instrument.initialVolume * (8 - Math.abs(instrument.volumeSweepChange))) /
    64
  );
};
 
export const getPatternTicksPerRow = (
  pattern: ReadonlyArray<PatternCell>,
  initialTicksPerRow: number,
) => {
  let currentTicksPerRow = initialTicksPerRow;
 
  return pattern.map((cell) => {
    if (cell.effectCode === SET_SPEED_EFFECT && (cell.effectParam ?? 0) > 0) {
      currentTicksPerRow = cell.effectParam ?? currentTicksPerRow;
    }
 
    return currentTicksPerRow;
  });
};
 
export const getPatternListStartTicksPerRow = (
  patterns: ReadonlyArray<ReadonlyArray<PatternCell> | undefined>,
  initialTicksPerRow: number,
) => {
  let currentPatternTicksPerRow = initialTicksPerRow;
 
  return patterns.map((pattern) => {
    const startTicksPerRow = currentPatternTicksPerRow;
 
    Iif (!pattern) {
      return startTicksPerRow;
    }
 
    const patternTicksPerRow = getPatternTicksPerRow(
      pattern,
      currentPatternTicksPerRow,
    );
 
    if (patternTicksPerRow.length > 0) {
      currentPatternTicksPerRow =
        patternTicksPerRow[patternTicksPerRow.length - 1];
    }
 
    return startTicksPerRow;
  });
};
 
export const getPatternListTicksPerRow = (
  patterns: ReadonlyArray<ReadonlyArray<PatternCell> | undefined>,
  initialTicksPerRow: number,
) => {
  const ticksPerRowByAbsRow: number[] = [];
  let currentPatternTicksPerRow = initialTicksPerRow;
 
  for (const pattern of patterns) {
    Iif (!pattern) {
      continue;
    }
 
    const patternTicksPerRow = getPatternTicksPerRow(
      pattern,
      currentPatternTicksPerRow,
    );
    ticksPerRowByAbsRow.push(...patternTicksPerRow);
 
    if (patternTicksPerRow.length > 0) {
      currentPatternTicksPerRow =
        patternTicksPerRow[patternTicksPerRow.length - 1];
    }
  }
 
  return ticksPerRowByAbsRow;
};
 
const getRowsForDurationSeconds = ({
  durationSeconds,
  startRowIndex,
  ticksPerRowByRow,
}: {
  durationSeconds: number;
  startRowIndex: number;
  ticksPerRowByRow: ReadonlyArray<number>;
}) => {
  let elapsedSeconds = 0;
 
  for (
    let rowIndex = startRowIndex;
    rowIndex < ticksPerRowByRow.length;
    rowIndex += 1
  ) {
    const rowDurationSeconds = ticksPerRowByRow[rowIndex] / TIMER_HZ;
    const nextElapsedSeconds = elapsedSeconds + rowDurationSeconds;
 
    Iif (nextElapsedSeconds >= durationSeconds) {
      const secondsIntoRow = durationSeconds - elapsedSeconds;
      return rowIndex - startRowIndex + secondsIntoRow / rowDurationSeconds;
    }
 
    elapsedSeconds = nextElapsedSeconds;
  }
 
  return ticksPerRowByRow.length - startRowIndex;
};
 
const getRowsUntilNextNote = (
  channelCells: ReadonlyArray<PatternCell>,
  rowIndex: number,
) => {
  for (
    let nextRow = rowIndex + 1;
    nextRow < channelCells.length;
    nextRow += 1
  ) {
    if (channelCells[nextRow].note !== null) {
      return nextRow - rowIndex;
    }
  }
 
  return null;
};
 
const getRowsUntilSilenceEffect = (
  channelCells: ReadonlyArray<PatternCell>,
  ticksPerRowByRow: ReadonlyArray<number>,
  rowIndex: number,
) => {
  for (let nextRow = rowIndex; nextRow < channelCells.length; nextRow += 1) {
    const cell = channelCells[nextRow];
 
    Iif (
      cell.effectCode === SET_VOLUME_EFFECT &&
      (cell.effectParam ?? 0) === 0
    ) {
      return nextRow - rowIndex + 1;
    }
 
    if (cell.effectCode === NOTE_CUT_EFFECT) {
      const ticksPerRow = ticksPerRowByRow[nextRow];
      const cutTick = cell.effectParam ?? 0;
 
      if (cutTick < ticksPerRow) {
        return nextRow - rowIndex + cutTick / ticksPerRow;
      }
    }
  }
 
  return null;
};
 
export const getPatternNoteSustain = ({
  instruments,
  channelCells,
  ticksPerRowByRow,
  rowIndex,
  instrumentId,
}: {
  instruments: ReadonlyArray<ChannelInstrument> | undefined;
  channelCells: ReadonlyArray<PatternCell>;
  ticksPerRowByRow: ReadonlyArray<number>;
  rowIndex: number;
  instrumentId: number | null;
}): number => {
  Iif (instrumentId === null || !instruments) {
    return 0;
  }
 
  const instrument = instruments[instrumentId];
  Iif (!instrument || !isInstrumentAudible(instrument)) {
    return 0;
  }
 
  const remainingRows = Math.max(channelCells.length - rowIndex, 1);
  let duration = remainingRows;
 
  // Check when note would end because another note played on the same channel
  const rowsUntilNextNote = getRowsUntilNextNote(channelCells, rowIndex);
  if (rowsUntilNextNote !== null && rowsUntilNextNote < duration) {
    duration = rowsUntilNextNote;
  }
 
  // Check when note would end because a Note Cut or Volume effect would stop it
  const rowsUntilSilenceEffect = getRowsUntilSilenceEffect(
    channelCells,
    ticksPerRowByRow,
    rowIndex,
  );
  if (rowsUntilSilenceEffect !== null && rowsUntilSilenceEffect < duration) {
    duration = rowsUntilSilenceEffect;
  }
 
  // Check when note would end because the instrument length was reached
  const instrumentLengthSeconds = getInstrumentLengthSeconds(instrument);
  Iif (instrumentLengthSeconds !== null) {
    const rowsUntilInstrumentLength = getRowsForDurationSeconds({
      durationSeconds: instrumentLengthSeconds,
      startRowIndex: rowIndex,
      ticksPerRowByRow,
    });
    Iif (rowsUntilInstrumentLength < duration) {
      duration = rowsUntilInstrumentLength;
    }
  }
 
  // Check when note would end because the instrument envelope fade out ended
  const fadeOutSeconds = getInstrumentFadeOutSeconds(instrument);
  Iif (fadeOutSeconds !== null) {
    const rowsUntilFadeOut = getRowsForDurationSeconds({
      durationSeconds: fadeOutSeconds,
      startRowIndex: rowIndex,
      ticksPerRowByRow,
    });
    Iif (rowsUntilFadeOut < duration) {
      duration = rowsUntilFadeOut;
    }
  }
 
  return Math.max(1, duration);
};
 
/** Calculates the pixel offset of the playback cursor in the piano-roll timeline. */
export const calculatePlaybackTrackerPosition = (
  playbackOrder: number,
  playbackRow: number,
  currentTick = 0,
  ticksPerRow = 0,
) =>
  playbackOrder * TRACKER_PATTERN_LENGTH * PIANO_ROLL_CELL_SIZE +
  (playbackRow +
    (ticksPerRow > 0 ? clamp(currentTick / ticksPerRow, 0, 1) : 0)) *
    PIANO_ROLL_CELL_SIZE;
 
/** Calculates the total pixel width of the piano-roll document for a given sequence length. */
export const calculateDocumentWidth = (sequenceLength: number) =>
  sequenceLength * TRACKER_PATTERN_LENGTH * PIANO_ROLL_CELL_SIZE;
 
/** Converts a MIDI-style note number to a piano-roll row index (top = highest note). */
export const noteToRow = (note: number) => TOTAL_NOTES - 1 - note;
 
/** Converts a piano-roll row index back to a MIDI-style note number. */
export const rowToNote = (row: number) => TOTAL_NOTES - 1 - row;
 
interface RollGridPoint {
  absRow: number;
  note: number;
}
 
/**
 * Bresenham line interpolation between two grid points. Returns all grid
 * positions that should be filled when drawing from `from` to `to`.
 */
export const interpolateGridLine = (
  from: RollGridPoint | null,
  to: RollGridPoint,
): RollGridPoint[] => {
  if (!from) {
    return [to];
  }
 
  const points: RollGridPoint[] = [];
  let x0 = from.absRow;
  let y0 = from.note;
  const x1 = to.absRow;
  const y1 = to.note;
  const dx = Math.abs(x1 - x0);
  const dy = Math.abs(y1 - y0);
  const sx = x0 < x1 ? 1 : -1;
  const sy = y0 < y1 ? 1 : -1;
  let err = dx - dy;
 
  while (x0 !== x1 || y0 !== y1) {
    const e2 = 2 * err;
    if (e2 > -dy) {
      err -= dy;
      x0 += sx;
    }
    if (e2 < dx) {
      err += dx;
      y0 += sy;
    }
    points.push({ absRow: x0, note: y0 });
  }
 
  return points;
};
 
/** Converts a pixel offset to a grid cell index using `PIANO_ROLL_CELL_SIZE`. */
export const pixelToGridIndex = (pixel: number) =>
  Math.floor(pixel / PIANO_ROLL_CELL_SIZE);
 
const pixelToGridStart = (pixel: number) =>
  pixelToGridIndex(pixel) * PIANO_ROLL_CELL_SIZE;
 
/**
 * Converts a pixel range [start, start+size] to a clamped grid cell range
 * [from, to]. Useful for determining which cells overlap a viewport region.
 */
export const pixelRangeToGridRange = (
  start: number,
  size: number,
  max: number,
) => {
  const from = clamp(Math.floor(start / PIANO_ROLL_CELL_SIZE), 0, max - 1);
 
  const to = clamp(
    Math.ceil((start + size) / PIANO_ROLL_CELL_SIZE),
    from + 1,
    max,
  );
 
  return { from, to };
};
 
/**
 * Converts page coordinates to a snapped grid point within the piano-roll
 * canvas. Clamps the result to the valid document bounds.
 */
export const pageToSnappedGridPoint = (
  pageX: number,
  pageY: number,
  bounds: DOMRect,
  sequenceLength: number,
) => {
  const totalAbsRows = sequenceLength * TRACKER_PATTERN_LENGTH;
 
  return {
    x: clamp(
      pixelToGridStart(pageX - bounds.left),
      0,
      totalAbsRows * PIANO_ROLL_CELL_SIZE - 1,
    ),
    y: clamp(
      pixelToGridStart(pageY - bounds.top),
      0,
      TOTAL_NOTES * PIANO_ROLL_CELL_SIZE - PIANO_ROLL_CELL_SIZE,
    ),
  };
};