@vielzeug/ink 26.11.23 → 26.11.25
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.
- package/README.md +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/ink.cjs +1 -1
- package/dist/ink.cjs.map +1 -1
- package/dist/ink.iife.js +1 -1
- package/dist/ink.iife.js.map +1 -1
- package/dist/ink.js +136 -27
- package/dist/ink.js.map +1 -1
- package/dist/outline.cjs +1 -1
- package/dist/outline.cjs.map +1 -1
- package/dist/outline.d.ts +32 -2
- package/dist/outline.d.ts.map +1 -1
- package/dist/outline.js +93 -11
- package/dist/outline.js.map +1 -1
- package/dist/widths.cjs +1 -1
- package/dist/widths.cjs.map +1 -1
- package/dist/widths.d.ts +34 -0
- package/dist/widths.d.ts.map +1 -1
- package/dist/widths.js +42 -14
- package/dist/widths.js.map +1 -1
- package/package.json +1 -1
package/dist/outline.js
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import { clamp as e, requireFiniteNumber as t, requireStrokePoints as n } from "./_validate.js";
|
|
2
2
|
import { InkConfigError as r } from "./errors.js";
|
|
3
3
|
// src/outline.ts
|
|
4
|
+
var i = [
|
|
5
|
+
"round",
|
|
6
|
+
"butt",
|
|
7
|
+
"square"
|
|
8
|
+
], a = [
|
|
9
|
+
"round",
|
|
10
|
+
"bevel",
|
|
11
|
+
"miter"
|
|
12
|
+
];
|
|
4
13
|
function normalAt(t, n) {
|
|
5
14
|
let r = t.length - 1, i = t[e(n - 1, 0, r)], a = t[e(n + 1, 0, r)], o = a.x - i.x, s = a.y - i.y;
|
|
6
15
|
if (o === 0 && s === 0) {
|
|
@@ -25,23 +34,96 @@ function appendCap(e, t, n, r) {
|
|
|
25
34
|
});
|
|
26
35
|
}
|
|
27
36
|
}
|
|
28
|
-
function
|
|
29
|
-
let
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
37
|
+
function segmentNormal(e, t) {
|
|
38
|
+
let n = t.x - e.x, r = t.y - e.y, i = Math.hypot(n, r);
|
|
39
|
+
return i === 0 ? null : {
|
|
40
|
+
x: r / i,
|
|
41
|
+
y: -n / i
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function applyJoin(e, t, n, r, i, a) {
|
|
45
|
+
let o = [];
|
|
46
|
+
for (let s = 0; s < e.length; s++) {
|
|
47
|
+
if (s === 0 || s === e.length - 1) {
|
|
48
|
+
o.push(e[s]);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
let c = t[s - 1], l = t[s], u = t[s + 1], d = l.x - c.x, f = l.y - c.y, p = u.x - l.x, m = u.y - l.y, h = Math.hypot(d, f), g = Math.hypot(p, m), _ = segmentNormal(c, l), v = segmentNormal(l, u), y = h === 0 || g === 0 ? 1 : (d * p + f * m) / (h * g), b = d * m - f * p, x = y < 0 && _ !== null && v !== null, S = b === 0 ? y < 0 : b < 0 == (a === 1);
|
|
52
|
+
if (!x || b === 0) {
|
|
53
|
+
o.push(e[s]);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
let C = n[s], w = a * (v.x - _.x) * C, T = a * (v.y - _.y) * C, E = (w * m - T * p) / b, D = (w * f - T * d) / b, O = {
|
|
57
|
+
x: l.x + a * _.x * C + E * d,
|
|
58
|
+
y: l.y + a * _.y * C + E * f
|
|
59
|
+
};
|
|
60
|
+
if (S) {
|
|
61
|
+
let t = E >= -1 - 1e-9 && E <= 1e-9 && D >= -1e-9 && D <= 1 + 1e-9;
|
|
62
|
+
o.push(t ? O : e[s]);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
let k = {
|
|
66
|
+
x: l.x + a * _.x * C,
|
|
67
|
+
y: l.y + a * _.y * C
|
|
68
|
+
}, A = {
|
|
69
|
+
x: l.x + a * v.x * C,
|
|
70
|
+
y: l.y + a * v.y * C
|
|
71
|
+
}, j = Math.hypot(O.x - l.x, O.y - l.y);
|
|
72
|
+
r === "miter" && j / C <= i ? o.push(O) : o.push(k, A);
|
|
73
|
+
}
|
|
74
|
+
return o;
|
|
75
|
+
}
|
|
76
|
+
function squareTangent(t, n) {
|
|
77
|
+
let r = t.length - 1, i = t[e(n - 1, 0, r)], a = t[e(n + 1, 0, r)], o = a.x - i.x, s = a.y - i.y, c = Math.hypot(o, s);
|
|
78
|
+
return c === 0 ? null : {
|
|
79
|
+
x: o / c,
|
|
80
|
+
y: s / c
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function strokeOutline(e, o, s = {}) {
|
|
84
|
+
let c = n(e, 1), l = typeof o == "number" ? c.map(() => o) : o;
|
|
85
|
+
if (l.length !== c.length) throw new r(`Expected widths to hold ${c.length} number(s), received ${l.length}.`);
|
|
86
|
+
for (let [e, n] of l.entries()) if (t(n, `widths[${e}]`), n <= 0) throw new r(`Expected widths[${e}] to be a positive finite number, received ${n}.`);
|
|
87
|
+
let u = s.cap ?? "round";
|
|
88
|
+
if (!i.includes(u)) throw new r(`Expected cap to be one of ${i.join(", ")}, received ${String(u)}.`);
|
|
89
|
+
let d = s.join ?? "round";
|
|
90
|
+
if (!a.includes(d)) throw new r(`Expected join to be one of ${a.join(", ")}, received ${String(d)}.`);
|
|
91
|
+
let f = 4;
|
|
92
|
+
if (s.miterLimit !== void 0) {
|
|
93
|
+
if (t(s.miterLimit, "miterLimit"), s.miterLimit <= 0) throw new r(`Expected miterLimit to be a positive finite number, received ${s.miterLimit}.`);
|
|
94
|
+
f = s.miterLimit;
|
|
95
|
+
}
|
|
96
|
+
let p = [], m = [], h = [];
|
|
97
|
+
for (let e = 0; e < c.length; e++) {
|
|
98
|
+
let t = c[e], n = l[e] / 2;
|
|
99
|
+
p.push(n);
|
|
100
|
+
let r = normalAt(c, e);
|
|
101
|
+
m.push({
|
|
36
102
|
x: t.x + r.x * n,
|
|
37
103
|
y: t.y + r.y * n
|
|
38
|
-
}),
|
|
104
|
+
}), h.push({
|
|
39
105
|
x: t.x - r.x * n,
|
|
40
106
|
y: t.y - r.y * n
|
|
41
107
|
});
|
|
42
108
|
}
|
|
43
|
-
let
|
|
44
|
-
|
|
109
|
+
let g = d === "round" ? m : applyJoin(m, c, p, d, f, 1), _ = d === "round" ? h : applyJoin(h, c, p, d, f, -1), v = c[0], y = c[c.length - 1], b = normalAt(c, 0), x = normalAt(c, c.length - 1), S = [];
|
|
110
|
+
if (u === "square") {
|
|
111
|
+
let e = p[0], t = p[p.length - 1], n = squareTangent(c, 0), r = squareTangent(c, c.length - 1);
|
|
112
|
+
return n && S.push({
|
|
113
|
+
x: h[0].x - n.x * e,
|
|
114
|
+
y: h[0].y - n.y * e
|
|
115
|
+
}, {
|
|
116
|
+
x: m[0].x - n.x * e,
|
|
117
|
+
y: m[0].y - n.y * e
|
|
118
|
+
}), S.push(...g), r && S.push({
|
|
119
|
+
x: m[m.length - 1].x + r.x * t,
|
|
120
|
+
y: m[m.length - 1].y + r.y * t
|
|
121
|
+
}, {
|
|
122
|
+
x: h[h.length - 1].x + r.x * t,
|
|
123
|
+
y: h[h.length - 1].y + r.y * t
|
|
124
|
+
}), S.push(..._.reverse()), S;
|
|
125
|
+
}
|
|
126
|
+
return u === "round" && appendCap(S, v, Math.atan2(b.y, b.x) + Math.PI, p[0]), S.push(...g), u === "round" && appendCap(S, y, Math.atan2(x.y, x.x), p[p.length - 1]), S.push(..._.reverse()), S;
|
|
45
127
|
}
|
|
46
128
|
export { strokeOutline };
|
|
47
129
|
|
package/dist/outline.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outline.js","names":["last","points","prev","clamp","i","next","tx","ty","other","len","s","angle","startAngle","center","radius","input","requireStrokePoints","perPoint","widths","InkConfigError","index","w","requireFiniteNumber","left","right","point","half","normal","first","firstNormal","lastNormal","outline"],"sources":["../src/outline.ts"],"sourcesContent":["/** Closed variable-width polygon approximating a stroked path. */\n\nimport { clamp, requireFiniteNumber, requireStrokePoints } from './_validate.js';\nimport { InkConfigError } from './errors.js';\nimport type { Point, StrokePoint } from './types.js';\n\n/** Unit normal at sample `i` of a polyline, derived from the central tangent; falls back to adjacent segments. */\nfunction normalAt(points: readonly Point[], i: number): Point {\n const last = points.length - 1;\n const prev = points[clamp(i - 1, 0, last)];\n const next = points[clamp(i + 1, 0, last)];\n let tx = next.x - prev.x;\n let ty = next.y - prev.y;\n if (tx === 0 && ty === 0) {\n // Degenerate central tangent (e.g. a spike back on itself): use the outgoing segment.\n const other = points[clamp(i + 1, 0, last)];\n tx = other.x - points[i].x;\n ty = other.y - points[i].y;\n }\n const len = Math.hypot(tx, ty);\n if (len === 0) return { x: 0, y: -1 };\n return { x: ty / len, y: -tx / len };\n}\n\n/** Append the interior points of a half-circle cap: samples from `startAngle` to `startAngle + PI`, endpoints excluded. */\nfunction appendCap(outline: Point[], center: Point, startAngle: number, radius: number): void {\n const steps = 8;\n for (let s = 1; s < steps; s++) {\n const angle = startAngle + Math.PI * (s / steps);\n outline.push({ x: center.x + Math.cos(angle) * radius, y: center.y + Math.sin(angle) * radius });\n }\n}\n\n/**\n * Build a closed polygon approximating the variable-width stroke through `points`.\n *\n * Each sample is offset by half its width along the local normal; the ring runs the start cap,\n * the left side forward, the end cap, and the right side backward, so it is closed without a\n * repeated final point. Pass a constant `width` for a uniform stroke, or one width per point\n * (from `strokeWidths`) for a variable one. Deterministic: identical input produces an identical ring.\n *\n * @throws {import('./errors.js').InkConfigError} When `widths` is a mismatched array or holds non-positive values.\n */\nexport function strokeOutline(points: readonly StrokePoint[], widths: number | readonly number[]): Point[] {\n const input = requireStrokePoints(points, 1);\n const perPoint: readonly number[] = typeof widths === 'number' ? input.map(() => widths) : widths;\n if (perPoint.length !== input.length) {\n throw new InkConfigError(`Expected widths to hold ${input.length} number(s), received ${perPoint.length}.`);\n }\n for (const [index, w] of perPoint.entries()) {\n requireFiniteNumber(w, `widths[${index}]`);\n if (w <= 0) {\n throw new InkConfigError(`Expected widths[${index}] to be a positive finite number, received ${w}.`);\n }\n }\n\n const left: Point[] = [];\n const right: Point[] = [];\n for (let i = 0; i < input.length; i++) {\n const point = input[i];\n const half = perPoint[i] / 2;\n const normal = normalAt(input, i);\n left.push({ x: point.x + normal.x * half, y: point.y + normal.y * half });\n right.push({ x: point.x - normal.x * half, y: point.y - normal.y * half });\n }\n\n const first = input[0];\n const last = input[input.length - 1];\n const firstNormal = normalAt(input, 0);\n const lastNormal = normalAt(input, input.length - 1);\n\n const outline: Point[] = [];\n // Start cap: half-circle from the right offset of the first sample, around its back, to the left offset.\n appendCap(outline, first, Math.atan2(firstNormal.y, firstNormal.x) + Math.PI, perPoint[0] / 2);\n outline.push(...left);\n // End cap: half-circle from the left offset of the last sample, around its front, to the right offset.\n appendCap(outline, last, Math.atan2(lastNormal.y, lastNormal.x), perPoint[perPoint.length - 1] / 2);\n outline.push(...right.reverse());\n return outline;\n}\n"],"mappings":";;;AAOA,SAAS,SAAS,GAA0B,GAAkB;CAC5D,IAAMA,IAAOC,EAAO,SAAS,GACvBC,IAAOD,EAAOE,EAAMC,IAAI,GAAG,GAAGJ,CAAI,IAClCK,IAAOJ,EAAOE,EAAMC,IAAI,GAAG,GAAGJ,CAAI,IACpCM,IAAKD,EAAK,IAAIH,EAAK,GACnBK,IAAKF,EAAK,IAAIH,EAAK;CACvB,IAAII,MAAO,KAAKC,MAAO,GAAG;EAExB,IAAMC,IAAQP,EAAOE,EAAMC,IAAI,GAAG,GAAGJ,CAAI;EAEzC,AADA,IAAKQ,EAAM,IAAIP,EAAOG,EAAE,CAAC,GACzB,IAAKI,EAAM,IAAIP,EAAOG,EAAE,CAAC;CAC3B;CACA,IAAMK,IAAM,KAAK,MAAMH,GAAIC,CAAE;CAE7B,OADIE,MAAQ,IAAU;EAAE,GAAG;EAAG,GAAG;CAAG,IAC7B;EAAE,GAAGF,IAAKE;EAAK,GAAG,CAACH,IAAKG;CAAI;AACrC;AAGA,SAAS,UAAU,GAAkB,GAAe,GAAoB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S,CAAC,GAE7CgB,IAAmB,CAAC;CAO1B,OALA,UAAUA,GAASH,GAAO,KAAK,MAAMC,EAAY,GAAGA,EAAY,CAAC,IAAI,KAAK,IAAIZ,EAAS,KAAK,CAAC,GAC7Fc,EAAQ,KAAK,GAAGR,CAAI,GAEpB,UAAUQ,GAAS/B,GAAM,KAAK,MAAM8B,EAAW,GAAGA,EAAW,CAAC,GAAGb,EAASA,EAAS,SAAS,KAAK,CAAC,GAClGc,EAAQ,KAAK,GAAGP,EAAM,QAAQ,CAAC,GACxBO;AACT"}
|
|
1
|
+
{"version":3,"file":"outline.js","names":["CAPS","JOINS","last","points","prev","clamp","i","next","tx","ty","other","len","s","angle","startAngle","center","radius","to","from","out","offsets","input","cur","t1x","t1y","t2x","t2y","l1","l2","n1","n2","cos","cross","sharp","inside","side","h","half","wx","wy","t","u","hit","within","o1","o2","miterLength","join","miterLimit","requireStrokePoints","perPoint","widths","InkConfigError","index","w","requireFiniteNumber","cap","options","left","right","point","normal","leftSide","rightSide","first","firstNormal","lastNormal","outline","startHalf","endHalf","startTangent","endTangent"],"sources":["../src/outline.ts"],"sourcesContent":["/** Closed variable-width polygon approximating a stroked path. */\n\nimport { clamp, requireFiniteNumber, requireStrokePoints } from './_validate.js';\nimport { InkConfigError } from './errors.js';\nimport type { Point, StrokePoint } from './types.js';\n\n/** End treatment for the outline ring. */\nexport type StrokeCap = 'round' | 'butt' | 'square';\n\n/** Corner treatment where the offset sides form a sharp angle. */\nexport type StrokeJoin = 'round' | 'bevel' | 'miter';\n\nexport interface StrokeOutlineOptions {\n /**\n * How the ring closes at each end. `round` adds a half-circle cap, `butt` adds none,\n * `square` extends each end by half the width along the tangent. Default `'round'`.\n */\n cap?: StrokeCap;\n /**\n * How sharp turns are joined on the inside of the turn. `round` keeps the plain\n * normal-offset samples (which approximate a round join), `bevel` replaces the joint\n * with the two adjacent segment-offset points, `miter` extends to the offset-line\n * intersection when within `miterLimit` and falls back to bevel otherwise. Default `'round'`.\n */\n join?: StrokeJoin;\n /**\n * Maximum ratio of miter length to half width before a `miter` join falls back to bevel.\n * Must be positive. Default `4`.\n */\n miterLimit?: number;\n}\n\nconst CAPS: readonly string[] = ['round', 'butt', 'square'];\nconst JOINS: readonly string[] = ['round', 'bevel', 'miter'];\n\n/** Unit normal at sample `i` of a polyline, derived from the central tangent; falls back to adjacent segments. */\nfunction normalAt(points: readonly Point[], i: number): Point {\n const last = points.length - 1;\n const prev = points[clamp(i - 1, 0, last)];\n const next = points[clamp(i + 1, 0, last)];\n let tx = next.x - prev.x;\n let ty = next.y - prev.y;\n if (tx === 0 && ty === 0) {\n // Degenerate central tangent (e.g. a spike back on itself): use the outgoing segment.\n const other = points[clamp(i + 1, 0, last)];\n tx = other.x - points[i].x;\n ty = other.y - points[i].y;\n }\n const len = Math.hypot(tx, ty);\n if (len === 0) return { x: 0, y: -1 };\n return { x: ty / len, y: -tx / len };\n}\n\n/** Append the interior points of a half-circle cap: samples from `startAngle` to `startAngle + PI`, endpoints excluded. */\nfunction appendCap(outline: Point[], center: Point, startAngle: number, radius: number): void {\n const steps = 8;\n for (let s = 1; s < steps; s++) {\n const angle = startAngle + Math.PI * (s / steps);\n outline.push({ x: center.x + Math.cos(angle) * radius, y: center.y + Math.sin(angle) * radius });\n }\n}\n\n/** Unit normal of the segment `from` → `to` using the same convention as `normalAt`; null for a degenerate segment. */\nfunction segmentNormal(from: StrokePoint, to: StrokePoint): Point | null {\n const tx = to.x - from.x;\n const ty = to.y - from.y;\n const len = Math.hypot(tx, ty);\n if (len === 0) return null;\n return { x: ty / len, y: -tx / len };\n}\n\n/**\n * Replace the naive central-tangent offset samples at sharp interior turns (angle between\n * consecutive tangents > 90°) with join geometry. `side` is `+1` for the left offsets and\n * `-1` for the right offsets. Only the inside of the turn spikes with plain offsets: there\n * the two offset edges cross, and the crossing is dropped by keeping their intersection\n * (the union vertex) instead of the naive sample. On the outside, `bevel` inserts the two\n * per-segment offset points (a flat corner) and `miter` extends to the offset-line\n * intersection while its distance from the joint stays within `miterLimit` × half width,\n * falling back to bevel beyond it. Turns at or below 90° keep the naive sample, which\n * already reads as a round join.\n */\nfunction applyJoin(\n offsets: readonly Point[],\n input: readonly StrokePoint[],\n half: readonly number[],\n join: 'bevel' | 'miter',\n miterLimit: number,\n side: 1 | -1,\n): Point[] {\n const out: Point[] = [];\n for (let i = 0; i < offsets.length; i++) {\n if (i === 0 || i === offsets.length - 1) {\n out.push(offsets[i]);\n continue;\n }\n const prev = input[i - 1];\n const cur = input[i];\n const next = input[i + 1];\n const t1x = cur.x - prev.x;\n const t1y = cur.y - prev.y;\n const t2x = next.x - cur.x;\n const t2y = next.y - cur.y;\n const l1 = Math.hypot(t1x, t1y);\n const l2 = Math.hypot(t2x, t2y);\n const n1 = segmentNormal(prev, cur);\n const n2 = segmentNormal(cur, next);\n const cos = l1 === 0 || l2 === 0 ? 1 : (t1x * t2x + t1y * t2y) / (l1 * l2);\n const cross = t1x * t2y - t1y * t2x;\n // A turn is sharp when its tangents differ by more than 90° (cos < 0). A left turn\n // (cross < 0 in this normal convention) puts the inside on the +normal side.\n const sharp = cos < 0 && n1 !== null && n2 !== null;\n const inside = cross === 0 ? cos < 0 : cross < 0 === (side === 1);\n if (!sharp || cross === 0) {\n // Not a sharp turn, a degenerate segment, or an exact reversal (parallel offset\n // edges, no finite join vertex): keep the naive sample.\n out.push(offsets[i]);\n continue;\n }\n const h = half[i];\n // Intersection of the two offset lines on this side:\n // line 1: cur + side*n1*h + t*t1; line 2: cur + side*n2*h + u*t2.\n // t = ((side*(n2-n1)*h) × t2) / (t1 × t2), u = ((side*(n2-n1)*h) × t1) / (t1 × t2).\n const wx = side * (n2.x - n1.x) * h;\n const wy = side * (n2.y - n1.y) * h;\n const t = (wx * t2y - wy * t2x) / cross;\n const u = (wx * t1y - wy * t1x) / cross;\n const hit = { x: cur.x + side * n1.x * h + t * t1x, y: cur.y + side * n1.y * h + t * t1y };\n if (inside) {\n // The inner union vertex sits behind the joint along segment 1 and forward along\n // segment 2 (in units of the full segment vectors). If it falls outside either\n // segment's span (e.g. a spike into a very short leg), no clean join vertex exists\n // and the naive sample is kept.\n const within = t >= -1 - 1e-9 && t <= 1e-9 && u >= -1e-9 && u <= 1 + 1e-9;\n out.push(within ? hit : offsets[i]);\n continue;\n }\n // Outside of a sharp turn.\n const o1 = { x: cur.x + side * n1.x * h, y: cur.y + side * n1.y * h };\n const o2 = { x: cur.x + side * n2.x * h, y: cur.y + side * n2.y * h };\n const miterLength = Math.hypot(hit.x - cur.x, hit.y - cur.y);\n if (join === 'miter' && miterLength / h <= miterLimit) {\n out.push(hit);\n } else {\n out.push(o1, o2);\n }\n }\n return out;\n}\n\n/** Unit tangent used to square off the cap at sample `i` (the central segment direction); null when degenerate. */\nfunction squareTangent(points: readonly StrokePoint[], i: number): Point | null {\n const last = points.length - 1;\n const from = points[clamp(i - 1, 0, last)];\n const to = points[clamp(i + 1, 0, last)];\n const tx = to.x - from.x;\n const ty = to.y - from.y;\n const len = Math.hypot(tx, ty);\n if (len === 0) return null;\n return { x: tx / len, y: ty / len };\n}\n\n/**\n * Build a closed polygon approximating the variable-width stroke through `points`.\n *\n * Each sample is offset by half its width along the local normal; the ring runs the start cap,\n * the left side forward, the end cap, and the right side backward, so it is closed without a\n * repeated final point. Pass a constant `width` for a uniform stroke, or one width per point\n * (from `strokeWidths`) for a variable one. Deterministic: identical input produces an identical ring.\n *\n * `options.cap` selects the end treatment: `'round'` half-circle caps (default), `'butt'` for\n * no cap points, `'square'` for a half-width tangent extension at each end. `options.join`\n * selects the inside-corner treatment at turns sharper than 90°: `'round'` (default) keeps the\n * plain offset samples, `'bevel'` replaces each sharp joint with the two adjacent segment-offset\n * points (dropping the crossing spike), and `'miter'` extends to the offset-line intersection\n * while the miter length stays within `options.miterLimit` × half width, falling back to bevel beyond it.\n *\n * @throws {import('./errors.js').InkConfigError} When `widths` is a mismatched array or holds non-positive values, when `cap` or `join` is not a known variant, or when `miterLimit` is not a positive finite number.\n */\nexport function strokeOutline(\n points: readonly StrokePoint[],\n widths: number | readonly number[],\n options: StrokeOutlineOptions = {},\n): Point[] {\n const input = requireStrokePoints(points, 1);\n const perPoint: readonly number[] = typeof widths === 'number' ? input.map(() => widths) : widths;\n if (perPoint.length !== input.length) {\n throw new InkConfigError(`Expected widths to hold ${input.length} number(s), received ${perPoint.length}.`);\n }\n for (const [index, w] of perPoint.entries()) {\n requireFiniteNumber(w, `widths[${index}]`);\n if (w <= 0) {\n throw new InkConfigError(`Expected widths[${index}] to be a positive finite number, received ${w}.`);\n }\n }\n const cap = options.cap ?? 'round';\n if (!CAPS.includes(cap)) {\n throw new InkConfigError(`Expected cap to be one of ${CAPS.join(', ')}, received ${String(cap)}.`);\n }\n const join = options.join ?? 'round';\n if (!JOINS.includes(join)) {\n throw new InkConfigError(`Expected join to be one of ${JOINS.join(', ')}, received ${String(join)}.`);\n }\n let miterLimit = 4;\n if (options.miterLimit !== undefined) {\n requireFiniteNumber(options.miterLimit, 'miterLimit');\n if (options.miterLimit <= 0) {\n throw new InkConfigError(`Expected miterLimit to be a positive finite number, received ${options.miterLimit}.`);\n }\n miterLimit = options.miterLimit;\n }\n\n const half: number[] = [];\n const left: Point[] = [];\n const right: Point[] = [];\n for (let i = 0; i < input.length; i++) {\n const point = input[i];\n const h = perPoint[i] / 2;\n half.push(h);\n const normal = normalAt(input, i);\n left.push({ x: point.x + normal.x * h, y: point.y + normal.y * h });\n right.push({ x: point.x - normal.x * h, y: point.y - normal.y * h });\n }\n const leftSide = join === 'round' ? left : applyJoin(left, input, half, join, miterLimit, 1);\n const rightSide = join === 'round' ? right : applyJoin(right, input, half, join, miterLimit, -1);\n\n const first = input[0];\n const last = input[input.length - 1];\n const firstNormal = normalAt(input, 0);\n const lastNormal = normalAt(input, input.length - 1);\n\n const outline: Point[] = [];\n if (cap === 'square') {\n // Square caps: extend each end by half the width along the tangent (two extra points per end).\n const startHalf = half[0];\n const endHalf = half[half.length - 1];\n const startTangent = squareTangent(input, 0);\n const endTangent = squareTangent(input, input.length - 1);\n if (startTangent) {\n outline.push(\n { x: right[0].x - startTangent.x * startHalf, y: right[0].y - startTangent.y * startHalf },\n { x: left[0].x - startTangent.x * startHalf, y: left[0].y - startTangent.y * startHalf },\n );\n }\n outline.push(...leftSide);\n if (endTangent) {\n outline.push(\n { x: left[left.length - 1].x + endTangent.x * endHalf, y: left[left.length - 1].y + endTangent.y * endHalf },\n {\n x: right[right.length - 1].x + endTangent.x * endHalf,\n y: right[right.length - 1].y + endTangent.y * endHalf,\n },\n );\n }\n outline.push(...rightSide.reverse());\n return outline;\n }\n\n if (cap === 'round') {\n // Start cap: half-circle from the right offset of the first sample, around its back, to the left offset.\n appendCap(outline, first, Math.atan2(firstNormal.y, firstNormal.x) + Math.PI, half[0]);\n }\n outline.push(...leftSide);\n if (cap === 'round') {\n // End cap: half-circle from the left offset of the last sample, around its front, to the right offset.\n appendCap(outline, last, Math.atan2(lastNormal.y, lastNormal.x), half[half.length - 1]);\n }\n outline.push(...rightSide.reverse());\n return outline;\n}\n"],"mappings":";;;AAgCA,IAAMA,IAA0B;CAAC;CAAS;CAAQ;AAAQ,GACpDC,IAA2B;CAAC;CAAS;CAAS;AAAO;AAG3D,SAAS,SAAS,GAA0B,GAAkB;CAC5D,IAAMC,IAAOC,EAAO,SAAS,GACvBC,IAAOD,EAAOE,EAAMC,IAAI,GAAG,GAAGJ,CAAI,IAClCK,IAAOJ,EAAOE,EAAMC,IAAI,GAAG,GAAGJ,CAAI,IACpCM,IAAKD,EAAK,IAAIH,EAAK,GACnBK,IAAKF,EAAK,IAAIH,EAAK;CACvB,IAAII,MAAO,KAAKC,MAAO,GAAG;EAExB,IAAMC,IAAQP,EAAOE,EAAMC,IAAI,GAAG,GAAGJ,CAAI;EAEzC,AADA,IAAKQ,EAAM,IAAIP,EAAOG,EAAE,CAAC,GACzB,IAAKI,EAAM,IAAIP,EAAOG,EAAE,CAAC;CAC3B;CACA,IAAMK,IAAM,KAAK,MAAMH,GAAIC,CAAE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,EAAQ,KACN;GAAE,GAAGR,EAAM,EAAE,CAAC,IAAIW,EAAa,IAAIF;GAAW,GAAGT,EAAM,EAAE,CAAC,IAAIW,EAAa,IAAIF;EAAU,GACzF;GAAE,GAAGV,EAAK,EAAE,CAAC,IAAIY,EAAa,IAAIF;GAAW,GAAGV,EAAK,EAAE,CAAC,IAAIY,EAAa,IAAIF;EAAU,CACzF,GAEFD,EAAQ,KAAK,GAAGL,CAAQ,GACpBS,KACFJ,EAAQ,KACN;GAAE,GAAGT,EAAKA,EAAK,SAAS,EAAE,CAAC,IAAIa,EAAW,IAAIF;GAAS,GAAGX,EAAKA,EAAK,SAAS,EAAE,CAAC,IAAIa,EAAW,IAAIF;EAAQ,GAC3G;GACE,GAAGV,EAAMA,EAAM,SAAS,EAAE,CAAC,IAAIY,EAAW,IAAIF;GAC9C,GAAGV,EAAMA,EAAM,SAAS,EAAE,CAAC,IAAIY,EAAW,IAAIF;EAChD,CACF,GAEFF,EAAQ,KAAK,GAAGJ,EAAU,QAAQ,CAAC,GAC5BI;CACT;CAYA,OAVIX,MAAQ,WAEV,UAAUW,GAASH,GAAO,KAAK,MAAMC,EAAY,GAAGA,EAAY,CAAC,IAAI,KAAK,IAAI5B,EAAK,EAAE,GAEvF8B,EAAQ,KAAK,GAAGL,CAAQ,GACpBN,MAAQ,WAEV,UAAUW,GAASjE,GAAM,KAAK,MAAMgE,EAAW,GAAGA,EAAW,CAAC,GAAG7B,EAAKA,EAAK,SAAS,EAAE,GAExF8B,EAAQ,KAAK,GAAGJ,EAAU,QAAQ,CAAC,GAC5BI;AACT"}
|
package/dist/widths.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./_validate.cjs");var
|
|
1
|
+
const e=require("./_validate.cjs"),t=require("./errors.cjs");var n=.25,r=2,i=.15,a=0,o=.15;function smoothstep(t){let n=e.clamp(t,0,1);return n*n*(3-2*n)}function arcLengths(t){let n=[0];for(let r=1;r<t.length;r++)n.push(n[r-1]+e.distance(t[r-1].x,t[r-1].y,t[r].x,t[r].y));return n}function requireTaperLength(n,r){if(e.requireFiniteNumber(n,r),n<0)throw new t.InkConfigError(`Expected ${r} to be non-negative, received ${n}.`);return n}function pressureScale(t){let n=e.clamp(t,0,1);return n<=.5?.5+n:1+(n-.5)*.5}function strokeWidths(t,s){let c=e.requireStrokePoints(t,1),l=e.requirePositive(s.width,`width`),u=e.requireRange(s.thinning??.5,`thinning`,0,1),d=e.requirePositive(s.referenceSpeed??.5,`referenceSpeed`),f=requireTaperLength(s.taper?.start??0,`taper.start`),p=requireTaperLength(s.taper?.end??0,`taper.end`),m=c.every(e=>e.time!==void 0),h=s.simulatePressure===!0&&m,g=f>0||p>0||h?arcLengths(c):null,_=g?g[g.length-1]:0,v=_*o,y=[],b=1;for(let t=0;t<c.length;t++){if(m&&u>0){let i=c[t],a=c[t+1],o=t>0?c[t-1]:i,s=t>0?i:a;if(s){let t=Math.abs(s.time-o.time);if(t>0){let i=e.distance(o.x,o.y,s.x,s.y)/t;b=e.clamp((d/i)**u,n,r)}}}let o=c[t].pressure;if(o===void 0&&g!==null&&h&&v>0){let e=g[t];o=a+.5*Math.min(smoothstep(e/v),smoothstep((_-e)/v))}let s=o===void 0?1:pressureScale(o),x=1;if(g&&(f>0||p>0)){let e=g[t];f>0&&e<f&&(x=i+.85*smoothstep(e/f));let n=_-e;if(p>0&&n<p){let e=i+.85*smoothstep(n/p);x=Math.min(x,e)}}y.push(l*b*s*x)}return y}exports.strokeWidths=strokeWidths;
|
|
2
2
|
//# sourceMappingURL=widths.cjs.map
|
package/dist/widths.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"widths.cjs","names":["clamp","requireStrokePoints","requirePositive","requireRange","distance","require__validate","MIN_SCALE","MAX_SCALE","p","pressure","input","points","width","options","thinning","referenceSpeed","timed","point","widths","lastScale","i","next","from","to","dt","speed"],"sources":["../src/widths.ts"],"sourcesContent":["/** Velocity- and pressure-modulated stroke widths. */\n\nimport { clamp, distance, requirePositive, requireRange, requireStrokePoints } from './_validate.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface StrokeWidthOptions {\n /** Pen speed treated as \"neutral\", in pixels per millisecond. Default `0.5`. */\n referenceSpeed?: number;\n /** How strongly speed modulates width: `0` disables velocity, `1` is fully inverse-proportional. Default `0.5`. */\n thinning?: number;\n /** Width at reference speed with neutral pressure. Must be positive. */\n width: number;\n}\n\n/** Fixed velocity-scale range; slow strokes at most double, fast strokes at most quarter. */\nconst MIN_SCALE = 0.25;\nconst MAX_SCALE = 2;\n\n/**\n * Pressure response curve, clamped to `[0, 1]`:\n * `0.5` (the neutral value a mouse reports) maps to exactly `1`, so a stroke with\n * neutral pressure is as wide as one without pressure data. Range: `[0.5, 1.25]`.\n */\nfunction pressureScale(pressure: number): number {\n const p = clamp(pressure, 0, 1);\n return p <= 0.5 ? 0.5 + p : 1 + (p - 0.5) * 0.5;\n}\n\n/**\n * Compute one width per stroke point from pen speed and optional pressure.\n *\n * Speed is `distance / Δtime` between consecutive points, which stays correct after any\n * smoothing, stabilization, or simplification — the pipeline order no longer matters. When any\n * point lacks `time`, or a Δtime is zero, velocity modulation is disabled for the whole stroke\n * (width becomes `width × pressure`) instead of falling back to a spacing proxy that resampling\n * would distort. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.\n *\n * The first point uses the forward segment; degenerate (zero-length) segments keep the previous\n * scale so stationary samples do not spike.\n *\n * @throws {import('./errors.js').InkConfigError} When options are out of range or `points` is empty.\n */\nexport function strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[] {\n const input = requireStrokePoints(points, 1);\n const width = requirePositive(options.width, 'width');\n const thinning = requireRange(options.thinning ?? 0.5, 'thinning', 0, 1);\n const referenceSpeed = requirePositive(options.referenceSpeed ?? 0.5, 'referenceSpeed');\n\n // Velocity needs a timestamp on every point; otherwise it is off for the whole stroke.\n const timed = input.every((point) => point.time !== undefined);\n\n const widths: number[] = [];\n let lastScale = 1;\n for (let i = 0; i < input.length; i++) {\n if (timed && thinning > 0) {\n const point = input[i];\n const next = input[i + 1];\n // First point looks forward; the rest look at the segment they arrived on.\n const from = i > 0 ? input[i - 1] : point;\n const to = i > 0 ? point : next;\n if (to) {\n const dt = Math.abs((to.time as number) - (from.time as number));\n if (dt > 0) {\n const speed = distance(from.x, from.y, to.x, to.y) / dt;\n // Slow (speed < reference) widens: scale = (referenceSpeed / speed) ^ thinning.\n lastScale = clamp((referenceSpeed / speed) ** thinning, MIN_SCALE, MAX_SCALE);\n }\n }\n }\n const pressure = input[i].pressure;\n widths.push(width * lastScale * (pressure === undefined ? 1 : pressureScale(pressure)));\n }\n return widths;\n}\n"],"mappings":"A,mCAeA,IAAMM,EAAY,IACZC,EAAY,EAOlB,SAAS,cAAc,EAA0B,CAC/C,IAAMC,EAAIR,EAAAA,MAAMS,EAAU,EAAG,CAAC,EAC9B,OAAOD,GAAK,GAAM,GAAMA,EAAI,GAAKA,EAAI,IAAO,EAC9C,CAgBA,SAAgB,aAAa,EAAgC,EAAuC,CAClG,IAAME,EAAQT,EAAAA,oBAAoBU,EAAQ,CAAC,EACrCC,EAAQV,EAAAA,gBAAgBW,EAAQ,MAAO,OAAO,EAC9CC,EAAWX,EAAAA,aAAaU,EAAQ,UAAY,GAAK,WAAY,EAAG,CAAC,EACjEE,EAAiBb,EAAAA,gBAAgBW,EAAQ,gBAAkB,GAAK,gBAAgB,EAGhFG,EAAQN,EAAM,MAAO,GAAUO,EAAM,OAAS,IAAA,EAAS,EAEvDC,EAAmB,CAAC,EACtBC,EAAY,EAChB,IAAK,IAAIC,EAAI,EAAGA,EAAIV,EAAM,OAAQ,IAAK,CACrC,GAAIM,GAASF,EAAW,EAAG,CACzB,IAAMG,EAAQP,EAAMU,GACdC,EAAOX,EAAMU,EAAI,GAEjBE,EAAOF,EAAI,EAAIV,EAAMU,EAAI,GAAKH,EAC9BM,EAAKH,EAAI,EAAIH,EAAQI,EAC3B,GAAIE,EAAI,CACN,IAAMC,EAAK,KAAK,IAAKD,EAAG,KAAmBD,EAAK,IAAe,EAC/D,GAAIE,EAAK,EAAG,CACV,IAAMC,EAAQrB,EAAAA,SAASkB,EAAK,EAAGA,EAAK,EAAGC,EAAG,EAAGA,EAAG,CAAC,EAAIC,EAErD,EAAYxB,EAAAA,OAAOe,EAAiBU,IAAUX,EAAUR,EAAWC,CAAS,CAC9E,CACF,CACF,CACA,IAAME,EAAWC,EAAMU,EAAE,CAAC,SAC1BF,EAAO,KAAKN,EAAQO,GAAaV,IAAa,IAAA,GAAY,EAAI,cAAcA,CAAQ,EAAE,CACxF,CACA,OAAOS,CACT,C"}
|
|
1
|
+
{"version":3,"file":"widths.cjs","names":["clamp","distance","InkConfigError","requireStrokePoints","requirePositive","requireRange","require__validate","require_errors","MIN_SCALE","MAX_SCALE","TAPER_FLOOR","PRESSURE_FLOOR","PRESSURE_RAMP_FRACTION","x","cum","i","points","value","name","p","pressure","input","width","options","thinning","referenceSpeed","taperStart","taperEnd","timed","point","simulate","total","pressureRamp","widths","lastScale","next","from","to","dt","speed","s","pressureFactor","taperFactor","remaining","endFactor"],"sources":["../src/widths.ts"],"sourcesContent":["/** Velocity- and pressure-modulated stroke widths. */\n\nimport {\n clamp,\n distance,\n requireFiniteNumber,\n requirePositive,\n requireRange,\n requireStrokePoints,\n} from './_validate.js';\nimport { InkConfigError } from './errors.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface StrokeTaperOptions {\n /**\n * Fade-out LENGTH measured along arc length from the last point, in the same units as\n * `width`. Symmetric to `start`. Default `0` (no fade-out).\n */\n end?: number;\n /**\n * Fade-in LENGTH measured along arc length from the first point, in the same units as\n * `width`. Within the first `start` units the width is multiplied by a smoothstep ramp\n * rising from `0.15` to `1`. Default `0` (no fade-in).\n */\n start?: number;\n}\n\nexport interface StrokeWidthOptions {\n /** Pen speed treated as \"neutral\", in pixels per millisecond. Default `0.5`. */\n referenceSpeed?: number;\n /**\n * When `true` and the stroke is timed, synthesize pressure for points that have NO `pressure`\n * from an in/out smoothstep ramp over arc length: the width multiplier drops to `0.5` at each\n * tip (pressure ramps from `0` to neutral `0.5`) so mouse strokes thin at the ends. Points that\n * DO carry `pressure` always use their real value; untimed strokes ignore this option.\n * Default `false`.\n */\n simulatePressure?: boolean;\n /**\n * Taper the stroke ends: fade the width in over `taper.start` and out over `taper.end`\n * units of arc length, multiplying the velocity/pressure profile by a smoothstep ramp that\n * bottoms out at `0.15` of full width. Applied on top of (not instead of) speed and pressure.\n */\n taper?: StrokeTaperOptions;\n /** How strongly speed modulates width: `0` disables velocity, `1` is fully inverse-proportional. Default `0.5`. */\n thinning?: number;\n /** Width at reference speed with neutral pressure. Must be positive. */\n width: number;\n}\n\n/** Fixed velocity-scale range; slow strokes at most double, fast strokes at most quarter. */\nconst MIN_SCALE = 0.25;\nconst MAX_SCALE = 2;\n\n/** Width multiplier at the very tip of a taper. */\nconst TAPER_FLOOR = 0.15;\n/** Synthesized pressure at the very tip of a simulated-pressure ramp (maps to 0.5x width). */\nconst PRESSURE_FLOOR = 0;\n/** Fraction of total arc length (each end) over which simulated pressure ramps. */\nconst PRESSURE_RAMP_FRACTION = 0.15;\n\n/** Smoothstep on `[0, 1]`: `3t² - 2t³`, clamped outside the range. */\nfunction smoothstep(t: number): number {\n const x = clamp(t, 0, 1);\n return x * x * (3 - 2 * x);\n}\n\n/** Cumulative arc length at each point, starting at `0`. */\nfunction arcLengths(points: readonly StrokePoint[]): number[] {\n const cum: number[] = [0];\n for (let i = 1; i < points.length; i++) {\n cum.push(cum[i - 1] + distance(points[i - 1].x, points[i - 1].y, points[i].x, points[i].y));\n }\n return cum;\n}\n\n/** Validate a taper length option: finite and non-negative. */\nfunction requireTaperLength(value: number, name: string): number {\n requireFiniteNumber(value, name);\n if (value < 0) {\n throw new InkConfigError(`Expected ${name} to be non-negative, received ${value}.`);\n }\n return value;\n}\n\n/**\n * Pressure response curve, clamped to `[0, 1]`:\n * `0.5` (the neutral value a mouse reports) maps to exactly `1`, so a stroke with\n * neutral pressure is as wide as one without pressure data. Range: `[0.5, 1.25]`.\n */\nfunction pressureScale(pressure: number): number {\n const p = clamp(pressure, 0, 1);\n return p <= 0.5 ? 0.5 + p : 1 + (p - 0.5) * 0.5;\n}\n\n/**\n * Compute one width per stroke point from pen speed and optional pressure.\n *\n * Speed is `distance / Δtime` between consecutive points, which stays correct after any\n * smoothing, stabilization, or simplification — the pipeline order no longer matters. When any\n * point lacks `time`, or a Δtime is zero, velocity modulation is disabled for the whole stroke\n * (width becomes `width × pressure`) instead of falling back to a spacing proxy that resampling\n * would distort. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.\n *\n * The first point uses the forward segment; degenerate (zero-length) segments keep the previous\n * scale so stationary samples do not spike.\n *\n * `taper` fades the width in over `taper.start` and out over `taper.end` units of arc length\n * (smoothstep ramp, floor `0.15`), multiplying whatever the speed/pressure profile produced, so\n * a tapered stroke still responds to speed in its body. `simulatePressure` fills in pressure for\n * points that lack it on a timed stroke, ramping the width multiplier from `0.5` at each tip to\n * neutral across the first and last 15% of arc length; points with real `pressure` are never\n * overridden.\n *\n * @throws {import('./errors.js').InkConfigError} When options are out of range or `points` is empty.\n */\nexport function strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[] {\n const input = requireStrokePoints(points, 1);\n const width = requirePositive(options.width, 'width');\n const thinning = requireRange(options.thinning ?? 0.5, 'thinning', 0, 1);\n const referenceSpeed = requirePositive(options.referenceSpeed ?? 0.5, 'referenceSpeed');\n const taperStart = requireTaperLength(options.taper?.start ?? 0, 'taper.start');\n const taperEnd = requireTaperLength(options.taper?.end ?? 0, 'taper.end');\n\n // Velocity needs a timestamp on every point; otherwise it is off for the whole stroke.\n const timed = input.every((point) => point.time !== undefined);\n // Simulated pressure only makes sense on a timed stroke, and never overrides real pressure.\n const simulate = options.simulatePressure === true && timed;\n\n const needArc = taperStart > 0 || taperEnd > 0 || simulate;\n const cum = needArc ? arcLengths(input) : null;\n const total = cum ? cum[cum.length - 1] : 0;\n const pressureRamp = total * PRESSURE_RAMP_FRACTION;\n\n const widths: number[] = [];\n let lastScale = 1;\n for (let i = 0; i < input.length; i++) {\n if (timed && thinning > 0) {\n const point = input[i];\n const next = input[i + 1];\n // First point looks forward; the rest look at the segment they arrived on.\n const from = i > 0 ? input[i - 1] : point;\n const to = i > 0 ? point : next;\n if (to) {\n const dt = Math.abs((to.time as number) - (from.time as number));\n if (dt > 0) {\n const speed = distance(from.x, from.y, to.x, to.y) / dt;\n // Slow (speed < reference) widens: scale = (referenceSpeed / speed) ^ thinning.\n lastScale = clamp((referenceSpeed / speed) ** thinning, MIN_SCALE, MAX_SCALE);\n }\n }\n }\n\n let pressure = input[i].pressure;\n if (pressure === undefined && cum !== null && simulate && pressureRamp > 0) {\n // Ramp from PRESSURE_FLOOR at each tip up to neutral (0.5) in the body.\n const s = cum[i];\n const ramp = Math.min(smoothstep(s / pressureRamp), smoothstep((total - s) / pressureRamp));\n pressure = PRESSURE_FLOOR + (0.5 - PRESSURE_FLOOR) * ramp;\n }\n const pressureFactor = pressure === undefined ? 1 : pressureScale(pressure);\n\n let taperFactor = 1;\n if (cum && (taperStart > 0 || taperEnd > 0)) {\n const s = cum[i];\n if (taperStart > 0 && s < taperStart) {\n taperFactor = TAPER_FLOOR + (1 - TAPER_FLOOR) * smoothstep(s / taperStart);\n }\n const remaining = total - s;\n if (taperEnd > 0 && remaining < taperEnd) {\n const endFactor = TAPER_FLOOR + (1 - TAPER_FLOOR) * smoothstep(remaining / taperEnd);\n taperFactor = Math.min(taperFactor, endFactor);\n }\n }\n\n widths.push(width * lastScale * pressureFactor * taperFactor);\n }\n return widths;\n}\n"],"mappings":"A,6DAmDA,IAAMQ,EAAY,IACZC,EAAY,EAGZC,EAAc,IAEdC,EAAiB,EAEjBC,EAAyB,IAG/B,SAAS,WAAW,EAAmB,CACrC,IAAMC,EAAIb,EAAAA,MAAM,EAAG,EAAG,CAAC,EACvB,OAAOa,EAAIA,GAAK,EAAI,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,CAC/C,CACF,CAEAX,EAAO,KAAKX,EAAQY,EAAYO,EAAiBC,CAAW,CAC9D,CACA,OAAOT,CACT,C"}
|
package/dist/widths.d.ts
CHANGED
|
@@ -1,8 +1,35 @@
|
|
|
1
1
|
/** Velocity- and pressure-modulated stroke widths. */
|
|
2
2
|
import type { StrokePoint } from './types.js';
|
|
3
|
+
export interface StrokeTaperOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Fade-out LENGTH measured along arc length from the last point, in the same units as
|
|
6
|
+
* `width`. Symmetric to `start`. Default `0` (no fade-out).
|
|
7
|
+
*/
|
|
8
|
+
end?: number;
|
|
9
|
+
/**
|
|
10
|
+
* Fade-in LENGTH measured along arc length from the first point, in the same units as
|
|
11
|
+
* `width`. Within the first `start` units the width is multiplied by a smoothstep ramp
|
|
12
|
+
* rising from `0.15` to `1`. Default `0` (no fade-in).
|
|
13
|
+
*/
|
|
14
|
+
start?: number;
|
|
15
|
+
}
|
|
3
16
|
export interface StrokeWidthOptions {
|
|
4
17
|
/** Pen speed treated as "neutral", in pixels per millisecond. Default `0.5`. */
|
|
5
18
|
referenceSpeed?: number;
|
|
19
|
+
/**
|
|
20
|
+
* When `true` and the stroke is timed, synthesize pressure for points that have NO `pressure`
|
|
21
|
+
* from an in/out smoothstep ramp over arc length: the width multiplier drops to `0.5` at each
|
|
22
|
+
* tip (pressure ramps from `0` to neutral `0.5`) so mouse strokes thin at the ends. Points that
|
|
23
|
+
* DO carry `pressure` always use their real value; untimed strokes ignore this option.
|
|
24
|
+
* Default `false`.
|
|
25
|
+
*/
|
|
26
|
+
simulatePressure?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Taper the stroke ends: fade the width in over `taper.start` and out over `taper.end`
|
|
29
|
+
* units of arc length, multiplying the velocity/pressure profile by a smoothstep ramp that
|
|
30
|
+
* bottoms out at `0.15` of full width. Applied on top of (not instead of) speed and pressure.
|
|
31
|
+
*/
|
|
32
|
+
taper?: StrokeTaperOptions;
|
|
6
33
|
/** How strongly speed modulates width: `0` disables velocity, `1` is fully inverse-proportional. Default `0.5`. */
|
|
7
34
|
thinning?: number;
|
|
8
35
|
/** Width at reference speed with neutral pressure. Must be positive. */
|
|
@@ -20,6 +47,13 @@ export interface StrokeWidthOptions {
|
|
|
20
47
|
* The first point uses the forward segment; degenerate (zero-length) segments keep the previous
|
|
21
48
|
* scale so stationary samples do not spike.
|
|
22
49
|
*
|
|
50
|
+
* `taper` fades the width in over `taper.start` and out over `taper.end` units of arc length
|
|
51
|
+
* (smoothstep ramp, floor `0.15`), multiplying whatever the speed/pressure profile produced, so
|
|
52
|
+
* a tapered stroke still responds to speed in its body. `simulatePressure` fills in pressure for
|
|
53
|
+
* points that lack it on a timed stroke, ramping the width multiplier from `0.5` at each tip to
|
|
54
|
+
* neutral across the first and last 15% of arc length; points with real `pressure` are never
|
|
55
|
+
* overridden.
|
|
56
|
+
*
|
|
23
57
|
* @throws {import('./errors.js').InkConfigError} When options are out of range or `points` is empty.
|
|
24
58
|
*/
|
|
25
59
|
export declare function strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[];
|
package/dist/widths.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"widths.d.ts","sourceRoot":"","sources":["../src/widths.ts"],"names":[],"mappings":"AAAA,sDAAsD;
|
|
1
|
+
{"version":3,"file":"widths.d.ts","sourceRoot":"","sources":["../src/widths.ts"],"names":[],"mappings":"AAAA,sDAAsD;AAWtD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,kBAAkB;IACjC,gFAAgF;IAChF,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;;OAIG;IACH,KAAK,CAAC,EAAE,kBAAkB,CAAC;IAC3B,mHAAmH;IACnH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,wEAAwE;IACxE,KAAK,EAAE,MAAM,CAAC;CACf;AA+CD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,EAAE,kBAAkB,GAAG,MAAM,EAAE,CA8DlG"}
|
package/dist/widths.js
CHANGED
|
@@ -1,27 +1,55 @@
|
|
|
1
|
-
import { clamp as e, distance as t,
|
|
1
|
+
import { clamp as e, distance as t, requireFiniteNumber as n, requirePositive as r, requireRange as i, requireStrokePoints as a } from "./_validate.js";
|
|
2
|
+
import { InkConfigError as o } from "./errors.js";
|
|
2
3
|
// src/widths.ts
|
|
3
|
-
var
|
|
4
|
+
var s = .25, c = 2, l = .15, u = 0, d = .15;
|
|
5
|
+
function smoothstep(t) {
|
|
6
|
+
let n = e(t, 0, 1);
|
|
7
|
+
return n * n * (3 - 2 * n);
|
|
8
|
+
}
|
|
9
|
+
function arcLengths(e) {
|
|
10
|
+
let n = [0];
|
|
11
|
+
for (let r = 1; r < e.length; r++) n.push(n[r - 1] + t(e[r - 1].x, e[r - 1].y, e[r].x, e[r].y));
|
|
12
|
+
return n;
|
|
13
|
+
}
|
|
14
|
+
function requireTaperLength(e, t) {
|
|
15
|
+
if (n(e, t), e < 0) throw new o(`Expected ${t} to be non-negative, received ${e}.`);
|
|
16
|
+
return e;
|
|
17
|
+
}
|
|
4
18
|
function pressureScale(t) {
|
|
5
19
|
let n = e(t, 0, 1);
|
|
6
20
|
return n <= .5 ? .5 + n : 1 + (n - .5) * .5;
|
|
7
21
|
}
|
|
8
|
-
function strokeWidths(
|
|
9
|
-
let
|
|
10
|
-
for (let n = 0; n <
|
|
11
|
-
if (
|
|
12
|
-
let r =
|
|
13
|
-
if (
|
|
14
|
-
let n = Math.abs(
|
|
22
|
+
function strokeWidths(n, o) {
|
|
23
|
+
let f = a(n, 1), p = r(o.width, "width"), m = i(o.thinning ?? .5, "thinning", 0, 1), h = r(o.referenceSpeed ?? .5, "referenceSpeed"), g = requireTaperLength(o.taper?.start ?? 0, "taper.start"), _ = requireTaperLength(o.taper?.end ?? 0, "taper.end"), v = f.every((e) => e.time !== void 0), y = o.simulatePressure === !0 && v, b = g > 0 || _ > 0 || y ? arcLengths(f) : null, x = b ? b[b.length - 1] : 0, S = x * d, C = [], w = 1;
|
|
24
|
+
for (let n = 0; n < f.length; n++) {
|
|
25
|
+
if (v && m > 0) {
|
|
26
|
+
let r = f[n], i = f[n + 1], a = n > 0 ? f[n - 1] : r, o = n > 0 ? r : i;
|
|
27
|
+
if (o) {
|
|
28
|
+
let n = Math.abs(o.time - a.time);
|
|
15
29
|
if (n > 0) {
|
|
16
|
-
let r = t(
|
|
17
|
-
|
|
30
|
+
let r = t(a.x, a.y, o.x, o.y) / n;
|
|
31
|
+
w = e((h / r) ** m, s, c);
|
|
18
32
|
}
|
|
19
33
|
}
|
|
20
34
|
}
|
|
21
|
-
let r =
|
|
22
|
-
|
|
35
|
+
let r = f[n].pressure;
|
|
36
|
+
if (r === void 0 && b !== null && y && S > 0) {
|
|
37
|
+
let e = b[n];
|
|
38
|
+
r = u + .5 * Math.min(smoothstep(e / S), smoothstep((x - e) / S));
|
|
39
|
+
}
|
|
40
|
+
let i = r === void 0 ? 1 : pressureScale(r), a = 1;
|
|
41
|
+
if (b && (g > 0 || _ > 0)) {
|
|
42
|
+
let e = b[n];
|
|
43
|
+
g > 0 && e < g && (a = l + .85 * smoothstep(e / g));
|
|
44
|
+
let t = x - e;
|
|
45
|
+
if (_ > 0 && t < _) {
|
|
46
|
+
let e = l + .85 * smoothstep(t / _);
|
|
47
|
+
a = Math.min(a, e);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
C.push(p * w * i * a);
|
|
23
51
|
}
|
|
24
|
-
return
|
|
52
|
+
return C;
|
|
25
53
|
}
|
|
26
54
|
export { strokeWidths };
|
|
27
55
|
|
package/dist/widths.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"widths.js","names":["MIN_SCALE","MAX_SCALE","p","clamp","pressure","input","requireStrokePoints","points","width","requirePositive","options","thinning","requireRange","referenceSpeed","timed","point","widths","lastScale","i","next","from","to","dt","speed","distance"],"sources":["../src/widths.ts"],"sourcesContent":["/** Velocity- and pressure-modulated stroke widths. */\n\nimport { clamp, distance, requirePositive, requireRange, requireStrokePoints } from './_validate.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface StrokeWidthOptions {\n /** Pen speed treated as \"neutral\", in pixels per millisecond. Default `0.5`. */\n referenceSpeed?: number;\n /** How strongly speed modulates width: `0` disables velocity, `1` is fully inverse-proportional. Default `0.5`. */\n thinning?: number;\n /** Width at reference speed with neutral pressure. Must be positive. */\n width: number;\n}\n\n/** Fixed velocity-scale range; slow strokes at most double, fast strokes at most quarter. */\nconst MIN_SCALE = 0.25;\nconst MAX_SCALE = 2;\n\n/**\n * Pressure response curve, clamped to `[0, 1]`:\n * `0.5` (the neutral value a mouse reports) maps to exactly `1`, so a stroke with\n * neutral pressure is as wide as one without pressure data. Range: `[0.5, 1.25]`.\n */\nfunction pressureScale(pressure: number): number {\n const p = clamp(pressure, 0, 1);\n return p <= 0.5 ? 0.5 + p : 1 + (p - 0.5) * 0.5;\n}\n\n/**\n * Compute one width per stroke point from pen speed and optional pressure.\n *\n * Speed is `distance / Δtime` between consecutive points, which stays correct after any\n * smoothing, stabilization, or simplification — the pipeline order no longer matters. When any\n * point lacks `time`, or a Δtime is zero, velocity modulation is disabled for the whole stroke\n * (width becomes `width × pressure`) instead of falling back to a spacing proxy that resampling\n * would distort. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.\n *\n * The first point uses the forward segment; degenerate (zero-length) segments keep the previous\n * scale so stationary samples do not spike.\n *\n * @throws {import('./errors.js').InkConfigError} When options are out of range or `points` is empty.\n */\nexport function strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[] {\n const input = requireStrokePoints(points, 1);\n const width = requirePositive(options.width, 'width');\n const thinning = requireRange(options.thinning ?? 0.5, 'thinning', 0, 1);\n const referenceSpeed = requirePositive(options.referenceSpeed ?? 0.5, 'referenceSpeed');\n\n // Velocity needs a timestamp on every point; otherwise it is off for the whole stroke.\n const timed = input.every((point) => point.time !== undefined);\n\n const widths: number[] = [];\n let lastScale = 1;\n for (let i = 0; i < input.length; i++) {\n if (timed && thinning > 0) {\n const point = input[i];\n const next = input[i + 1];\n // First point looks forward; the rest look at the segment they arrived on.\n const from = i > 0 ? input[i - 1] : point;\n const to = i > 0 ? point : next;\n if (to) {\n const dt = Math.abs((to.time as number) - (from.time as number));\n if (dt > 0) {\n const speed = distance(from.x, from.y, to.x, to.y) / dt;\n // Slow (speed < reference) widens: scale = (referenceSpeed / speed) ^ thinning.\n lastScale = clamp((referenceSpeed / speed) ** thinning, MIN_SCALE, MAX_SCALE);\n }\n }\n }\n const pressure = input[i].pressure;\n widths.push(width * lastScale * (pressure === undefined ? 1 : pressureScale(pressure)));\n }\n return widths;\n}\n"],"mappings":";;AAeA,IAAMA,IAAY,KACZC,IAAY;AAOlB,SAAS,cAAc,GAA0B;CAC/C,IAAMC,IAAIC,EAAMC,GAAU,GAAG,CAAC;CAC9B,OAAOF,KAAK,KAAM,KAAMA,IAAI,KAAKA,IAAI,MAAO;AAC9C;AAgBA,SAAgB,aAAa,GAAgC,GAAuC;CAClG,IAAMG,IAAQC,EAAoBC,GAAQ,CAAC,GACrCC,IAAQC,EAAgBC,EAAQ,OAAO,OAAO,GAC9CC,IAAWC,EAAaF,EAAQ,YAAY,IAAK,YAAY,GAAG,CAAC,GACjEG,IAAiBJ,EAAgBC,EAAQ,kBAAkB,IAAK,gBAAgB,GAGhFI,IAAQT,EAAM,OAAO,MAAUU,EAAM,SAAS,KAAA,CAAS,GAEvDC,IAAmB,CAAC,GACtBC,IAAY;CAChB,KAAK,IAAIC,IAAI,GAAGA,IAAIb,EAAM,QAAQ,KAAK;EACrC,IAAIS,KAASH,IAAW,GAAG;GACzB,IAAMI,IAAQV,EAAMa,IACdC,IAAOd,EAAMa,IAAI,IAEjBE,IAAOF,IAAI,IAAIb,EAAMa,IAAI,KAAKH,GAC9BM,IAAKH,IAAI,IAAIH,IAAQI;GAC3B,IAAIE,GAAI;IACN,IAAMC,IAAK,KAAK,IAAKD,EAAG,OAAmBD,EAAK,IAAe;IAC/D,IAAIE,IAAK,GAAG;KACV,IAAMC,IAAQC,EAASJ,EAAK,GAAGA,EAAK,GAAGC,EAAG,GAAGA,EAAG,CAAC,IAAIC;KAErD,IAAYnB,GAAOU,IAAiBU,MAAUZ,GAAUX,GAAWC,CAAS;IAC9E;GACF;EACF;EACA,IAAMG,IAAWC,EAAMa,EAAE,CAAC;EAC1B,EAAO,KAAKV,IAAQS,KAAab,MAAa,KAAA,IAAY,IAAI,cAAcA,CAAQ,EAAE;CACxF;CACA,OAAOY;AACT"}
|
|
1
|
+
{"version":3,"file":"widths.js","names":["MIN_SCALE","MAX_SCALE","TAPER_FLOOR","PRESSURE_FLOOR","PRESSURE_RAMP_FRACTION","x","clamp","cum","i","points","distance","requireFiniteNumber","value","name","InkConfigError","p","pressure","input","requireStrokePoints","width","requirePositive","options","thinning","requireRange","referenceSpeed","taperStart","taperEnd","timed","point","simulate","total","pressureRamp","widths","lastScale","next","from","to","dt","speed","s","pressureFactor","taperFactor","remaining","endFactor"],"sources":["../src/widths.ts"],"sourcesContent":["/** Velocity- and pressure-modulated stroke widths. */\n\nimport {\n clamp,\n distance,\n requireFiniteNumber,\n requirePositive,\n requireRange,\n requireStrokePoints,\n} from './_validate.js';\nimport { InkConfigError } from './errors.js';\nimport type { StrokePoint } from './types.js';\n\nexport interface StrokeTaperOptions {\n /**\n * Fade-out LENGTH measured along arc length from the last point, in the same units as\n * `width`. Symmetric to `start`. Default `0` (no fade-out).\n */\n end?: number;\n /**\n * Fade-in LENGTH measured along arc length from the first point, in the same units as\n * `width`. Within the first `start` units the width is multiplied by a smoothstep ramp\n * rising from `0.15` to `1`. Default `0` (no fade-in).\n */\n start?: number;\n}\n\nexport interface StrokeWidthOptions {\n /** Pen speed treated as \"neutral\", in pixels per millisecond. Default `0.5`. */\n referenceSpeed?: number;\n /**\n * When `true` and the stroke is timed, synthesize pressure for points that have NO `pressure`\n * from an in/out smoothstep ramp over arc length: the width multiplier drops to `0.5` at each\n * tip (pressure ramps from `0` to neutral `0.5`) so mouse strokes thin at the ends. Points that\n * DO carry `pressure` always use their real value; untimed strokes ignore this option.\n * Default `false`.\n */\n simulatePressure?: boolean;\n /**\n * Taper the stroke ends: fade the width in over `taper.start` and out over `taper.end`\n * units of arc length, multiplying the velocity/pressure profile by a smoothstep ramp that\n * bottoms out at `0.15` of full width. Applied on top of (not instead of) speed and pressure.\n */\n taper?: StrokeTaperOptions;\n /** How strongly speed modulates width: `0` disables velocity, `1` is fully inverse-proportional. Default `0.5`. */\n thinning?: number;\n /** Width at reference speed with neutral pressure. Must be positive. */\n width: number;\n}\n\n/** Fixed velocity-scale range; slow strokes at most double, fast strokes at most quarter. */\nconst MIN_SCALE = 0.25;\nconst MAX_SCALE = 2;\n\n/** Width multiplier at the very tip of a taper. */\nconst TAPER_FLOOR = 0.15;\n/** Synthesized pressure at the very tip of a simulated-pressure ramp (maps to 0.5x width). */\nconst PRESSURE_FLOOR = 0;\n/** Fraction of total arc length (each end) over which simulated pressure ramps. */\nconst PRESSURE_RAMP_FRACTION = 0.15;\n\n/** Smoothstep on `[0, 1]`: `3t² - 2t³`, clamped outside the range. */\nfunction smoothstep(t: number): number {\n const x = clamp(t, 0, 1);\n return x * x * (3 - 2 * x);\n}\n\n/** Cumulative arc length at each point, starting at `0`. */\nfunction arcLengths(points: readonly StrokePoint[]): number[] {\n const cum: number[] = [0];\n for (let i = 1; i < points.length; i++) {\n cum.push(cum[i - 1] + distance(points[i - 1].x, points[i - 1].y, points[i].x, points[i].y));\n }\n return cum;\n}\n\n/** Validate a taper length option: finite and non-negative. */\nfunction requireTaperLength(value: number, name: string): number {\n requireFiniteNumber(value, name);\n if (value < 0) {\n throw new InkConfigError(`Expected ${name} to be non-negative, received ${value}.`);\n }\n return value;\n}\n\n/**\n * Pressure response curve, clamped to `[0, 1]`:\n * `0.5` (the neutral value a mouse reports) maps to exactly `1`, so a stroke with\n * neutral pressure is as wide as one without pressure data. Range: `[0.5, 1.25]`.\n */\nfunction pressureScale(pressure: number): number {\n const p = clamp(pressure, 0, 1);\n return p <= 0.5 ? 0.5 + p : 1 + (p - 0.5) * 0.5;\n}\n\n/**\n * Compute one width per stroke point from pen speed and optional pressure.\n *\n * Speed is `distance / Δtime` between consecutive points, which stays correct after any\n * smoothing, stabilization, or simplification — the pipeline order no longer matters. When any\n * point lacks `time`, or a Δtime is zero, velocity modulation is disabled for the whole stroke\n * (width becomes `width × pressure`) instead of falling back to a spacing proxy that resampling\n * would distort. Slow widens, fast narrows, clamped to a fixed `[0.25, 2]` scale.\n *\n * The first point uses the forward segment; degenerate (zero-length) segments keep the previous\n * scale so stationary samples do not spike.\n *\n * `taper` fades the width in over `taper.start` and out over `taper.end` units of arc length\n * (smoothstep ramp, floor `0.15`), multiplying whatever the speed/pressure profile produced, so\n * a tapered stroke still responds to speed in its body. `simulatePressure` fills in pressure for\n * points that lack it on a timed stroke, ramping the width multiplier from `0.5` at each tip to\n * neutral across the first and last 15% of arc length; points with real `pressure` are never\n * overridden.\n *\n * @throws {import('./errors.js').InkConfigError} When options are out of range or `points` is empty.\n */\nexport function strokeWidths(points: readonly StrokePoint[], options: StrokeWidthOptions): number[] {\n const input = requireStrokePoints(points, 1);\n const width = requirePositive(options.width, 'width');\n const thinning = requireRange(options.thinning ?? 0.5, 'thinning', 0, 1);\n const referenceSpeed = requirePositive(options.referenceSpeed ?? 0.5, 'referenceSpeed');\n const taperStart = requireTaperLength(options.taper?.start ?? 0, 'taper.start');\n const taperEnd = requireTaperLength(options.taper?.end ?? 0, 'taper.end');\n\n // Velocity needs a timestamp on every point; otherwise it is off for the whole stroke.\n const timed = input.every((point) => point.time !== undefined);\n // Simulated pressure only makes sense on a timed stroke, and never overrides real pressure.\n const simulate = options.simulatePressure === true && timed;\n\n const needArc = taperStart > 0 || taperEnd > 0 || simulate;\n const cum = needArc ? arcLengths(input) : null;\n const total = cum ? cum[cum.length - 1] : 0;\n const pressureRamp = total * PRESSURE_RAMP_FRACTION;\n\n const widths: number[] = [];\n let lastScale = 1;\n for (let i = 0; i < input.length; i++) {\n if (timed && thinning > 0) {\n const point = input[i];\n const next = input[i + 1];\n // First point looks forward; the rest look at the segment they arrived on.\n const from = i > 0 ? input[i - 1] : point;\n const to = i > 0 ? point : next;\n if (to) {\n const dt = Math.abs((to.time as number) - (from.time as number));\n if (dt > 0) {\n const speed = distance(from.x, from.y, to.x, to.y) / dt;\n // Slow (speed < reference) widens: scale = (referenceSpeed / speed) ^ thinning.\n lastScale = clamp((referenceSpeed / speed) ** thinning, MIN_SCALE, MAX_SCALE);\n }\n }\n }\n\n let pressure = input[i].pressure;\n if (pressure === undefined && cum !== null && simulate && pressureRamp > 0) {\n // Ramp from PRESSURE_FLOOR at each tip up to neutral (0.5) in the body.\n const s = cum[i];\n const ramp = Math.min(smoothstep(s / pressureRamp), smoothstep((total - s) / pressureRamp));\n pressure = PRESSURE_FLOOR + (0.5 - PRESSURE_FLOOR) * ramp;\n }\n const pressureFactor = pressure === undefined ? 1 : pressureScale(pressure);\n\n let taperFactor = 1;\n if (cum && (taperStart > 0 || taperEnd > 0)) {\n const s = cum[i];\n if (taperStart > 0 && s < taperStart) {\n taperFactor = TAPER_FLOOR + (1 - TAPER_FLOOR) * smoothstep(s / taperStart);\n }\n const remaining = total - s;\n if (taperEnd > 0 && remaining < taperEnd) {\n const endFactor = TAPER_FLOOR + (1 - TAPER_FLOOR) * smoothstep(remaining / taperEnd);\n taperFactor = Math.min(taperFactor, endFactor);\n }\n }\n\n widths.push(width * lastScale * pressureF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