jpfun 0.4.1 → 0.5.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 (73) hide show
  1. package/README.md +53 -113
  2. package/dist/converter/midi/convert.js +14 -7
  3. package/dist/converter/musicxml/features.d.ts +57 -16
  4. package/dist/converter/musicxml/features.js +204 -42
  5. package/dist/converter/musicxml/index.d.ts +7 -2
  6. package/dist/converter/musicxml/index.js +256 -268
  7. package/dist/converter/musicxml/model.d.ts +36 -7
  8. package/dist/converter/musicxml/resolve.d.ts +10 -0
  9. package/dist/converter/musicxml/resolve.js +152 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/fraction.js +7 -1
  13. package/dist/functions/ASTtypes.d.ts +2 -3
  14. package/dist/functions/ASTtypes.js +5 -9
  15. package/dist/functions/adjust/index.js +4 -48
  16. package/dist/functions/arpeggio/index.js +21 -13
  17. package/dist/functions/box/index.js +81 -82
  18. package/dist/functions/dash/index.js +20 -11
  19. package/dist/functions/div/index.d.ts +1 -1
  20. package/dist/functions/div/index.js +7 -7
  21. package/dist/functions/dot/index.js +4 -5
  22. package/dist/functions/dyn/index.js +28 -32
  23. package/dist/functions/grace/index.d.ts +19 -6
  24. package/dist/functions/grace/index.js +123 -115
  25. package/dist/functions/key/index.js +1 -1
  26. package/dist/functions/meter/index.js +14 -1
  27. package/dist/functions/note/index.d.ts +6 -1
  28. package/dist/functions/note/index.js +37 -14
  29. package/dist/functions/note/source-transform.d.ts +21 -0
  30. package/dist/functions/note/source-transform.js +164 -0
  31. package/dist/functions/page/index.d.ts +5 -0
  32. package/dist/functions/page/index.js +8 -5
  33. package/dist/functions/set/index.js +5 -1
  34. package/dist/functions/symbol/index.d.ts +2 -0
  35. package/dist/functions/symbol/index.js +1 -1
  36. package/dist/functions/symbol/ornament.d.ts +3 -3
  37. package/dist/functions/symbol/ornament.js +21 -35
  38. package/dist/functions/symbol/symbols/accent.js +5 -5
  39. package/dist/functions/symbol/symbols/fermata.js +5 -4
  40. package/dist/functions/tie/index.js +22 -32
  41. package/dist/functions/tuplet/index.js +19 -23
  42. package/dist/functions/up/index.js +9 -9
  43. package/dist/functions/voice/index.js +4 -3
  44. package/dist/functions/volta/index.js +7 -12
  45. package/dist/jpfun.core.min.js +40 -37
  46. package/dist/jpfun.from-midi.min.js +5 -5
  47. package/dist/jpfun.from-musicxml.min.js +8 -8
  48. package/dist/jpfun.min.js +49 -46
  49. package/dist/layout/engine.d.ts +11 -1
  50. package/dist/layout/engine.js +299 -96
  51. package/dist/layout/page.js +2 -0
  52. package/dist/layout/range.d.ts +26 -0
  53. package/dist/layout/range.js +75 -0
  54. package/dist/layout/types.d.ts +33 -4
  55. package/dist/lowering/types.d.ts +5 -0
  56. package/dist/parser/parse-utils/length-utils.js +2 -0
  57. package/dist/parser/parse-utils/note-utils.d.ts +2 -0
  58. package/dist/parser/parse-utils/note-utils.js +6 -2
  59. package/dist/parser/parserContext.js +1 -1
  60. package/dist/playback/compile.d.ts +2 -9
  61. package/dist/playback/compile.js +297 -186
  62. package/dist/playback/event.d.ts +8 -16
  63. package/dist/playback/event.js +13 -3
  64. package/dist/playback/types.d.ts +76 -18
  65. package/dist/playback/types.js +1 -0
  66. package/dist/render/index.d.ts +1 -1
  67. package/dist/render/index.js +1 -1
  68. package/dist/render/recording.d.ts +1 -0
  69. package/dist/render/recording.js +21 -0
  70. package/dist/render/translate.d.ts +14 -0
  71. package/dist/render/translate.js +48 -0
  72. package/grammar.md +13 -6
  73. package/package.json +4 -4
@@ -0,0 +1,164 @@
1
+ import { Diagnostic, ErrorDiagnostic } from "../../diagnostic.js";
2
+ import { preprocessSource } from "../../parser/preprocess.js";
3
+ import { readCall } from "../../parser/parse-utils/call-utils.js";
4
+ import { findClosingQuote, quote } from "../../parser/parse-utils/string-utils.js";
5
+ import { NoteNameMap, SHARP_NOTE_NAMES, FLAT_NOTE_NAMES, resolveLetterNameToJianpu, tonality2Midi } from "../../parser/parse-utils/note-utils.js";
6
+ import { parseNoteName } from "./noteNameFSM.js";
7
+ const LETTERS = "CDEFGAB";
8
+ const mod = (value, base) => ((value % base) + base) % base;
9
+ const accidental = (offset) => offset < 0 ? "b".repeat(-offset) : "#".repeat(offset);
10
+ function fail(span) {
11
+ throw new ErrorDiagnostic("E_NOTE_TRANSFORM", "无法安全改写此音符的音高", span);
12
+ }
13
+ /** 音高计算只读固化事实;互转保留调内级数,半音操作采用最少升降号的拼写 */
14
+ function targetPitch(note, operation) {
15
+ const absolute = operation === "to-absolute"
16
+ || operation !== "to-relative" && LETTERS.includes(note.ast.name);
17
+ const midi = note.resolvedMidi + (operation === "semitone-up" ? 1 : operation === "semitone-down" ? -1 : 0);
18
+ const tonic = tonality2Midi(note.keySignature, 4);
19
+ if (![midi, tonic, note.ast.octave, note.ast.jeOctaveOffset].every(Number.isSafeInteger))
20
+ fail(note.ast.sourceSpan);
21
+ const spelling = operation === "semitone-down" ? FLAT_NOTE_NAMES : SHARP_NOTE_NAMES;
22
+ let name, acc, octave;
23
+ if (operation === "to-absolute") {
24
+ const tonicLetter = LETTERS.indexOf(note.keySignature[0]);
25
+ const base = tonicLetter < 0 ? LETTERS.indexOf(SHARP_NOTE_NAMES[mod(tonic, 12)][0]) : tonicLetter;
26
+ const degree = Number(note.ast.name) - 1;
27
+ name = LETTERS[(base + degree) % 7];
28
+ const tonicAcc = mod(tonic - NoteNameMap[LETTERS[base]] + 6, 12) - 6;
29
+ octave = Math.floor((tonic - tonicAcc) / 12) - 1 + Math.floor((base + degree) / 7)
30
+ + note.ast.octave + note.ast.jeOctaveOffset;
31
+ acc = accidental(midi - ((octave + 1) * 12 + NoteNameMap[name]));
32
+ }
33
+ else if (operation === "to-relative") {
34
+ const ast = note.ast;
35
+ const key = LETTERS.includes(note.keySignature[0]) ? note.keySignature
36
+ : SHARP_NOTE_NAMES[mod(tonic, 12)] + (Math.floor(tonic / 12) - 1);
37
+ const relative = resolveLetterNameToJianpu(ast.name, ast.acc, ast.octave + ast.jeOctaveOffset, key);
38
+ if (!relative)
39
+ fail(ast.sourceSpan);
40
+ ({ renderName: name, renderAcc: acc, renderOctave: octave } = relative);
41
+ }
42
+ else {
43
+ const value = absolute ? midi : midi - tonic;
44
+ const pitch = spelling[mod(value, 12)];
45
+ name = absolute ? pitch[0] : String(LETTERS.indexOf(pitch[0]) + 1);
46
+ acc = pitch.slice(1);
47
+ octave = Math.floor(value / 12) - (absolute ? 1 : 0);
48
+ }
49
+ return { name, acc, octave: octave - note.ast.jeOctaveOffset, absolute };
50
+ }
51
+ /** 仅在函数参数的顶层保护低八度逗号;已有大括号内的简写无需再包装 */
52
+ function needsBraces(masked, ast) {
53
+ for (let parent = ast.parent; parent; parent = parent.parent) {
54
+ const call = readCall(masked, parent.sourceSpan.start, parent.sourceSpan.end);
55
+ if (!call)
56
+ continue;
57
+ const arg = call.args.find(item => item.valueSpan.start <= ast.sourceSpan.start
58
+ && item.valueSpan.end >= ast.sourceSpan.end);
59
+ if (!arg)
60
+ continue;
61
+ let depth = 0;
62
+ for (let position = arg.valueSpan.start; position < ast.sourceSpan.start; position++) {
63
+ if (masked[position] === '"')
64
+ position = findClosingQuote(masked, position, arg.valueSpan.end);
65
+ else if (masked[position] === "{")
66
+ depth++;
67
+ else if (masked[position] === "}")
68
+ depth--;
69
+ }
70
+ return depth === 0;
71
+ }
72
+ return false;
73
+ }
74
+ /** edits 始终引用原文;参数只改值,默认参数只在当前调用覆盖,避免影响其他音符 */
75
+ export function rewriteNotes(source, notes, operation, ranges) {
76
+ const { maskedSource: masked } = preprocessSource(source);
77
+ const edits = [];
78
+ const tokens = [];
79
+ function replace(span, text) {
80
+ if (source.slice(span.start, span.end) === text)
81
+ return;
82
+ if (source.slice(span.start, span.end) !== masked.slice(span.start, span.end))
83
+ fail(span);
84
+ edits.push({ span, text });
85
+ }
86
+ for (const note of notes) {
87
+ const { ast } = note;
88
+ const span = ast.sourceSpan;
89
+ const call = readCall(masked, span.start, span.end);
90
+ const explicit = call?.span.end === span.end && call.closeParenSpan;
91
+ const already = operation === "to-absolute" && LETTERS.includes(ast.name)
92
+ || operation === "to-relative" && /^[1-7]$/.test(ast.name);
93
+ if (!explicit)
94
+ tokens.push({ span, text: source.slice(span.start, span.end) });
95
+ if (ranges && !ranges.some(range => range.start <= span.start && range.end >= span.end))
96
+ continue;
97
+ if (note.resolvedMidi === null || already)
98
+ continue;
99
+ const pitch = targetPitch(note, operation);
100
+ const octaveText = pitch.absolute ? String(pitch.octave)
101
+ : pitch.octave < 0 ? ",".repeat(-pitch.octave) : "'".repeat(pitch.octave);
102
+ const nameText = (acc, octave) => pitch.absolute
103
+ ? pitch.name + acc + octave : acc + pitch.name + octave;
104
+ if (!explicit) {
105
+ let text = nameText(pitch.acc, octaveText);
106
+ if (text.includes(",") && needsBraces(masked, ast))
107
+ text = `{${text}}`;
108
+ tokens[tokens.length - 1].text = text;
109
+ continue;
110
+ }
111
+ const slots = new Map();
112
+ call.args.forEach((arg, index) => {
113
+ if (arg.valueSpan.start === arg.valueSpan.end)
114
+ return;
115
+ slots.set(arg.nameSpan ? masked.slice(arg.nameSpan.start, arg.nameSpan.end).toLowerCase() : index, arg.valueSpan);
116
+ });
117
+ const nameSlot = slots.get("name") ?? slots.get(0);
118
+ const accSlot = slots.get("acc") ?? slots.get(1);
119
+ const octaveSlot = slots.get("octave") ?? slots.get(2);
120
+ const additions = [];
121
+ function write(slot, name, value) {
122
+ const text = !value || value.includes(",")
123
+ || slot && source[slot.start] === '"' ? quote(value) : value;
124
+ if (slot)
125
+ replace(slot, text);
126
+ else
127
+ additions.push(`${name}=${text}`);
128
+ }
129
+ write(nameSlot, "name", nameText(accSlot ? "" : pitch.acc, octaveSlot ? "" : octaveText));
130
+ if (accSlot)
131
+ write(accSlot, "acc", pitch.acc);
132
+ else if (ast.hasDefaultAcc)
133
+ additions.push('acc=""');
134
+ if (octaveSlot)
135
+ replace(octaveSlot, String(pitch.octave));
136
+ if (additions.length) {
137
+ const at = call.closeParenSpan.start;
138
+ const prefix = masked.slice(call.openParenSpan.end, at).trimEnd();
139
+ replace({ start: at, end: at }, (prefix ? prefix.endsWith(",") ? " " : ", " : "") + additions.join(", "));
140
+ }
141
+ }
142
+ // 相邻原子改写后仍须是两个音符,例如 C4D4 -> C4 2,不能合并成 C42。
143
+ tokens.sort((left, right) => left.span.start - right.span.start);
144
+ for (let index = 0; index < tokens.length - 1; index++) {
145
+ const left = tokens[index], right = tokens[index + 1];
146
+ if (left.span.end !== right.span.start || left.text.endsWith("}"))
147
+ continue;
148
+ const parsed = parseNoteName(left.text + right.text);
149
+ if (parsed instanceof Diagnostic || parsed.next !== left.text.length) {
150
+ if (left.text !== source.slice(left.span.start, left.span.end))
151
+ left.text += " ";
152
+ else
153
+ right.text = " " + right.text;
154
+ }
155
+ }
156
+ for (const token of tokens)
157
+ replace(token.span, token.text);
158
+ edits.sort((left, right) => left.span.start - right.span.start);
159
+ for (let index = 1; index < edits.length; index++) {
160
+ if (edits[index - 1].span.end > edits[index].span.start)
161
+ fail(edits[index].span);
162
+ }
163
+ return edits;
164
+ }
@@ -19,6 +19,11 @@ export declare class PageFunction extends ASTFunctionNode {
19
19
  description: string;
20
20
  type: "string";
21
21
  default: string;
22
+ } | {
23
+ name: string;
24
+ description: string;
25
+ type: "number";
26
+ default: number;
22
27
  })[];
23
28
  };
24
29
  readonly config: PageConfig | null;
@@ -45,15 +45,15 @@ class PageNumberAttachment {
45
45
  export class PageFunction extends ASTFunctionNode {
46
46
  static def = {
47
47
  name: ["page"],
48
- description: "设置文档页面尺寸、边距、最小谱面行间距和页码",
48
+ description: "设置文档页面",
49
49
  details: `\
50
50
  ~~~jpfun
51
51
  @page(
52
52
  width=794px, height=1123px, top=48px, bottom=48px,
53
- left=40px, right=40px, gap=1em, numbering="1/1"
53
+ left=40px, right=40px, gap=1em, numbering="1/1", fillRatio=0.5
54
54
  )
55
55
  ~~~
56
- 尺寸接受 \`px\` 或 \`em\`。页边距和行距须非负,左右边距之和须小于页宽;固定页高时,上下边距之和也须小于页高。`,
56
+ 尺寸接受 \`px\` 或 \`em\`。页边距和行距须非负;左右边距之和须小于页宽,固定页高时上下边距之和须小于页高。`,
57
57
  allowExtraArgs: false,
58
58
  args: [
59
59
  { name: "width", description: "页面宽度,须大于左右页边距之和", type: "length", default: px(DEFAULT_PAGE_CONFIG.width) },
@@ -66,6 +66,7 @@ export class PageFunction extends ASTFunctionNode {
66
66
  // 单个 1 取当前页;多个 1 中最后一个取总页数
67
67
  { name: "numbering", description: "页码格式,空值隐藏;`1` 显示当前页,`1/1` 显示当前页/总页数", type: "string", default: "" },
68
68
  { name: "font", description: "页码字体,空值沿用当前字体设置", type: "string", default: "" },
69
+ { name: "fillRatio", description: "自然宽度达到该比例后撑满", type: "number", default: DEFAULT_PAGE_CONFIG.fillRatio },
69
70
  ],
70
71
  };
71
72
  config;
@@ -86,6 +87,7 @@ export class PageFunction extends ASTFunctionNode {
86
87
  }
87
88
  ctx.documentDeclarations["page"] = true;
88
89
  const values = this.getArgValue(args, ctx);
90
+ const fillRatio = values.pop();
89
91
  this.font = values.pop() || ctx.variables.font;
90
92
  const numbering = values.pop();
91
93
  const [width, height, top, bottom, left, right, gap] = values.map(value => ctx.length2px(value));
@@ -109,6 +111,7 @@ export class PageFunction extends ASTFunctionNode {
109
111
  marginLeft: left,
110
112
  marginRight: right,
111
113
  lineGap: gap,
114
+ fillRatio,
112
115
  });
113
116
  this.numbering = numbering;
114
117
  }
@@ -124,8 +127,8 @@ export class PageFunction extends ASTFunctionNode {
124
127
  toString() {
125
128
  if (!this.config)
126
129
  return "@page()";
127
- const { width, height, marginTop, marginBottom, marginLeft, marginRight, lineGap } = this.config;
128
- return `@page(width=${width}px, height=${Number.isFinite(height) ? height : 0}px, top=${marginTop}px, bottom=${marginBottom}px, left=${marginLeft}px, right=${marginRight}px, gap=${lineGap}px, numbering=${quote(this.numbering)}, font=${quote(this.font)})`;
130
+ const { width, height, marginTop, marginBottom, marginLeft, marginRight, lineGap, fillRatio } = this.config;
131
+ return `@page(width=${width}px, height=${Number.isFinite(height) ? height : 0}px, top=${marginTop}px, bottom=${marginBottom}px, left=${marginLeft}px, right=${marginRight}px, gap=${lineGap}px, numbering=${quote(this.numbering)}, font=${quote(this.font)}, fillRatio=${fillRatio})`;
129
132
  }
130
133
  }
131
134
  export const PageNode = PageFunction;
@@ -62,7 +62,11 @@ class SetFunction extends ASTFunctionNode {
62
62
  }
63
63
  }
64
64
  toString() {
65
- return `@set(${Array.from(this.args, ([key, value]) => `${key}=${typeof value === "string" ? quote(value) : value}`).join(", ")})`;
65
+ return `@set(${Array.from(this.args, ([key, value]) => {
66
+ const text = typeof value === "string" ? quote(value)
67
+ : value && typeof value === "object" && "unit" in value ? `${value.value}${value.unit}` : value;
68
+ return `${key}=${text}`;
69
+ }).join(", ")})`;
66
70
  }
67
71
  }
68
72
  export const SetNode = SetFunction;
@@ -19,6 +19,8 @@ export interface SymbolDefinition {
19
19
  };
20
20
  /** 符号高度 = size × weight,用来修正宽扁字形的视觉重量;默认 1 */
21
21
  readonly weight?: number;
22
+ /** 图形下方留白,使用符号自身坐标并随 scale 缩放;默认 0 */
23
+ readonly paddingBottom?: number;
22
24
  /** 写入本位置之后持续生效的状态,例如力度记号的 velocity */
23
25
  readonly onTimeState?: (state: TimeState) => void;
24
26
  /** 发布系统控制,或注册对同一折叠序列后续音符的局部变换 */
@@ -121,7 +121,7 @@ class SymbolTemporal extends TemporalNodeBase {
121
121
  else {
122
122
  this.scale = this.height / this.bounds.h;
123
123
  this.box.w = this.bounds.w * this.scale;
124
- this.box.h = this.height;
124
+ this.box.h = this.height + (this.ast.definition.paddingBottom ?? 0) * this.scale;
125
125
  }
126
126
  this.box.anchor = this.box.w / 2;
127
127
  this.box.visualAxis = this.box.h / 2;
@@ -6,10 +6,10 @@ interface OrnamentPattern {
6
6
  readonly repeat?: boolean;
7
7
  }
8
8
  /**
9
- * 把一个音按固定音级模式展开成装饰音序列
9
+ * 按调内音级模式拆分传入音段,使用结构完成后的范围和最终播放速度
10
10
  *
11
- * 密度按发声时的速度决定而不是固定的记谱时值:固定 1/8 四分音符在慢速下
12
- * 每秒只有两三次,听起来根本不是颤音。默认速度下仍然恰好是 1/8 四分音符。
11
+ * 重复式模式按速度计算次数,固定模式在整段时值内均分。
12
+ * 派生音段继承轨道和来源,仍只声明音段,不直接发布 NoteOn/NoteOff。
13
13
  */
14
14
  export declare function ornament(pattern: OrnamentPattern): PlaybackTransform;
15
15
  export {};
@@ -6,67 +6,53 @@ const MAX_BPM = 480;
6
6
  /** 一个装饰音能展开的子音上限;防的是 `@tempo(0.01)` 这类手滑 */
7
7
  const MAX_SUBNOTES = 256;
8
8
  /**
9
- * 把一个音按固定音级模式展开成装饰音序列
9
+ * 按调内音级模式拆分传入音段,使用结构完成后的范围和最终播放速度
10
10
  *
11
- * 密度按发声时的速度决定而不是固定的记谱时值:固定 1/8 四分音符在慢速下
12
- * 每秒只有两三次,听起来根本不是颤音。默认速度下仍然恰好是 1/8 四分音符。
11
+ * 重复式模式按速度计算次数,固定模式在整段时值内均分。
12
+ * 派生音段继承轨道和来源,仍只声明音段,不直接发布 NoteOn/NoteOff。
13
13
  */
14
14
  export function ornament(pattern) {
15
15
  return (context, owned) => {
16
- const noteOffs = new Map();
17
- for (const event of owned) {
18
- if (event.kind === "note-off")
19
- noteOffs.set(event.noteId, event);
20
- }
21
- const removed = new Set();
22
- const added = [];
16
+ const result = [];
17
+ // 前一项声音变换可能已产生多个音段,因此逐段处理,不能假定只剩一个宿主音。
23
18
  for (const note of owned) {
24
- if (note.kind !== "note-on" || !note.transpose)
25
- continue;
26
- const off = noteOffs.get(note.noteId);
27
- if (!off)
19
+ // 缺少调内移调能力的目标原样保留,例如固定打击音。
20
+ if (!note.transpose) {
21
+ result.push(note);
28
22
  continue;
29
- const duration = off.at.clone().sub(note.at);
30
- const bpm = context.stateAt(note.at).effectiveBpm;
23
+ }
24
+ const duration = note.end.clone().sub(note.start);
25
+ // 此处读取最终速度,结构延长和其他声部的速度效果都已计入。
26
+ const bpm = context.stateAt(note.start).effectiveBpm;
31
27
  const steps = pattern.repeat ? repeatToFill(pattern.body, duration.toNumber(), bpm) : pattern.body;
32
28
  const step = duration.div(steps.length);
33
- removed.add(note);
34
- removed.add(off);
29
+ // 用 Fraction 等分最终区间,保证首尾边界准确且不会积累浮点时间误差。
35
30
  for (let index = 0; index < steps.length; index++) {
36
31
  const offset = steps[index];
37
- const noteId = context.nextNoteId();
38
- const at = note.at.clone().add(step.clone().mul(index));
39
- const order = note.order + index / steps.length;
40
- const on = {
32
+ const start = note.start.clone().add(step.clone().mul(index));
33
+ result.push({
41
34
  ...note,
42
- at,
43
- noteId,
44
- order,
35
+ start,
36
+ end: start.clone().add(step),
45
37
  // 本音保留主体的临时升降号,只有偏移音才走调内换算
46
38
  midi: offset === 0 ? note.midi : note.transpose(offset),
47
39
  // 后续 ornament 要从这个派生音继续移调,不能仍以最初的宿主为基准
48
40
  transpose: delta => note.transpose(offset + delta),
49
- origins: [...note.origins],
50
- sourceSpans: note.sourceSpans.map(span => ({ ...span })),
51
- };
52
- added.push(on, {
53
- ...off,
54
- at: at.clone().add(step),
55
- noteId,
56
- order,
57
- origins: [...off.origins],
58
41
  });
59
42
  }
60
43
  }
61
- return [...owned.filter(event => !removed.has(event)), ...added];
44
+ return result;
62
45
  };
63
46
  }
47
+ /** 按最终速度计算完整音型的重复次数,并限制总子音数 */
64
48
  function repeatToFill(body, duration, bpm) {
65
49
  // 名义密度与速度无关(秒数里的 bpm 与频率里的 bpm 恰好抵消),只在 bpm 越界时按比例修正
66
50
  const ratio = Math.min(MAX_BPM, Math.max(MIN_BPM, bpm)) / bpm;
51
+ // 预算按完整音型计算,避免在达到子音上限时留下半个音型。
67
52
  const limit = Math.floor(MAX_SUBNOTES / body.length);
68
53
  const cycles = Math.min(limit, Math.max(1, Math.round(duration * NOMINAL_RATE * ratio / body.length)));
69
54
  const result = [];
55
+ // 先得到完整音级序列,调用方再按实际子音总数统一分配宿主时值。
70
56
  for (let i = 0; i < cycles; i++)
71
57
  result.push(...body);
72
58
  return result;
@@ -14,11 +14,11 @@ export const accentSymbol = {
14
14
  style: { stroke: "#000", strokeWidth: 1 },
15
15
  },
16
16
  ],
17
- emitPlayback: emitter => emitter.affectFollowing((_context, events) => {
18
- for (const event of events) {
19
- if (event.kind === "note-on") {
20
- event.velocity = Math.min(MAX_VELOCITY, event.velocity + ACCENT_BOOST);
21
- }
17
+ /** 将重音登记为声音变换,保留音段的结构边界和系统速度 */
18
+ emitPlayback: emitter => emitter.affectFollowing((_context, notes) => {
19
+ // 前序装饰可能已拆出多个子音,逐个增加原有力度并限制到 MIDI 最大力度。
20
+ for (const note of notes) {
21
+ note.velocity = Math.min(MAX_VELOCITY, note.velocity + ACCENT_BOOST);
22
22
  }
23
23
  }),
24
24
  };
@@ -1,7 +1,10 @@
1
+ // 多声部常在同一时段各写一个延长记号;按区间并集减速一次,避免速度随记号数指数下降
2
+ const FERMATA_BPM_SCALE = {};
1
3
  export const fermataSymbol = {
2
4
  name: "fermata",
3
5
  description: "延长记号:覆盖区间速度减半,目标音实际时长翻倍",
4
6
  weight: 0.6,
7
+ paddingBottom: 3,
5
8
  shapes: [
6
9
  {
7
10
  path: [
@@ -17,8 +20,6 @@ export const fermataSymbol = {
17
20
  style: { fill: "#000" },
18
21
  },
19
22
  ],
20
- emitPlayback: emitter => {
21
- emitter.control(emitter.start, state => state.bpmScale.div(2));
22
- emitter.control(emitter.end, state => state.bpmScale.mul(2));
23
- },
23
+ /** 声明同 key 的减速区间,沿逻辑连接延续终点;范围不依赖实际子音的拆分结果 */
24
+ emitPlayback: emitter => emitter.scaleFollowingBpm(FERMATA_BPM_SCALE, 1, 2, { followConnections: true }),
24
25
  };
@@ -14,10 +14,10 @@ class TieFunction extends ASTFunctionNode {
14
14
  ~~~jpfun
15
15
  1@a 2 3@b @tie(a, b, height=0.5em)
16
16
  ~~~
17
- - **位置参数**:端点标签,可传多个,按顺序连接;省略时查找最近的可连接对象
17
+ - **位置参数**:端点标签,可传多个,按顺序连接;省略时查找最近的可标记对象,包括增时线
18
18
  - **height**:弧线高度,默认 \`0.5em\`
19
19
 
20
- 同行端点用一条弧线连接,跨行时自动拆成多段`,
20
+ 同行端点用一条弧线连接,跨行时自动拆成多段。同轨同音且时间连续的音段建立播放连接,各段保留自己的装饰,例如 \`1 ^ $tr 1 @tie()\` 的后一音段不继承颤音。涉及增时线的连接仅绘制,不合并播放音符。`,
21
21
  allowExtraArgs: true,
22
22
  extraArgType: "label",
23
23
  args: []
@@ -72,7 +72,10 @@ class TieFunction extends ASTFunctionNode {
72
72
  return [];
73
73
  }
74
74
  toString(source) {
75
- return `@tie(${this.endPoints.map(p => `${p.label ?? 'anon'}:[${p.toString(source)}]`).join(", ")})`;
75
+ const labels = this.endPoints.map(endpoint => endpoint.label);
76
+ if (labels.some(label => label === undefined))
77
+ return source.slice(this.sourceSpan.start, this.sourceSpan.end);
78
+ return `@tie(${labels.join(", ")}, height=${this.height}px)`;
76
79
  }
77
80
  }
78
81
  export const TieNode = TieFunction;
@@ -91,39 +94,26 @@ class TieLayoutAttachment {
91
94
  this.thickness = Math.max(1.2, size * THICKNESS_RATIO);
92
95
  }
93
96
  /**
94
- * 只有同轨、同音、演奏时间连续的事件对才合并,其余 tie 纯视觉
95
- *
96
- * 反复会让同一个端点产生多个事件对,所以按首端点的每一个 NoteOn 各串一条链。
97
+ * 为同轨、同音且时间相接的逻辑音段建立连接,各次反复及各段装饰保持独立
98
+ * 此时只匹配来源和逻辑音高,实际子音是否能合并由声音展开后的核心处理
97
99
  */
98
100
  applyPlayback(context) {
99
- const noteOns = () => context.events
100
- .filter((event) => event.kind === "note-on");
101
- const noteOff = (noteId) => context.events
102
- .find((event) => event.kind === "note-off" && event.noteId === noteId);
103
- for (const head of noteOns().filter(note => note.origins.some(origin => origin.node === this.endPoints[0]))) {
104
- for (let i = 1; i < this.endPoints.length; i++) {
105
- const end = noteOff(head.noteId);
106
- if (!end)
107
- break;
108
- const next = noteOns().find(note => note.noteId !== head.noteId
109
- && note.origins.some(origin => origin.node === this.endPoints[i])
110
- && note.track === head.track
111
- && note.midi === head.midi
112
- && note.percussion === head.percussion
113
- && end.at.equals(note.at));
101
+ // 整体端点可能包含和弦多个成员或多遍访问,每个首段分别寻找自己的连接链。
102
+ for (const head of context.notes.filter(note => note.origins.some(origin => origin.node === this.endPoints[0]))) {
103
+ let previous = head;
104
+ // 按显式端点顺序延续;某一端点没有相接音段就停止,不能跨过缺口连接。
105
+ for (let index = 1; index < this.endPoints.length; index++) {
106
+ // connect 同时认领候选:配对冲突时继续找其他成员,重复声明可复用原配对。
107
+ const next = context.notes.find(note => note !== previous
108
+ && note.origins.some(origin => origin.node === this.endPoints[index])
109
+ && note.track === previous.track
110
+ && note.midi === previous.midi
111
+ && note.percussion === previous.percussion
112
+ && previous.end.equals(note.start)
113
+ && context.connect(previous, note));
114
114
  if (!next)
115
115
  break;
116
- const nextOff = noteOff(next.noteId);
117
- if (!nextOff)
118
- break;
119
- head.sourceSpans.push(...next.sourceSpans);
120
- for (const origin of next.origins) {
121
- if (!head.origins.includes(origin))
122
- head.origins.push(origin);
123
- }
124
- nextOff.noteId = head.noteId;
125
- nextOff.origins = [...head.origins];
126
- context.events.splice(0, context.events.length, ...context.events.filter(event => event !== end && event !== next));
116
+ previous = next;
127
117
  }
128
118
  }
129
119
  }
@@ -48,21 +48,19 @@ class TupletFunction extends ASTFunctionNode {
48
48
  };
49
49
  }
50
50
  loweringEnter(ctx) {
51
- const events = [];
52
51
  const group = {
53
- events,
54
- onTemporal(node) {
55
- // 此时不能改 T:actual 依赖整个作用域的最短值和总和。
56
- events.push(node);
57
- },
52
+ nodes: [],
53
+ attachments: [],
54
+ onTemporal(node) { group.nodes.push(node); },
55
+ onAttachment(attachment) { group.attachments.push(attachment); },
58
56
  };
59
57
  ctx.beginLoweringGroup(this, group);
60
58
  return [];
61
59
  }
62
60
  loweringExit(ctx, _track, timeOffset) {
63
- const group = ctx.endLoweringGroup(this);
61
+ const content = ctx.endLoweringGroup(this);
64
62
  // 零时长控制事件不构成连音单位,但稍后仍要随整组移动其开始位置。
65
- const positive = group.events.filter(event => event.T.compare(0) > 0);
63
+ const positive = content.nodes.filter(event => event.T.compare(0) > 0);
66
64
  if (positive.length === 0) {
67
65
  throw new ErrorDiagnostic("E_TUPLET_EMPTY", "@tuplet 的内容必须产生至少一个正时值事件", this.sourceSpan);
68
66
  }
@@ -88,15 +86,15 @@ class TupletFunction extends ASTFunctionNode {
88
86
  throw new ErrorDiagnostic("E_TUPLET_INVALID_RATIO", `@tuplet 的 normal 不能等于推导出的 actual (${actual})`, this.sourceSpan);
89
87
  }
90
88
  // 以作用域最早时间为仿射缩放原点,不能直接缩放绝对 t,否则嵌套位置会漂移。
91
- let start = group.events[0].t;
92
- for (let i = 1; i < group.events.length; i++) {
93
- if (group.events[i].t.compare(start) < 0)
94
- start = group.events[i].t;
89
+ let start = content.nodes[0].t;
90
+ for (let i = 1; i < content.nodes.length; i++) {
91
+ if (content.nodes[i].t.compare(start) < 0)
92
+ start = content.nodes[i].t;
95
93
  }
96
94
  start = start.clone();
97
95
  // t、T 与 lowering 游标必须一起修改;后继节点才会从缩放后的组尾继续。
98
96
  const offset = new Fraction();
99
- for (const event of group.events) {
97
+ for (const event of content.nodes) {
100
98
  offset.copyFrom(event.t).sub(start).mul(this.normal, actual);
101
99
  event.t.copyFrom(start).add(offset);
102
100
  event.T.mul(this.normal, actual);
@@ -105,7 +103,7 @@ class TupletFunction extends ASTFunctionNode {
105
103
  // 括线只依附可见主体;时值缩放本身仍覆盖所有收集到的事件。
106
104
  const visible = positive.filter(isVisualTemporalNode);
107
105
  if (visible.length >= 2) {
108
- ctx.addAttachment(new TupletLayoutAttachment(visible, actual, this.sourceSpan, this.font));
106
+ ctx.addAttachment(new TupletLayoutAttachment(visible, actual, this.sourceSpan, this.font, content));
109
107
  }
110
108
  return [];
111
109
  }
@@ -131,6 +129,7 @@ export const TupletNode = TupletFunction;
131
129
  * layout 根据最终宿主坐标测量数字和括线,paint 只回放已冻结的绝对几何。
132
130
  */
133
131
  class TupletLayoutAttachment {
132
+ content;
134
133
  layer = "foreground";
135
134
  /** lowering 固化的连音语义;重复 layout 时保持不变 */
136
135
  endPoints;
@@ -139,7 +138,8 @@ class TupletLayoutAttachment {
139
138
  /** 由端点最大字号冻结的绘制规格 */
140
139
  style;
141
140
  size;
142
- constructor(endPoints, actual, sourceSpan, font) {
141
+ constructor(endPoints, actual, sourceSpan, font, content) {
142
+ this.content = content;
143
143
  this.endPoints = endPoints;
144
144
  this.actual = actual;
145
145
  this.sourceSpan = sourceSpan;
@@ -174,15 +174,11 @@ class TupletLayoutAttachment {
174
174
  const textGap = this.size * 0.12;
175
175
  const hookHeight = this.size * 0.18;
176
176
  const hostGap = this.size * 0.14;
177
- // 只测首尾时间列,并合并先注册的 attachment,使后声明的括线排在外层。
178
- const view = context.lines[first.layoutLine];
179
- const from = view?.columnOf(first) ?? -1;
180
- const to = view?.columnOf(last) ?? -1;
177
+ // 范围避让与内容包含分别由系统查询,局部成员和正文使用同一入口。
181
178
  const axis = context.getVisualAxis(first.layoutLine, first.track);
182
- const extent = from < 0 || to < 0
183
- ? undefined
184
- : context.getRangeExtents(first.layoutLine, [Math.min(from, to), Math.max(from, to)]).get(first.track);
185
- const hostTop = axis + (extent?.top ?? 0);
179
+ const extent = context.getRangeExtents(first.layoutLine, [first, last], first.track);
180
+ const bounds = context.getContentBounds(this.content);
181
+ const hostTop = Math.min(axis + (extent?.top ?? 0), bounds?.y ?? Infinity);
186
182
  const strokeWidth = Math.max(1, this.size * 0.055);
187
183
  const lineY = hostTop - hostGap - Math.max(hookHeight, metrics.h / 2);
188
184
  const hookBottom = lineY + hookHeight;