jpfun 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +141 -11
  2. package/dist/converter/midi/convert.d.ts +50 -0
  3. package/dist/converter/midi/convert.js +700 -0
  4. package/dist/converter/midi/index.d.ts +5 -0
  5. package/dist/converter/midi/index.js +11 -0
  6. package/dist/converter/midi/json.d.ts +38 -0
  7. package/dist/converter/midi/json.js +1 -0
  8. package/dist/converter/midi/triplet.d.ts +30 -0
  9. package/dist/converter/midi/triplet.js +75 -0
  10. package/dist/converter/musicxml/dom.d.ts +25 -0
  11. package/dist/converter/musicxml/dom.js +65 -0
  12. package/dist/converter/musicxml/features.d.ts +51 -0
  13. package/dist/converter/musicxml/features.js +232 -0
  14. package/dist/converter/musicxml/index.d.ts +9 -0
  15. package/dist/converter/musicxml/index.js +1140 -0
  16. package/dist/converter/musicxml/model.d.ts +123 -0
  17. package/dist/converter/musicxml/model.js +1 -0
  18. package/dist/converter/source.d.ts +22 -0
  19. package/dist/converter/source.js +51 -0
  20. package/dist/core.d.ts +22 -0
  21. package/dist/core.js +22 -0
  22. package/dist/diagnostic.js +5 -2
  23. package/dist/fraction.d.ts +24 -0
  24. package/dist/fraction.js +132 -0
  25. package/dist/functions/ASTtypes.d.ts +51 -31
  26. package/dist/functions/ASTtypes.js +59 -38
  27. package/dist/functions/adjust/index.d.ts +2 -0
  28. package/dist/functions/adjust/index.js +193 -0
  29. package/dist/functions/arpeggio/index.d.ts +2 -0
  30. package/dist/functions/arpeggio/index.js +180 -0
  31. package/dist/functions/arpeggio/shape.d.ts +7 -0
  32. package/dist/functions/arpeggio/shape.js +122 -0
  33. package/dist/functions/bar/index.d.ts +8 -0
  34. package/dist/functions/bar/index.js +62 -25
  35. package/dist/functions/beam/auto.d.ts +1 -1
  36. package/dist/functions/beam/auto.js +33 -16
  37. package/dist/functions/beam/index.js +10 -6
  38. package/dist/functions/beam/layout.d.ts +4 -3
  39. package/dist/functions/beam/layout.js +43 -65
  40. package/dist/functions/box/index.js +37 -36
  41. package/dist/functions/br/index.js +10 -8
  42. package/dist/functions/dash/index.js +40 -7
  43. package/dist/functions/default.js +19 -8
  44. package/dist/functions/div/index.d.ts +16 -0
  45. package/dist/functions/div/index.js +45 -17
  46. package/dist/functions/dot/index.js +23 -25
  47. package/dist/functions/dyn/index.d.ts +2 -0
  48. package/dist/functions/dyn/index.js +242 -0
  49. package/dist/functions/grace/index.d.ts +8 -11
  50. package/dist/functions/grace/index.js +84 -79
  51. package/dist/functions/head/index.d.ts +2 -0
  52. package/dist/functions/head/index.js +496 -0
  53. package/dist/functions/key/index.js +98 -3
  54. package/dist/functions/meter/index.d.ts +2 -0
  55. package/dist/functions/meter/index.js +155 -0
  56. package/dist/functions/note/accidentals.d.ts +24 -3
  57. package/dist/functions/note/accidentals.js +31 -1
  58. package/dist/functions/note/index.js +106 -79
  59. package/dist/functions/note/noteNameFSM.js +52 -63
  60. package/dist/functions/page/index.d.ts +11 -2
  61. package/dist/functions/page/index.js +65 -4
  62. package/dist/functions/program/index.d.ts +2 -0
  63. package/dist/functions/program/index.js +30 -0
  64. package/dist/functions/set/index.js +43 -32
  65. package/dist/functions/stack/index.js +26 -22
  66. package/dist/functions/symbol/index.d.ts +31 -0
  67. package/dist/functions/symbol/index.js +139 -0
  68. package/dist/functions/symbol/ornament.d.ts +15 -0
  69. package/dist/functions/symbol/ornament.js +73 -0
  70. package/dist/functions/symbol/shape.d.ts +24 -0
  71. package/dist/functions/symbol/shape.js +52 -0
  72. package/dist/functions/symbol/symbols/accent.d.ts +2 -0
  73. package/dist/functions/symbol/symbols/accent.js +24 -0
  74. package/dist/functions/symbol/symbols/dc.d.ts +4 -0
  75. package/dist/functions/symbol/symbols/dc.js +82 -0
  76. package/dist/functions/symbol/symbols/ds.d.ts +2 -0
  77. package/dist/functions/symbol/symbols/ds.js +93 -0
  78. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  79. package/dist/functions/symbol/symbols/dynamics.js +168 -0
  80. package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
  81. package/dist/functions/symbol/symbols/fermata.js +24 -0
  82. package/dist/functions/symbol/symbols/fine.d.ts +2 -0
  83. package/dist/functions/symbol/symbols/fine.js +12 -0
  84. package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
  85. package/dist/functions/symbol/symbols/mordent.js +56 -0
  86. package/dist/functions/symbol/symbols/prall.d.ts +2 -0
  87. package/dist/functions/symbol/symbols/prall.js +42 -0
  88. package/dist/functions/symbol/symbols/segno.d.ts +4 -0
  89. package/dist/functions/symbol/symbols/segno.js +82 -0
  90. package/dist/functions/symbol/symbols/tr.d.ts +2 -0
  91. package/dist/functions/symbol/symbols/tr.js +71 -0
  92. package/dist/functions/tempo/glyph.d.ts +12 -0
  93. package/dist/functions/tempo/glyph.js +30 -0
  94. package/dist/functions/tempo/index.js +57 -4
  95. package/dist/functions/temporal.d.ts +138 -0
  96. package/dist/functions/temporal.js +101 -0
  97. package/dist/functions/text/index.js +86 -27
  98. package/dist/functions/tie/index.js +136 -152
  99. package/dist/functions/tuplet/index.d.ts +2 -0
  100. package/dist/functions/tuplet/index.js +218 -0
  101. package/dist/functions/up/index.d.ts +1 -0
  102. package/dist/functions/up/index.js +258 -182
  103. package/dist/functions/voice/index.js +203 -109
  104. package/dist/functions/volta/index.d.ts +2 -0
  105. package/dist/functions/volta/index.js +230 -0
  106. package/dist/iife/core.d.ts +1 -0
  107. package/dist/iife/core.js +3 -0
  108. package/dist/iife/from-midi.d.ts +1 -0
  109. package/dist/iife/from-midi.js +15 -0
  110. package/dist/iife/from-musicxml.d.ts +1 -0
  111. package/dist/iife/from-musicxml.js +3 -0
  112. package/dist/iife/full.d.ts +1 -0
  113. package/dist/iife/full.js +3 -0
  114. package/dist/index.d.ts +3 -17
  115. package/dist/index.js +3 -17
  116. package/dist/jpfun.core.min.js +153 -0
  117. package/dist/jpfun.from-midi.min.js +9 -0
  118. package/dist/jpfun.from-musicxml.min.js +12 -0
  119. package/dist/jpfun.min.js +166 -0
  120. package/dist/layout/default.js +2 -3
  121. package/dist/layout/engine.d.ts +6 -12
  122. package/dist/layout/engine.js +115 -64
  123. package/dist/layout/model.d.ts +12 -5
  124. package/dist/layout/model.js +31 -18
  125. package/dist/layout/page.js +5 -4
  126. package/dist/layout/path.d.ts +19 -0
  127. package/dist/layout/path.js +101 -0
  128. package/dist/layout/types.d.ts +71 -20
  129. package/dist/layout/types.js +3 -1
  130. package/dist/lowering/loweringContext.d.ts +20 -20
  131. package/dist/lowering/loweringContext.js +153 -101
  132. package/dist/lowering/track.d.ts +5 -9
  133. package/dist/lowering/track.js +7 -2
  134. package/dist/lowering/types.d.ts +26 -112
  135. package/dist/lowering/types.js +1 -92
  136. package/dist/parser/parse-utils/call-utils.d.ts +0 -2
  137. package/dist/parser/parse-utils/call-utils.js +0 -6
  138. package/dist/parser/parse-utils/note-utils.d.ts +8 -0
  139. package/dist/parser/parse-utils/note-utils.js +35 -13
  140. package/dist/parser/parse-utils/string-utils.d.ts +10 -0
  141. package/dist/parser/parse-utils/string-utils.js +24 -0
  142. package/dist/parser/parserContext.d.ts +11 -9
  143. package/dist/parser/parserContext.js +65 -55
  144. package/dist/parser/preprocess.js +17 -11
  145. package/dist/pipeline.d.ts +6 -5
  146. package/dist/pipeline.js +4 -5
  147. package/dist/playback/compile.d.ts +18 -0
  148. package/dist/playback/compile.js +414 -0
  149. package/dist/playback/event.d.ts +105 -0
  150. package/dist/playback/event.js +105 -0
  151. package/dist/playback/time.d.ts +14 -0
  152. package/dist/playback/time.js +81 -0
  153. package/dist/playback/types.d.ts +129 -0
  154. package/dist/playback/types.js +3 -0
  155. package/dist/render/canvas.d.ts +4 -4
  156. package/dist/render/canvas.js +20 -5
  157. package/dist/render/index.d.ts +1 -0
  158. package/dist/render/index.js +1 -0
  159. package/dist/render/paint.d.ts +8 -0
  160. package/dist/render/paint.js +101 -0
  161. package/dist/render/svg.d.ts +3 -3
  162. package/dist/render/svg.js +10 -8
  163. package/dist/render/text.d.ts +22 -0
  164. package/dist/render/text.js +42 -0
  165. package/dist/render/types.d.ts +1 -1
  166. package/grammar.md +132 -13
  167. package/package.json +19 -6
@@ -1,6 +1,7 @@
1
1
  import { ASTFunctionNode } from "../ASTtypes.js";
2
- import { ErrorDiagnostic } from "../../diagnostic.js";
3
- import { isVisualTemporalNode, } from "../../lowering/types.js";
2
+ import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
+ import { isVisualTemporalNode, } from "../temporal.js";
4
+ import { pathBounds } from "../../layout/path.js";
4
5
  /** 三次贝塞尔控制点的抬高系数:两个控制点同高时,实际弧高恰好是抬高的 3/4 */
5
6
  const CUBIC_LIFT = 4 / 3;
6
7
  /** 弧带中部最大厚度与字号之比 */
@@ -19,28 +20,27 @@ class TieFunction extends ASTFunctionNode {
19
20
  height;
20
21
  constructor(sourceSpan, args, ctx, parent = null) {
21
22
  super(sourceSpan, parent);
22
- let height = ctx.fontSize * 0.5;
23
+ let height = ctx.variables.fontsize * 0.5;
23
24
  for (const [key, value] of args) {
24
25
  if (key === "height") {
25
- const length = ctx.parseArgWithType(value.start, value.end, "length", sourceSpan.start);
26
+ const length = ctx.parseArgWithType(value.valueSpan, "length", sourceSpan.start);
26
27
  if (length)
27
28
  height = Math.max(0, ctx.length2px(length));
28
29
  continue;
29
30
  }
30
31
  const v = value instanceof ASTFunctionNode
31
32
  ? value
32
- : ctx.parseArgWithType(value.start, value.end, "label", sourceSpan.start);
33
+ : ctx.parseArgWithType(value.valueSpan, "label", sourceSpan.start);
33
34
  if (v !== null)
34
35
  this.endPoints.push(v);
35
36
  }
36
- // 数目不足,则找最近的
37
+ // 数目不足,则找最近的;用 unshift 而不是按下标赋值,否则空洞会让 length 虚高、骗过下面的校验
37
38
  let k = ctx.labelableNodes.length - 1;
38
- for (let i = this.endPoints.length; i < 2; i++) {
39
- while (k >= 0 && this.endPoints.includes(ctx.labelableNodes[k]))
40
- k--;
41
- if (k < 0)
42
- break;
43
- this.endPoints[1 - i] = ctx.labelableNodes[k--]; // 保持顺序
39
+ while (this.endPoints.length < 2 && k >= 0) {
40
+ const candidate = ctx.labelableNodes[k--];
41
+ if (!candidate || this.endPoints.includes(candidate))
42
+ continue;
43
+ this.endPoints.unshift(candidate);
44
44
  }
45
45
  if (this.endPoints.length < 2)
46
46
  throw new ErrorDiagnostic("E_NOT_ENOUGH_ARGS", "@tie 连音线需要至少两个端点", sourceSpan);
@@ -58,9 +58,11 @@ class TieFunction extends ASTFunctionNode {
58
58
  continue;
59
59
  endPoints.push(temporal);
60
60
  }
61
- if (endPoints.length < 2)
61
+ if (endPoints.length < 2) {
62
+ ctx.diagnostics.push(Diagnostic.warning.UnresolvedEndpoint("tie", this.sourceSpan));
62
63
  return [];
63
- ctx.addLayoutAttachment(new TieLayoutAttachment(endPoints, this.height));
64
+ }
65
+ ctx.addAttachment(new TieLayoutAttachment(endPoints, this.height, this.sourceSpan));
64
66
  return [];
65
67
  }
66
68
  toString(source) {
@@ -68,123 +70,89 @@ class TieFunction extends ASTFunctionNode {
68
70
  }
69
71
  }
70
72
  export const TieNode = TieFunction;
71
- /** 二次贝塞尔在某一维上的内部极值 */
72
- function quadExtremum(p0, p1, p2) {
73
- const d = p0 - 2 * p1 + p2;
74
- if (Math.abs(d) < 1e-9)
75
- return null;
76
- const t = (p0 - p1) / d;
77
- if (t <= 0 || t >= 1)
78
- return null;
79
- const u = 1 - t;
80
- return u * u * p0 + 2 * u * t * p1 + t * t * p2;
81
- }
82
- /** 三次贝塞尔在某一维上的内部极值,最多两个 */
83
- function cubicExtrema(p0, p1, p2, p3, out) {
84
- // 导数为 3(qa*t^2 + qb*t + a),下面的 a 就是常数项
85
- const a = p1 - p0;
86
- const b = p2 - p1;
87
- const c = p3 - p2;
88
- const qa = a - 2 * b + c;
89
- const qb = 2 * (b - a);
90
- const push = (t) => {
91
- if (t <= 0 || t >= 1)
92
- return;
93
- const u = 1 - t;
94
- out.push(u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3);
95
- };
96
- if (Math.abs(qa) < 1e-9) {
97
- if (Math.abs(qb) > 1e-9)
98
- push(-a / qb);
99
- return;
100
- }
101
- const disc = qb * qb - 4 * qa * a;
102
- if (disc < 0)
103
- return;
104
- const root = Math.sqrt(disc);
105
- push((-qb + root) / (2 * qa));
106
- push((-qb - root) / (2 * qa));
107
- }
108
- /**
109
- * 精确求出路径的外接矩形
110
- *
111
- * 控制点不直接计入:贝塞尔曲线并不会到达控制点,
112
- * 直接用它会把弧顶高估约三分之一,从而让上方的轨道被无谓推开
113
- */
114
- function pathBounds(commands) {
115
- let left = Infinity;
116
- let top = Infinity;
117
- let right = -Infinity;
118
- let bottom = -Infinity;
119
- const includeX = (x) => { left = Math.min(left, x); right = Math.max(right, x); };
120
- const includeY = (y) => { top = Math.min(top, y); bottom = Math.max(bottom, y); };
121
- let cx = 0;
122
- let cy = 0;
123
- const extrema = [];
124
- for (const command of commands) {
125
- if (command.op === "Z")
126
- continue;
127
- if (command.op === "Q") {
128
- const ex = quadExtremum(cx, command.cx, command.x);
129
- if (ex !== null)
130
- includeX(ex);
131
- const ey = quadExtremum(cy, command.cy, command.y);
132
- if (ey !== null)
133
- includeY(ey);
134
- }
135
- else if (command.op === "C") {
136
- extrema.length = 0;
137
- cubicExtrema(cx, command.cx1, command.cx2, command.x, extrema);
138
- for (const value of extrema)
139
- includeX(value);
140
- extrema.length = 0;
141
- cubicExtrema(cy, command.cy1, command.cy2, command.y, extrema);
142
- for (const value of extrema)
143
- includeY(value);
144
- }
145
- includeX(cx = command.x);
146
- includeY(cy = command.y);
147
- }
148
- if (!Number.isFinite(left))
149
- return { left: 0, top: 0, right: 0, bottom: 0 };
150
- return { left, top, right, bottom };
151
- }
152
73
  class TieLayoutAttachment {
153
- box = {
154
- x: 0,
155
- y: 0,
156
- w: 0,
157
- h: 0,
158
- };
159
74
  layer = "foreground";
75
+ sourceSpan;
160
76
  endPoints;
161
77
  height;
162
- segments = [];
163
- /** 弧带中部厚度;两端收尖到 0 */
164
- thickness = 1;
165
- constructor(endPoints, height) {
78
+ /** 弧带中部厚度;两端收尖到 0。端点字号不随布局变化,可以一次算定 */
79
+ thickness;
80
+ constructor(endPoints, height, sourceSpan) {
166
81
  this.endPoints = endPoints;
167
82
  this.height = height;
83
+ this.sourceSpan = sourceSpan;
84
+ const size = endPoints.reduce((current, endpoint) => Math.max(current, endpoint.ast.size), 0);
85
+ this.thickness = Math.max(1.2, size * THICKNESS_RATIO);
168
86
  }
169
- layout(context) {
170
- this.updateGeometry(context);
171
- return this.segments.map(segment => ({
172
- x: segment.left,
173
- y: segment.top,
174
- w: segment.right - segment.left,
175
- h: segment.bottom - segment.top,
176
- line: segment.line,
177
- track: segment.track,
178
- }));
179
- }
180
- paint(painter) {
181
- for (const segment of this.segments) {
182
- // 弧带本身就是闭合轮廓,直接填充就能得到两端收尖、中部较粗的乐谱弧线
183
- painter.drawPath(segment.commands, { fill: "#000" });
87
+ /**
88
+ * 只有同轨、同音、演奏时间连续的事件对才合并,其余 tie 纯视觉
89
+ *
90
+ * 反复会让同一个端点产生多个事件对,所以按首端点的每一个 NoteOn 各串一条链。
91
+ */
92
+ applyPlayback(context) {
93
+ const noteOns = () => context.events
94
+ .filter((event) => event.kind === "note-on");
95
+ const noteOff = (noteId) => context.events
96
+ .find((event) => event.kind === "note-off" && event.noteId === noteId);
97
+ for (const head of noteOns().filter(note => note.origins.some(origin => origin.node === this.endPoints[0]))) {
98
+ for (let i = 1; i < this.endPoints.length; i++) {
99
+ const end = noteOff(head.noteId);
100
+ if (!end)
101
+ break;
102
+ const next = noteOns().find(note => note.noteId !== head.noteId
103
+ && note.origins.some(origin => origin.node === this.endPoints[i])
104
+ && note.track === head.track
105
+ && note.midi === head.midi
106
+ && note.percussion === head.percussion
107
+ && end.at.equals(note.at));
108
+ if (!next)
109
+ break;
110
+ const nextOff = noteOff(next.noteId);
111
+ if (!nextOff)
112
+ break;
113
+ head.sourceSpans.push(...next.sourceSpans);
114
+ for (const origin of next.origins) {
115
+ if (!head.origins.includes(origin))
116
+ head.origins.push(origin);
117
+ }
118
+ nextOff.noteId = head.noteId;
119
+ nextOff.origins = [...head.origins];
120
+ context.events.splice(0, context.events.length, ...context.events.filter(event => event !== end && event !== next));
121
+ }
184
122
  }
185
123
  }
186
- absolutePort(node, name) {
187
- const port = node.ports[name];
124
+ createGeometry(context) {
125
+ const segments = this.createSegments(context);
126
+ const regions = segments.map(({ commands, ...region }) => region);
127
+ const occupancy = segments.map(segment => {
128
+ // 只申报主体上方那一段,下半截由主体自己占;本行没有主体时就只有弧带本身
129
+ // 用 getHostExtent 而不是 getRangeExtents:连音线只避让主体,彼此之间允许重叠
130
+ const hostExtent = context.getHostExtent(segment.line, segment.track);
131
+ const bottom = hostExtent
132
+ ? Math.max(segment.y, context.getVisualAxis(segment.line, segment.track) + hostExtent.top)
133
+ : segment.y + segment.h;
134
+ return {
135
+ x: segment.x,
136
+ y: segment.y,
137
+ w: segment.w,
138
+ h: bottom - segment.y,
139
+ line: segment.line,
140
+ track: segment.track,
141
+ };
142
+ });
143
+ return {
144
+ regions,
145
+ occupancy,
146
+ paint(painter) {
147
+ for (const segment of segments) {
148
+ // 弧带本身就是闭合轮廓,直接填充就能得到两端收尖、中部较粗的乐谱弧线
149
+ painter.drawPath(segment.commands, { fill: "#000" });
150
+ }
151
+ },
152
+ };
153
+ }
154
+ tiePort(node) {
155
+ const port = node.ports["tie.top"];
188
156
  if (port) {
189
157
  return {
190
158
  x: node.box.x + port.x,
@@ -196,45 +164,62 @@ class TieLayoutAttachment {
196
164
  y: node.box.y,
197
165
  };
198
166
  }
199
- /** 根据端点固化后的行号选择同行弧线或跨行分段。 */
200
- updateGeometry(context) {
201
- const size = this.endPoints.reduce((current, endpoint) => Math.max(current, endpoint.ast.size), 0);
202
- this.segments.length = 0;
203
- this.thickness = Math.max(1.2, size * THICKNESS_RATIO);
167
+ /** 根据端点固化后的行号选择同行弧线或跨行分段 */
168
+ createSegments(context) {
169
+ const segments = [];
204
170
  for (let i = 1; i < this.endPoints.length; i++) {
205
171
  let startNode = this.endPoints[i - 1];
206
172
  let endNode = this.endPoints[i];
207
173
  // 标签书写顺序不保证时间顺序,先按谱面行升序规范化
208
174
  if (startNode.layoutLine > endNode.layoutLine)
209
175
  [startNode, endNode] = [endNode, startNode];
210
- const start = this.absolutePort(startNode, "tie.top");
211
- const end = this.absolutePort(endNode, "tie.top");
176
+ const start = this.tiePort(startNode);
177
+ const end = this.tiePort(endNode);
212
178
  if (startNode.layoutLine === endNode.layoutLine) {
213
179
  const startTop = context.getVisualAxis(startNode.layoutLine, startNode.track)
214
180
  + (context.getHostExtent(startNode.layoutLine, startNode.track)?.top ?? 0);
215
181
  const endTop = context.getVisualAxis(endNode.layoutLine, endNode.track)
216
182
  + (context.getHostExtent(endNode.layoutLine, endNode.track)?.top ?? 0);
217
- this.addArc(start, end, startNode.layoutLine, startTop <= endTop ? startNode.track : endNode.track);
183
+ segments.push(this.arcSegment(start, end, startNode.layoutLine, startTop <= endTop ? startNode.track : endNode.track));
218
184
  continue;
219
185
  }
220
186
  // 首行先起弧,再沿水平段延伸到当前谱面行最右侧
221
- this.addOpeningSegment(start, context.originX + context.width, this.plateauY(context, startNode.layoutLine, startNode.track, start.y), startNode.layoutLine, startNode.track);
187
+ segments.push(this.openingSegment(start, this.lineRightX(context, startNode.layoutLine), this.plateauY(context, startNode.layoutLine, startNode.track, start.y), startNode.layoutLine, startNode.track));
222
188
  // 中间行可能没有任何可见对象,仍然需要逐行补一段水平线
223
189
  for (let line = startNode.layoutLine + 1; line < endNode.layoutLine; line++) {
224
- this.addHorizontalSegment(context.originX, context.originX + context.width, this.plateauY(context, line, startNode.track), line, startNode.track);
190
+ segments.push(this.horizontalSegment(this.lineEntryX(context, line, startNode.track), this.lineRightX(context, line), this.plateauY(context, line, startNode.track), line, startNode.track));
225
191
  }
226
- // 末行从最左侧进入,经过水平段后落弧到终点
227
- this.addClosingSegment(context.originX, end, this.plateauY(context, endNode.layoutLine, endNode.track, end.y), endNode.layoutLine, endNode.track);
192
+ // 跳过声部名、大括号等位于端点列之前的系统前缀,再落弧到终点
193
+ segments.push(this.closingSegment(this.lineEntryX(context, endNode.layoutLine, endNode.track), end, this.plateauY(context, endNode.layoutLine, endNode.track, end.y), endNode.layoutLine, endNode.track));
194
+ }
195
+ return segments;
196
+ }
197
+ lineEntryX(context, lineIndex, track) {
198
+ const line = context.lines[lineIndex];
199
+ const host = line.trackRuns.get(track)?.find(host => !host.T.isZero());
200
+ return host?.box.x ?? context.originX;
201
+ }
202
+ lineRightX(context, lineIndex) {
203
+ const runs = context.lines[lineIndex].trackRuns;
204
+ if (runs.size === 0)
205
+ return context.originX + context.width;
206
+ let right = context.originX;
207
+ for (const run of runs.values()) {
208
+ for (const host of run)
209
+ right = Math.max(right, host.box.x + host.box.w);
228
210
  }
211
+ return right;
229
212
  }
230
- /** 沿用普通端点的抬高量,但基准至少是当前 Track 的最高主体。 */
213
+ /** 有端点时从端点固定抬高;中间段没有端点,才以当前 Track 的主体顶部为基准 */
231
214
  plateauY(context, line, track, endpointY = Infinity) {
215
+ if (Number.isFinite(endpointY))
216
+ return endpointY - this.height;
232
217
  const axis = context.getVisualAxis(line, track);
233
218
  const hostTop = context.getHostExtent(line, track)?.top ?? 0;
234
- return Math.min(endpointY, axis + hostTop) - this.height;
219
+ return axis + hostTop - this.height;
235
220
  }
236
221
  /** 一条三次贝塞尔的外缘配上反向内缘,得到两端收尖、中部最厚的乐谱弧线 */
237
- addArc(startInput, endInput, line, track) {
222
+ arcSegment(startInput, endInput, line, track) {
238
223
  let start = startInput;
239
224
  let end = endInput;
240
225
  if (start.x > end.x)
@@ -250,16 +235,16 @@ class TieLayoutAttachment {
250
235
  { op: "C", cx1: rightX, cy1: end.y - inner, cx2: leftX, cy2: start.y - inner, x: start.x, y: start.y },
251
236
  { op: "Z" },
252
237
  ];
253
- this.addSegment(commands, line, track);
238
+ return makeSegment(commands, line, track);
254
239
  }
255
240
  /** 跨行首段:从端点起弧,随后水平延伸到右边界 */
256
- addOpeningSegment(start, right, plateauY, line, track) {
257
- const span = Math.max(0, right - start.x);
258
- const run = Math.min(this.height * 1.2, span * 0.4);
241
+ openingSegment(start, right, plateauY, line, track) {
242
+ const run = this.height * 1.2;
243
+ right = Math.max(right, start.x + run);
259
244
  const curveX = start.x + run;
260
245
  const controlX = start.x + run * 0.45;
261
246
  const bottom = plateauY + this.thickness;
262
- this.addSegment([
247
+ return makeSegment([
263
248
  { op: "M", x: start.x, y: start.y },
264
249
  { op: "Q", cx: controlX, cy: plateauY, x: curveX, y: plateauY },
265
250
  { op: "L", x: right, y: plateauY },
@@ -270,13 +255,13 @@ class TieLayoutAttachment {
270
255
  ], line, track);
271
256
  }
272
257
  /** 跨行末段:从左边界水平进入,最后落弧到端点 */
273
- addClosingSegment(left, end, plateauY, line, track) {
274
- const span = Math.max(0, end.x - left);
275
- const run = Math.min(this.height * 1.2, span * 0.4);
258
+ closingSegment(left, end, plateauY, line, track) {
259
+ const run = this.height * 1.2;
260
+ left = Math.min(left, end.x - run);
276
261
  const curveX = end.x - run;
277
262
  const controlX = end.x - run * 0.45;
278
263
  const bottom = plateauY + this.thickness;
279
- this.addSegment([
264
+ return makeSegment([
280
265
  { op: "M", x: left, y: plateauY },
281
266
  { op: "L", x: curveX, y: plateauY },
282
267
  { op: "Q", cx: controlX, cy: plateauY, x: end.x, y: end.y },
@@ -285,8 +270,8 @@ class TieLayoutAttachment {
285
270
  { op: "Z" },
286
271
  ], line, track);
287
272
  }
288
- addHorizontalSegment(left, right, y, line, track) {
289
- this.addSegment([
273
+ horizontalSegment(left, right, y, line, track) {
274
+ return makeSegment([
290
275
  { op: "M", x: left, y },
291
276
  { op: "L", x: right, y },
292
277
  { op: "L", x: right, y: y + this.thickness },
@@ -294,8 +279,7 @@ class TieLayoutAttachment {
294
279
  { op: "Z" },
295
280
  ], line, track);
296
281
  }
297
- addSegment(commands, line, track) {
298
- const bounds = pathBounds(commands);
299
- this.segments.push({ commands, line, track, ...bounds });
300
- }
282
+ }
283
+ function makeSegment(commands, line, track) {
284
+ return { commands, line, track, ...pathBounds(commands) };
301
285
  }
@@ -0,0 +1,2 @@
1
+ import { type ASTFunctionClass } from "../ASTtypes.js";
2
+ export declare const TupletNode: ASTFunctionClass;
@@ -0,0 +1,218 @@
1
+ import { ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { Fraction } from "../../fraction.js";
3
+ import { isVisualTemporalNode, } from "../temporal.js";
4
+ import { ASTFunctionNode, } from "../ASTtypes.js";
5
+ /**
6
+ * 多连音是范围时值变换,不产生自己的 Temporal:
7
+ * actual = 内容原总时值 / 最短正时值
8
+ * 目标总时值 = 最短正时值 * normal
9
+ */
10
+ class TupletFunction extends ASTFunctionNode {
11
+ static def = {
12
+ name: ["tuplet"],
13
+ description: "多连音",
14
+ example: `@tuplet({1/23}, 4): 内容含5个最短时值单位,压缩到4倍最短单位的总时长,所以是八分音符的五连音,总时长为二分音符`,
15
+ allowExtraArgs: false,
16
+ args: [
17
+ {
18
+ type: "content",
19
+ default: null,
20
+ },
21
+ {
22
+ name: "normal",
23
+ type: "number",
24
+ default: null,
25
+ },
26
+ ],
27
+ };
28
+ static loweringFinalize = (result) => {
29
+ for (const attachment of result.attachments) {
30
+ if (attachment instanceof TupletLayoutAttachment)
31
+ attachment.validate();
32
+ }
33
+ };
34
+ content;
35
+ normal;
36
+ font;
37
+ get children() { return [this.content]; }
38
+ timeFlowModel() {
39
+ return {
40
+ mode: "sequence",
41
+ children: [this.content],
42
+ };
43
+ }
44
+ loweringEnter(ctx) {
45
+ const events = [];
46
+ const group = {
47
+ events,
48
+ onTemporal(node) {
49
+ // 此时不能改 T:actual 依赖整个作用域的最短值和总和。
50
+ events.push(node);
51
+ },
52
+ };
53
+ ctx.beginLoweringGroup(this, group);
54
+ return [];
55
+ }
56
+ loweringExit(ctx, _track, timeOffset) {
57
+ const group = ctx.endLoweringGroup(this);
58
+ // 零时长控制事件不构成连音单位,但稍后仍要随整组移动其开始位置。
59
+ const positive = group.events.filter(event => event.T.compare(0) > 0);
60
+ if (positive.length === 0) {
61
+ throw new ErrorDiagnostic("E_TUPLET_EMPTY", "@tuplet 的内容必须产生至少一个正时值事件", this.sourceSpan);
62
+ }
63
+ // 一个 tuplet 只拥有一个时间游标和一条括线;并行分支无法用这组语义表达。
64
+ const track = positive[0].track;
65
+ if (positive.some(event => event.track !== track)) {
66
+ throw new ErrorDiagnostic("E_TUPLET_PARALLEL_CONTENT", "@tuplet 的内容不能包含并行音轨", this.sourceSpan);
67
+ }
68
+ // writtenTotal / shortest 必须精确为整数,该整数就是谱面上显示的 actual
69
+ const shortest = positive[0].T.clone();
70
+ const writtenTotal = new Fraction();
71
+ for (const event of positive) {
72
+ if (event.T.compare(shortest) < 0)
73
+ shortest.copyFrom(event.T);
74
+ writtenTotal.add(event.T);
75
+ }
76
+ const units = writtenTotal.clone().div(shortest);
77
+ const actual = units.numerator;
78
+ if (units.denominator !== 1 || actual < 2 || !Number.isSafeInteger(actual)) {
79
+ throw new ErrorDiagnostic("E_TUPLET_NON_INTEGRAL_UNITS", "@tuplet 的总时值必须是最短正时值的整数倍,且至少包含2个单位", this.sourceSpan);
80
+ }
81
+ if (this.normal === actual) {
82
+ throw new ErrorDiagnostic("E_TUPLET_INVALID_RATIO", `@tuplet 的 normal 不能等于推导出的 actual (${actual})`, this.sourceSpan);
83
+ }
84
+ // 以作用域最早时间为仿射缩放原点,不能直接缩放绝对 t,否则嵌套位置会漂移。
85
+ let start = group.events[0].t;
86
+ for (let i = 1; i < group.events.length; i++) {
87
+ if (group.events[i].t.compare(start) < 0)
88
+ start = group.events[i].t;
89
+ }
90
+ start = start.clone();
91
+ // t、T 与 lowering 游标必须一起修改;后继节点才会从缩放后的组尾继续。
92
+ const offset = new Fraction();
93
+ for (const event of group.events) {
94
+ offset.copyFrom(event.t).sub(start).mul(this.normal, actual);
95
+ event.t.copyFrom(start).add(offset);
96
+ event.T.mul(this.normal, actual);
97
+ }
98
+ timeOffset.copyFrom(start).add(shortest.mul(this.normal));
99
+ // 括线只依附可见主体;时值缩放本身仍覆盖所有收集到的事件。
100
+ const visible = positive.filter(isVisualTemporalNode);
101
+ if (visible.length >= 2) {
102
+ ctx.addAttachment(new TupletLayoutAttachment(visible, actual, this.sourceSpan, this.font));
103
+ }
104
+ return [];
105
+ }
106
+ constructor(span, args, ctx, parent = null) {
107
+ super(span, parent);
108
+ const [content, normal] = this.getArgValue(args, ctx);
109
+ this.font = ctx.variables.numberfont;
110
+ // normal 是目标包含的“最短时值单位数”,不是 QN 数,也不是显示的 actual。
111
+ if (!Number.isSafeInteger(normal) || normal <= 0) {
112
+ throw new ErrorDiagnostic("E_TUPLET_INVALID_NORMAL", "@tuplet 的 normal 必须是正的安全整数", span);
113
+ }
114
+ this.content = content;
115
+ this.normal = normal;
116
+ content.parent = this;
117
+ }
118
+ toString(source) {
119
+ return `@tuplet(${this.content.toString(source)}, ${this.normal})`;
120
+ }
121
+ }
122
+ export const TupletNode = TupletFunction;
123
+ /**
124
+ * 多连音括线是跨多个宿主的前景 attachment。lowering 冻结端点与 actual,
125
+ * layout 根据最终宿主坐标测量数字和括线,paint 只回放已冻结的绝对几何。
126
+ */
127
+ class TupletLayoutAttachment {
128
+ layer = "foreground";
129
+ /** lowering 固化的连音语义;重复 layout 时保持不变 */
130
+ endPoints;
131
+ actual;
132
+ sourceSpan;
133
+ /** 由端点最大字号冻结的绘制规格 */
134
+ style;
135
+ size;
136
+ constructor(endPoints, actual, sourceSpan, font) {
137
+ this.endPoints = endPoints;
138
+ this.actual = actual;
139
+ this.sourceSpan = sourceSpan;
140
+ this.size = endPoints.reduce((size, endpoint) => Math.max(size, endpoint.ast.size), 0);
141
+ this.style = {
142
+ fontSize: this.size * 0.72,
143
+ fontFamily: font,
144
+ textAlign: "center",
145
+ fill: "#000",
146
+ };
147
+ }
148
+ validate() {
149
+ const first = this.endPoints[0];
150
+ // 当前实现只有单段括线,没有跨谱面行的首段/末段几何。
151
+ if (this.endPoints.some(endpoint => endpoint.layoutLine !== first.layoutLine)) {
152
+ throw new ErrorDiagnostic("E_TUPLET_CROSS_LINE", "@tuplet 的内容不能跨越谱面行", this.sourceSpan);
153
+ }
154
+ }
155
+ createGeometry(context) {
156
+ const first = this.endPoints[0];
157
+ const last = this.endPoints[this.endPoints.length - 1];
158
+ // 括线覆盖首末主体的核心范围;没有 body 端口时回退到完整盒边界。
159
+ const firstLeft = first.ports["body.left"]?.x ?? 0;
160
+ const lastRight = last.ports["body.right"]?.x ?? last.box.w;
161
+ let left = first.box.x + firstLeft;
162
+ let right = last.box.x + lastRight;
163
+ if (left > right)
164
+ [left, right] = [right, left];
165
+ // 数字位于跨度中心,水平线在数字两侧断开,并预留一个字号相关的空隙。
166
+ const metrics = context.textMeasurer.measureText(String(this.actual), this.style);
167
+ const center = (left + right) / 2;
168
+ const textGap = this.size * 0.12;
169
+ const hookHeight = this.size * 0.18;
170
+ const hostGap = this.size * 0.14;
171
+ // 只测首尾时间列,并合并先注册的 attachment,使后声明的括线排在外层。
172
+ const view = context.lines[first.layoutLine];
173
+ const from = view?.columnOf(first) ?? -1;
174
+ const to = view?.columnOf(last) ?? -1;
175
+ const axis = context.getVisualAxis(first.layoutLine, first.track);
176
+ const extent = from < 0 || to < 0
177
+ ? undefined
178
+ : context.getRangeExtents(first.layoutLine, [Math.min(from, to), Math.max(from, to)]).get(first.track);
179
+ const hostTop = axis + (extent?.top ?? 0);
180
+ const strokeWidth = Math.max(1, this.size * 0.055);
181
+ const lineY = hostTop - hostGap - Math.max(hookHeight, metrics.h / 2);
182
+ const hookBottom = lineY + hookHeight;
183
+ const textBaseline = lineY - metrics.h / 2 + metrics.baseline;
184
+ const textLeft = center - metrics.w / 2 - textGap;
185
+ const textRight = center + metrics.w / 2 + textGap;
186
+ // 先记录左右横线,再记录两端向下的短钩;短跨度允许省略横线但保留端钩
187
+ const lines = [];
188
+ if (textLeft > left)
189
+ lines.push([left, lineY, textLeft, lineY]);
190
+ if (textRight < right)
191
+ lines.push([textRight, lineY, right, lineY]);
192
+ lines.push([left, lineY, left, hookBottom], [right, lineY, right, hookBottom]);
193
+ // region 同时包含文字与描边,并声明 line/track 让纵向求解为括线腾出空间
194
+ const halfStroke = strokeWidth / 2;
195
+ const top = Math.min(lineY - metrics.h / 2, lineY - halfStroke);
196
+ const bottom = Math.max(lineY + metrics.h / 2, hookBottom + halfStroke);
197
+ const regions = [{
198
+ x: left - halfStroke,
199
+ y: top,
200
+ w: right - left + strokeWidth,
201
+ h: bottom - top,
202
+ line: first.layoutLine,
203
+ track: first.track,
204
+ }];
205
+ const text = String(this.actual);
206
+ const style = this.style;
207
+ return {
208
+ regions,
209
+ paint(painter) {
210
+ const lineStyle = { stroke: "#000", strokeWidth };
211
+ for (const [x1, y1, x2, y2] of lines) {
212
+ painter.drawLine(x1, y1, x2, y2, lineStyle);
213
+ }
214
+ painter.drawText(text, center, textBaseline, style);
215
+ },
216
+ };
217
+ }
218
+ }
@@ -1,2 +1,3 @@
1
1
  import { ASTFunctionClass } from "../ASTtypes.js";
2
2
  export declare const UpNode: ASTFunctionClass;
3
+ export declare const DownNode: ASTFunctionClass;