@es3d/es3d 0.0.0-stage → 1.0.1

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 (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +85 -2
  3. package/docs/REFERENCE.md +581 -0
  4. package/docs/SPEC.md +417 -0
  5. package/package.json +50 -4
  6. package/scripts/es3d-cli.mjs +377 -0
  7. package/src/cache/geometry-store.js +392 -0
  8. package/src/cache/mesh-bundle.js +123 -0
  9. package/src/cache/sha256.js +73 -0
  10. package/src/format/ast.js +238 -0
  11. package/src/format/colors.js +93 -0
  12. package/src/format/compact-parser.js +171 -0
  13. package/src/format/compact-tokenizer.js +165 -0
  14. package/src/format/errors.js +247 -0
  15. package/src/format/json.js +55 -0
  16. package/src/format/limits.js +14 -0
  17. package/src/format/parse.js +92 -0
  18. package/src/format/schema.js +617 -0
  19. package/src/format/serializer.js +333 -0
  20. package/src/format/validator.js +330 -0
  21. package/src/format/value-error.js +12 -0
  22. package/src/format/value-format.js +314 -0
  23. package/src/format/values.js +459 -0
  24. package/src/format/xml-parser.js +136 -0
  25. package/src/format/xml-tokenizer.js +237 -0
  26. package/src/geometry/contour.js +86 -0
  27. package/src/geometry/extrude.js +175 -0
  28. package/src/geometry/gear.js +85 -0
  29. package/src/geometry/geometry-cache.js +159 -0
  30. package/src/geometry/lod-error.js +178 -0
  31. package/src/geometry/mesh.js +458 -0
  32. package/src/geometry/primitives.js +299 -0
  33. package/src/geometry/registry.js +645 -0
  34. package/src/geometry/revolve.js +136 -0
  35. package/src/geometry/sweep.js +441 -0
  36. package/src/index.js +47 -0
  37. package/src/io/compression.js +67 -0
  38. package/src/io/convert.js +236 -0
  39. package/src/io/download.js +13 -0
  40. package/src/io/external-scene.js +127 -0
  41. package/src/io/file-loader.js +28 -0
  42. package/src/io/gltf.js +630 -0
  43. package/src/io/mesh-import.js +104 -0
  44. package/src/io/obj.js +352 -0
  45. package/src/io/step-brep.js +439 -0
  46. package/src/io/step-exact.js +1149 -0
  47. package/src/io/step.js +1418 -0
  48. package/src/io/stl.js +193 -0
  49. package/src/io/svg-import.js +787 -0
  50. package/src/material/materials.js +154 -0
  51. package/src/math/mat4.js +475 -0
  52. package/src/math/random.js +30 -0
  53. package/src/math/trig.js +65 -0
  54. package/src/math/vec3.js +81 -0
  55. package/src/optimize/optimizer.js +579 -0
  56. package/src/path/path-flatten.js +322 -0
  57. package/src/path/path-parser.js +332 -0
  58. package/src/path/shapes.js +129 -0
  59. package/src/path/triangulate.js +517 -0
  60. package/src/pipeline.js +74 -0
  61. package/src/render/camera.js +168 -0
  62. package/src/render/frame-builder.js +362 -0
  63. package/src/render/geometry-pool.js +149 -0
  64. package/src/render/lighting.js +149 -0
  65. package/src/render/orbit-controls.js +237 -0
  66. package/src/render/renderer.js +258 -0
  67. package/src/render/scroll-timeline.js +104 -0
  68. package/src/render/shaders/glsl.js +285 -0
  69. package/src/render/shaders/wgsl.js +252 -0
  70. package/src/render/stage.js +364 -0
  71. package/src/render/texture-cache.js +40 -0
  72. package/src/render/textures.js +223 -0
  73. package/src/render/webgl2/webgl2-backend.js +586 -0
  74. package/src/render/webgpu/webgpu-backend.js +482 -0
  75. package/src/scene/animation.js +171 -0
  76. package/src/scene/camera-constraints.js +117 -0
  77. package/src/scene/flatten.js +754 -0
  78. package/src/scene/picking.js +161 -0
  79. package/src/scene/scene-graph.js +320 -0
  80. package/src/transform/transform.js +211 -0
  81. package/src/wasm/kernels-binary.js +3 -0
  82. package/src/wasm/kernels.js +385 -0
@@ -0,0 +1,322 @@
1
+ // Flattening of path segments into polylines ("contours").
2
+ //
3
+ // Curves are subdivided adaptively from a geometric tolerance (Wang's formula
4
+ // for Béziers, chord error for arcs), so the same path produces coarser or
5
+ // finer polylines for different levels of detail. Every output point carries a
6
+ // `smooth` flag: true for curve interiors and tangent-continuous joints, false
7
+ // for corners. Geometry generators use the flags to decide where normals must
8
+ // be split (sharp edges) and where they are shared (smooth surfaces).
9
+
10
+ const SMOOTH_JOINT_COS = Math.cos((8 * Math.PI) / 180);
11
+ const MAX_SEGMENTS = 256;
12
+
13
+ function norm2(x, y) {
14
+ const l = Math.hypot(x, y);
15
+ return l > 1e-12 ? [x / l, y / l, 0] : null;
16
+ }
17
+ function norm3(x, y, z) {
18
+ const l = Math.hypot(x, y, z);
19
+ return l > 1e-12 ? [x / l, y / l, z / l] : null;
20
+ }
21
+
22
+ class ContourBuilder {
23
+ constructor(dim) {
24
+ this.dim = dim;
25
+ this.pts = [];
26
+ this.smooth = [];
27
+ this.firstTan = null;
28
+ this.lastTan = null;
29
+ this.closed = false;
30
+ }
31
+
32
+ get count() {
33
+ return this.smooth.length;
34
+ }
35
+
36
+ lastPoint() {
37
+ const d = this.dim;
38
+ const p = this.pts;
39
+ const k = p.length - d;
40
+ return d === 3 ? [p[k], p[k + 1], p[k + 2]] : [p[k], p[k + 1], 0];
41
+ }
42
+
43
+ start(x, y, z) {
44
+ this.pts.push(x, y);
45
+ if (this.dim === 3) this.pts.push(z);
46
+ this.smooth.push(0);
47
+ }
48
+
49
+ /** Begin a piece: decide whether the joint at the current last point is smooth. */
50
+ joint(tan) {
51
+ if (!tan) return;
52
+ if (this.lastTan) {
53
+ const c = this.lastTan[0] * tan[0] + this.lastTan[1] * tan[1] + this.lastTan[2] * tan[2];
54
+ this.smooth[this.smooth.length - 1] = c >= SMOOTH_JOINT_COS ? 1 : 0;
55
+ } else {
56
+ this.firstTan = tan;
57
+ }
58
+ }
59
+
60
+ push(x, y, z, smooth) {
61
+ // skip duplicate points
62
+ const d = this.dim;
63
+ const p = this.pts;
64
+ const k = p.length - d;
65
+ if (Math.abs(p[k] - x) < 1e-12 && Math.abs(p[k + 1] - y) < 1e-12 && (d === 2 || Math.abs(p[k + 2] - z) < 1e-12)) return;
66
+ p.push(x, y);
67
+ if (d === 3) p.push(z);
68
+ this.smooth.push(smooth ? 1 : 0);
69
+ }
70
+
71
+ end(tan) {
72
+ if (tan) this.lastTan = tan;
73
+ }
74
+ }
75
+
76
+ function tangent(dim, x, y, z) {
77
+ return dim === 3 ? norm3(x, y, z) : norm2(x, y);
78
+ }
79
+
80
+ /**
81
+ * @param {object[]} segments absolute segments from parsePathData
82
+ * @param {{tolerance:number, dim?:2|3, maxSegments?:number}} opts
83
+ * @returns {{points: Float64Array, smooth: Uint8Array, closed: boolean}[]}
84
+ */
85
+ export function flattenPath(segments, opts) {
86
+ const dim = opts.dim || 2;
87
+ const tol = Math.max(opts.tolerance, 1e-9);
88
+ const maxSeg = opts.maxSegments || MAX_SEGMENTS;
89
+ const out = [];
90
+ let b = null;
91
+
92
+ const finish = () => {
93
+ if (!b) return;
94
+ if (b.closed) {
95
+ // drop a duplicated end point and resolve the joint at the start point
96
+ const d = dim;
97
+ const p = b.pts;
98
+ const n = b.count;
99
+ if (n > 1) {
100
+ const k = (n - 1) * d;
101
+ const same = Math.abs(p[k] - p[0]) < 1e-9 && Math.abs(p[k + 1] - p[1]) < 1e-9 && (d === 2 || Math.abs(p[k + 2] - p[2]) < 1e-9);
102
+ if (same) {
103
+ p.length -= d;
104
+ b.smooth.pop();
105
+ } else {
106
+ // implicit closing line
107
+ const t = tangent(dim, p[0] - p[k], p[1] - p[k + 1], d === 3 ? p[2] - p[k + 2] : 0);
108
+ b.joint(t);
109
+ b.end(t);
110
+ }
111
+ }
112
+ if (b.firstTan && b.lastTan) {
113
+ const c = b.lastTan[0] * b.firstTan[0] + b.lastTan[1] * b.firstTan[1] + b.lastTan[2] * b.firstTan[2];
114
+ b.smooth[0] = c >= SMOOTH_JOINT_COS ? 1 : 0;
115
+ }
116
+ }
117
+ if (b.count >= (b.closed ? 3 : 2)) {
118
+ out.push({ points: Float64Array.from(b.pts), smooth: Uint8Array.from(b.smooth), closed: b.closed });
119
+ } else if (b.count >= 2) {
120
+ // a closed contour with fewer than 3 distinct points is degenerate; keep it open so it can be reported
121
+ out.push({ points: Float64Array.from(b.pts), smooth: Uint8Array.from(b.smooth), closed: false, degenerate: true });
122
+ }
123
+ b = null;
124
+ };
125
+
126
+ for (const s of segments) {
127
+ if (s.c === 'M') {
128
+ finish();
129
+ b = new ContourBuilder(dim);
130
+ b.start(s.x, s.y, s.z || 0);
131
+ continue;
132
+ }
133
+ if (!b) continue;
134
+ const [px, py, pz] = b.lastPoint();
135
+ switch (s.c) {
136
+ case 'L': {
137
+ const t = tangent(dim, s.x - px, s.y - py, (s.z || 0) - pz);
138
+ if (!t) break;
139
+ b.joint(t);
140
+ b.push(s.x, s.y, s.z || 0, false);
141
+ b.end(t);
142
+ break;
143
+ }
144
+ case 'Q': {
145
+ const x0 = px, y0 = py, z0 = pz;
146
+ const ddx = x0 - 2 * s.x1 + s.x, ddy = y0 - 2 * s.y1 + s.y, ddz = dim === 3 ? z0 - 2 * s.z1 + s.z : 0;
147
+ const M = Math.hypot(ddx, ddy, ddz);
148
+ const n = Math.max(1, Math.min(maxSeg, Math.ceil(Math.sqrt((0.25 * M) / tol))));
149
+ const t0 = tangent(dim, s.x1 - x0, s.y1 - y0, (s.z1 || 0) - z0) || tangent(dim, s.x - x0, s.y - y0, (s.z || 0) - z0);
150
+ const t1 = tangent(dim, s.x - s.x1, s.y - s.y1, (s.z || 0) - (s.z1 || 0)) || t0;
151
+ if (!t0) break;
152
+ b.joint(t0);
153
+ for (let i = 1; i <= n; i++) {
154
+ const t = i / n, mt = 1 - t;
155
+ const a = mt * mt, bb = 2 * mt * t, c = t * t;
156
+ b.push(a * x0 + bb * s.x1 + c * s.x, a * y0 + bb * s.y1 + c * s.y, a * z0 + bb * (s.z1 || 0) + c * (s.z || 0), i < n);
157
+ }
158
+ b.end(t1);
159
+ break;
160
+ }
161
+ case 'C': {
162
+ const x0 = px, y0 = py, z0 = pz;
163
+ const z1 = s.z1 || 0, z2 = s.z2 || 0, z3 = s.z || 0;
164
+ const d1 = Math.hypot(x0 - 2 * s.x1 + s.x2, y0 - 2 * s.y1 + s.y2, dim === 3 ? z0 - 2 * z1 + z2 : 0);
165
+ const d2 = Math.hypot(s.x1 - 2 * s.x2 + s.x, s.y1 - 2 * s.y2 + s.y, dim === 3 ? z1 - 2 * z2 + z3 : 0);
166
+ const M = Math.max(d1, d2);
167
+ const n = Math.max(1, Math.min(maxSeg, Math.ceil(Math.sqrt((0.75 * M) / tol))));
168
+ const t0 =
169
+ tangent(dim, s.x1 - x0, s.y1 - y0, z1 - z0) ||
170
+ tangent(dim, s.x2 - x0, s.y2 - y0, z2 - z0) ||
171
+ tangent(dim, s.x - x0, s.y - y0, z3 - z0);
172
+ const t1 =
173
+ tangent(dim, s.x - s.x2, s.y - s.y2, z3 - z2) ||
174
+ tangent(dim, s.x - s.x1, s.y - s.y1, z3 - z1) ||
175
+ t0;
176
+ if (!t0) break;
177
+ b.joint(t0);
178
+ for (let i = 1; i <= n; i++) {
179
+ const t = i / n, mt = 1 - t;
180
+ const a = mt * mt * mt, bb = 3 * mt * mt * t, c = 3 * mt * t * t, d = t * t * t;
181
+ b.push(
182
+ a * x0 + bb * s.x1 + c * s.x2 + d * s.x,
183
+ a * y0 + bb * s.y1 + c * s.y2 + d * s.y,
184
+ a * z0 + bb * z1 + c * z2 + d * z3,
185
+ i < n,
186
+ );
187
+ }
188
+ b.end(t1);
189
+ break;
190
+ }
191
+ case 'A': {
192
+ const arc = arcToCenter(px, py, s.rx, s.ry, s.rot, s.large, s.sweep, s.x, s.y);
193
+ if (!arc) {
194
+ const t = tangent(2, s.x - px, s.y - py, 0);
195
+ if (!t) break;
196
+ b.joint(t);
197
+ b.push(s.x, s.y, 0, false);
198
+ b.end(t);
199
+ break;
200
+ }
201
+ const r = Math.max(arc.rx, arc.ry);
202
+ const step = tol >= r ? Math.PI / 2 : 2 * Math.acos(1 - tol / r);
203
+ const n = Math.max(1, Math.min(maxSeg, Math.ceil(Math.abs(arc.dtheta) / step)));
204
+ b.joint(arc.tangentAt(arc.theta1));
205
+ for (let i = 1; i <= n; i++) {
206
+ const th = arc.theta1 + (arc.dtheta * i) / n;
207
+ if (i === n) b.push(s.x, s.y, 0, false);
208
+ else {
209
+ const p = arc.pointAt(th);
210
+ b.push(p[0], p[1], 0, true);
211
+ }
212
+ }
213
+ b.end(arc.tangentAt(arc.theta1 + arc.dtheta));
214
+ break;
215
+ }
216
+ case 'Z':
217
+ b.closed = true;
218
+ finish();
219
+ break;
220
+ default:
221
+ break;
222
+ }
223
+ }
224
+ finish();
225
+ return out;
226
+ }
227
+
228
+ /** SVG arc endpoint -> center parameterization (SVG 1.1 implementation notes F.6.5). */
229
+ export function arcToCenter(x1, y1, rx, ry, rotDeg, large, sweep, x2, y2) {
230
+ if (x1 === x2 && y1 === y2) return null;
231
+ rx = Math.abs(rx);
232
+ ry = Math.abs(ry);
233
+ if (rx < 1e-12 || ry < 1e-12) return null;
234
+ const phi = (rotDeg * Math.PI) / 180;
235
+ const cosP = Math.cos(phi), sinP = Math.sin(phi);
236
+ const dx2 = (x1 - x2) / 2, dy2 = (y1 - y2) / 2;
237
+ const x1p = cosP * dx2 + sinP * dy2;
238
+ const y1p = -sinP * dx2 + cosP * dy2;
239
+ const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
240
+ if (lambda > 1) {
241
+ const s = Math.sqrt(lambda);
242
+ rx *= s;
243
+ ry *= s;
244
+ }
245
+ const rx2 = rx * rx, ry2 = ry * ry;
246
+ const num = rx2 * ry2 - rx2 * y1p * y1p - ry2 * x1p * x1p;
247
+ const den = rx2 * y1p * y1p + ry2 * x1p * x1p;
248
+ let coef = den > 0 ? Math.sqrt(Math.max(0, num / den)) : 0;
249
+ if (large === sweep) coef = -coef;
250
+ const cxp = (coef * rx * y1p) / ry;
251
+ const cyp = (-coef * ry * x1p) / rx;
252
+ const cx = cosP * cxp - sinP * cyp + (x1 + x2) / 2;
253
+ const cy = sinP * cxp + cosP * cyp + (y1 + y2) / 2;
254
+ const ang = (ux, uy, vx, vy) => {
255
+ const a = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
256
+ return a;
257
+ };
258
+ const ux = (x1p - cxp) / rx, uy = (y1p - cyp) / ry;
259
+ const vx = (-x1p - cxp) / rx, vy = (-y1p - cyp) / ry;
260
+ const theta1 = Math.atan2(uy, ux);
261
+ let dtheta = ang(ux, uy, vx, vy);
262
+ if (!sweep && dtheta > 0) dtheta -= 2 * Math.PI;
263
+ else if (sweep && dtheta < 0) dtheta += 2 * Math.PI;
264
+ const sign = dtheta >= 0 ? 1 : -1;
265
+ return {
266
+ cx,
267
+ cy,
268
+ rx,
269
+ ry,
270
+ theta1,
271
+ dtheta,
272
+ pointAt(th) {
273
+ const c = Math.cos(th), s = Math.sin(th);
274
+ return [cx + rx * cosP * c - ry * sinP * s, cy + rx * sinP * c + ry * cosP * s];
275
+ },
276
+ tangentAt(th) {
277
+ const c = Math.cos(th), s = Math.sin(th);
278
+ return norm2(sign * (-rx * cosP * s - ry * sinP * c), sign * (-rx * sinP * s + ry * cosP * c));
279
+ },
280
+ };
281
+ }
282
+
283
+ /** Polyline points (flat array) -> contour with corner detection by turning angle. */
284
+ export function polylineContour(points, dim, closed) {
285
+ const n = points.length / dim;
286
+ const smooth = new Uint8Array(n);
287
+ return { points: Float64Array.from(points), smooth, closed };
288
+ }
289
+
290
+ /** Regular polygon approximation of a circle (all points smooth), counter-clockwise. */
291
+ export function circleContour(r, segments) {
292
+ const pts = new Float64Array(segments * 2);
293
+ for (let i = 0; i < segments; i++) {
294
+ const a = (i / segments) * Math.PI * 2;
295
+ pts[i * 2] = Math.cos(a) * r;
296
+ pts[i * 2 + 1] = Math.sin(a) * r;
297
+ }
298
+ return { points: pts, smooth: new Uint8Array(segments).fill(1), closed: true };
299
+ }
300
+
301
+ /** Signed area of a 2D contour (positive = counter-clockwise with y up). */
302
+ export function signedArea(points) {
303
+ let a = 0;
304
+ const n = points.length / 2;
305
+ for (let i = 0, j = n - 1; i < n; j = i++) {
306
+ a += (points[j * 2] - points[i * 2]) * (points[j * 2 + 1] + points[i * 2 + 1]);
307
+ }
308
+ return a / 2;
309
+ }
310
+
311
+ /** Reverse a 2D/3D contour in place-safe manner (returns a new contour). */
312
+ export function reverseContour(c, dim = 2) {
313
+ const n = c.points.length / dim;
314
+ const pts = new Float64Array(c.points.length);
315
+ const sm = new Uint8Array(n);
316
+ for (let i = 0; i < n; i++) {
317
+ const j = n - 1 - i;
318
+ for (let k = 0; k < dim; k++) pts[i * dim + k] = c.points[j * dim + k];
319
+ sm[i] = c.smooth[j];
320
+ }
321
+ return { ...c, points: pts, smooth: sm };
322
+ }
@@ -0,0 +1,332 @@
1
+ // SVG-style path data parser.
2
+ //
3
+ // 2D paths accept the full SVG grammar: M L H V C S Q T A Z (absolute and
4
+ // relative), implicit command repetition, optional separators ("M10-5"),
5
+ // compact arc flags ("a1,1 0 00 1,1") and closepath semantics.
6
+ //
7
+ // 3D paths (sweep spines) use the same letters with three coordinates per
8
+ // point: M L C S Q T Z (H, V and A have no unambiguous 3D meaning).
9
+ //
10
+ // The result is a list of absolute segments; H/V become L, S becomes C and
11
+ // T becomes Q. Each segment remembers its source offset for error reporting.
12
+
13
+ import { MAX_PATH_COMMANDS } from '../format/limits.js';
14
+
15
+ export class PathError extends Error {
16
+ constructor(message, offset, length = 1, code = null) {
17
+ super(message);
18
+ this.name = 'PathError';
19
+ this.offset = offset;
20
+ this.length = length;
21
+ this.code = code;
22
+ }
23
+ }
24
+
25
+ const ARG_COUNT_2D = { M: 2, L: 2, H: 1, V: 1, C: 6, S: 4, Q: 4, T: 2, A: 7, Z: 0 };
26
+ const ARG_COUNT_3D = { M: 3, L: 3, C: 9, S: 6, Q: 6, T: 3, Z: 0 };
27
+
28
+ function isWs(c) {
29
+ return c === 32 || c === 9 || c === 10 || c === 13 || c === 12;
30
+ }
31
+
32
+ /** Scan a number at i; returns the end index or -1. */
33
+ export function scanNumber(s, i) {
34
+ return readNumber(s, i);
35
+ }
36
+
37
+ const POW10 = Array.from({ length: 23 }, (_, k) => Number(`1e${k}`));
38
+
39
+ /** Value of the number that readNumber last read. */
40
+ export let numberValue = 0;
41
+
42
+ /**
43
+ * Read the number at i: returns its end index (or -1 when no number starts
44
+ * there) and leaves its value in `numberValue`, exactly as Number() would give
45
+ * it for s.slice(i, end). When the digits form an integer of at most 2^53 and
46
+ * the decimal exponent is within ±22, both are exact in binary64, so one IEEE
47
+ * multiply or divide is correctly rounded (Clinger's fast path) and no
48
+ * substring is made; anything else goes through Number(). Mesh data is
49
+ * hundreds of thousands of such numbers, so this is one pass over the digits.
50
+ */
51
+ export function readNumber(s, i) {
52
+ const start = i;
53
+ let c = s.charCodeAt(i);
54
+ const neg = c === 45;
55
+ if (c === 43 || c === 45) c = s.charCodeAt(++i);
56
+ // the mantissa only grows, so it is exact whenever it ends at most 2^53
57
+ let m = 0;
58
+ const intStart = i;
59
+ while (c >= 48 && c <= 57) {
60
+ m = m * 10 + (c - 48);
61
+ c = s.charCodeAt(++i);
62
+ }
63
+ let digits = i - intStart, frac = 0;
64
+ if (c === 46) {
65
+ const fracStart = ++i;
66
+ c = s.charCodeAt(i);
67
+ while (c >= 48 && c <= 57) {
68
+ m = m * 10 + (c - 48);
69
+ c = s.charCodeAt(++i);
70
+ }
71
+ frac = i - fracStart;
72
+ digits += frac;
73
+ }
74
+ if (!digits) return -1;
75
+ let e = 0;
76
+ if (c === 101 || c === 69) {
77
+ // the exponent belongs to the number only when digits follow
78
+ let j = i + 1;
79
+ let c2 = s.charCodeAt(j);
80
+ const eneg = c2 === 45;
81
+ if (c2 === 43 || c2 === 45) c2 = s.charCodeAt(++j);
82
+ if (c2 >= 48 && c2 <= 57) {
83
+ while (c2 >= 48 && c2 <= 57) {
84
+ e = e * 10 + (c2 - 48);
85
+ c2 = s.charCodeAt(++j);
86
+ }
87
+ if (eneg) e = -e;
88
+ i = j;
89
+ }
90
+ }
91
+ e -= frac;
92
+ if (m > 9007199254740992 || e > 22 || e < -22) numberValue = Number(s.slice(start, i));
93
+ else {
94
+ const v = e >= 0 ? m * POW10[e] : m / POW10[-e];
95
+ numberValue = neg ? -v : v;
96
+ }
97
+ return i;
98
+ }
99
+
100
+ /**
101
+ * @param {string} s path data
102
+ * @param {2|3} dim
103
+ * @returns {{segments: object[], subpaths: number}}
104
+ */
105
+ export function parsePathData(s, dim = 2) {
106
+ const counts = dim === 3 ? ARG_COUNT_3D : ARG_COUNT_2D;
107
+ const n = s.length;
108
+ let i = 0;
109
+ const segs = [];
110
+ let cx = 0, cy = 0, cz = 0;
111
+ let sx = 0, sy = 0, sz = 0;
112
+ // previous control point for S/T reflection
113
+ let pcx = 0, pcy = 0, pcz = 0;
114
+ let prev = '';
115
+ let cmd = '';
116
+ let subpaths = 0;
117
+ let pendingMoveAfterZ = false;
118
+
119
+ const skipWs = () => {
120
+ while (i < n && isWs(s.charCodeAt(i))) i++;
121
+ };
122
+ const skipSep = () => {
123
+ skipWs();
124
+ if (s.charCodeAt(i) === 44) {
125
+ i++;
126
+ skipWs();
127
+ }
128
+ };
129
+ const num = () => {
130
+ skipSep();
131
+ const end = readNumber(s, i);
132
+ if (end < 0) {
133
+ if (i >= n) throw new PathError(`Command '${cmd}' expects ${counts[cmd.toUpperCase()]} numbers but the path data ended.`, Math.max(0, n - 1), 1);
134
+ throw new PathError(`Expected a number in '${cmd}' command but found '${s[i]}'.`, i, 1);
135
+ }
136
+ i = end;
137
+ return numberValue;
138
+ };
139
+ const flag = () => {
140
+ skipSep();
141
+ const c = s.charCodeAt(i);
142
+ if (c !== 48 && c !== 49) throw new PathError("Arc flags must be '0' or '1'.", i, 1);
143
+ i++;
144
+ return c === 49 ? 1 : 0;
145
+ };
146
+ const startsNumber = () => {
147
+ let j = i;
148
+ while (j < n && isWs(s.charCodeAt(j))) j++;
149
+ if (s.charCodeAt(j) === 44) {
150
+ j++;
151
+ while (j < n && isWs(s.charCodeAt(j))) j++;
152
+ }
153
+ const c = s.charCodeAt(j);
154
+ return (c >= 48 && c <= 57) || c === 45 || c === 43 || c === 46;
155
+ };
156
+
157
+ skipWs();
158
+ if (i >= n) return { segments: segs, subpaths: 0 };
159
+
160
+ while (true) {
161
+ skipWs();
162
+ if (i >= n) break;
163
+ if (segs.length >= MAX_PATH_COMMANDS) {
164
+ throw new PathError(`Path data has more than ${MAX_PATH_COMMANDS.toLocaleString('en-US')} commands.`, i, 1, 'E_PATH_LIMIT');
165
+ }
166
+ const c = s[i];
167
+ const code = s.charCodeAt(i);
168
+ const isLetter = (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
169
+ const segStart = i;
170
+ if (isLetter) {
171
+ const up = c.toUpperCase();
172
+ if (!(up in ARG_COUNT_2D)) throw new PathError(`Unknown path command '${c}'. Valid commands: M L H V C S Q T A Z.`, i, 1);
173
+ if (!(up in counts)) throw new PathError(`Command '${c}' is not available in 3D path data (use M L C S Q T Z).`, i, 1);
174
+ if (!cmd && up !== 'M') throw new PathError('Path data must begin with a moveto command (M or m).', i, 1);
175
+ cmd = c;
176
+ i++;
177
+ if (up === 'Z') {
178
+ // closepath
179
+ segs.push({ c: 'Z', o: segStart });
180
+ cx = sx;
181
+ cy = sy;
182
+ cz = sz;
183
+ prev = 'Z';
184
+ pendingMoveAfterZ = true;
185
+ continue;
186
+ }
187
+ if (!startsNumber()) {
188
+ skipWs();
189
+ throw new PathError(`Command '${c}' expects ${counts[up]} numbers.`, Math.min(i, n - 1), 1);
190
+ }
191
+ } else {
192
+ if (!cmd) throw new PathError('Path data must begin with a moveto command (M or m).', i, 1);
193
+ if (cmd === 'Z' || cmd === 'z') throw new PathError(`Unexpected '${c}' after closepath; start a new command.`, i, 1);
194
+ if (!startsNumber()) throw new PathError(`Unexpected character '${c}' in path data.`, i, 1);
195
+ // implicit repetition: subsequent moveto pairs are lineto
196
+ if (cmd === 'M') cmd = 'L';
197
+ else if (cmd === 'm') cmd = 'l';
198
+ }
199
+
200
+ const rel = cmd === cmd.toLowerCase();
201
+ const up = cmd.toUpperCase();
202
+ if (pendingMoveAfterZ && up !== 'M') {
203
+ // a subpath that continues after Z starts at the previous subpath's start point
204
+ segs.push({ c: 'M', x: sx, y: sy, z: sz, o: segStart, implicit: true });
205
+ subpaths++;
206
+ }
207
+ pendingMoveAfterZ = false;
208
+ const ox = rel ? cx : 0, oy = rel ? cy : 0, oz = rel ? cz : 0;
209
+
210
+ switch (up) {
211
+ case 'M': {
212
+ const x = num() + ox, y = num() + oy;
213
+ const z = dim === 3 ? num() + oz : 0;
214
+ segs.push({ c: 'M', x, y, z, o: segStart });
215
+ cx = sx = x;
216
+ cy = sy = y;
217
+ cz = sz = z;
218
+ subpaths++;
219
+ break;
220
+ }
221
+ case 'L': {
222
+ const x = num() + ox, y = num() + oy;
223
+ const z = dim === 3 ? num() + oz : 0;
224
+ segs.push({ c: 'L', x, y, z, o: segStart });
225
+ cx = x;
226
+ cy = y;
227
+ cz = z;
228
+ break;
229
+ }
230
+ case 'H': {
231
+ const x = num() + ox;
232
+ segs.push({ c: 'L', x, y: cy, z: 0, o: segStart });
233
+ cx = x;
234
+ break;
235
+ }
236
+ case 'V': {
237
+ const y = num() + oy;
238
+ segs.push({ c: 'L', x: cx, y, z: 0, o: segStart });
239
+ cy = y;
240
+ break;
241
+ }
242
+ case 'C': {
243
+ const x1 = num() + ox, y1 = num() + oy, z1 = dim === 3 ? num() + oz : 0;
244
+ const x2 = num() + ox, y2 = num() + oy, z2 = dim === 3 ? num() + oz : 0;
245
+ const x = num() + ox, y = num() + oy, z = dim === 3 ? num() + oz : 0;
246
+ segs.push({ c: 'C', x1, y1, z1, x2, y2, z2, x, y, z, o: segStart });
247
+ pcx = x2; pcy = y2; pcz = z2;
248
+ cx = x; cy = y; cz = z;
249
+ break;
250
+ }
251
+ case 'S': {
252
+ let x1 = cx, y1 = cy, z1 = cz;
253
+ if (prev === 'C' || prev === 'S') {
254
+ x1 = 2 * cx - pcx;
255
+ y1 = 2 * cy - pcy;
256
+ z1 = 2 * cz - pcz;
257
+ }
258
+ const x2 = num() + ox, y2 = num() + oy, z2 = dim === 3 ? num() + oz : 0;
259
+ const x = num() + ox, y = num() + oy, z = dim === 3 ? num() + oz : 0;
260
+ segs.push({ c: 'C', x1, y1, z1, x2, y2, z2, x, y, z, o: segStart });
261
+ pcx = x2; pcy = y2; pcz = z2;
262
+ cx = x; cy = y; cz = z;
263
+ break;
264
+ }
265
+ case 'Q': {
266
+ const x1 = num() + ox, y1 = num() + oy, z1 = dim === 3 ? num() + oz : 0;
267
+ const x = num() + ox, y = num() + oy, z = dim === 3 ? num() + oz : 0;
268
+ segs.push({ c: 'Q', x1, y1, z1, x, y, z, o: segStart });
269
+ pcx = x1; pcy = y1; pcz = z1;
270
+ cx = x; cy = y; cz = z;
271
+ break;
272
+ }
273
+ case 'T': {
274
+ let x1 = cx, y1 = cy, z1 = cz;
275
+ if (prev === 'Q' || prev === 'T') {
276
+ x1 = 2 * cx - pcx;
277
+ y1 = 2 * cy - pcy;
278
+ z1 = 2 * cz - pcz;
279
+ }
280
+ const x = num() + ox, y = num() + oy, z = dim === 3 ? num() + oz : 0;
281
+ segs.push({ c: 'Q', x1, y1, z1, x, y, z, o: segStart });
282
+ pcx = x1; pcy = y1; pcz = z1;
283
+ cx = x; cy = y; cz = z;
284
+ break;
285
+ }
286
+ case 'A': {
287
+ const rx = num();
288
+ const ry = num();
289
+ const rot = num();
290
+ const large = flag();
291
+ const sweep = flag();
292
+ const x = num() + ox, y = num() + oy;
293
+ if (rx < 0 || ry < 0) throw new PathError('Arc radii must not be negative.', segStart, i - segStart);
294
+ segs.push({ c: 'A', rx, ry, rot, large, sweep, x0: cx, y0: cy, x, y, z: 0, o: segStart });
295
+ cx = x;
296
+ cy = y;
297
+ break;
298
+ }
299
+ default:
300
+ throw new PathError(`Unsupported command '${cmd}'.`, segStart, 1);
301
+ }
302
+ prev = up;
303
+ }
304
+ return { segments: segs, subpaths };
305
+ }
306
+
307
+ /** Axis-aligned bounds of the control polygon (a conservative bound for curves; arcs use their endpoints and radii). */
308
+ export function pathControlBounds(segments) {
309
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
310
+ const add = (x, y) => {
311
+ if (x < minX) minX = x;
312
+ if (y < minY) minY = y;
313
+ if (x > maxX) maxX = x;
314
+ if (y > maxY) maxY = y;
315
+ };
316
+ for (const s of segments) {
317
+ if (s.c === 'Z') continue;
318
+ add(s.x, s.y);
319
+ if (s.c === 'C') {
320
+ add(s.x1, s.y1);
321
+ add(s.x2, s.y2);
322
+ } else if (s.c === 'Q') add(s.x1, s.y1);
323
+ else if (s.c === 'A') {
324
+ const r = Math.max(s.rx, s.ry);
325
+ add(s.x - r, s.y - r);
326
+ add(s.x + r, s.y + r);
327
+ add(s.x0 - r, s.y0 - r);
328
+ add(s.x0 + r, s.y0 + r);
329
+ }
330
+ }
331
+ return { minX, minY, maxX, maxY };
332
+ }