jevstrudel.git / packages / core / drawLine.mjs

drawLine.mjs - <short description TODO> Copyright (C) 2022 Strudel contributors - see https://codeberg.org/uzu/strudel/src/branch/main/packages/core/drawLine.mjs This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/.

7import Fraction, { gcd } from './fraction.mjs';

Intended for a debugging, drawLine renders the pattern as a string, where each character represents the same time span. Should only be used with single characters as values, otherwise the character slots will be messed up. Character legend:

  • "|" cycle separator
  • "-" hold previous value
  • "." silence

@tags visualization @param {Pattern} pattern the pattern to use @param {number} chars max number of characters (approximately) @returns string @example const line = drawLine("0 [1 2 3]", 10); // |0--123|0--123 console.log(line); silence;

27function drawLine(pat, chars = 60) {
28  let cycle = 0;
29  let pos = Fraction(0);
30  let lines = [''];
31  let emptyLine = ''; // this will be the "reference" empty line, which will be copied into extra lines
32  while (lines[0].length < chars) {
33    const haps = pat.queryArc(cycle, cycle + 1);
34    const durations = haps.filter((hap) => hap.hasOnset()).map((hap) => hap.duration);
35    const charFraction = gcd(...durations);
36    const totalSlots = charFraction.inverse(); // number of character slots for the current cycle
37    lines = lines.map((line) => line + '|'); // add pipe character before each cycle
38    emptyLine += '|';
39    for (let i = 0; i < totalSlots; i++) {
40      const [begin, end] = [pos, pos.add(charFraction)];
41      const matches = haps.filter((hap) => hap.whole.begin.lte(begin) && hap.whole.end.gte(end));
42      const missingLines = matches.length - lines.length;
43      if (missingLines > 0) {
44        lines = lines.concat(Array(missingLines).fill(emptyLine));
45      }
46      lines = lines.map((line, i) => {
47        const hap = matches[i];
48        if (hap) {
49          const isOnset = hap.whole.begin.eq(begin);
50          const char = isOnset ? '' + hap.value : '-';
51          return line + char;
52        }
53        return line + '.';
54      });
55      emptyLine += '.';
56      pos = pos.add(charFraction);
57    }
58    cycle++;
59  }
60  return lines.join('\n');
61}
63export default drawLine;