forked from 0xfe/vexflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtabnote.ts
486 lines (409 loc) · 15.1 KB
/
tabnote.ts
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
// [VexFlow](https://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
//
// ## Description
//
// The file implements notes for Tablature notation. This consists of one or
// more fret positions, and can either be drawn with or without stems.
//
// See `tests/tabnote_tests.ts` for usage examples.
import { Font } from './font';
import { Glyph, GlyphProps } from './glyph';
import { Modifier } from './modifier';
import { Stave } from './stave';
import { StaveNoteStruct } from './stavenote';
import { Stem } from './stem';
import { StemmableNote } from './stemmablenote';
import { Tables } from './tables';
import { Category, isDot } from './typeguard';
import { defined, RuntimeError } from './util';
export interface TabNotePosition {
// For example, on a six stringed instrument, `str` ranges from 1 to 6.
str: number;
// fret: 'X' indicates an unused/muted string.
// fret: 3 indicates the third fret.
fret: number | string;
}
export interface TabNoteStruct extends StaveNoteStruct {
positions: TabNotePosition[];
}
// Gets the unused strings grouped together if consecutive.
//
// Parameters:
// * num_lines - The number of lines
// * strings_used - An array of numbers representing which strings have fret positions
function getUnusedStringGroups(num_lines: number, strings_used: number[]) {
const stem_through = [];
let group = [];
for (let string = 1; string <= num_lines; string++) {
const is_used = strings_used.indexOf(string) > -1;
if (!is_used) {
group.push(string);
} else {
stem_through.push(group);
group = [];
}
}
if (group.length > 0) stem_through.push(group);
return stem_through;
}
// Gets groups of points that outline the partial stem lines
// between fret positions
//
// Parameters:
// * stem_Y - The `y` coordinate the stem is located on
// * unused_strings - An array of groups of unused strings
// * stave - The stave to use for reference
// * stem_direction - The direction of the stem
function getPartialStemLines(stem_y: number, unused_strings: number[][], stave: Stave, stem_direction: number) {
const up_stem = stem_direction !== 1;
const down_stem = stem_direction !== -1;
const line_spacing = stave.getSpacingBetweenLines();
const total_lines = stave.getNumLines();
const stem_lines: number[][] = [];
unused_strings.forEach((strings) => {
const containsLastString = strings.indexOf(total_lines) > -1;
const containsFirstString = strings.indexOf(1) > -1;
if ((up_stem && containsFirstString) || (down_stem && containsLastString)) {
return;
}
// If there's only one string in the group, push a duplicate value.
// We do this because we need 2 strings to convert into upper/lower y
// values.
if (strings.length === 1) {
strings.push(strings[0]);
}
const line_ys: number[] = [];
// Iterate through each group string and store it's y position
strings.forEach((string, index, strings) => {
const isTopBound = string === 1;
const isBottomBound = string === total_lines;
// Get the y value for the appropriate staff line,
// we adjust for a 0 index array, since string numbers are index 1
let y = stave.getYForLine(string - 1);
// Unless the string is the first or last, add padding to each side
// of the line
if (index === 0 && !isTopBound) {
y -= line_spacing / 2 - 1;
} else if (index === strings.length - 1 && !isBottomBound) {
y += line_spacing / 2 - 1;
}
// Store the y value
line_ys.push(y);
// Store a subsequent y value connecting this group to the main
// stem above/below the stave if it's the top/bottom string
if (stem_direction === 1 && isTopBound) {
line_ys.push(stem_y - 2);
} else if (stem_direction === -1 && isBottomBound) {
line_ys.push(stem_y + 2);
}
});
// Add the sorted y values to the
stem_lines.push(line_ys.sort((a, b) => a - b));
});
return stem_lines;
}
export class TabNote extends StemmableNote {
static get CATEGORY(): string {
return Category.TabNote;
}
protected ghost: boolean;
protected glyphPropsArr: GlyphProps[] = [];
protected positions: TabNotePosition[];
// Initialize the TabNote with a `noteStruct` full of properties
// and whether to `draw_stem` when rendering the note
constructor(noteStruct: TabNoteStruct, draw_stem: boolean = false) {
super(noteStruct);
this.ghost = false; // Renders parenthesis around notes
// Note properties
// The fret positions in the note. An array of `{ str: X, fret: X }`
this.positions = noteStruct.positions || [];
// Render Options
this.render_options = {
...this.render_options,
// font size for note heads and rests
glyph_font_scale: Tables.TABLATURE_FONT_SCALE,
// Flag to draw a stem
draw_stem,
// Flag to draw dot modifiers
draw_dots: draw_stem,
// Flag to extend the main stem through the stave and fret positions
draw_stem_through_stave: false,
// vertical shift from stave line
y_shift: 0,
// normal glyph scale
scale: 1.0,
// default tablature font
font: `${Font.SIZE}pt ${Font.SANS_SERIF}`,
};
this.glyphProps = Tables.getGlyphProps(this.duration, this.noteType);
defined(
this.glyphProps,
'BadArguments',
`No glyph found for duration '${this.duration}' and type '${this.noteType}'`
);
this.buildStem();
if (noteStruct.stem_direction) {
this.setStemDirection(noteStruct.stem_direction);
} else {
this.setStemDirection(Stem.UP);
}
// Renders parenthesis around notes
this.ghost = false;
this.updateWidth();
}
// Return the number of the greatest string, which is the string lowest on the display
greatestString = (): number => {
return this.positions.map((x) => x.str).reduce((a, b) => (a > b ? a : b));
};
// Return the number of the least string, which is the string highest on the display
leastString = (): number => {
return this.positions.map((x) => x.str).reduce((a, b) => (a < b ? a : b));
};
reset(): this {
super.reset();
if (this.stave) this.setStave(this.stave);
return this;
}
// Set as ghost `TabNote`, surrounds the fret positions with parenthesis.
// Often used for indicating frets that are being bent to
setGhost(ghost: boolean): this {
this.ghost = ghost;
this.updateWidth();
return this;
}
// Determine if the note has a stem
hasStem(): boolean {
if (this.render_options.draw_stem) return true;
return false;
}
// Get the default stem extension for the note
getStemExtension(): number {
const glyphProps = this.getGlyphProps();
if (this.stem_extension_override != null) {
return this.stem_extension_override;
}
if (glyphProps) {
return this.getStemDirection() === Stem.UP
? glyphProps.tabnote_stem_up_extension
: glyphProps.tabnote_stem_down_extension;
}
return 0;
}
// Calculate and store the width of the note
updateWidth(): void {
this.glyphPropsArr = [];
this.width = 0;
for (let i = 0; i < this.positions.length; ++i) {
let fret = this.positions[i].fret;
if (this.ghost) fret = '(' + fret + ')';
const glyphProps = Tables.tabToGlyphProps(fret.toString(), this.render_options.scale);
this.glyphPropsArr.push(glyphProps);
this.width = Math.max(glyphProps.getWidth(), this.width);
}
// For some reason we associate a notehead glyph with a TabNote, and this
// glyph is used for certain width calculations. Of course, this is totally
// incorrect since a notehead is a poor approximation for the dimensions of
// a fret number which can have multiple digits. As a result, we must
// overwrite getWidth() to return the correct width
this.glyphProps.getWidth = () => this.width;
}
// Set the `stave` to the note
setStave(stave: Stave): this {
super.setStave(stave);
const ctx = stave.getContext();
this.setContext(ctx);
// Calculate the fret number width based on font used
if (ctx) {
this.width = 0;
for (let i = 0; i < this.glyphPropsArr.length; ++i) {
const glyphProps = this.glyphPropsArr[i];
const text = '' + glyphProps.text;
if (text.toUpperCase() !== 'X') {
ctx.save();
ctx.setFont(this.render_options.font);
glyphProps.width = ctx.measureText(text).width;
ctx.restore();
glyphProps.getWidth = () => glyphProps.width as number;
}
this.width = Math.max(glyphProps.getWidth(), this.width);
}
this.glyphProps.getWidth = () => this.width;
}
// we subtract 1 from `line` because getYForLine expects a 0-based index,
// while the position.str is a 1-based index
const ys = this.positions.map(({ str: line }) => stave.getYForLine(Number(line) - 1));
this.setYs(ys);
if (this.stem) {
this.stem.setYBounds(this.getStemY(), this.getStemY());
}
return this;
}
// Get the fret positions for the note
getPositions(): TabNotePosition[] {
return this.positions;
}
// Get the default `x` and `y` coordinates for a modifier at a specific
// `position` at a fret position `index`
getModifierStartXY(position: number, index: number): { x: number; y: number } {
if (!this.preFormatted) {
throw new RuntimeError('UnformattedNote', "Can't call GetModifierStartXY on an unformatted note");
}
if (this.ys.length === 0) {
throw new RuntimeError('NoYValues', 'No Y-Values calculated for this note.');
}
let x = 0;
if (position === Modifier.Position.LEFT) {
x = -1 * 2; // FIXME: modifier padding, move to font file
} else if (position === Modifier.Position.RIGHT) {
x = this.width + 2; // FIXME: modifier padding, move to font file
} else if (position === Modifier.Position.BELOW || position === Modifier.Position.ABOVE) {
const note_glyph_width = this.glyphProps.getWidth();
x = note_glyph_width / 2;
}
return {
x: this.getAbsoluteX() + x,
y: this.ys[index],
};
}
// Get the default line for rest
getLineForRest(): number {
return Number(this.positions[0].str);
}
// Pre-render formatting
preFormat(): void {
if (this.preFormatted) return;
if (this.modifierContext) this.modifierContext.preFormat();
// width is already set during init()
this.preFormatted = true;
}
// Get the x position for the stem
getStemX(): number {
return this.getCenterGlyphX();
}
// Get the y position for the stem
getStemY(): number {
const num_lines = this.checkStave().getNumLines();
// The decimal staff line amounts provide optimal spacing between the
// fret number and the stem
const stemUpLine = -0.5;
const stemDownLine = num_lines - 0.5;
const stemStartLine = Stem.UP === this.stem_direction ? stemUpLine : stemDownLine;
return this.checkStave().getYForLine(stemStartLine);
}
// Get the stem extents for the tabnote
getStemExtents(): { topY: number; baseY: number } {
return this.checkStem().getExtents();
}
// Draw the fal onto the context
drawFlag(): void {
const {
beam,
glyphProps,
render_options: { draw_stem },
} = this;
const context = this.checkContext();
const shouldDrawFlag = beam == undefined && draw_stem;
// Now it's the flag's turn.
if (glyphProps.flag && shouldDrawFlag) {
const flag_x = this.getStemX();
const flag_y =
this.getStemDirection() === Stem.DOWN
? // Down stems are below the note head and have flags on the right.
this.getStemY() - this.checkStem().getHeight() - (this.glyphProps ? this.glyphProps.stem_down_extension : 0)
: // Up stems are above the note head and have flags on the right.
this.getStemY() - this.checkStem().getHeight() + (this.glyphProps ? this.glyphProps.stem_up_extension : 0);
// Draw the Flag
//this.flag?.setOptions({ category: 'flag.tabStem' });
this.flag?.render(context, flag_x, flag_y);
//Glyph.renderGlyph(context, flag_x, flag_y, glyph_font_scale, flag_code, { category: 'flag.tabStem' });
}
}
// Render the modifiers onto the context.
drawModifiers(): void {
this.modifiers.forEach((modifier) => {
// Only draw the dots if enabled.
if (isDot(modifier) && !this.render_options.draw_dots) {
return;
}
modifier.setContext(this.getContext());
modifier.drawWithStyle();
});
}
// Render the stem extension through the fret positions
drawStemThrough(): void {
const stemX = this.getStemX();
const stemY = this.getStemY();
const ctx = this.checkContext();
const drawStem = this.render_options.draw_stem;
const stemThrough = this.render_options.draw_stem_through_stave;
if (drawStem && stemThrough) {
const numLines = this.checkStave().getNumLines();
const stringsUsed = this.positions.map((position) => Number(position.str));
const unusedStrings = getUnusedStringGroups(numLines, stringsUsed);
const stemLines = getPartialStemLines(stemY, unusedStrings, this.checkStave(), this.getStemDirection());
ctx.save();
ctx.setLineWidth(Stem.WIDTH);
stemLines.forEach((bounds) => {
if (bounds.length === 0) return;
ctx.beginPath();
ctx.moveTo(stemX, bounds[0]);
ctx.lineTo(stemX, bounds[bounds.length - 1]);
ctx.stroke();
ctx.closePath();
});
ctx.restore();
}
}
// Render the fret positions onto the context
drawPositions(): void {
const ctx = this.checkContext();
const x = this.getAbsoluteX();
const ys = this.ys;
for (let i = 0; i < this.positions.length; ++i) {
const y = ys[i] + this.render_options.y_shift;
const glyphProps = this.glyphPropsArr[i];
// Center the fret text beneath the notation note head
const note_glyph_width = this.glyphProps.getWidth();
const tab_x = x + note_glyph_width / 2 - glyphProps.getWidth() / 2;
// FIXME: Magic numbers.
ctx.clearRect(tab_x - 2, y - 3, glyphProps.getWidth() + 4, 6);
if (glyphProps.code) {
Glyph.renderGlyph(
ctx,
tab_x,
y,
this.render_options.glyph_font_scale * this.render_options.scale,
glyphProps.code
);
} else {
ctx.save();
ctx.setFont(this.render_options.font);
const text = glyphProps.text ?? '';
ctx.fillText(text, tab_x, y + 5 * this.render_options.scale);
ctx.restore();
}
}
}
// The main rendering function for the entire note.
draw(): void {
const ctx = this.checkContext();
if (this.ys.length === 0) {
throw new RuntimeError('NoYValues', "Can't draw note without Y values.");
}
this.setRendered();
const render_stem = this.beam == undefined && this.render_options.draw_stem;
this.applyStyle();
ctx.openGroup('tabnote', this.getAttribute('id'), { pointerBBox: true });
this.drawPositions();
this.drawStemThrough();
if (this.stem && render_stem) {
const stem_x = this.getStemX();
this.stem.setNoteHeadXBounds(stem_x, stem_x);
this.stem.setContext(ctx).draw();
}
this.drawFlag();
this.drawModifiers();
ctx.closeGroup();
this.restoreStyle();
}
}