VexFlowMusicSheetDrawer.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import Vex = require("vexflow");
  2. import { MusicSheetDrawer } from "../MusicSheetDrawer";
  3. import { RectangleF2D } from "../../../Common/DataObjects/RectangleF2D";
  4. import { VexFlowMeasure } from "./VexFlowMeasure";
  5. import { PointF2D } from "../../../Common/DataObjects/PointF2D";
  6. import { GraphicalLabel } from "../GraphicalLabel";
  7. import { VexFlowTextMeasurer } from "./VexFlowTextMeasurer";
  8. import { MusicSystem } from "../MusicSystem";
  9. import { GraphicalObject } from "../GraphicalObject";
  10. import { GraphicalLayers } from "../DrawingEnums";
  11. import { GraphicalStaffEntry } from "../GraphicalStaffEntry";
  12. import { VexFlowBackend } from "./VexFlowBackend";
  13. import { VexFlowOctaveShift } from "./VexFlowOctaveShift";
  14. import { VexFlowInstantaneousDynamicExpression } from "./VexFlowInstantaneousDynamicExpression";
  15. import { VexFlowInstrumentBracket } from "./VexFlowInstrumentBracket";
  16. import { VexFlowInstrumentBrace } from "./VexFlowInstrumentBrace";
  17. import { GraphicalLyricEntry } from "../GraphicalLyricEntry";
  18. import { VexFlowStaffLine } from "./VexFlowStaffLine";
  19. import { StaffLine } from "../StaffLine";
  20. import { GraphicalSlur } from "../GraphicalSlur";
  21. import { PlacementEnum } from "../../VoiceData/Expressions/AbstractExpression";
  22. import { GraphicalInstantaneousTempoExpression } from "../GraphicalInstantaneousTempoExpression";
  23. import { GraphicalInstantaneousDynamicExpression } from "../GraphicalInstantaneousDynamicExpression";
  24. import log = require("loglevel");
  25. import { GraphicalContinuousDynamicExpression } from "../GraphicalContinuousDynamicExpression";
  26. import { VexFlowContinuousDynamicExpression } from "./VexFlowContinuousDynamicExpression";
  27. import { DrawingParameters } from "../DrawingParameters";
  28. import { GraphicalMusicPage } from "../GraphicalMusicPage";
  29. import { GraphicalMusicSheet } from "../GraphicalMusicSheet";
  30. /**
  31. * This is a global constant which denotes the height in pixels of the space between two lines of the stave
  32. * (when zoom = 1.0)
  33. * @type number
  34. */
  35. export const unitInPixels: number = 10;
  36. export class VexFlowMusicSheetDrawer extends MusicSheetDrawer {
  37. private backend: VexFlowBackend;
  38. private backends: VexFlowBackend[] = [];
  39. private zoom: number = 1.0;
  40. private pageIdx: number = 0; // this is a bad solution, should use MusicPage.PageNumber instead.
  41. constructor(drawingParameters: DrawingParameters = new DrawingParameters()) {
  42. super(new VexFlowTextMeasurer(drawingParameters.Rules), drawingParameters);
  43. }
  44. public get Backends(): VexFlowBackend[] {
  45. return this.backends;
  46. }
  47. public drawSheet(graphicalMusicSheet: GraphicalMusicSheet): void {
  48. this.pageIdx = 0;
  49. for (const graphicalMusicPage of graphicalMusicSheet.MusicPages) {
  50. const backend: VexFlowBackend = this.backends[this.pageIdx];
  51. backend.graphicalMusicPage = graphicalMusicPage;
  52. backend.scale(this.zoom);
  53. //backend.resize(graphicalMusicSheet.ParentMusicSheet.pageWidth * unitInPixels * this.zoom,
  54. // EngravingRules.Rules.PageHeight * unitInPixels * this.zoom);
  55. this.pageIdx += 1;
  56. }
  57. this.pageIdx = 0;
  58. this.backend = this.backends[0];
  59. super.drawSheet(graphicalMusicSheet);
  60. }
  61. protected drawPage(page: GraphicalMusicPage): void {
  62. this.backend = this.backends[page.PageNumber - 1]; // TODO we may need to set this in a couple of other places. this.pageIdx is a bad solution
  63. super.drawPage(page);
  64. this.pageIdx += 1;
  65. this.backend = this.backends[this.pageIdx];
  66. }
  67. public clear(): void {
  68. for (const backend of this.backends) {
  69. backend.clear();
  70. }
  71. }
  72. public setZoom(zoom: number): void {
  73. this.zoom = zoom;
  74. }
  75. /**
  76. * Converts a distance from unit to pixel space.
  77. * @param unitDistance the distance in units
  78. * @returns {number} the distance in pixels
  79. */
  80. public calculatePixelDistance(unitDistance: number): number {
  81. return unitDistance * unitInPixels;
  82. }
  83. protected drawStaffLine(staffLine: StaffLine): void {
  84. super.drawStaffLine(staffLine);
  85. const absolutePos: PointF2D = staffLine.PositionAndShape.AbsolutePosition;
  86. if (this.rules.RenderSlurs) {
  87. this.drawSlurs(staffLine as VexFlowStaffLine, absolutePos);
  88. }
  89. }
  90. private drawSlurs(vfstaffLine: VexFlowStaffLine, absolutePos: PointF2D): void {
  91. for (const graphicalSlur of vfstaffLine.GraphicalSlurs) {
  92. // don't draw crossed slurs, as their curve calculation is not implemented yet:
  93. if (graphicalSlur.slur.isCrossed()) {
  94. continue;
  95. }
  96. this.drawSlur(graphicalSlur, absolutePos);
  97. }
  98. }
  99. private drawSlur(graphicalSlur: GraphicalSlur, abs: PointF2D): void {
  100. const curvePointsInPixels: PointF2D[] = [];
  101. // 1) create inner or original curve:
  102. const p1: PointF2D = new PointF2D(graphicalSlur.bezierStartPt.x + abs.x, graphicalSlur.bezierStartPt.y + abs.y);
  103. const p2: PointF2D = new PointF2D(graphicalSlur.bezierStartControlPt.x + abs.x, graphicalSlur.bezierStartControlPt.y + abs.y);
  104. const p3: PointF2D = new PointF2D(graphicalSlur.bezierEndControlPt.x + abs.x, graphicalSlur.bezierEndControlPt.y + abs.y);
  105. const p4: PointF2D = new PointF2D(graphicalSlur.bezierEndPt.x + abs.x, graphicalSlur.bezierEndPt.y + abs.y);
  106. // put screen transformed points into array
  107. curvePointsInPixels.push(this.applyScreenTransformation(p1));
  108. curvePointsInPixels.push(this.applyScreenTransformation(p2));
  109. curvePointsInPixels.push(this.applyScreenTransformation(p3));
  110. curvePointsInPixels.push(this.applyScreenTransformation(p4));
  111. // 2) create second outer curve to create a thickness for the curve:
  112. if (graphicalSlur.placement === PlacementEnum.Above) {
  113. p1.y -= 0.05;
  114. p2.y -= 0.3;
  115. p3.y -= 0.3;
  116. p4.y -= 0.05;
  117. } else {
  118. p1.y += 0.05;
  119. p2.y += 0.3;
  120. p3.y += 0.3;
  121. p4.y += 0.05;
  122. }
  123. // put screen transformed points into array
  124. curvePointsInPixels.push(this.applyScreenTransformation(p1));
  125. curvePointsInPixels.push(this.applyScreenTransformation(p2));
  126. curvePointsInPixels.push(this.applyScreenTransformation(p3));
  127. curvePointsInPixels.push(this.applyScreenTransformation(p4));
  128. this.backend.renderCurve(curvePointsInPixels);
  129. }
  130. protected drawMeasure(measure: VexFlowMeasure): void {
  131. measure.setAbsoluteCoordinates(
  132. measure.PositionAndShape.AbsolutePosition.x * unitInPixels,
  133. measure.PositionAndShape.AbsolutePosition.y * unitInPixels
  134. );
  135. measure.draw(this.backend.getContext());
  136. // Draw the StaffEntries
  137. for (const staffEntry of measure.staffEntries) {
  138. this.drawStaffEntry(staffEntry);
  139. }
  140. }
  141. // private drawPixel(coord: PointF2D): void {
  142. // coord = this.applyScreenTransformation(coord);
  143. // const ctx: any = this.backend.getContext();
  144. // const oldStyle: string = ctx.fillStyle;
  145. // ctx.fillStyle = "#00FF00FF";
  146. // ctx.fillRect( coord.x, coord.y, 2, 2 );
  147. // ctx.fillStyle = oldStyle;
  148. // }
  149. /** Draws a line in the current backend. Only usable while pages are drawn sequentially, because backend reference is updated in that process.
  150. * To add your own lines after rendering, use DrawOverlayLine.
  151. */
  152. protected drawLine(start: PointF2D, stop: PointF2D, color: string = "#FF0000FF", lineWidth: number = 0.2): void {
  153. // TODO maybe the backend should be given as an argument here as well, otherwise this can't be used after rendering of multiple pages is done.
  154. start = this.applyScreenTransformation(start);
  155. stop = this.applyScreenTransformation(stop);
  156. /*if (!this.backend) {
  157. this.backend = this.backends[0];
  158. }*/
  159. this.backend.renderLine(start, stop, color, lineWidth * unitInPixels);
  160. }
  161. /** Lets a user/developer draw an overlay line on the score. Use this instead of drawLine, which is for OSMD internally only.
  162. * The MusicPage has to be specified, because each page and Vexflow backend has its own relative coordinates.
  163. * (the AbsolutePosition of a GraphicalNote is relative to its backend)
  164. * To get a MusicPage, use GraphicalNote.ParentMusicPage.
  165. */
  166. public DrawOverlayLine(start: PointF2D, stop: PointF2D, musicPage: GraphicalMusicPage,
  167. color: string = "#FF0000FF", lineWidth: number = 0.2): void {
  168. if (!musicPage.PageNumber || musicPage.PageNumber > this.backends.length || musicPage.PageNumber < 1) {
  169. console.log("VexFlowMusicSheetDrawer.drawOverlayLine: invalid page number / music page number doesn't correspond to an existing backend.");
  170. return;
  171. }
  172. const musicPageIndex: number = musicPage.PageNumber - 1;
  173. const backendToUse: VexFlowBackend = this.backends[musicPageIndex];
  174. start = this.applyScreenTransformation(start);
  175. stop = this.applyScreenTransformation(stop);
  176. backendToUse.renderLine(start, stop, color, lineWidth * unitInPixels);
  177. }
  178. protected drawSkyLine(staffline: StaffLine): void {
  179. const startPosition: PointF2D = staffline.PositionAndShape.AbsolutePosition;
  180. const width: number = staffline.PositionAndShape.Size.width;
  181. this.drawSampledLine(staffline.SkyLine, startPosition, width);
  182. }
  183. protected drawBottomLine(staffline: StaffLine): void {
  184. const startPosition: PointF2D = new PointF2D(staffline.PositionAndShape.AbsolutePosition.x,
  185. staffline.PositionAndShape.AbsolutePosition.y);
  186. const width: number = staffline.PositionAndShape.Size.width;
  187. this.drawSampledLine(staffline.BottomLine, startPosition, width, "#0000FFFF");
  188. }
  189. /**
  190. * Draw a line with a width and start point in a chosen color (used for skyline/bottom line debugging) from
  191. * a simple array
  192. * @param line numeric array. 0 marks the base line. Direction given by sign. Dimensions in units
  193. * @param startPosition Start position in units
  194. * @param width Max line width in units
  195. * @param color Color to paint in. Default is red
  196. */
  197. private drawSampledLine(line: number[], startPosition: PointF2D, width: number, color: string = "#FF0000FF"): void {
  198. const indices: number[] = [];
  199. let currentValue: number = 0;
  200. for (let i: number = 0; i < line.length; i++) {
  201. if (line[i] !== currentValue) {
  202. indices.push(i);
  203. currentValue = line[i];
  204. }
  205. }
  206. const absolute: PointF2D = startPosition;
  207. if (indices.length > 0) {
  208. const samplingUnit: number = this.rules.SamplingUnit;
  209. let horizontalStart: PointF2D = new PointF2D(absolute.x, absolute.y);
  210. let horizontalEnd: PointF2D = new PointF2D(indices[0] / samplingUnit + absolute.x, absolute.y);
  211. this.drawLine(horizontalStart, horizontalEnd, color);
  212. let verticalStart: PointF2D;
  213. let verticalEnd: PointF2D;
  214. if (line[0] >= 0) {
  215. verticalStart = new PointF2D(indices[0] / samplingUnit + absolute.x, absolute.y);
  216. verticalEnd = new PointF2D(indices[0] / samplingUnit + absolute.x, absolute.y + line[indices[0]]);
  217. this.drawLine(verticalStart, verticalEnd, color);
  218. }
  219. for (let i: number = 1; i < indices.length; i++) {
  220. horizontalStart = new PointF2D(indices[i - 1] / samplingUnit + absolute.x, absolute.y + line[indices[i - 1]]);
  221. horizontalEnd = new PointF2D(indices[i] / samplingUnit + absolute.x, absolute.y + line[indices[i - 1]]);
  222. this.drawLine(horizontalStart, horizontalEnd, color);
  223. verticalStart = new PointF2D(indices[i] / samplingUnit + absolute.x, absolute.y + line[indices[i - 1]]);
  224. verticalEnd = new PointF2D(indices[i] / samplingUnit + absolute.x, absolute.y + line[indices[i]]);
  225. this.drawLine(verticalStart, verticalEnd, color);
  226. }
  227. if (indices[indices.length - 1] < line.length) {
  228. horizontalStart = new PointF2D(indices[indices.length - 1] / samplingUnit + absolute.x, absolute.y + line[indices[indices.length - 1]]);
  229. horizontalEnd = new PointF2D(absolute.x + width, absolute.y + line[indices[indices.length - 1]]);
  230. this.drawLine(horizontalStart, horizontalEnd, color);
  231. } else {
  232. horizontalStart = new PointF2D(indices[indices.length - 1] / samplingUnit + absolute.x, absolute.y);
  233. horizontalEnd = new PointF2D(absolute.x + width, absolute.y);
  234. this.drawLine(horizontalStart, horizontalEnd, color);
  235. }
  236. } else {
  237. // Flat line
  238. const start: PointF2D = new PointF2D(absolute.x, absolute.y);
  239. const end: PointF2D = new PointF2D(absolute.x + width, absolute.y);
  240. this.drawLine(start, end, color);
  241. }
  242. }
  243. private drawStaffEntry(staffEntry: GraphicalStaffEntry): void {
  244. // Draw ChordSymbols
  245. if (staffEntry.graphicalChordContainers !== undefined && staffEntry.graphicalChordContainers.length > 0) {
  246. for (const graphicalChordContainer of staffEntry.graphicalChordContainers) {
  247. this.drawLabel(graphicalChordContainer.GetGraphicalLabel, <number>GraphicalLayers.Notes);
  248. }
  249. }
  250. if (this.rules.RenderLyrics) {
  251. if (staffEntry.LyricsEntries.length > 0) {
  252. this.drawLyrics(staffEntry.LyricsEntries, <number>GraphicalLayers.Notes);
  253. }
  254. }
  255. }
  256. /**
  257. * Draw all lyrics to the canvas
  258. * @param lyricEntries Array of lyric entries to be drawn
  259. * @param layer Number of the layer that the lyrics should be drawn in
  260. */
  261. private drawLyrics(lyricEntries: GraphicalLyricEntry[], layer: number): void {
  262. lyricEntries.forEach(lyricsEntry => this.drawLabel(lyricsEntry.GraphicalLabel, layer));
  263. }
  264. protected drawInstrumentBrace(brace: GraphicalObject, system: MusicSystem): void {
  265. // Draw InstrumentBrackets at beginning of line
  266. const vexBrace: VexFlowInstrumentBrace = (brace as VexFlowInstrumentBrace);
  267. vexBrace.draw(this.backend.getContext());
  268. }
  269. protected drawGroupBracket(bracket: GraphicalObject, system: MusicSystem): void {
  270. // Draw InstrumentBrackets at beginning of line
  271. const vexBrace: VexFlowInstrumentBracket = (bracket as VexFlowInstrumentBracket);
  272. vexBrace.draw(this.backend.getContext());
  273. }
  274. protected drawOctaveShifts(staffLine: StaffLine): void {
  275. for (const graphicalOctaveShift of staffLine.OctaveShifts) {
  276. if (graphicalOctaveShift) {
  277. const ctx: Vex.IRenderContext = this.backend.getContext();
  278. const textBracket: Vex.Flow.TextBracket = (graphicalOctaveShift as VexFlowOctaveShift).getTextBracket();
  279. textBracket.setContext(ctx);
  280. const startX: number = staffLine.PositionAndShape.AbsolutePosition.x + textBracket.start.getX() / 10;
  281. const stopX: number = staffLine.PositionAndShape.AbsolutePosition.x + textBracket.stop.getX() / 10;
  282. if ((<any>textBracket).position === Vex.Flow.TextBracket.Positions.TOP) {
  283. const headroom: number = staffLine.SkyBottomLineCalculator.getSkyLineMinInRange(startX, stopX);
  284. if (headroom === Infinity) { // will cause Vexflow error
  285. return;
  286. }
  287. textBracket.start.getStave().options.space_above_staff_ln = headroom;
  288. } else {
  289. const footroom: number = staffLine.SkyBottomLineCalculator.getBottomLineMaxInRange(startX, stopX);
  290. if (footroom === Infinity) { // will cause Vexflow error
  291. return;
  292. }
  293. textBracket.start.getStave().options.space_below_staff_ln = footroom;
  294. }
  295. textBracket.draw();
  296. }
  297. }
  298. }
  299. protected drawExpressions(staffline: StaffLine): void {
  300. // Draw all Expressions
  301. for (const abstractGraphicalExpression of staffline.AbstractExpressions) {
  302. // Draw InstantaniousDynamics
  303. if (abstractGraphicalExpression instanceof GraphicalInstantaneousDynamicExpression) {
  304. this.drawInstantaneousDynamic((abstractGraphicalExpression as VexFlowInstantaneousDynamicExpression));
  305. // Draw InstantaniousTempo
  306. } else if (abstractGraphicalExpression instanceof GraphicalInstantaneousTempoExpression) {
  307. this.drawLabel((abstractGraphicalExpression as GraphicalInstantaneousTempoExpression).GraphicalLabel, GraphicalLayers.Notes);
  308. // Draw ContinuousDynamics
  309. } else if (abstractGraphicalExpression instanceof GraphicalContinuousDynamicExpression) {
  310. this.drawContinuousDynamic((abstractGraphicalExpression as VexFlowContinuousDynamicExpression));
  311. // Draw ContinuousTempo
  312. // } else if (abstractGraphicalExpression instanceof GraphicalContinuousTempoExpression) {
  313. // this.drawLabel((abstractGraphicalExpression as GraphicalContinuousTempoExpression).GraphicalLabel, GraphicalLayers.Notes);
  314. // // Draw Mood
  315. // } else if (abstractGraphicalExpression instanceof GraphicalMoodExpression) {
  316. // GraphicalMoodExpression; graphicalMood = (GraphicalMoodExpression); abstractGraphicalExpression;
  317. // drawLabel(graphicalMood.GetGraphicalLabel, (int)GraphicalLayers.Notes);
  318. // // Draw Unknown
  319. // } else if (abstractGraphicalExpression instanceof GraphicalUnknownExpression) {
  320. // GraphicalUnknownExpression; graphicalUnknown =
  321. // (GraphicalUnknownExpression); abstractGraphicalExpression;
  322. // drawLabel(graphicalUnknown.GetGraphicalLabel, (int)GraphicalLayers.Notes);
  323. // }
  324. } else {
  325. log.warn("Unkown type of expression!");
  326. }
  327. }
  328. }
  329. protected drawInstantaneousDynamic(instantaneousDynamic: GraphicalInstantaneousDynamicExpression): void {
  330. this.drawLabel((instantaneousDynamic as VexFlowInstantaneousDynamicExpression).Label, <number>GraphicalLayers.Notes);
  331. }
  332. protected drawContinuousDynamic(graphicalExpression: VexFlowContinuousDynamicExpression): void {
  333. if (graphicalExpression.IsVerbal) {
  334. this.drawLabel(graphicalExpression.Label, <number>GraphicalLayers.Notes);
  335. } else {
  336. for (const line of graphicalExpression.Lines) {
  337. const start: PointF2D = new PointF2D(graphicalExpression.ParentStaffLine.PositionAndShape.AbsolutePosition.x + line.Start.x,
  338. graphicalExpression.ParentStaffLine.PositionAndShape.AbsolutePosition.y + line.Start.y);
  339. const end: PointF2D = new PointF2D(graphicalExpression.ParentStaffLine.PositionAndShape.AbsolutePosition.x + line.End.x,
  340. graphicalExpression.ParentStaffLine.PositionAndShape.AbsolutePosition.y + line.End.y);
  341. this.drawLine(start, end, "black", line.Width);
  342. }
  343. }
  344. }
  345. /**
  346. * Renders a Label to the screen (e.g. Title, composer..)
  347. * @param graphicalLabel holds the label string, the text height in units and the font parameters
  348. * @param layer is the current rendering layer. There are many layers on top of each other to which can be rendered. Not needed for now.
  349. * @param bitmapWidth Not needed for now.
  350. * @param bitmapHeight Not needed for now.
  351. * @param heightInPixel the height of the text in screen coordinates
  352. * @param screenPosition the position of the lower left corner of the text in screen coordinates
  353. */
  354. protected renderLabel(graphicalLabel: GraphicalLabel, layer: number, bitmapWidth: number,
  355. bitmapHeight: number, heightInPixel: number, screenPosition: PointF2D): void {
  356. const height: number = graphicalLabel.Label.fontHeight * unitInPixels;
  357. const { fontStyle, font, text } = graphicalLabel.Label;
  358. let color: string;
  359. if (this.rules.ColoringEnabled) {
  360. color = graphicalLabel.Label.colorDefault;
  361. if (!color) {
  362. color = this.rules.DefaultColorLabel;
  363. }
  364. }
  365. this.backend.renderText(height, fontStyle, font, text, heightInPixel, screenPosition, color);
  366. }
  367. /**
  368. * Renders a rectangle with the given style to the screen.
  369. * It is given in screen coordinates.
  370. * @param rectangle the rect in screen coordinates
  371. * @param layer is the current rendering layer. There are many layers on top of each other to which can be rendered. Not needed for now.
  372. * @param styleId the style id
  373. * @param alpha alpha value between 0 and 1
  374. */
  375. protected renderRectangle(rectangle: RectangleF2D, layer: number, styleId: number, alpha: number): void {
  376. this.backend.renderRectangle(rectangle, styleId, alpha);
  377. }
  378. /**
  379. * Converts a point from unit to pixel space.
  380. * @param point
  381. * @returns {PointF2D}
  382. */
  383. protected applyScreenTransformation(point: PointF2D): PointF2D {
  384. return new PointF2D(point.x * unitInPixels, point.y * unitInPixels);
  385. }
  386. /**
  387. * Converts a rectangle from unit to pixel space.
  388. * @param rectangle
  389. * @returns {RectangleF2D}
  390. */
  391. protected applyScreenTransformationForRect(rectangle: RectangleF2D): RectangleF2D {
  392. return new RectangleF2D(rectangle.x * unitInPixels, rectangle.y * unitInPixels, rectangle.width * unitInPixels, rectangle.height * unitInPixels);
  393. }
  394. }