jpfun 0.6.0 → 0.8.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 (134) hide show
  1. package/Bravura-LICENSE.txt +93 -0
  2. package/README.md +49 -146
  3. package/dist/Bravura-LICENSE.txt +93 -0
  4. package/dist/converter/midi/convert.d.ts +3 -11
  5. package/dist/converter/midi/convert.js +89 -67
  6. package/dist/converter/musicxml/features.d.ts +34 -12
  7. package/dist/converter/musicxml/features.js +131 -24
  8. package/dist/converter/musicxml/index.js +221 -54
  9. package/dist/converter/musicxml/model.d.ts +24 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/diagnostic.d.ts +7 -1
  13. package/dist/diagnostic.js +40 -88
  14. package/dist/fraction.js +3 -2
  15. package/dist/functions/ASTtypes.d.ts +2 -18
  16. package/dist/functions/ASTtypes.js +0 -16
  17. package/dist/functions/arpeggio/index.js +17 -22
  18. package/dist/functions/arpeggio/shape.d.ts +1 -1
  19. package/dist/functions/arpeggio/shape.js +27 -21
  20. package/dist/functions/bar/index.d.ts +8 -0
  21. package/dist/functions/bar/index.js +139 -36
  22. package/dist/functions/beam/auto.d.ts +1 -2
  23. package/dist/functions/beam/auto.js +44 -27
  24. package/dist/functions/beam/index.js +2 -3
  25. package/dist/functions/beam/layout.d.ts +1 -1
  26. package/dist/functions/beam/layout.js +16 -24
  27. package/dist/functions/br/index.d.ts +34 -2
  28. package/dist/functions/br/index.js +8 -8
  29. package/dist/functions/dash/index.js +6 -6
  30. package/dist/functions/default.js +10 -5
  31. package/dist/functions/div/index.d.ts +1 -0
  32. package/dist/functions/div/index.js +8 -4
  33. package/dist/functions/dot/index.js +2 -2
  34. package/dist/functions/dyn/index.js +49 -31
  35. package/dist/functions/gliss/index.d.ts +2 -0
  36. package/dist/functions/gliss/index.js +202 -0
  37. package/dist/functions/grace/index.d.ts +1 -7
  38. package/dist/functions/grace/index.js +11 -19
  39. package/dist/functions/head/index.js +41 -60
  40. package/dist/functions/key/index.js +8 -10
  41. package/dist/functions/meter/index.d.ts +56 -1
  42. package/dist/functions/meter/index.js +30 -24
  43. package/dist/functions/note/accidentals.js +10 -16
  44. package/dist/functions/note/index.js +18 -8
  45. package/dist/functions/note/noteName.d.ts +16 -0
  46. package/dist/functions/note/noteName.js +88 -0
  47. package/dist/functions/note/source-transform.js +6 -5
  48. package/dist/functions/ottava/index.d.ts +2 -0
  49. package/dist/functions/ottava/index.js +233 -0
  50. package/dist/functions/page/index.d.ts +1 -0
  51. package/dist/functions/page/index.js +22 -13
  52. package/dist/functions/pagebreak/index.d.ts +2 -0
  53. package/dist/functions/pagebreak/index.js +36 -0
  54. package/dist/functions/rest/index.js +15 -15
  55. package/dist/functions/set/index.js +4 -4
  56. package/dist/functions/slide/index.d.ts +2 -0
  57. package/dist/functions/slide/index.js +132 -0
  58. package/dist/functions/stack/index.js +8 -15
  59. package/dist/functions/symbol/index.d.ts +30 -2
  60. package/dist/functions/symbol/index.js +93 -19
  61. package/dist/functions/symbol/ornament.d.ts +1 -2
  62. package/dist/functions/symbol/ornament.js +14 -19
  63. package/dist/functions/symbol/shape.d.ts +6 -0
  64. package/dist/functions/symbol/shape.js +20 -4
  65. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  66. package/dist/functions/symbol/symbols/coda.js +56 -0
  67. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  68. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  69. package/dist/functions/symbol/symbols/fine.js +1 -1
  70. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  71. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  72. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  73. package/dist/functions/symbol/symbols/marcato.js +22 -0
  74. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  75. package/dist/functions/symbol/symbols/staccato.js +24 -0
  76. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  77. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  78. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  79. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  80. package/dist/functions/symbol/symbols/tr.js +46 -1
  81. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  82. package/dist/functions/symbol/symbols/turn.js +50 -0
  83. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  84. package/dist/functions/symbol/symbols/wheel.js +36 -0
  85. package/dist/functions/temporal.d.ts +17 -6
  86. package/dist/functions/temporal.js +17 -6
  87. package/dist/functions/text/index.js +15 -6
  88. package/dist/functions/tie/index.js +64 -30
  89. package/dist/functions/tremolo/index.d.ts +2 -0
  90. package/dist/functions/tremolo/index.js +319 -0
  91. package/dist/functions/tuplet/index.js +4 -8
  92. package/dist/functions/up/index.js +7 -9
  93. package/dist/functions/voice/connections.js +7 -5
  94. package/dist/functions/voice/index.js +19 -11
  95. package/dist/functions/volta/index.js +41 -21
  96. package/dist/jpfun.core.min.js +64 -80
  97. package/dist/jpfun.from-midi.min.js +5 -5
  98. package/dist/jpfun.from-musicxml.min.js +8 -8
  99. package/dist/jpfun.min.js +69 -85
  100. package/dist/layout/default.d.ts +0 -1
  101. package/dist/layout/default.js +0 -1
  102. package/dist/layout/engine.d.ts +1 -0
  103. package/dist/layout/engine.js +42 -11
  104. package/dist/layout/page.d.ts +3 -2
  105. package/dist/layout/page.js +6 -5
  106. package/dist/layout/types.d.ts +4 -0
  107. package/dist/lowering/loweringContext.d.ts +11 -13
  108. package/dist/lowering/loweringContext.js +30 -197
  109. package/dist/lowering/types.d.ts +1 -3
  110. package/dist/parser/parse-utils/note-utils.d.ts +1 -1
  111. package/dist/parser/parse-utils/note-utils.js +8 -9
  112. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  113. package/dist/parser/parse-utils/string-utils.js +16 -3
  114. package/dist/parser/parserContext.d.ts +2 -0
  115. package/dist/parser/parserContext.js +36 -8
  116. package/dist/pipeline.js +0 -1
  117. package/dist/playback/compile.js +131 -72
  118. package/dist/playback/event.d.ts +1 -1
  119. package/dist/playback/event.js +9 -9
  120. package/dist/playback/time.js +42 -31
  121. package/dist/playback/types.d.ts +7 -3
  122. package/dist/render/canvas.d.ts +2 -0
  123. package/dist/render/canvas.js +25 -22
  124. package/dist/render/recording.js +1 -4
  125. package/dist/render/svg.js +1 -0
  126. package/dist/render/text.d.ts +1 -1
  127. package/dist/render/text.js +3 -2
  128. package/dist/render/translate.d.ts +0 -1
  129. package/dist/render/translate.js +6 -23
  130. package/dist/render/types.d.ts +1 -0
  131. package/grammar.md +52 -25
  132. package/package.json +3 -3
  133. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  134. package/dist/functions/note/noteNameFSM.js +0 -181
@@ -1,5 +1,45 @@
1
1
  import { ASTFunctionNode } from "../ASTtypes.js";
2
+ import { Fraction } from "../../fraction.js";
2
3
  import { ANCHOR_KEY, isVisualTemporalNode, TemporalNodeBase } from "../temporal.js";
4
+ /**
5
+ * 按需注册行首小节号:统计从第二行起每条谱面行首小节的序号,并生成行首小节号附件
6
+ *
7
+ * 小节边界仅在正时值事件之后遇到 ANCHOR_KEY 时推进(兼容 @rest 补入的虚拟边界,且曲首 |: 不多计);
8
+ * 若上一行末尾未写小节线,当前小节跨行延续,新行行首因 measureRecorded 为 true 不重复标号。
9
+ */
10
+ export function registerBarNumbering(ctx, pattern, font) {
11
+ ctx.deferFinalize(result => {
12
+ const items = [];
13
+ const measureStart = new Fraction();
14
+ let measureNumber = 1;
15
+ let measureRecorded = false;
16
+ let lastLine = -1;
17
+ for (const column of result.columns) {
18
+ const time = column[0].t;
19
+ if (column.some(node => node.mergeKey === ANCHOR_KEY)) {
20
+ // 只有当前小节已走过正时值才闭合进入下一小节
21
+ if (time.compare(measureStart) > 0) {
22
+ measureNumber++;
23
+ measureStart.copyFrom(time);
24
+ measureRecorded = false;
25
+ }
26
+ }
27
+ else if (column.some(node => !node.T.isZero() && isVisualTemporalNode(node))) {
28
+ const line = column[0].layoutLine;
29
+ if (line !== lastLine) {
30
+ // 首行(lastLine < 0)与单行谱不标号;跨行未闭合的小节不重复标号
31
+ if (lastLine >= 0 && !measureRecorded)
32
+ items.push({ line, number: measureNumber });
33
+ lastLine = line;
34
+ }
35
+ measureRecorded = true;
36
+ }
37
+ }
38
+ if (items.length > 0) {
39
+ result.attachments.push(new BarNumberAttachment(items, pattern, font));
40
+ }
41
+ });
42
+ }
3
43
  class BarFunction extends ASTFunctionNode {
4
44
  static def = {
5
45
  name: ["bar", "|"],
@@ -13,7 +53,7 @@ class BarFunction extends ASTFunctionNode {
13
53
  args: [
14
54
  {
15
55
  name: "type",
16
- description: "0:普通线 `|`;1:终止线 `||`(左细右粗);2:反复起点 `|:`;3:反复终点 `:|`;4:左右反复 `:|:`",
56
+ description: "0:普通线 `|`;1:双竖线 `||`;2:终止线 `|||`(左细右粗);3:反复起点 `|:`;4:反复终点 `:|`;5:左右反复 `:|:`",
17
57
  type: "number",
18
58
  default: 0,
19
59
  },
@@ -31,16 +71,19 @@ class BarFunction extends ASTFunctionNode {
31
71
  static deSugarAtom(source, start, _end) {
32
72
  let pos = start;
33
73
  let type = 0;
74
+ const slice3 = source.slice(pos, pos + 3);
34
75
  const slice2 = source.slice(pos, pos + 2);
35
- if (slice2 === "||")
76
+ if (slice3 === "|||")
77
+ type = 2, pos += 3;
78
+ else if (slice2 === "||")
36
79
  type = 1, pos += 2;
37
80
  else if (slice2 === "|:")
38
- type = 2, pos += 2;
81
+ type = 3, pos += 2;
39
82
  else if (slice2 === ":|") {
40
83
  if (source[pos + 2] === ":")
41
- type = 4, pos += 3;
84
+ type = 5, pos += 3;
42
85
  else
43
- type = 3, pos += 2;
86
+ type = 4, pos += 2;
44
87
  }
45
88
  else if (source[pos] === "|")
46
89
  type = 0, pos += 1;
@@ -68,12 +111,76 @@ class BarFunction extends ASTFunctionNode {
68
111
  this.size = ctx.length2px(size);
69
112
  }
70
113
  loweringEnter() {
71
- return [this.type >= 2 ? new RepeatBarTemporalNode(this) : new BarTemporalNode(this)];
114
+ return [this.type >= 3 && this.type <= 5
115
+ ? new RepeatBarTemporalNode(this)
116
+ : new BarTemporalNode(this)];
72
117
  }
73
118
  toString() {
74
119
  return `@bar(${this.type}, ${this.size}px)`;
75
120
  }
76
121
  }
122
+ /**
123
+ * 每行行首的小节号附件
124
+ *
125
+ * 多声部行首锚定在连谱号细竖线正上方居中(通过首声部名称宿主发布的 bar.number 端口);
126
+ * 单声部行首无连谱号时统一右对齐到版心左边界 originX 外侧,保证各行纵向对齐且不压住行首升降号或记号。
127
+ */
128
+ class BarNumberAttachment {
129
+ items;
130
+ pattern;
131
+ font;
132
+ layer = "foreground";
133
+ sourceSpan = undefined;
134
+ constructor(items, pattern, font) {
135
+ this.items = items;
136
+ this.pattern = pattern;
137
+ this.font = font;
138
+ }
139
+ createGeometry(context) {
140
+ const draws = this.items.map(({ line, number }) => {
141
+ const firstCol = context.lines[line].columns[0];
142
+ // 选取行首列中视觉轴最靠上的宿主,确保小节号只挂在最顶层声部上方
143
+ const topHost = firstCol.reduce((top, host) => context.getVisualAxis(line, host.track) < context.getVisualAxis(line, top.track) ? host : top);
144
+ const fontSize = topHost.ast.size;
145
+ const port = topHost.ports["bar.number"];
146
+ const style = {
147
+ fontSize: fontSize * 0.5,
148
+ fontFamily: this.font,
149
+ textAlign: port ? "center" : "right",
150
+ fill: "#000",
151
+ };
152
+ // 仅将模板中的首个 1 替换为当前小节序号
153
+ const text = this.pattern.replace("1", String(number));
154
+ const metrics = context.textMeasurer.measureText(text, style);
155
+ const x = port ? topHost.box.x + port.x : context.originX - fontSize * 0.15;
156
+ const topY = port
157
+ ? topHost.box.y + port.y
158
+ : Math.min(topHost.box.y, context.getVisualAxis(line, topHost.track) - fontSize * 0.5);
159
+ const baselineY = topY - fontSize * 0.04;
160
+ return {
161
+ text,
162
+ x,
163
+ y: baselineY,
164
+ style,
165
+ region: {
166
+ x: port ? x - metrics.w / 2 : x - metrics.w,
167
+ y: baselineY - metrics.baseline,
168
+ w: metrics.w,
169
+ h: metrics.baseline,
170
+ line,
171
+ track: topHost.track,
172
+ },
173
+ };
174
+ });
175
+ return {
176
+ regions: draws.map(draw => draw.region),
177
+ paint(painter) {
178
+ for (const draw of draws)
179
+ painter.drawText(draw.text, draw.x, draw.y, draw.style);
180
+ },
181
+ };
182
+ }
183
+ }
77
184
  export const BarNode = BarFunction;
78
185
  class BarTemporalNode extends TemporalNodeBase {
79
186
  lines = [];
@@ -99,30 +206,20 @@ class BarTemporalNode extends TemporalNodeBase {
99
206
  if (!isVisualTemporalNode(host))
100
207
  return;
101
208
  const run = line.trackRuns.get(host.track);
102
- const index = run?.indexOf(host) ?? -1;
209
+ const index = line.trackIndexOf(host);
103
210
  if (!run || index < 0)
104
211
  return;
105
- line.registerHorizontalLayoutHook(host, host, ({ columns, start }) => {
106
- const current = columns[start].find(element => element.time === host);
107
- if (!current)
108
- return;
109
- const elementOf = (node) => {
110
- const column = line.columnOf(node);
111
- return column < 0 ? undefined : columns[column].find(element => element.time === node);
112
- };
113
- const left = index > 0 ? elementOf(run[index - 1]) : undefined;
114
- if (left) {
115
- left.config.mu_R *= 4;
116
- current.config.mu_L *= 4;
117
- }
118
- const rightNode = run[index + 1];
119
- const right = rightNode ? elementOf(rightNode) : undefined;
120
- // 相邻两个 bar 的中间 gap 由右侧 bar 处理,避免重复增强
121
- if (right && rightNode.mergeKey !== ANCHOR_KEY) {
122
- current.config.mu_R *= 4;
123
- right.config.mu_L *= 4;
124
- }
125
- });
212
+ const left = run[index - 1];
213
+ if (left) {
214
+ left.springConfig.mu_R *= 4;
215
+ host.springConfig.mu_L *= 4;
216
+ }
217
+ const right = run[index + 1];
218
+ // 相邻两个 bar 的中间 gap 由右侧 bar 处理,避免重复增强
219
+ if (right && right.mergeKey !== ANCHOR_KEY) {
220
+ host.springConfig.mu_R *= 4;
221
+ right.springConfig.mu_L *= 4;
222
+ }
126
223
  }
127
224
  prepareLayout() {
128
225
  const { type, size } = this.ast;
@@ -134,16 +231,22 @@ class BarTemporalNode extends TemporalNodeBase {
134
231
  const gap = thin * 1.8;
135
232
  const dotRadius = thin * 0.8;
136
233
  const dotGap = gap + dotRadius;
137
- const hasLeftDots = type === 3 || type === 4;
138
- const hasRightDots = type === 2 || type === 4;
234
+ const hasLeftDots = type === 4 || type === 5;
235
+ const hasRightDots = type === 3 || type === 5;
139
236
  let x = hasLeftDots ? dotRadius * 2 + dotGap : 0;
140
- if (type === 1 || type === 3 || type === 4) {
237
+ if (type === 1) {
238
+ this.lines.push({ x, w: thin });
239
+ x += thin + gap;
240
+ this.lines.push({ x, w: thin });
241
+ x += thin;
242
+ }
243
+ else if (type === 2 || type === 4 || type === 5) {
141
244
  this.lines.push({ x, w: thin });
142
245
  x += thin + gap;
143
246
  this.lines.push({ x, w: thick });
144
247
  x += thick;
145
248
  }
146
- else if (type === 2) {
249
+ else if (type === 3) {
147
250
  this.lines.push({ x, w: thick });
148
251
  x += thick + gap;
149
252
  this.lines.push({ x, w: thin });
@@ -166,7 +269,7 @@ class BarTemporalNode extends TemporalNodeBase {
166
269
  }
167
270
  this.box.w = x;
168
271
  this.box.h = h;
169
- const anchorLine = type >= 2 ? this.lines[0] : undefined;
272
+ const anchorLine = type >= 3 && type <= 5 ? this.lines[0] : undefined;
170
273
  this.box.anchor = anchorLine ? anchorLine.x + anchorLine.w / 2 : x / 2;
171
274
  this.box.visualAxis = h / 2;
172
275
  for (const line of this.lines)
@@ -195,13 +298,13 @@ export function repeatPass(cursor, column) {
195
298
  }
196
299
  /** 只有反复线参与播放顺序;普通小节线太多,进控制流扫描是纯开销 */
197
300
  class RepeatBarTemporalNode extends BarTemporalNode {
198
- /** 只在 type>=2 时创建,所以剩下的三种是:2 段首、3 段尾、4 两者都是 */
301
+ /** 只在 type 3–5 时创建,所以三种分别是:3 段首、4 段尾、5 两者都是 */
199
302
  playbackMarks() {
200
- return this.ast.type === 3 ? [] : [REPEAT_START];
303
+ return this.ast.type === 4 ? [] : [REPEAT_START];
201
304
  }
202
305
  /** 每条反复线只回跳一次,所以连写几条就是几遍 */
203
306
  playbackFlow(columnOf) {
204
- if (this.ast.type === 2)
307
+ if (this.ast.type === 3)
205
308
  return;
206
309
  const at = columnOf(this);
207
310
  if (at === undefined)
@@ -1,4 +1,3 @@
1
1
  import type { LoweringResult } from "../../lowering/types.js";
2
- import type { LayoutAttachment } from "../../layout/types.js";
3
2
  /** beam 域在 lowering 固化后统一生成作用域连接和相邻自动连接 */
4
- export declare function createAutomaticBeamAttachments(result: LoweringResult): LayoutAttachment[];
3
+ export declare function createAutomaticBeamAttachments(result: LoweringResult): void;
@@ -1,11 +1,14 @@
1
1
  import { ANCHOR_KEY, isVisualTemporalNode, } from "../temporal.js";
2
2
  import { Fraction } from "../../fraction.js";
3
3
  import { DIV_ADDON_KEY, DivNode, } from "../div/index.js";
4
+ import { meterChangeAt } from "../meter/index.js";
4
5
  import { collectExplicitBeamEndpoints, createBeamLayoutAttachment, } from "./layout.js";
5
6
  /** 只返回实际参与当前事件 div addon 的 div,先沿祖先链找,不够再按书写顺序向下补 */
6
7
  function findActiveDivs(node) {
7
- const result = [];
8
8
  let remainingLevels = Math.max(0, Math.floor(Number(node.addon?.[DIV_ADDON_KEY]) || 0));
9
+ if (remainingLevels <= 0)
10
+ return [];
11
+ const result = [];
9
12
  const take = (div) => {
10
13
  result.push(div);
11
14
  remainingLevels -= Math.max(0, div.n);
@@ -16,6 +19,8 @@ function findActiveDivs(node) {
16
19
  take(ast);
17
20
  ast = ast.parent;
18
21
  }
22
+ if (remainingLevels <= 0)
23
+ return result;
19
24
  // 复合节点(如 up)把代表成员的修饰提升成了自己的,提供层级的 div 在子树里
20
25
  const descend = (parent) => {
21
26
  for (const child of parent.children ?? []) {
@@ -71,24 +76,21 @@ function outermostScopes(scopes) {
71
76
  return true;
72
77
  });
73
78
  }
74
- function sourceSpanForAutoBeam(nodes) {
79
+ function createAutoBeam(nodes, nodeScopes) {
75
80
  let start = Infinity;
76
81
  let end = -Infinity;
77
82
  for (const node of nodes) {
78
83
  start = Math.min(start, node.ast.sourceSpan.start);
79
84
  end = Math.max(end, node.ast.sourceSpan.end);
80
- for (const div of findActiveDivs(node)) {
81
- start = Math.min(start, div.sourceSpan.start);
82
- end = Math.max(end, div.sourceSpan.end);
85
+ for (const { owner } of nodeScopes.get(node) ?? []) {
86
+ start = Math.min(start, owner.sourceSpan.start);
87
+ end = Math.max(end, owner.sourceSpan.end);
83
88
  }
84
89
  }
85
- return { start, end };
86
- }
87
- function createAutoBeam(nodes) {
88
- return createBeamLayoutAttachment(nodes, false, sourceSpanForAutoBeam(nodes));
90
+ return createBeamLayoutAttachment(nodes, false, { start, end });
89
91
  }
90
92
  /** 同一个 div 内部始终按轨道连接,手工 beam 端点会截断自动片段 */
91
- function createScopeBeams(scopes, explicitEndpoints) {
93
+ function createScopeBeams(scopes, nodeScopes, explicitEndpoints) {
92
94
  const attachments = [];
93
95
  for (const scope of outermostScopes(scopes)) {
94
96
  const tracks = new Map();
@@ -103,7 +105,7 @@ function createScopeBeams(scopes, explicitEndpoints) {
103
105
  let segment = [];
104
106
  const flush = () => {
105
107
  if (segment.length >= 2)
106
- attachments.push(createAutoBeam(segment));
108
+ attachments.push(createAutoBeam(segment, nodeScopes));
107
109
  segment = [];
108
110
  };
109
111
  for (const node of nodes) {
@@ -118,15 +120,12 @@ function createScopeBeams(scopes, explicitEndpoints) {
118
120
  }
119
121
  return attachments;
120
122
  }
121
- function beatAt(time) {
122
- return Math.floor(time.numerator / time.denominator);
123
- }
124
123
  /**
125
124
  * 多个独立 div 的默认连接规则
126
125
  *
127
126
  * MuseScore 和 LilyPond 都以拍号的 beat structure 作为默认分组边界,并允许手工 beam 覆盖。
128
- * 当前语言没有拍号,暂以四分音符为拍单位。
129
- * 分组不跨轨道、逻辑行、拍点、小节线、时间间隙、普通长事件、开关边界或显式 beam。
127
+ * 随当前生效的 @meter 分拍(缺省或散板按四分音符,复拍子及 3/8 按三个分母单位,其余短分母按一个分母单位)。
128
+ * 分组不跨轨道、逻辑行、拍点、小节线、拍号变更、时间间隙、普通长事件、开关边界或显式 beam。
130
129
  */
131
130
  function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
132
131
  const attachments = [];
@@ -134,6 +133,8 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
134
133
  const lineStarts = new Map();
135
134
  const measureStart = new Fraction();
136
135
  const beatTime = new Fraction();
136
+ const beatDuration = new Fraction(1);
137
+ let candidateDuration = 1;
137
138
  for (const column of result.columns) {
138
139
  for (const node of column) {
139
140
  const current = lineStarts.get(node.layoutLine);
@@ -147,17 +148,33 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
147
148
  return;
148
149
  groups.delete(track);
149
150
  if (group.nodes.length >= 2)
150
- attachments.push(createAutoBeam(group.nodes));
151
+ attachments.push(createAutoBeam(group.nodes, nodeScopes));
151
152
  };
152
153
  const flushAll = () => {
153
- for (const track of [...groups.keys()])
154
+ for (const track of groups.keys())
154
155
  flush(track);
155
156
  };
156
157
  for (const column of result.columns) {
157
- const anchor = column.find(node => node.mergeKey === ANCHOR_KEY);
158
- if (anchor) {
158
+ let meter;
159
+ let hasAnchor = false;
160
+ for (const node of column) {
161
+ meter = meterChangeAt(node) ?? meter;
162
+ if (node.mergeKey === ANCHOR_KEY)
163
+ hasAnchor = true;
164
+ }
165
+ if (meter || hasAnchor) {
159
166
  flushAll();
160
- measureStart.copyFrom(anchor.t);
167
+ measureStart.copyFrom(column[0].t);
168
+ }
169
+ if (meter) {
170
+ const { numerator, denominator } = meter;
171
+ if (numerator > 0 && denominator > 4) {
172
+ beatDuration.set(denominator >= 8 && numerator % 3 === 0 ? 12 : 4, denominator);
173
+ }
174
+ else {
175
+ beatDuration.set(1);
176
+ }
177
+ candidateDuration = beatDuration.compare(1) < 0 ? beatDuration : 1;
161
178
  }
162
179
  for (const node of column) {
163
180
  if (node.mergeKey === ANCHOR_KEY)
@@ -168,7 +185,7 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
168
185
  const isCandidate = isVisualTemporalNode(node)
169
186
  && isIndependentDiv
170
187
  && autoBeamEnabled
171
- && node.T.compare(1) < 0
188
+ && node.T.compare(candidateDuration) < 0
172
189
  && !explicitEndpoints.has(node);
173
190
  if (!isCandidate) {
174
191
  // 同轨可见元素必须打断相邻关系,即使它本身是零时长文本
@@ -179,7 +196,8 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
179
196
  }
180
197
  const lineStart = lineStarts.get(node.layoutLine) ?? node.t;
181
198
  const activeStart = measureStart.compare(lineStart) >= 0 ? measureStart : lineStart;
182
- const beat = beatAt(beatTime.copyFrom(node.t).sub(activeStart));
199
+ beatTime.copyFrom(node.t).sub(activeStart);
200
+ const beat = Math.floor(beatTime.numerator * beatDuration.denominator / (beatTime.denominator * beatDuration.numerator));
183
201
  const current = groups.get(node.track);
184
202
  const isContinuous = current && node.t.equals(current.endTime);
185
203
  if (!current || node.layoutLine !== current.line || beat !== current.beat || !isContinuous) {
@@ -202,9 +220,8 @@ function createAdjacentBeams(result, nodeScopes, explicitEndpoints) {
202
220
  /** beam 域在 lowering 固化后统一生成作用域连接和相邻自动连接 */
203
221
  export function createAutomaticBeamAttachments(result) {
204
222
  const { scopes, nodeScopes } = collectDivScopes(result);
223
+ if (scopes.length === 0)
224
+ return;
205
225
  const explicitEndpoints = collectExplicitBeamEndpoints(result.attachments);
206
- return [
207
- ...createScopeBeams(scopes, explicitEndpoints),
208
- ...createAdjacentBeams(result, nodeScopes, explicitEndpoints),
209
- ];
226
+ result.attachments.push(...createScopeBeams(scopes, nodeScopes, explicitEndpoints), ...createAdjacentBeams(result, nodeScopes, explicitEndpoints));
210
227
  }
@@ -1,9 +1,7 @@
1
1
  import { ASTFunctionNode } from "../ASTtypes.js";
2
2
  import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
3
- import { createAutomaticBeamAttachments } from "./auto.js";
4
3
  import { createBeamLayoutAttachment, validateExplicitBeamAttachments, } from "./layout.js";
5
4
  class BeamFunction extends ASTFunctionNode {
6
- static loweringAugment = createAutomaticBeamAttachments;
7
5
  static loweringFinalize = validateExplicitBeamAttachments;
8
6
  static def = {
9
7
  name: ["beam"],
@@ -37,7 +35,7 @@ class BeamFunction extends ASTFunctionNode {
37
35
  this.endPoints.unshift(candidate);
38
36
  }
39
37
  if (this.endPoints.length < 2) {
40
- throw new ErrorDiagnostic("E_NOT_ENOUGH_ARGS", "@beam 至少需要两个端点", sourceSpan);
38
+ throw new ErrorDiagnostic("E_NOT_ENOUGH_ARGS", "@{fn} 至少需要两个端点", sourceSpan, { fn: "beam" });
41
39
  }
42
40
  }
43
41
  /** 与 tie 一样,只注册不推进时间的关系排版对象 */
@@ -57,6 +55,7 @@ class BeamFunction extends ASTFunctionNode {
57
55
  return [];
58
56
  }
59
57
  ctx.addAttachment(createBeamLayoutAttachment(endPoints, true, this.sourceSpan));
58
+ ctx.deferFinalize(BeamFunction.loweringFinalize);
60
59
  return [];
61
60
  }
62
61
  }
@@ -6,5 +6,5 @@ import type { LoweringAttachment, LoweringResult } from "../../lowering/types.js
6
6
  export declare function createBeamLayoutAttachment(endPoints: TemporalNodeBase[], explicit: boolean, sourceSpan: SourceSpan): LayoutAttachment;
7
7
  /** 显式 beam 连接同轨同谱面行中的相邻可见主体,忽略零时长小节线 */
8
8
  export declare function validateExplicitBeamAttachments(result: LoweringResult): void;
9
- /** 自动分组在 loweringAugment 当下读取已经注册的显式 beam 端点 */
9
+ /** 自动分组在收尾阶段读取已经注册的显式 beam 端点 */
10
10
  export declare function collectExplicitBeamEndpoints(attachments: readonly LoweringAttachment[]): Set<TemporalNodeBase>;
@@ -8,6 +8,7 @@ export function createBeamLayoutAttachment(endPoints, explicit, sourceSpan) {
8
8
  /** 显式 beam 连接同轨同谱面行中的相邻可见主体,忽略零时长小节线 */
9
9
  export function validateExplicitBeamAttachments(result) {
10
10
  const tracks = new Map();
11
+ const positions = new Map();
11
12
  for (const column of result.columns) {
12
13
  for (const node of column) {
13
14
  if (!isVisualTemporalNode(node))
@@ -19,19 +20,9 @@ export function validateExplicitBeamAttachments(result) {
19
20
  lineTracks = new Map();
20
21
  tracks.set(node.layoutLine, lineTracks);
21
22
  }
22
- const sequence = lineTracks.get(node.track);
23
- if (sequence)
24
- sequence.push(node);
25
- else
26
- lineTracks.set(node.track, [node]);
27
- }
28
- }
29
- const positions = new Map();
30
- for (const [line, lineTracks] of tracks) {
31
- for (const [track, sequence] of lineTracks) {
32
- for (let index = 0; index < sequence.length; index++) {
33
- positions.set(sequence[index], { line, track, index });
34
- }
23
+ const index = lineTracks.get(node.track) ?? 0;
24
+ positions.set(node, { line: node.layoutLine, track: node.track, index });
25
+ lineTracks.set(node.track, index + 1);
35
26
  }
36
27
  }
37
28
  for (const attachment of result.attachments) {
@@ -56,7 +47,7 @@ export function validateExplicitBeamAttachments(result) {
56
47
  }
57
48
  }
58
49
  }
59
- /** 自动分组在 loweringAugment 当下读取已经注册的显式 beam 端点 */
50
+ /** 自动分组在收尾阶段读取已经注册的显式 beam 端点 */
60
51
  export function collectExplicitBeamEndpoints(attachments) {
61
52
  const result = new Set();
62
53
  for (const attachment of attachments) {
@@ -84,18 +75,19 @@ class BeamLayoutAttachment {
84
75
  }
85
76
  /** 同一 beam 组内的相邻元素使用更短的自然弹簧间距 */
86
77
  prepareHorizontal(context) {
87
- const endPoints = new Set(this.endPoints);
88
- for (const line of context) {
89
- for (const run of line.trackRuns.values()) {
90
- for (let i = 1; i < run.length; i++) {
91
- const left = run[i - 1];
92
- const right = run[i];
93
- if (!endPoints.has(left) || !endPoints.has(right))
94
- continue;
95
- left.springConfig.alpha_R = left.springConfig.alpha_R * 0.8;
96
- right.springConfig.alpha_L = right.springConfig.alpha_L * 0.8;
78
+ let left;
79
+ for (const node of this.endPoints) {
80
+ if (!isVisualTemporalNode(node))
81
+ continue;
82
+ if (left && left.layoutLine === node.layoutLine && left.track === node.track) {
83
+ const line = context[left.layoutLine];
84
+ const index = line ? line.trackIndexOf(left) : -1;
85
+ if (index >= 0 && index + 1 === line.trackIndexOf(node)) {
86
+ left.springConfig.alpha_R *= 0.8;
87
+ node.springConfig.alpha_L *= 0.8;
97
88
  }
98
89
  }
90
+ left = node;
99
91
  }
100
92
  }
101
93
  createGeometry(context) {
@@ -1,2 +1,34 @@
1
- import { ASTFunctionClass } from "../ASTtypes.js";
2
- export declare const BrNode: ASTFunctionClass;
1
+ import { ASTNodeBase, FunctionArgs, SourceSpan, ASTFunctionNode } from "../ASTtypes.js";
2
+ import { ParserContext } from "../../parser/parserContext.js";
3
+ import { TemporalNodeBase } from "../temporal.js";
4
+ import type { LoweringContext } from "../../lowering/loweringContext.js";
5
+ import type { LoweringResult } from "../../lowering/types.js";
6
+ import { GrammarCallNodeTyped } from "../../parser/grammarType.js";
7
+ declare class BrFunction extends ASTFunctionNode {
8
+ static def: {
9
+ name: string[];
10
+ description: string;
11
+ details: string;
12
+ allowExtraArgs: boolean;
13
+ args: {
14
+ name: string;
15
+ description: string;
16
+ type: "number";
17
+ default: number;
18
+ }[];
19
+ };
20
+ static deSugarAtom(source: string, start: number, end: number, depth: number): {
21
+ next: number;
22
+ node: GrammarCallNodeTyped;
23
+ } | null;
24
+ readonly offset: number;
25
+ loweringEnter(ctx: LoweringContext): TemporalNodeBase[];
26
+ /**
27
+ * 换行与换页共享校验;边界会切开全谱,不能截断持续事件
28
+ */
29
+ static loweringFinalize(result: LoweringResult): void;
30
+ constructor(span: SourceSpan, args: FunctionArgs, ctx: ParserContext, parent?: ASTNodeBase | null);
31
+ toString(): string;
32
+ }
33
+ export declare const BrNode: typeof BrFunction;
34
+ export {};
@@ -46,23 +46,23 @@ class BrFunction extends ASTFunctionNode {
46
46
  return { next, node };
47
47
  }
48
48
  offset;
49
- loweringEnter() {
49
+ loweringEnter(ctx) {
50
+ ctx.deferFinalize(BrFunction.loweringFinalize);
50
51
  const br = new TemporalNodeBase();
51
52
  br.ast = this;
52
53
  br.mergeKey = -1;
53
- br.breakBefore = this.offset;
54
+ br.addon = { breakBefore: this.offset };
54
55
  return [br];
55
56
  }
56
57
  /**
57
- * 检查换行是否切断了持续事件
58
- * 换行会把整条时间线切开,因此跨越换行点的持续事件无法被完整绘制
58
+ * 换行与换页共享校验;边界会切开全谱,不能截断持续事件
59
59
  */
60
- static loweringFinalize = (result) => {
60
+ static loweringFinalize(result) {
61
61
  const latestEnd = new Fraction();
62
62
  const candidateEnd = new Fraction();
63
63
  let latestNode = null;
64
64
  for (const column of result.columns) {
65
- if (latestNode && latestEnd.compare(column[0].t) > 0 && column.some(node => node.breakBefore > 0)) {
65
+ if (latestNode && latestEnd.compare(column[0].t) > 0 && column.some(node => (node.addon?.breakBefore ?? 0) > 0)) {
66
66
  throw Diagnostic.error.BreakInsideEvent(latestNode.ast.sourceSpan);
67
67
  }
68
68
  for (const node of column) {
@@ -75,13 +75,13 @@ class BrFunction extends ASTFunctionNode {
75
75
  }
76
76
  }
77
77
  }
78
- };
78
+ }
79
79
  constructor(span, args, ctx, parent = null) {
80
80
  super(span, parent);
81
81
  const [offset] = this.getArgValue(args, ctx);
82
82
  this.offset = Number.isFinite(offset) ? Math.max(1, Math.floor(offset)) : 1;
83
83
  if (this.offset !== offset) {
84
- ctx.diagnostics.push(new WarningDiagnostic("W_BR_OFFSET", `@br 的 offset 必须是大于等于 1 的整数,已被修正为 ${this.offset}`, this.sourceSpan));
84
+ ctx.diagnostics.push(new WarningDiagnostic("W_BR_OFFSET", "@br 的 offset 必须是大于等于 1 的整数,已被修正为 {offset}", this.sourceSpan, { offset: this.offset }));
85
85
  }
86
86
  }
87
87
  toString() { return `@br(${this.offset})`; }
@@ -75,14 +75,13 @@ class DashTemporalNode extends TemporalNodeBase {
75
75
  // 这里只查询已发布的结构前缀;装饰音尚未展开,不需要逐个修改子音。
76
76
  emitter.defer(context => {
77
77
  let rootOrigin;
78
- // 从最近发布的区间向前找,锁定与当前起点相接的那次顶层访问。
78
+ let extended = false;
79
+ // 同轨最近一次顶层访问是唯一可能与当前起点相接的目标组;
79
80
  // 来源身份限定了整组目标,防止延长更早的音符或另一遍反复中的同一节点。
80
81
  for (let index = context.spans.length - 1; index >= 0; index--) {
81
82
  const span = context.spans[index];
82
- if (span.track !== track)
83
- continue;
84
- if (rootOrigin === undefined) {
85
- if (!span.end.equals(start))
83
+ if (!rootOrigin) {
84
+ if (span.track !== track)
86
85
  continue;
87
86
  rootOrigin = span.origins[0];
88
87
  }
@@ -92,9 +91,10 @@ class DashTemporalNode extends TemporalNodeBase {
92
91
  // 一组目标可以含多个成员;extend 同时承接当前访问在新增部分上的速度效果。
93
92
  if (span.end.equals(start)) {
94
93
  emitter.extend(span);
94
+ extended = true;
95
95
  }
96
96
  }
97
- if (rootOrigin === undefined) {
97
+ if (!extended) {
98
98
  context.diagnostics.push(new WarningDiagnostic("W_PLAYBACK_SUSTAIN_WITHOUT_TARGET", "增时线前没有可延续的音段", sourceSpan));
99
99
  }
100
100
  });