jpfun 0.7.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 (110) 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 +0 -10
  5. package/dist/converter/midi/convert.js +11 -1
  6. package/dist/converter/musicxml/features.d.ts +15 -7
  7. package/dist/converter/musicxml/features.js +87 -18
  8. package/dist/converter/musicxml/index.js +80 -32
  9. package/dist/converter/musicxml/model.d.ts +9 -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 +15 -17
  18. package/dist/functions/bar/index.d.ts +8 -0
  19. package/dist/functions/bar/index.js +102 -0
  20. package/dist/functions/beam/auto.d.ts +1 -2
  21. package/dist/functions/beam/auto.js +30 -16
  22. package/dist/functions/beam/index.js +2 -3
  23. package/dist/functions/beam/layout.d.ts +1 -1
  24. package/dist/functions/beam/layout.js +1 -1
  25. package/dist/functions/br/index.d.ts +34 -2
  26. package/dist/functions/br/index.js +5 -4
  27. package/dist/functions/dash/index.js +6 -6
  28. package/dist/functions/default.js +2 -1
  29. package/dist/functions/div/index.d.ts +1 -0
  30. package/dist/functions/div/index.js +8 -4
  31. package/dist/functions/dot/index.js +2 -2
  32. package/dist/functions/dyn/index.js +49 -31
  33. package/dist/functions/gliss/index.js +75 -53
  34. package/dist/functions/grace/index.d.ts +1 -7
  35. package/dist/functions/grace/index.js +8 -13
  36. package/dist/functions/head/index.js +1 -1
  37. package/dist/functions/key/index.js +8 -10
  38. package/dist/functions/meter/index.d.ts +56 -1
  39. package/dist/functions/meter/index.js +12 -7
  40. package/dist/functions/note/index.js +5 -5
  41. package/dist/functions/note/noteName.d.ts +16 -0
  42. package/dist/functions/note/noteName.js +88 -0
  43. package/dist/functions/note/source-transform.js +6 -5
  44. package/dist/functions/ottava/index.js +24 -8
  45. package/dist/functions/page/index.d.ts +1 -0
  46. package/dist/functions/page/index.js +20 -11
  47. package/dist/functions/pagebreak/index.js +2 -2
  48. package/dist/functions/rest/index.js +3 -1
  49. package/dist/functions/set/index.js +4 -4
  50. package/dist/functions/symbol/index.d.ts +21 -2
  51. package/dist/functions/symbol/index.js +69 -24
  52. package/dist/functions/symbol/ornament.d.ts +1 -2
  53. package/dist/functions/symbol/shape.d.ts +6 -0
  54. package/dist/functions/symbol/shape.js +16 -3
  55. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  56. package/dist/functions/symbol/symbols/coda.js +56 -0
  57. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  58. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  59. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  60. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  61. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  62. package/dist/functions/symbol/symbols/marcato.js +22 -0
  63. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  64. package/dist/functions/symbol/symbols/staccato.js +24 -0
  65. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  66. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  67. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  68. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  69. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  70. package/dist/functions/symbol/symbols/turn.js +50 -0
  71. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  72. package/dist/functions/symbol/symbols/wheel.js +36 -0
  73. package/dist/functions/temporal.d.ts +1 -0
  74. package/dist/functions/temporal.js +1 -0
  75. package/dist/functions/text/index.js +15 -6
  76. package/dist/functions/tie/index.js +30 -6
  77. package/dist/functions/tremolo/index.d.ts +2 -0
  78. package/dist/functions/tremolo/index.js +319 -0
  79. package/dist/functions/tuplet/index.js +4 -8
  80. package/dist/functions/up/index.js +2 -2
  81. package/dist/functions/voice/index.js +17 -10
  82. package/dist/jpfun.core.min.js +57 -49
  83. package/dist/jpfun.from-midi.min.js +5 -5
  84. package/dist/jpfun.from-musicxml.min.js +8 -8
  85. package/dist/jpfun.min.js +62 -54
  86. package/dist/layout/default.d.ts +0 -1
  87. package/dist/layout/default.js +0 -1
  88. package/dist/lowering/loweringContext.d.ts +11 -13
  89. package/dist/lowering/loweringContext.js +26 -33
  90. package/dist/lowering/types.d.ts +1 -3
  91. package/dist/parser/parse-utils/note-utils.d.ts +1 -1
  92. package/dist/parser/parse-utils/note-utils.js +8 -9
  93. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  94. package/dist/parser/parse-utils/string-utils.js +16 -3
  95. package/dist/parser/parserContext.js +9 -2
  96. package/dist/pipeline.js +0 -1
  97. package/dist/playback/compile.js +120 -70
  98. package/dist/playback/event.d.ts +1 -1
  99. package/dist/playback/event.js +9 -9
  100. package/dist/playback/time.js +42 -31
  101. package/dist/playback/types.d.ts +3 -1
  102. package/dist/render/canvas.d.ts +2 -0
  103. package/dist/render/canvas.js +25 -22
  104. package/dist/render/recording.js +1 -4
  105. package/dist/render/translate.d.ts +0 -1
  106. package/dist/render/translate.js +6 -23
  107. package/grammar.md +26 -20
  108. package/package.json +3 -3
  109. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  110. package/dist/functions/note/noteNameFSM.js +0 -181
@@ -13,15 +13,17 @@ import { isPlaybackRelation } from "./types.js";
13
13
  */
14
14
  function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
15
15
  const columns = lowering.columns;
16
- const columnOf = new Map();
17
- // 先建立时间流内的 TemporalNode 的列索引
18
- for (let index = 0; index < columns.length; index++) {
19
- for (const node of columns[index])
20
- columnOf.set(node, index);
21
- }
16
+ let columnOf;
22
17
  // 折叠成员不单独占列,沿 foldedInto 找到最近的已入列宿主
23
18
  // 标记和关系端点都使用这个映射,保持控制流与实际时间列一致
24
19
  const resolveColumn = (node, edge) => {
20
+ if (!columnOf) {
21
+ columnOf = new Map();
22
+ for (let index = 0; index < columns.length; index++) {
23
+ for (const item of columns[index])
24
+ columnOf.set(item, index);
25
+ }
26
+ }
25
27
  for (let at = node; at; at = at.foldedInto) {
26
28
  const index = columnOf.get(at);
27
29
  if (index === undefined)
@@ -49,7 +51,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
49
51
  const [from, to] = hook.range ?? [0, columns.length - 1];
50
52
  if (hook.range && (!Number.isSafeInteger(from) || !Number.isSafeInteger(to)
51
53
  || from < 0 || to < from || to >= columns.length)) {
52
- throw new ErrorDiagnostic("E_PLAYBACK_FLOW_RANGE", `播放控制流范围 [${from}, ${to}] 超出时间列边界`, sourceSpan);
54
+ throw new ErrorDiagnostic("E_PLAYBACK_FLOW_RANGE", "播放控制流范围 [{from}, {to}] 超出时间列边界", sourceSpan, { from, to });
53
55
  }
54
56
  const registered = { hook, sourceSpan };
55
57
  // 预先按范围分发,执行时只检查当前列相关的声明。
@@ -66,7 +68,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
66
68
  for (const node of nodes) {
67
69
  addHook(node, node.ast.sourceSpan);
68
70
  const marks = node.playbackMarks?.();
69
- if (!marks)
71
+ if (!marks?.length)
70
72
  continue;
71
73
  const at = resolveColumn(node);
72
74
  if (at === void 0)
@@ -113,7 +115,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
113
115
  // 先记录到达,再决定本列去留;跳过的列也算一次到达,但不会发布声音
114
116
  while (index < columns.length) {
115
117
  if (++steps > maxFlowSteps) {
116
- throw new ErrorDiagnostic("E_PLAYBACK_FLOW_LIMIT", `播放控制流访问超过 ${maxFlowSteps} 步;可通过 maxFlowSteps 提高展开预算`, columns[index][0].ast.sourceSpan);
118
+ throw new ErrorDiagnostic("E_PLAYBACK_FLOW_LIMIT", "播放控制流访问超过 {maxFlowSteps} 步;可通过 maxFlowSteps 提高展开预算", columns[index][0].ast.sourceSpan, { maxFlowSteps });
117
119
  }
118
120
  visits[index]++;
119
121
  let jumpTo;
@@ -128,7 +130,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
128
130
  return order;
129
131
  if (!Number.isSafeInteger(action.column)
130
132
  || action.column < 0 || action.column > columns.length) {
131
- throw new ErrorDiagnostic("E_PLAYBACK_FLOW_JUMP", `播放控制流跳转目标 ${action.column} 超出时间列边界`, registered.sourceSpan);
133
+ throw new ErrorDiagnostic("E_PLAYBACK_FLOW_JUMP", "播放控制流跳转目标 {column} 超出时间列边界", registered.sourceSpan, { column: action.column });
132
134
  }
133
135
  // 取最小的跳转目标到最前面
134
136
  jumpTo = Math.min(jumpTo ?? Infinity, action.column);
@@ -140,11 +142,11 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
140
142
  index++;
141
143
  }
142
144
  }
143
- // 正常走到文末才报告从未演奏的列;连续缺失区间只报第一列
145
+ // 正常走到文末才报告从未演奏的正时值列;换行、声部头、回跳小节线等零时值列不算未演奏
144
146
  const played = new Set(order);
145
147
  let previousMissing = false;
146
148
  for (let index = 0; index < columns.length; index++) {
147
- const missing = !played.has(index);
149
+ const missing = !played.has(index) && columns[index].some(node => !node.T.isZero());
148
150
  if (missing && !previousMissing) {
149
151
  diagnostics.push(new WarningDiagnostic("W_PLAYBACK_COLUMN_NEVER_PLAYED", "这里在任何一遍里都不会演奏", columns[index][0].ast.sourceSpan));
150
152
  }
@@ -175,7 +177,18 @@ export function compilePlayback(lowering, options) {
175
177
  const changes = [{ kind: "initial", at: new Fraction(), origins: [] }];
176
178
  const factors = new Map();
177
179
  const spanScales = new Map();
178
- const structureContext = { spans, notes, diagnostics };
180
+ const structureContext = {
181
+ spans,
182
+ notes,
183
+ diagnostics,
184
+ transform(note, transform) {
185
+ if (notes.lastIndexOf(note) < 0) {
186
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_TARGET", "声音变换目标必须属于当前计划的已发布音段", note.sourceSpans?.[0] ?? { start: 0, end: 0 });
187
+ }
188
+ const list = transforms.get(note);
189
+ transforms.set(note, list ? [...list, transform] : [transform]);
190
+ },
191
+ };
179
192
  /** 固化控制的演奏时刻和来源,回调留到最终状态扫描时统一执行 */
180
193
  const scheduleControl = (at, origins, apply) => {
181
194
  if (!Number.isFinite(at.toNumber()) || at.compare(0) < 0) {
@@ -187,13 +200,15 @@ export function compilePlayback(lowering, options) {
187
200
  function play(node, activeTransforms, activeScales, start, duration, ancestors = [],
188
201
  // 折叠成员沿用正文事件的轨发声,倚音各声部的私有轨因此并入宿主轨
189
202
  track = node.track) {
203
+ if (!node.playbackState && !node.emitPlayback)
204
+ return;
190
205
  const lineage = [...ancestors, { node }];
191
- // 当前目标使用进入时的效果快照;子节点序列使用副本,内部新增效果不会回灌外层
192
- const childTransforms = [...activeTransforms];
193
- const inheritedTransforms = [...activeTransforms];
194
- const childScales = [...activeScales];
195
- const inheritedScales = [...activeScales];
196
- const deferred = [];
206
+ // 当前目标使用进入时的效果快照;子节点序列按需复制,内部新增效果不会回灌外层
207
+ const inheritedTransforms = activeTransforms.length ? [...activeTransforms] : undefined;
208
+ const inheritedScales = activeScales.length ? [...activeScales] : undefined;
209
+ let childTransforms;
210
+ let childScales;
211
+ let deferred;
197
212
  /** 复制可变的时间和源码位置,避免结构修改影响输入或另一遍访问 */
198
213
  function publishSpan(input) {
199
214
  const span = {
@@ -205,7 +220,7 @@ export function compilePlayback(lowering, options) {
205
220
  sourceSpans: [{ ...node.ast.sourceSpan }],
206
221
  };
207
222
  spans.push(span);
208
- if (inheritedScales.length)
223
+ if (inheritedScales)
209
224
  spanScales.set(span, inheritedScales);
210
225
  return span;
211
226
  }
@@ -228,12 +243,13 @@ export function compilePlayback(lowering, options) {
228
243
  note(input) {
229
244
  const note = publishSpan(input);
230
245
  notes.push(note);
231
- if (inheritedTransforms.length)
246
+ if (inheritedTransforms)
232
247
  transforms.set(note, inheritedTransforms);
233
248
  },
234
249
  /** 延长原区间,并把当前访问携带的效果定位到新增部分 */
235
250
  extend(span) {
236
- if (!spans.includes(span) || !span.end.equals(start) || duration.compare(0) <= 0) {
251
+ // 待延长目标总在已发布末尾附近,反向查找无需额外 Set 即可 O(1) 命中
252
+ if (spans.lastIndexOf(span) < 0 || !span.end.equals(start) || duration.compare(0) <= 0) {
237
253
  throw new ErrorDiagnostic("E_PLAYBACK_EXTEND_RANGE", "扩展必须接续当前计划内的区间且时值为正", node.ast.sourceSpan);
238
254
  }
239
255
  const previousDuration = span.end.clone().sub(span.start);
@@ -243,8 +259,10 @@ export function compilePlayback(lowering, options) {
243
259
  ? { ...scale, startRatio: scale.startRatio.clone().mul(previousDuration).div(extendedDuration) }
244
260
  : scale);
245
261
  // 新效果从旧终点开始;保存比例后,后续整体结构缩放仍能同步移动它的起点
246
- for (const scale of inheritedScales) {
247
- scales.push({ ...scale, startRatio: previousDuration.clone().div(extendedDuration) });
262
+ if (inheritedScales) {
263
+ for (const scale of inheritedScales) {
264
+ scales.push({ ...scale, startRatio: previousDuration.clone().div(extendedDuration) });
265
+ }
248
266
  }
249
267
  if (scales.length)
250
268
  spanScales.set(span, scales);
@@ -269,12 +287,13 @@ export function compilePlayback(lowering, options) {
269
287
  origins: lineage });
270
288
  },
271
289
  affectFollowing: transform => activeTransforms.push(transform),
272
- defer: hook => deferred.push(hook),
273
- play: (child, childStart, childDuration) => play(child, childTransforms, childScales, childStart ?? start, childDuration ?? duration, lineage, track),
290
+ defer: hook => (deferred ??= []).push(hook),
291
+ play: (child, childStart, childDuration) => play(child, childTransforms ??= [...activeTransforms], childScales ??= [...activeScales], childStart ?? start, childDuration ?? duration, lineage, track),
274
292
  });
275
293
  // 当前节点发布完成就执行结构处理,因此 hook 只能看到当前位置此前的目标
276
- for (const hook of deferred)
277
- hook(structureContext);
294
+ if (deferred)
295
+ for (const hook of deferred)
296
+ hook(structureContext);
278
297
  }
279
298
  const order = linearizeColumns(lowering, diagnostics, maxFlowSteps);
280
299
  const firstScore = lowering.columns[order[0]]?.[0]?.t.clone() ?? new Fraction();
@@ -289,6 +308,8 @@ export function compilePlayback(lowering, options) {
289
308
  const index = order[step];
290
309
  // 同列各顶层访问共享演奏坐标,但分别建立自己的效果作用域
291
310
  for (const node of lowering.columns[index]) {
311
+ if (!node.playbackState && !node.emitPlayback)
312
+ continue;
292
313
  play(node, [], [], node.t.clone().add(shift), node.T.clone());
293
314
  }
294
315
  const boundary = lowering.columns[index + 1]?.[0]?.t ?? lowering.duration; // 当前列的控制终点
@@ -326,7 +347,7 @@ export function compilePlayback(lowering, options) {
326
347
  Object.freeze(span.sourceSpans);
327
348
  Object.freeze(span);
328
349
  }
329
- const noteSet = new Set(notes);
350
+ let noteSet;
330
351
  const connections = new Map();
331
352
  const predecessors = new Map();
332
353
  const relationContext = {
@@ -334,6 +355,7 @@ export function compilePlayback(lowering, options) {
334
355
  diagnostics,
335
356
  /** 只建立一进一出的逻辑连接,保留两个音段各自的边界和修饰 */
336
357
  connect(from, to) {
358
+ noteSet ??= new Set(notes);
337
359
  if (!noteSet.has(from) || !noteSet.has(to) || !from.end.equals(to.start)) {
338
360
  throw new ErrorDiagnostic("E_PLAYBACK_CONNECTION", "音段连接必须属于当前计划且时间相接", from.sourceSpans[0]);
339
361
  }
@@ -350,23 +372,19 @@ export function compilePlayback(lowering, options) {
350
372
  if (isPlaybackRelation(attachment))
351
373
  attachment.applyPlayback(relationContext);
352
374
  }
353
- const reverseNotes = [...notes].sort((left, right) => right.start.compare(left.start));
354
- const connectedEnds = new Map();
355
- // 连接严格向未来推进;逆序处理保证后继的链尾已知,一次算出所有逻辑终点
356
- for (const note of reverseNotes) {
357
- const next = connections.get(note);
358
- const end = next ? connectedEnds.get(next) : note.end;
359
- connectedEnds.set(note, end);
360
- }
361
375
  // 将有声、无声区间上的效果转换为进入和退出边界,交给同一条全局状态时间线
362
- for (const span of spans) {
363
- const end = connectedEnds.get(span) ?? span.end;
376
+ for (const [span, scales] of spanScales) {
377
+ let tail = span;
378
+ if (scales.some(scale => scale.followConnections)) {
379
+ while (connections.has(tail))
380
+ tail = connections.get(tail);
381
+ }
364
382
  // 连接只可能延续效果终点;每个效果仍从自己在原区间内的位置开始
365
- for (const scale of spanScales.get(span) ?? []) {
383
+ for (const scale of scales) {
366
384
  const start = scale.startRatio
367
385
  ? span.start.clone().add(span.end.clone().sub(span.start).mul(scale.startRatio))
368
386
  : span.start;
369
- changes.push({ kind: "scale", at: start, origins: scale.origins, scale, delta: 1 }, { kind: "scale", at: scale.followConnections ? end : span.end,
387
+ changes.push({ kind: "scale", at: start, origins: scale.origins, scale, delta: 1 }, { kind: "scale", at: scale.followConnections ? tail.end : span.end,
370
388
  origins: scale.origins, scale, delta: -1 });
371
389
  }
372
390
  }
@@ -445,57 +463,89 @@ export function compilePlayback(lowering, options) {
445
463
  return { ...snapshot, bpmScale: snapshot.bpmScale.clone() };
446
464
  },
447
465
  };
466
+ const canAbsorb = (from, to) => !transforms.has(to)
467
+ && from.track === to.track && from.midi === to.midi && from.percussion === to.percussion;
448
468
  const realized = new Map();
449
- // 每个逻辑音段独立展开声音,连接不会让后一段继承前一段的装饰
469
+ // 后继无独立变换时直接并入前驱音段,使首段装饰与奏法覆盖连续连音;有新变换时从该处分段并在交界处合并同音
450
470
  for (const note of notes) {
451
- let owned = [{ ...note, start: note.start.clone(), end: note.end.clone() }];
452
- // 变换按登记顺序消费上一项的结果,每项对这个逻辑音段只执行一次
453
- for (const transform of transforms.get(note) ?? []) {
454
- owned = transform(transformContext, owned) ?? owned;
471
+ const previous = predecessors.get(note);
472
+ if (previous && canAbsorb(previous, note))
473
+ continue;
474
+ let tail = note;
475
+ let next = connections.get(tail);
476
+ let mergedSpans;
477
+ while (next && canAbsorb(tail, next)) {
478
+ connections.delete(tail);
479
+ mergedSpans ??= [...note.sourceSpans];
480
+ mergedSpans.push(...next.sourceSpans);
481
+ tail = next;
482
+ next = connections.get(tail);
455
483
  }
456
- let first;
457
- let last;
458
- // 各子音必须留在原区间内;同时收集整体边界,防止声音阶段改写已确定的结构范围
459
- for (const sound of owned) {
460
- if (!Number.isFinite(sound.start.toNumber()) || !Number.isFinite(sound.end.toNumber())
461
- || sound.start.compare(note.start) < 0 || sound.end.compare(note.end) > 0
462
- || sound.end.compare(sound.start) <= 0) {
463
- throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须位于原音段区间内且时值为正", note.sourceSpans[0]);
484
+ if (tail !== note) {
485
+ connections.delete(tail);
486
+ if (next)
487
+ connections.set(note, next);
488
+ }
489
+ const segmentEnd = tail.end;
490
+ const segmentSpans = mergedSpans ? Object.freeze(mergedSpans) : note.sourceSpans;
491
+ const noteTransforms = transforms.get(note);
492
+ let owned;
493
+ if (noteTransforms) {
494
+ owned = [{ ...note, start: note.start.clone(), end: segmentEnd.clone(), sourceSpans: segmentSpans }];
495
+ // 变换按登记顺序消费上一项的结果,每项对这个逻辑音段只执行一次
496
+ for (const transform of noteTransforms) {
497
+ owned = transform(transformContext, owned) ?? owned;
498
+ }
499
+ let first;
500
+ // 各子音必须留在原区间内;同时收集整体起点,防止声音阶段延迟起音或返回空结果
501
+ for (const sound of owned) {
502
+ if (!Number.isFinite(sound.start.toNumber()) || !Number.isFinite(sound.end.toNumber())
503
+ || sound.start.compare(note.start) < 0 || sound.end.compare(segmentEnd) > 0
504
+ || sound.end.compare(sound.start) <= 0) {
505
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须位于原音段区间内且时值为正", note.sourceSpans[0]);
506
+ }
507
+ if (!first || sound.start.compare(first) < 0)
508
+ first = sound.start;
509
+ }
510
+ if (!first?.equals(note.start)) {
511
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须保持原音段的起点", note.sourceSpans[0]);
464
512
  }
465
- if (!first || sound.start.compare(first) < 0)
466
- first = sound.start;
467
- if (!last || sound.end.compare(last) > 0)
468
- last = sound.end;
469
513
  }
470
- if (!first?.equals(note.start) || !last?.equals(note.end)) {
471
- throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须保持原音段的起止边界", note.sourceSpans[0]);
514
+ else {
515
+ owned = [tail === note ? note : { ...note, end: segmentEnd, sourceSpans: segmentSpans }];
472
516
  }
473
- // 现在才分配实际音符身份;变换专用字段不再进入点事件,配对留给边界合并使用
474
- realized.set(note, owned.map(sound => {
517
+ // 现在才分配实际音符身份;仅分段后仍存在跨段连接的音段需要记录事件对供边界合并
518
+ const pairs = (next !== undefined || previous !== undefined)
519
+ ? []
520
+ : undefined;
521
+ for (const sound of owned) {
475
522
  const { start, end, track, midi, velocity, percussion, origins, sourceSpans } = sound;
476
523
  const noteId = nextNoteId++;
477
524
  const on = {
478
525
  kind: "note-on", at: start.clone(), noteId, order: nextEventOrder++,
479
526
  track, midi, velocity, percussion,
480
- origins: [...origins], sourceSpans: sourceSpans.map(span => ({ ...span })),
527
+ origins, sourceSpans: [...sourceSpans],
481
528
  };
482
529
  const off = {
483
- kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++, origins: [...origins],
530
+ kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++, origins,
484
531
  };
485
532
  events.push(on, off);
486
- return { on, off };
487
- }));
533
+ pairs?.push({ on, off });
534
+ }
535
+ if (pairs)
536
+ realized.set(note, pairs);
488
537
  }
489
538
  const removed = new Set();
490
539
  const joinedSources = new Map();
540
+ const connectedNotes = connections.size > 1
541
+ ? [...connections.keys()].sort((left, right) => right.start.compare(left.start))
542
+ : connections.keys();
491
543
  // 后继先完成合并,前驱便可直接接到它更新后的终点;仅合并连接处实际同音的事件
492
- for (const note of reverseNotes) {
544
+ for (const note of connectedNotes) {
493
545
  const next = connections.get(note);
494
- if (!next)
495
- continue;
496
546
  // 只有到达原音段末端的子音可以跨边界连接,中间子音保留自己的起止
497
547
  for (const tail of realized.get(note)) {
498
- if (!tail.off.at.equals(note.end))
548
+ if (!tail.off.at.equals(next.start))
499
549
  continue;
500
550
  const head = realized.get(next).find(pair => !removed.has(pair.on)
501
551
  && pair.on.at.equals(next.start) && pair.on.track === tail.on.track
@@ -46,7 +46,7 @@ export interface PlaybackOrigin {
46
46
  interface PlaybackDraftEventBase {
47
47
  at: Fraction;
48
48
  order: number;
49
- origins: PlaybackOrigin[];
49
+ origins: readonly PlaybackOrigin[];
50
50
  }
51
51
  /** 声音展开后生成的点事件;最终输出前会校验并剥离内部字段 */
52
52
  export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
@@ -30,7 +30,8 @@ export function finalizePlaybackEvents(events, trackOrder) {
30
30
  noteOffs.set(event.noteId, event);
31
31
  }
32
32
  }
33
- // 物理合并完成后仍必须一一配对,并保留正时值和可追溯的来源
33
+ const audible = new Set();
34
+ // 物理合并完成后仍必须一一配对,并保留正时值和可追溯的来源;同时收集实际发声轨道
34
35
  for (const [noteId, on] of noteOns) {
35
36
  const off = noteOffs.get(noteId);
36
37
  if (!off)
@@ -39,16 +40,15 @@ export function finalizePlaybackEvents(events, trackOrder) {
39
40
  throw new Error(`Note ${noteId} has a non-positive duration`);
40
41
  if (on.origins.length === 0 || off.origins.length === 0)
41
42
  throw new Error(`Note ${noteId} has no origin`);
43
+ audible.add(on.track);
42
44
  }
43
- // 再从关音侧反查,避免只检查开音时漏掉孤立的 NoteOff
44
- for (const noteId of noteOffs.keys()) {
45
- if (!noteOns.has(noteId))
46
- throw new Error(`NoteOff ${noteId} has no NoteOn`);
45
+ // 仅当关音数量多于开音时反查孤立的 NoteOff
46
+ if (noteOffs.size !== noteOns.size) {
47
+ for (const noteId of noteOffs.keys()) {
48
+ if (!noteOns.has(noteId))
49
+ throw new Error(`NoteOff ${noteId} has no NoteOn`);
50
+ }
47
51
  }
48
- const audible = new Set();
49
- // 只从实际 NoteOn 收集轨道,无声区间和纯布局轨道不占输出编号
50
- for (const on of noteOns.values())
51
- audible.add(on.track);
52
52
  // 保留 lowering 的稳定轨道顺序,只过滤未实际发声的轨道
53
53
  const trackIds = new Map();
54
54
  for (const track of trackOrder) {
@@ -1,7 +1,11 @@
1
1
  import { DEFAULT_BPM } from "../functions/temporal.js";
2
- /** 演奏时间(QN)按分段速度积分为秒 */
3
- export function performanceTimeToSeconds(events, performanceTime) {
4
- const target = Math.max(0, performanceTime);
2
+ const tempoSegmentsCache = new WeakMap();
3
+ /** 提取并缓存分段速度积分表,使帧级时间换算无需重复扫描全部音符事件 */
4
+ function tempoSegmentsOf(events) {
5
+ let segments = tempoSegmentsCache.get(events);
6
+ if (segments)
7
+ return segments;
8
+ const built = [{ performance: 0, seconds: 0, bpm: DEFAULT_BPM }];
5
9
  let seconds = 0;
6
10
  let position = 0;
7
11
  let bpm = DEFAULT_BPM;
@@ -9,43 +13,50 @@ export function performanceTimeToSeconds(events, performanceTime) {
9
13
  if (event.kind !== "tempo")
10
14
  continue;
11
15
  const next = event.at.toNumber();
12
- if (next > target)
13
- break;
14
- if (next > position)
16
+ if (next > position) {
15
17
  seconds += (next - position) * 60 / bpm;
16
- position = next;
18
+ position = next;
19
+ }
17
20
  bpm = event.bpm;
21
+ const last = built[built.length - 1];
22
+ if (last.performance === position)
23
+ last.bpm = bpm;
24
+ else
25
+ built.push({ performance: position, seconds, bpm });
18
26
  }
19
- return seconds + (target - position) * 60 / bpm;
27
+ tempoSegmentsCache.set(events, built);
28
+ return built;
20
29
  }
21
- export function secondsToPerformanceTime(events, seconds) {
22
- let remaining = Math.max(0, seconds);
23
- let position = 0;
24
- let bpm = DEFAULT_BPM;
25
- for (const event of events) {
26
- if (event.kind !== "tempo")
27
- continue;
28
- const next = event.at.toNumber();
29
- const segmentSeconds = (next - position) * 60 / bpm;
30
- if (remaining < segmentSeconds)
31
- return position + remaining * bpm / 60;
32
- remaining -= segmentSeconds;
33
- position = next;
34
- bpm = event.bpm;
30
+ function stepAt(items, target, valueOf) {
31
+ let low = 0;
32
+ let high = items.length;
33
+ while (low < high) {
34
+ const middle = (low + high) >>> 1;
35
+ if (valueOf(items[middle]) <= target)
36
+ low = middle + 1;
37
+ else
38
+ high = middle;
35
39
  }
36
- return position + remaining * bpm / 60;
40
+ return items[Math.max(0, low - 1)];
41
+ }
42
+ /** 演奏时间(QN)按分段速度积分为秒 */
43
+ export function performanceTimeToSeconds(events, performanceTime) {
44
+ const target = Math.max(0, performanceTime);
45
+ const segment = stepAt(tempoSegmentsOf(events), target, item => item.performance);
46
+ return segment.seconds + (target - segment.performance) * 60 / segment.bpm;
47
+ }
48
+ export function secondsToPerformanceTime(events, seconds) {
49
+ const target = Math.max(0, seconds);
50
+ const segment = stepAt(tempoSegmentsOf(events), target, item => item.seconds);
51
+ return segment.performance + (target - segment.seconds) * segment.bpm / 60;
37
52
  }
38
53
  /** 演奏进度换算为谱面进度 */
39
54
  export function performanceTimeToScoreTime(scoreMap, performanceTime) {
40
55
  const target = Math.max(0, performanceTime);
41
- let result = target;
42
- for (const point of scoreMap) {
43
- const performance = point.performance.toNumber();
44
- if (performance > target)
45
- break;
46
- result = point.score.toNumber() + target - performance;
47
- }
48
- return result;
56
+ const point = stepAt(scoreMap, target, item => item.performance.toNumber());
57
+ return point && point.performance.toNumber() <= target
58
+ ? point.score.toNumber() + target - point.performance.toNumber()
59
+ : target;
49
60
  }
50
61
  /**
51
62
  * 谱面位置换算为演奏时间,供“点击谱面从这里播放”使用
@@ -92,7 +92,7 @@ export interface PlaybackNote extends PlaybackNoteInput, PlaybackSpan {
92
92
  }
93
93
  /** 当前节点发布完成后,修改此前音段的结构;此时尚未生成系统状态 */
94
94
  export type PlaybackHook = (context: PlaybackHookContext) => void;
95
- /** 在最终状态下展开一个音段;结果须保持原音段的起止边界 */
95
+ /** 在最终状态下展开一个音段;结果须位于原音段区间内并保持原起点 */
96
96
  export type PlaybackTransform = (context: PlaybackTransformContext, notes: PlaybackNote[]) => PlaybackNote[] | void;
97
97
  /** 结构阶段的已发布前缀;集合只读,其中区间的边界仍可调整 */
98
98
  export interface PlaybackHookContext {
@@ -101,6 +101,8 @@ export interface PlaybackHookContext {
101
101
  /** 按发布顺序排列,仅包含当前位置此前已发布的有声音段 */
102
102
  readonly notes: readonly PlaybackNote[];
103
103
  readonly diagnostics: Diagnostic[];
104
+ /** 为当前计划内的已发布音段追加声音展开变换 */
105
+ transform(note: PlaybackNote, transform: PlaybackTransform): void;
104
106
  }
105
107
  /** 声音阶段只查询最终状态,接口不提供全局区间的写入口 */
106
108
  export interface PlaybackTransformContext {
@@ -9,6 +9,8 @@ import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from
9
9
  export declare class CanvasPainter implements Painter {
10
10
  private readonly context;
11
11
  constructor(context: CanvasRenderingContext2D);
12
+ private beginOpacity;
13
+ private endOpacity;
12
14
  drawText(text: string, x: number, y: number, style: TextStyle): void;
13
15
  drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
14
16
  drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;
@@ -24,11 +24,6 @@ function tracePath(context, commands, x = 0, y = 0, scaleX = 1, scaleY = 1) {
24
24
  context.bezierCurveTo(x + command.cx1 * scaleX, y + command.cy1 * scaleY, x + command.cx2 * scaleX, y + command.cy2 * scaleY, x + command.x * scaleX, y + command.y * scaleY);
25
25
  }
26
26
  }
27
- function applyOpacity(context, style) {
28
- if (style?.opacity === void 0)
29
- return;
30
- context.globalAlpha *= style.opacity;
31
- }
32
27
  /**
33
28
  * CanvasRenderingContext2D 的 Painter 适配器
34
29
  *
@@ -40,19 +35,28 @@ export class CanvasPainter {
40
35
  constructor(context) {
41
36
  this.context = context;
42
37
  }
38
+ beginOpacity(style) {
39
+ if (style?.opacity === void 0)
40
+ return void 0;
41
+ const previous = this.context.globalAlpha;
42
+ this.context.globalAlpha = previous * style.opacity;
43
+ return previous;
44
+ }
45
+ endOpacity(previous) {
46
+ if (previous !== void 0)
47
+ this.context.globalAlpha = previous;
48
+ }
43
49
  drawText(text, x, y, style) {
44
- this.context.save();
45
- applyOpacity(this.context, style);
50
+ const previousAlpha = this.beginOpacity(style);
46
51
  this.context.fillStyle = style.fill ?? "#000";
47
52
  this.context.font = canvasFont(style);
48
53
  this.context.textAlign = style.textAlign ?? "left";
49
54
  this.context.textBaseline = "alphabetic";
50
55
  this.context.fillText(text, x, y);
51
- this.context.restore();
56
+ this.endOpacity(previousAlpha);
52
57
  }
53
58
  drawLine(x1, y1, x2, y2, style) {
54
- this.context.save();
55
- applyOpacity(this.context, style);
59
+ const previousAlpha = this.beginOpacity(style);
56
60
  this.context.beginPath();
57
61
  this.context.moveTo(x1, y1);
58
62
  this.context.lineTo(x2, y2);
@@ -60,13 +64,12 @@ export class CanvasPainter {
60
64
  this.context.lineWidth = style?.strokeWidth ?? 1;
61
65
  this.context.lineCap = "round";
62
66
  this.context.stroke();
63
- this.context.restore();
67
+ this.endOpacity(previousAlpha);
64
68
  }
65
69
  drawRect(x, y, w, h, style) {
66
70
  if (w < 0 || h < 0)
67
71
  return;
68
- this.context.save();
69
- applyOpacity(this.context, style);
72
+ const previousAlpha = this.beginOpacity(style);
70
73
  if (style?.fill) {
71
74
  this.context.fillStyle = style.fill;
72
75
  this.context.fillRect(x, y, w, h);
@@ -74,19 +77,20 @@ export class CanvasPainter {
74
77
  if (style?.stroke) {
75
78
  this.context.strokeStyle = style.stroke;
76
79
  this.context.lineWidth = style.strokeWidth ?? 1;
80
+ this.context.lineJoin = "miter";
77
81
  this.context.strokeRect(x, y, w, h);
78
82
  }
79
- this.context.restore();
83
+ this.endOpacity(previousAlpha);
80
84
  }
81
85
  drawCircle(cx, cy, r, style) {
82
86
  if (r < 0)
83
87
  return;
84
- this.context.save();
85
- applyOpacity(this.context, style);
88
+ const previousAlpha = this.beginOpacity(style);
86
89
  this.context.beginPath();
87
90
  this.context.arc(cx, cy, r, 0, Math.PI * 2);
88
- if (style?.fill ?? true) {
89
- this.context.fillStyle = style?.fill ?? "#000";
91
+ const fill = style?.fill ?? "#000";
92
+ if (fill && fill !== "none") {
93
+ this.context.fillStyle = fill;
90
94
  this.context.fill();
91
95
  }
92
96
  if (style?.stroke) {
@@ -94,13 +98,12 @@ export class CanvasPainter {
94
98
  this.context.lineWidth = style.strokeWidth ?? 1;
95
99
  this.context.stroke();
96
100
  }
97
- this.context.restore();
101
+ this.endOpacity(previousAlpha);
98
102
  }
99
103
  drawPath(commands, style, transform) {
100
104
  if (commands.length === 0)
101
105
  return;
102
- this.context.save();
103
- applyOpacity(this.context, style);
106
+ const previousAlpha = this.beginOpacity(style);
104
107
  tracePath(this.context, commands, transform?.x, transform?.y, transform?.scaleX, transform?.scaleY);
105
108
  if (style?.fill) {
106
109
  this.context.fillStyle = style.fill;
@@ -113,7 +116,7 @@ export class CanvasPainter {
113
116
  this.context.lineJoin = "round";
114
117
  this.context.stroke();
115
118
  }
116
- this.context.restore();
119
+ this.endOpacity(previousAlpha);
117
120
  }
118
121
  }
119
122
  /** 使用 Canvas 后端把一个布局结果一次绘制到独立页面 context */
@@ -70,9 +70,6 @@ function transformPathCommand(command, transform) {
70
70
  return { ...command };
71
71
  const x = (value) => transform.x + value * transform.scaleX;
72
72
  const y = (value) => transform.y + value * transform.scaleY;
73
- if (command.op === "M" || command.op === "L") {
74
- return { op: command.op, x: x(command.x), y: y(command.y) };
75
- }
76
73
  if (command.op === "Q") {
77
74
  return {
78
75
  op: "Q",
@@ -93,5 +90,5 @@ function transformPathCommand(command, transform) {
93
90
  y: y(command.y),
94
91
  };
95
92
  }
96
- return { ...command };
93
+ return { op: command.op, x: x(command.x), y: y(command.y) };
97
94
  }
@@ -10,5 +10,4 @@ export declare class TranslatingPainter implements Painter {
10
10
  drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;
11
11
  drawCircle(cx: number, cy: number, r: number, style?: PaintStyle): void;
12
12
  drawPath(commands: readonly PathCommand[], style?: PaintStyle, transform?: PathTransform): void;
13
- private translateCommand;
14
13
  }