Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
527 lines (470 loc) · 16.4 KB
/
Copy pathscript.js
File metadata and controls
527 lines (470 loc) · 16.4 KB
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// Global Constants
const OCTAVE_DISPLACEMENT = 2;
const NODE_START_OFFSET = 36;
const midiNotes = [
//bb b = # X
[-2, -1, 0, 1, 2], // c
[ 0, 1, 2, 3, 4], // d
[ 2, 3, 4, 5, 6], // e
[ 3, 4, 5, 6, 7], // f
[ 5, 6, 7, 8, 9], // g
[ 7, 8, 9, 10, 11], // a
[ 9, 10, 11, 12, 13], // b
];
const noteNames = [
['C', 'D', 'E', 'F', 'G', 'A', 'B'],
['c', 'd', 'e', 'f', 'g', 'a', 'b']
];
const accidentalNames = [ '__', '_', '', '^', '^^' ];
/**
* convertToAbcString - Converts an array of notes into the ABC string format
*
* @param {[]} data - array of note numbers
* @returns {string} - abcjs string format
*/
function convertToAbcString(data, beams, breaks) {
let compiled = "M:\nL: 1/16\n";
let noteCount = 1;
// Buffer for saving accidentals within the bar
let accBuffer = {};
let octBuffer = false;
let permute = (perm.checked === true);
// Regex for accidentals, notes and octaves
const noteRegex = /^(?<accidental>[_^=]?)(?<note>[a-gA-G])(?<octave>[',]*)$/;
for (let i = 0; i < data.length; i+=beams) {
let motiv = data.slice(i, i + beams);
let oor = 0; // out of range
let stringBuf = "";
let bestNotes = findKey(motiv);
let permutations = [];
if (permute) generatePermutations(bestNotes);
for (let j = 0; j < bestNotes.length; j++) {
let converted = convertCoordToAbc(bestNotes[j]);
const match = converted.match(noteRegex);
let accidental = "", note = "", octave = "";
if (match && match.groups) {
accidental = match.groups.accidental;
note = match.groups.note;
octave = match.groups.octave;
}
// Handle sharps and naturals
if (/^[\^_]/.test(converted)) {
accBuffer[note] = true;
} else {
// If previously sharp, and now natural, add '='
if (accBuffer[note]) {
converted = "=" + note + octave;
accBuffer[note] = false;
}
}
if (compress.checked === true) {
if (motiv[j] > 78) oor++;
if (motiv[j] < 45) oor--;
}
stringBuf += converted;
// Draw a barline every X notes
if (noteCount % beams === 0) {
stringBuf += '|\n';
accBuffer = {}; // Reset buffer at barline
}
noteCount++;
}
if (oor > 1 && !octBuffer) {
compiled += '[K:octave=-1][I:MIDI=transpose 12]"^8va Start"';
octBuffer = true;
}
if (oor < -1 && !octBuffer) {
compiled += '[K:octave=1][I:MIDI=transpose -12]"^8vb Start"';
octBuffer = true;
}
if ((oor > -2 && oor < 2) && octBuffer) {
compiled += '[K:octave=0][I:MIDI=transpose 0]"^End"';
octBuffer = false;
}
stringBuf += " " // Beamgroups
compiled += stringBuf;
}
compiled += '|\n';
return compiled;
}
// thanks to perplexity
function generatePermutations(arr) {
function perms(a) {
if (a.length <= 1) return [a];
return a.flatMap((v, i) =>
perms(a.slice(0, i).concat(a.slice(i + 1))).map(p => [v, ...p])
);
}
const all = perms(arr);
arr.push(...all
.filter(p => p.some((v, i) => v !== arr[i])) // Original nicht doppelt anhängen
.flat());
}
function findKey(motiv) {
// reconstruct interpolation intervals
let interpolationIntervals = getRelativeInterpolationIntervals(motiv);
let roots = findAllRoots(motiv[0]);
let coordinates = [];
let idx = 0;
for (let i=0; i < roots.length; i++) {
let buffer = coordinatesFromMotiv(interpolationIntervals, roots[i]);
// console.log(buffer)
if (buffer.length === motiv.length) {
coordinates[idx++] = buffer;
}
}
return findBestScore(coordinates);
}
function getInterpolationIntervals(motiv) {
let results = [];
for (let i=0; i < motiv.length-1; i++) {
results[i] = motiv[i +1] - motiv[0];
}
return results;
}
function getRelativeInterpolationIntervals(motiv) {
let results = [];
for (let i=0; i < motiv.length-1; i++) {
results[i] = motiv[i +1] - motiv[i];
}
return results;
}
function findOctave(value) {
return Math.floor(value / 12);
}
function findMidiNote(coordArray) {
let y = coordArray[0];
let x = coordArray[1];
let o = coordArray[2];
return midiNotes[y][x] + (o - octWrap(y,x)) * 12;
}
function findAllRoots(value) {
const results = [];
const oct = findOctave(value);
for (let row = 0; row < midiNotes.length; row++) {
for (let col = 0; col < midiNotes[row].length; col++) {
if (midiNotes[row][col] === value % 12) {
results.push([row, col, oct + octWrap(row,col)]);
}
}
}
// console.log(results);
return results;
}
function octWrap (y, x) {
let z = 0;
if (y === 0 && x < 2) z++;
if (y === 6 && x > 2) z--;
return z;
}
function negWrap(n, m) {
return ((n % m) + m) % m;
}
function roundHalfInterval(value) {
return value >= 0 ? Math.ceil(value / 2) : Math.floor(value / 2);
}
/*//bb b = # X
[10, 11, 0, 1, 2], // c
[ 0, 1, 2, 3, 4], // d
[ 2, 3, 4, 5, 6], // e
[ 3, 4, 5, 6, 7], // f
[ 5, 6, 7, 8, 9], // g
[ 7, 8, 9, 10, 11], // a
[ 9, 10, 11, 0, 1], // b */
function coordinatesFromMotiv(itpl, rootCoord) {
let results = [];
let rootMidi = findMidiNote(rootCoord);
let currRootNoteLine = rootCoord[0];
let currRootAccidental = rootCoord[1];
let currRootOctave = rootCoord[2];
results.push(rootCoord);
let tries = 0;
for (let i=0; i < itpl.length; i++) {
let midiNumTarget = rootMidi + itpl[i];
let noteLineSteps = roundHalfInterval(itpl[i] % 12) + Math.trunc(itpl[i] / 12) * 7;
// console.log(noteLineSteps);
let noteLineTarget = currRootNoteLine + noteLineSteps;
// console.log(noteLineTarget);
let octTarget = currRootOctave + Math.floor(noteLineTarget / 7);
// console.log(octTarget)
peekTargetMidi = midiNotes[negWrap(noteLineTarget, 7)][currRootAccidental] + octTarget * 12;
// console.log(peekTargetMidi);
let offset = midiNumTarget - peekTargetMidi;
// console.log(offset);
let targetAccidental = currRootAccidental + offset;
if (targetAccidental < 0) {
if (noteLineTarget == 0) {
noteLineTarget += 7;
octTarget--;
}
noteLineTarget--;
peekTargetMidi = midiNotes[negWrap(noteLineTarget, 7)][targetAccidental] + octTarget * 12;
offset = midiNumTarget - peekTargetMidi;
}
if (targetAccidental > 4) {
if (noteLineTarget == 6) {
noteLineTarget -= 7;
octTarget++;
}
noteLineTarget++;
targetAccidental = negWrap(targetAccidental, 5);
peekTargetMidi = midiNotes[negWrap(noteLineTarget, 7)][targetAccidental] + octTarget * 12;
offset = midiNumTarget - peekTargetMidi;
}
let midiGuess = midiNotes[negWrap(noteLineTarget, 7)][targetAccidental];
// console.log("Root: " + rootMidi + "\nTarget: " + midiNumTarget + "\nEstimate: " + peekTargetMidi +"\nError: " + offset + "\nTargetAccidental: " + targetAccidental + "\nNoteLineTarget: " + negWrap(noteLineTarget, 7));
if (negWrap(midiGuess, 12) === midiNumTarget % 12) {
results.push([negWrap(noteLineTarget, 7), targetAccidental, octTarget]);
rootMidi = midiNumTarget;
currRootAccidental = targetAccidental;
currRootNoteLine = negWrap(noteLineTarget, 7);
currRootOctave = octTarget;
} else {
if (++tries > 3) {
results.push([negWrap(noteLineTarget, 7), targetAccidental, octTarget]);
continue;
}
currRootNoteLine++;
i--;
}
}
// console.log(results);
return results;
}
function findBestScore(notes) {
let bestScore = 0;
let lastScore = 6;
let i = 0;
for (i=0; i < notes.length; i++) {
let score = 0;
for (let j=0; j < notes[i].length; j++) {
score += Math.abs(notes[i][j][1] - 2) / notes[i].length;
}
if (score < lastScore) {
bestScore = i;
lastScore = score;
}
}
return notes[bestScore];
}
function convertCoordToAbc(coord) {
const useLowerCase = coord[2] >= 5;
const name = accidentalNames[coord[1]] + noteNames[useLowerCase ? 1 : 0][coord[0]];
let octaveSuffix = '';
if (coord[2] < 4) {
octaveSuffix = ','.repeat(4 - coord[2]);
} else if (coord[2] > 5) {
octaveSuffix = '\''.repeat(coord[2] - 5);
}
return name + octaveSuffix;
}
/**
* generateScale - Generates the scales!
*
* @param divisions - the base interval between each node
* @param {int} start - which note number should we start on?
* @param {int} nodes - the number of nodes to add
* @param {int} interpolation - the number of interpolations to add
* @param {array} interpolationIntervals - An array that contains each interval from the node
* @returns {array} of notes to be drawn
*/
function generateScale(divisions, start, nodes, interpolation, interpolationInterval, direction) {
// if (divisions <= 0) return;
if (nodes <= 0) return;
let scaleArray = [];
let startingNote = start + NODE_START_OFFSET;
// add the nodes base note to the scale array
for (i = 0; i < nodes; i++) {
let tempScaleArray = [];
tempScaleArray.push(startingNote + (i * divisions));
// add each of the interpolations to the scale array
for (x = 0; x < interpolation; x++) {
tempScaleArray.push(startingNote + (i * divisions) + interpolationInterval[x]);
}
switch (direction) {
case 1:
tempScaleArray.reverse();
break;
case 2:
if (i % 2 != 0) tempScaleArray.reverse();
break;
case 3:
if (i % 2 === 0) tempScaleArray.reverse();
break;
case 0:
default:
break;
}
scaleArray.push(...tempScaleArray);
}
return scaleArray;
}
/**
* compileAbcString - Collects all the user input, generate the scale and the abc string
*
* @returns ABC string to be passed to the visualiser or playback
*/
function compileAbcString() {
// Collect all the values from the DOM
const divisions = parseInt(divisionInput.value);
const starting = parseInt(startingNote.value)
const nodes = parseInt(numberOfNodes.value)
const interpolation = parseInt(interpolationInput.value)
const interpolationInterval = [parseInt(interpolationIntervalInput1.value), parseInt(interpolationIntervalInput2.value), parseInt(interpolationIntervalInput3.value), parseInt(interpolationIntervalInput4.value)]
const direction = parseInt(directionInput.value)
// Control which interpolation interval inputs the user can edit
disableInterpolationInputs(interpolation)
// Generate the scale and if reverse is checked, append the reversed array
let noteArray = generateScale(divisions, starting, nodes, interpolation, interpolationInterval, direction);
if (descending.checked === true) noteArray = noteArray.reverse();
// choose sane numbers for linebreaks
let beams = interpolation + 1;
let breaks = beams * nodes;
while (breaks > 60) {
breaks -= beams;
}
// Convert to ABC and return
const abcString = convertToAbcString(noteArray, beams, breaks);
generateMidiFile(abcString);
return abcString;
}
/**
* disableInterpolationInputs - controls how many of the interval inputs are editable
*
* @param {int} number
*/
function disableInterpolationInputs(number) {
// Disable them all
interpolationIntervalInput1.disabled = true;
interpolationIntervalInput2.disabled = true;
interpolationIntervalInput3.disabled = true;
interpolationIntervalInput4.disabled = true;
// Enable them one by one
if(number >= 4) interpolationIntervalInput4.disabled = false;
if(number >= 3) interpolationIntervalInput3.disabled = false;
if(number >= 2) interpolationIntervalInput2.disabled = false;
if(number >= 1) interpolationIntervalInput1.disabled = false;
}
/**
* drawNotation is called when a change is made to the user inputs, updates the notation
*
*/
function drawNotation() {
const abcString = compileAbcString();
var visualOptions = {
//responsive: 'resize',
staffwidth: window.innerWidth / 1.1,
wrap: {
minSpacing: .5,
maxSpacing: 4,
preferredMeasuresPerLine: 8
},
// scale: 1.8
};
var visualObj = ABCJS.renderAbc("paper", abcString, visualOptions);
loadSynthControl(visualObj[0]);
}
/**
* play - generates the ABC string and starts playback
*
* from basic playback example in abcjs lib
*/
function loadSynthControl(abcString) {
var synthControl = new ABCJS.synth.SynthController();
synthControl.load("#audio",
{},
{
displayLoop: true,
displayRestart: true,
displayPlay: true,
displayProgress: true,
displayWarp: true
}
);
let audioParams = { chordsOff: true };
// let abc = compileAbcString();
// let abcString = ABCJS.renderAbc("*", abc)[0];
var createSynth = new ABCJS.synth.CreateSynth();
createSynth.init({ visualObj: abcString }).then(function () {
synthControl.setTune(abcString, false, audioParams).then(function () {
console.log("Audio successfully loaded.")
}).catch(function (error) {
console.warn("Audio problem:", error);
});
}).catch(function (error) {
console.warn("Audio problem:", error);
});
}
function generateMidiFile(abc) {
options = {
midiOutputType: "link",
// The following OPTIONAL parameters are only used when the type is "link":
// downloadClass: "class-name-to-add",
// preTextDownload: "text that appears before the link",
downloadLabel: "Download MIDI",
// postTextDownload: "text that appears after the link",
fileName: "pattern"
}
var midi = ABCJS.synth.getMidiFile(abc, options);
document.getElementById("midi-link").innerHTML = midi;
}
window.addEventListener("resize", function () {
drawNotation();
});
function copyPresetLinkToClipboard() {
const values = [
document.getElementById('divisions-input').value,
document.getElementById('starting-input').value,
document.getElementById('notes-input').value,
document.getElementById('interpolation-input').value,
document.getElementById('interpolation-interval-input1').value,
document.getElementById('interpolation-interval-input2').value,
document.getElementById('interpolation-interval-input3').value,
document.getElementById('interpolation-interval-input4').value,
document.getElementById('descending').checked ? 1 : 0,
document.getElementById('compress').checked ? 1 : 0,
document.getElementById('perm').checked ? 1 : 0
];
const presetString = values.join(',');
const url = window.location.href.split('?')[0] + '?preset=' + presetString;
navigator.clipboard.writeText(url).then(function() {
alert('Preset link copied to clipboard!');
});
}
function applyPresetFromURL() {
const params = new URLSearchParams(window.location.search);
if (params.has('preset')) {
const values = params.get('preset').split(',');
if (values.length >= 11) {
document.getElementById('divisions-input').value = values[0];
document.getElementById('starting-input').value = values[1];
document.getElementById('notes-input').value = values[2];
document.getElementById('interpolation-input').value = values[3];
document.getElementById('interpolation-interval-input1').value = values[4];
document.getElementById('interpolation-interval-input2').value = values[5];
document.getElementById('interpolation-interval-input3').value = values[6];
document.getElementById('interpolation-interval-input4').value = values[7];
document.getElementById('descending').checked = values[8] === '1';
document.getElementById('compress').checked = values[9] === '1';
document.getElementById('perm').checked = values[10] === '1';
if (typeof drawNotation === "function") drawNotation();
}
}
}
window.onload = function() {
applyPresetFromURL();
drawNotation();
};
// DOM variable declarations
const divisionInput = document.getElementById("divisions-input");
const startingNote = document.getElementById("starting-input");
const numberOfNodes = document.getElementById("notes-input");
const interpolationInput = document.getElementById("interpolation-input");
const interpolationIntervalInput1 = document.getElementById("interpolation-interval-input1");
const interpolationIntervalInput2 = document.getElementById("interpolation-interval-input2");
const interpolationIntervalInput3 = document.getElementById("interpolation-interval-input3");
const interpolationIntervalInput4 = document.getElementById("interpolation-interval-input4");
const descending = document.getElementById("descending");
const directionInput = document.getElementById("direction-input");
const compress = document.getElementById("compress");
const perm = document.getElementById("perm");