swf2js 0.0.0-stage → 0.1.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 (38) hide show
  1. package/LICENSE-GPL +680 -0
  2. package/README.md +208 -2
  3. package/package.json +24 -4
  4. package/src/cli.js +272 -0
  5. package/src/decoder/button-decoder.js +136 -0
  6. package/src/decoder/shape-decoder.js +786 -0
  7. package/src/decoder/symbol-table.js +36 -0
  8. package/src/decoder/tag-decoder.js +1190 -0
  9. package/src/decoder/tag-types.js +258 -0
  10. package/src/emitter/asset-encoder.js +708 -0
  11. package/src/emitter/bundle-emitter.js +596 -0
  12. package/src/emitter/embedded-swf.js +246 -0
  13. package/src/emitter/font-encoder.js +365 -0
  14. package/src/emitter/timeline-data-codec.js +58 -0
  15. package/src/model/swf-document.js +59 -0
  16. package/src/model/transpile-result.js +32 -0
  17. package/src/parser/bit-reader.js +237 -0
  18. package/src/parser/decompressor.js +91 -0
  19. package/src/parser/swf-parser.js +164 -0
  20. package/src/pretty-printer/pretty-printer.js +137 -0
  21. package/src/runtime/avm1-runtime.js +4907 -0
  22. package/src/runtime/avm2-runtime.js +1591 -0
  23. package/src/runtime/embedded-movie-runtime.js +208 -0
  24. package/src/runtime/index.js +17 -0
  25. package/src/runtime/movie-runtime.js +306 -0
  26. package/src/runtime/swflib.js +14050 -0
  27. package/src/transpiler/actionscript.js +390 -0
  28. package/src/transpiler/avm1/avm1-ir.js +205 -0
  29. package/src/transpiler/avm1/avm1-opcodes.js +149 -0
  30. package/src/transpiler/avm1/avm1-rewrite.js +291 -0
  31. package/src/transpiler/avm1/avm1-transpiler.js +2082 -0
  32. package/src/transpiler/avm2/abc-reader.js +416 -0
  33. package/src/transpiler/avm2/avm2-transpiler.js +2560 -0
  34. package/src/transpiler/cfg-structurer.js +876 -0
  35. package/src/transpiler/timeline/display-list.js +643 -0
  36. package/src/transpiler/timeline/timeline-codegen.js +6354 -0
  37. package/src/util/diagnostics.js +50 -0
  38. package/src/util/logger.js +40 -0
@@ -0,0 +1,786 @@
1
+ /**
2
+ * @fileoverview Decode SWF SHAPEWITHSTYLE → canvas-ready path draw lists.
3
+ *
4
+ * FillStyle0 is left of directed edges, FillStyle1 is right. Edges for fill0
5
+ * are reversed so each fill gets consistent winding for Canvas.
6
+ */
7
+
8
+ import { BitReader } from '../parser/bit-reader.js';
9
+
10
+ /**
11
+ * @typedef {{ type: 'solid', color: string }} SolidFill
12
+ * @typedef {{ type: 'linear'|'radial', matrix: object, stops: { ratio: number, color: string }[], focal?: number, spreadMode?: number, interpolationMode?: number }} GradientFill
13
+ * @typedef {{ type: 'bitmap', bitmapId: number, matrix: object, repeat: boolean, smoothed: boolean }} BitmapFill
14
+ * @typedef {SolidFill|GradientFill|BitmapFill} FillStyle
15
+ * @typedef {{ width: number, color?: string, fill?: FillStyle, noClose?: boolean, startCap?: number, endCap?: number, joinStyle?: number, miterLimit?: number, noHScale?: boolean, noVScale?: boolean, pixelHinting?: boolean }} LineStyle
16
+ * @typedef {{ x0: number, y0: number, x1: number, y1: number, cx?: number, cy?: number }} Edge
17
+ * @typedef {{ style: number, edge: Edge, startsStroke: boolean }} StrokeEdge
18
+ * @typedef {(string|number)[]} PathCmd
19
+ * @typedef {{ fill?: FillStyle, stroke?: LineStyle, path: PathCmd[], evenOdd?: boolean }} ShapeDraw
20
+ */
21
+
22
+ /**
23
+ * Decode DefineShape raw tag body into drawable path layers (pixel space).
24
+ * @param {Uint8Array} rawData - full DefineShape tag body
25
+ * @param {number} version - 1..4
26
+ * @returns {{ bounds: { xMin: number, xMax: number, yMin: number, yMax: number }, draws: ShapeDraw[], evenOdd: boolean }}
27
+ */
28
+ export function decodeShape(rawData, version = 1) {
29
+ const r = new BitReader(rawData);
30
+ r.readUI16(); // characterId
31
+ const bounds = r.readRect();
32
+ r.align();
33
+
34
+ let evenOdd = true;
35
+ if (version >= 4) {
36
+ r.readRect(); // edgeBounds
37
+ r.align();
38
+ r.readUB(5); // reserved
39
+ evenOdd = !r.readUB(1); // UsesFillWindingRule selects nonzero winding.
40
+ r.readUB(1); // UsesNonScalingStrokes
41
+ r.readUB(1); // UsesScalingStrokes
42
+ }
43
+
44
+ const parsed = parseShapeRecords(r, version);
45
+ return { bounds, draws: buildDrawList(parsed, evenOdd), evenOdd };
46
+ }
47
+
48
+ /** Decode the paired geometry and styles stored by DefineMorphShape/2. */
49
+ export function decodeMorphShape(rawData, version = 1) {
50
+ const r = new BitReader(rawData);
51
+ const characterId = r.readUI16();
52
+ const startBounds = r.readRect();
53
+ r.align();
54
+ const endBounds = r.readRect();
55
+ r.align();
56
+ if (version >= 2) {
57
+ r.readRect(); r.align(); r.readRect(); r.align();
58
+ r.readUB(6); r.readUB(1); r.readUB(1);
59
+ }
60
+ const offset = r.readUI32();
61
+ const endEdgesPos = r.bytePos + offset;
62
+ if (endEdgesPos > rawData.length || endEdgesPos < r.bytePos) throw new Error('Invalid morph EndEdges offset');
63
+
64
+ const startFills = [], endFills = [];
65
+ const fillCount = readStyleCount(r);
66
+ for (let i = 0; i < fillCount; i++) {
67
+ const pair = readMorphFillStyle(r);
68
+ startFills.push(pair.start); endFills.push(pair.end);
69
+ }
70
+ const startLines = [], endLines = [];
71
+ const lineCount = readStyleCount(r);
72
+ for (let i = 0; i < lineCount; i++) {
73
+ const pair = readMorphLineStyle(r, version >= 2);
74
+ startLines.push(pair.start); endLines.push(pair.end);
75
+ }
76
+
77
+ const startRecords = readMorphEdges(r, false);
78
+ if (r.bytePos > endEdgesPos) throw new Error('Morph StartEdges crossed EndEdges offset');
79
+ r.seek(endEdgesPos);
80
+ const endRecords = readMorphEdges(r, true);
81
+ if (startRecords.edges.length !== endRecords.edges.length) {
82
+ throw new Error(`Morph edge count mismatch (${startRecords.edges.length}/${endRecords.edges.length})`);
83
+ }
84
+
85
+ const start = parsedMorphDraws(startRecords, startFills, startLines);
86
+ const end = parsedMorphDraws(endRecords, endFills, endLines, startRecords.styles);
87
+ const paired = alignMorphDraws(start, end);
88
+ return { characterId, version, startBounds, endBounds, startDraws: paired.start, endDraws: paired.end };
89
+ }
90
+
91
+ /** Normalize compatible paired contours to a shared, linearly interpolable path topology. */
92
+ export function alignMorphDraws(startDraws, endDraws) {
93
+ const start = startDraws.map((draw) => ({ ...draw, path: draw.path.map((cmd) => cmd.slice()) }));
94
+ const end = endDraws.map((draw) => ({ ...draw, path: draw.path.map((cmd) => cmd.slice()) }));
95
+ const count = Math.min(start.length, end.length);
96
+ for (let i = 0; i < count; i++) {
97
+ const sameTopology = samePathTopology(start[i].path, end[i].path);
98
+ const pair = alignMorphPaths(start[i].path, end[i].path);
99
+ if (!pair) continue;
100
+ if (!sameTopology) {
101
+ start[i].endpointPath = start[i].path.map((command) => command.slice());
102
+ end[i].endpointPath = end[i].path.map((command) => command.slice());
103
+ }
104
+ start[i].path = pair.start;
105
+ end[i].path = pair.end;
106
+ }
107
+ return { start, end };
108
+ }
109
+
110
+ function alignMorphPaths(startPath, endPath) {
111
+ if (samePathTopology(startPath, endPath)) return { start: startPath, end: endPath };
112
+ const startContours = flattenPathContours(startPath);
113
+ const endContours = flattenPathContours(endPath);
114
+ if (startContours.length !== endContours.length) return null;
115
+ const alignedStart = [], alignedEnd = [];
116
+ for (let i = 0; i < startContours.length; i++) {
117
+ const a = startContours[i], b = endContours[i];
118
+ if (a.closed !== b.closed) return null;
119
+ const segmentCount = Math.min(256, Math.max(a.points.length - (a.closed ? 0 : 1), b.points.length - (b.closed ? 0 : 1), 1));
120
+ const ap = resampleContour(a.points, a.closed, segmentCount);
121
+ const bp = resampleContour(b.points, b.closed, segmentCount);
122
+ if (!ap.length || ap.length !== bp.length) return null;
123
+ alignedStart.push(['M', ap[0][0], ap[0][1]]);
124
+ alignedEnd.push(['M', bp[0][0], bp[0][1]]);
125
+ for (let j = 1; j < ap.length; j++) {
126
+ alignedStart.push(['L', ap[j][0], ap[j][1]]);
127
+ alignedEnd.push(['L', bp[j][0], bp[j][1]]);
128
+ }
129
+ if (a.closed) {
130
+ alignedStart.push(['Z']);
131
+ alignedEnd.push(['Z']);
132
+ }
133
+ }
134
+ return { start: alignedStart, end: alignedEnd };
135
+ }
136
+
137
+ function samePathTopology(a, b) {
138
+ return a.length === b.length && a.every((cmd, i) => cmd[0] === b[i][0] && cmd.length === b[i].length);
139
+ }
140
+
141
+ function flattenPathContours(path) {
142
+ const contours = [];
143
+ let contour = null, x = 0, y = 0;
144
+ const add = (px, py) => {
145
+ const points = contour.points;
146
+ const last = points[points.length - 1];
147
+ if (!last || Math.hypot(px - last[0], py - last[1]) > 1e-6) points.push([px, py]);
148
+ };
149
+ const flattenQuadratic = (x0, y0, cx, cy, x1, y1, depth = 0) => {
150
+ const chord = Math.hypot(x1 - x0, y1 - y0);
151
+ const flatness = chord
152
+ ? Math.abs((y1 - y0) * cx - (x1 - x0) * cy + x1 * y0 - y1 * x0) / chord
153
+ : Math.hypot(cx - x0, cy - y0);
154
+ if (flatness <= 0.25 || depth >= 10) { add(x1, y1); return; }
155
+ const x01 = (x0 + cx) / 2, y01 = (y0 + cy) / 2;
156
+ const x12 = (cx + x1) / 2, y12 = (cy + y1) / 2;
157
+ const xm = (x01 + x12) / 2, ym = (y01 + y12) / 2;
158
+ flattenQuadratic(x0, y0, x01, y01, xm, ym, depth + 1);
159
+ flattenQuadratic(xm, ym, x12, y12, x1, y1, depth + 1);
160
+ };
161
+ for (const cmd of path) {
162
+ if (cmd[0] === 'M') {
163
+ contour = { points: [[+cmd[1], +cmd[2]]], closed: false };
164
+ contours.push(contour); x = +cmd[1]; y = +cmd[2];
165
+ } else if (cmd[0] === 'L' && contour) {
166
+ x = +cmd[1]; y = +cmd[2]; add(x, y);
167
+ } else if (cmd[0] === 'Q' && contour) {
168
+ const x0 = x, y0 = y;
169
+ flattenQuadratic(x0, y0, +cmd[1], +cmd[2], +cmd[3], +cmd[4]);
170
+ x = +cmd[3]; y = +cmd[4];
171
+ } else if (cmd[0] === 'Z' && contour) {
172
+ contour.closed = true;
173
+ const first = contour.points[0];
174
+ x = first[0]; y = first[1]; contour = null;
175
+ } else if (cmd[0] !== 'Z') return [];
176
+ }
177
+ return contours;
178
+ }
179
+
180
+ function resampleContour(points, closed, segmentCount) {
181
+ if (!points.length) return [];
182
+ const polyline = points.slice();
183
+ if (closed && (polyline[0][0] !== polyline[polyline.length - 1][0] || polyline[0][1] !== polyline[polyline.length - 1][1])) polyline.push(polyline[0]);
184
+ const lengths = [0];
185
+ for (let i = 1; i < polyline.length; i++) {
186
+ const a = polyline[i - 1], b = polyline[i];
187
+ lengths.push(lengths[i - 1] + Math.hypot(b[0] - a[0], b[1] - a[1]));
188
+ }
189
+ const total = lengths[lengths.length - 1];
190
+ if (total < 1e-6) return Array.from({ length: closed ? segmentCount : segmentCount + 1 }, () => points[0].slice());
191
+ const sampleCount = closed ? segmentCount : segmentCount + 1;
192
+ const output = [];
193
+ for (let sample = 0; sample < sampleCount; sample++) {
194
+ const distance = total * sample / segmentCount;
195
+ let index = 1;
196
+ while (index < lengths.length - 1 && lengths[index] < distance) index++;
197
+ const a = polyline[index - 1], b = polyline[index];
198
+ const span = lengths[index] - lengths[index - 1];
199
+ const t = span ? (distance - lengths[index - 1]) / span : 0;
200
+ output.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
201
+ }
202
+ return output;
203
+ }
204
+
205
+ function readStyleCount(r) {
206
+ let count = r.readUI8();
207
+ if (count === 0xff) count = r.readUI16();
208
+ return count;
209
+ }
210
+
211
+ function readMorphFillStyle(r) {
212
+ const type = r.readUI8();
213
+ if (type === 0) {
214
+ const a = colorToCss(r.readRGBA()), b = colorToCss(r.readRGBA());
215
+ return { start: { type: 'solid', color: a }, end: { type: 'solid', color: b } };
216
+ }
217
+ if (type === 0x10 || type === 0x12 || type === 0x13) {
218
+ const startMatrix = r.readMatrix(), endMatrix = r.readMatrix();
219
+ const spreadMode = r.readUB(2), interpolationMode = r.readUB(2);
220
+ const n = r.readUB(4), startStops = [], endStops = [];
221
+ for (let i = 0; i < n; i++) {
222
+ startStops.push({ ratio: r.readUI8(), color: colorToCss(r.readRGBA()) });
223
+ endStops.push({ ratio: r.readUI8(), color: colorToCss(r.readRGBA()) });
224
+ }
225
+ const base = { type: type === 0x10 ? 'linear' : 'radial', spreadMode, interpolationMode };
226
+ const start = { ...base, matrix: startMatrix, stops: startStops };
227
+ const end = { ...base, matrix: endMatrix, stops: endStops };
228
+ if (type === 0x13) {
229
+ start.focal = r.readSI16() / 256;
230
+ end.focal = r.readSI16() / 256;
231
+ }
232
+ return { start, end };
233
+ }
234
+ if (type >= 0x40 && type <= 0x43) {
235
+ const bitmapId = r.readUI16(), startMatrix = r.readMatrix(), endMatrix = r.readMatrix();
236
+ const base = { type: 'bitmap', bitmapId, repeat: type === 0x40 || type === 0x42, smoothed: type === 0x40 || type === 0x41 };
237
+ return { start: { ...base, matrix: startMatrix }, end: { ...base, matrix: endMatrix } };
238
+ }
239
+ throw new Error(`Unsupported morph fill style ${type}`);
240
+ }
241
+
242
+ function readMorphLineStyle(r, v2) {
243
+ const startWidth = r.readUI16(), endWidth = r.readUI16();
244
+ if (v2) {
245
+ const startCap = r.readUB(2), join = r.readUB(2), hasFill = r.readUB(1);
246
+ const noHScale = !!r.readUB(1), noVScale = !!r.readUB(1), pixelHinting = !!r.readUB(1); r.readUB(5);
247
+ const noClose = !!r.readUB(1), endCap = r.readUB(2);
248
+ const miterLimit = join === 2 ? r.readUI16() / 256 : undefined;
249
+ r.align();
250
+ const common = { noClose, startCap, endCap, joinStyle: join, miterLimit, noHScale, noVScale, pixelHinting };
251
+ if (hasFill) {
252
+ const fill = readMorphFillStyle(r);
253
+ return {
254
+ start: { ...common, width: startWidth, color: fill.start.color, fill: fill.start },
255
+ end: { ...common, width: endWidth, color: fill.end.color, fill: fill.end },
256
+ };
257
+ }
258
+ return {
259
+ start: { ...common, width: startWidth, color: colorToCss(r.readRGBA()) },
260
+ end: { ...common, width: endWidth, color: colorToCss(r.readRGBA()) },
261
+ };
262
+ }
263
+ return { start: { width: startWidth, color: colorToCss(r.readRGBA()) }, end: { width: endWidth, color: colorToCss(r.readRGBA()) } };
264
+ }
265
+
266
+ function readMorphEdges(r, endShape) {
267
+ let fillBits = r.readUB(4), lineBits = r.readUB(4);
268
+ let x = 0, y = 0, fill0 = 0, fill1 = 0, line = 0;
269
+ let startsStroke = true;
270
+ const edges = [], styles = [];
271
+ while (!r.eof) {
272
+ const type = r.readUB(1);
273
+ if (!type) {
274
+ const newStyles = r.readUB(1), hasLine = r.readUB(1), hasFill1 = r.readUB(1), hasFill0 = r.readUB(1), hasMove = r.readUB(1);
275
+ if (!(newStyles || hasLine || hasFill1 || hasFill0 || hasMove)) break;
276
+ if (hasMove) {
277
+ const bits = r.readUB(5);
278
+ x = r.readSB(bits); y = r.readSB(bits);
279
+ startsStroke = true;
280
+ }
281
+ if (hasFill0) { const value = r.readUB(fillBits); if (!endShape) fill0 = value; }
282
+ if (hasFill1) { const value = r.readUB(fillBits); if (!endShape) fill1 = value; }
283
+ if (hasLine) {
284
+ const value = r.readUB(lineBits);
285
+ if (!endShape) {
286
+ startsStroke ||= line !== value;
287
+ line = value;
288
+ }
289
+ }
290
+ if (newStyles) throw new Error('NewStyles is invalid in morph edge records');
291
+ continue;
292
+ }
293
+ const straight = r.readUB(1), bits = r.readUB(4) + 2;
294
+ let edge;
295
+ if (straight) {
296
+ const general = r.readUB(1); let dx = 0, dy = 0;
297
+ if (general) { dx = r.readSB(bits); dy = r.readSB(bits); }
298
+ else if (r.readUB(1)) dy = r.readSB(bits); else dx = r.readSB(bits);
299
+ edge = { x0: x, y0: y, x1: x + dx, y1: y + dy }; x += dx; y += dy;
300
+ } else {
301
+ const cdx = r.readSB(bits), cdy = r.readSB(bits), adx = r.readSB(bits), ady = r.readSB(bits);
302
+ const cx = x + cdx, cy = y + cdy, x1 = cx + adx, y1 = cy + ady;
303
+ edge = { x0: x, y0: y, cx, cy, x1, y1 }; x = x1; y = y1;
304
+ }
305
+ edges.push(edge); styles.push({ fill0, fill1, line, startsStroke });
306
+ startsStroke = false;
307
+ }
308
+ r.align();
309
+ return { edges, styles };
310
+ }
311
+
312
+ function parsedMorphDraws(records, fills, lines, sharedStyles = records.styles) {
313
+ const fillEdges = [], strokes = [];
314
+ for (let i = 0; i < records.edges.length; i++) {
315
+ const edge = records.edges[i], style = sharedStyles[i];
316
+ if (style.fill1) fillEdges.push({ style: style.fill1, edge });
317
+ if (style.fill0) fillEdges.push({ style: style.fill0, edge: reverseEdge(edge) });
318
+ if (style.line) strokes.push({ style: style.line, edge, startsStroke: style.startsStroke || records.styles[i].startsStroke });
319
+ }
320
+ return buildDrawList({ fillStyles: fills, lineStyles: lines, fills: fillEdges, strokes }, true);
321
+ }
322
+
323
+ /**
324
+ * @param {BitReader} r
325
+ * @param {number} version
326
+ */
327
+ function parseShapeRecords(r, version) {
328
+ /** @type {FillStyle[]} */
329
+ let fillStyles = readFillStyleArray(r, version);
330
+ /** @type {LineStyle[]} */
331
+ let lineStyles = readLineStyleArray(r, version);
332
+ let numFillBits = r.readUB(4);
333
+ let numLineBits = r.readUB(4);
334
+
335
+ /** @type {{ style: number, edge: Edge }[]} */
336
+ const fills = [];
337
+ /** @type {StrokeEdge[]} */
338
+ const strokes = [];
339
+
340
+ // Style indices are 1-based into the *current* style arrays. When NewStyles
341
+ // appears, arrays are replaced — we offset so indices stay unique globally.
342
+ let fillOffset = 0;
343
+ let lineOffset = 0;
344
+ /** @type {FillStyle[]} */
345
+ const allFills = fillStyles.slice();
346
+ /** @type {LineStyle[]} */
347
+ const allLines = lineStyles.slice();
348
+
349
+ let fill0 = 0;
350
+ let fill1 = 0;
351
+ let line = 0;
352
+ let x = 0;
353
+ let y = 0;
354
+ let startsStroke = true;
355
+
356
+ for (;;) {
357
+ const typeFlag = r.readUB(1);
358
+ if (typeFlag === 0) {
359
+ const stateNewStyles = r.readUB(1);
360
+ const stateLineStyle = r.readUB(1);
361
+ const stateFillStyle1 = r.readUB(1);
362
+ const stateFillStyle0 = r.readUB(1);
363
+ const stateMoveTo = r.readUB(1);
364
+
365
+ if (!stateNewStyles && !stateLineStyle && !stateFillStyle1 && !stateFillStyle0 && !stateMoveTo) {
366
+ break; // EndShapeRecord
367
+ }
368
+
369
+ if (stateMoveTo) {
370
+ const moveBits = r.readUB(5);
371
+ x = r.readSB(moveBits);
372
+ y = r.readSB(moveBits);
373
+ startsStroke = true;
374
+ }
375
+ if (stateFillStyle0) fill0 = r.readUB(numFillBits);
376
+ if (stateFillStyle1) fill1 = r.readUB(numFillBits);
377
+ if (stateLineStyle) {
378
+ const nextLine = r.readUB(numLineBits);
379
+ startsStroke ||= line !== nextLine;
380
+ line = nextLine;
381
+ }
382
+
383
+ if (stateNewStyles) {
384
+ fillOffset = allFills.length;
385
+ lineOffset = allLines.length;
386
+ fillStyles = readFillStyleArray(r, version);
387
+ lineStyles = readLineStyleArray(r, version);
388
+ for (const fs of fillStyles) allFills.push(fs);
389
+ for (const ls of lineStyles) allLines.push(ls);
390
+ numFillBits = r.readUB(4);
391
+ numLineBits = r.readUB(4);
392
+ fill0 = 0;
393
+ fill1 = 0;
394
+ line = 0;
395
+ startsStroke = true;
396
+ }
397
+ continue;
398
+ }
399
+
400
+ const straightFlag = r.readUB(1);
401
+ const numBits = r.readUB(4) + 2;
402
+ /** @type {Edge} */
403
+ let edge;
404
+ if (straightFlag) {
405
+ const general = r.readUB(1);
406
+ let dx = 0;
407
+ let dy = 0;
408
+ if (general) {
409
+ dx = r.readSB(numBits);
410
+ dy = r.readSB(numBits);
411
+ } else if (r.readUB(1)) {
412
+ dy = r.readSB(numBits);
413
+ } else {
414
+ dx = r.readSB(numBits);
415
+ }
416
+ edge = { x0: x, y0: y, x1: x + dx, y1: y + dy };
417
+ x += dx;
418
+ y += dy;
419
+ } else {
420
+ const cdx = r.readSB(numBits);
421
+ const cdy = r.readSB(numBits);
422
+ const adx = r.readSB(numBits);
423
+ const ady = r.readSB(numBits);
424
+ const cx = x + cdx;
425
+ const cy = y + cdy;
426
+ const x1 = cx + adx;
427
+ const y1 = cy + ady;
428
+ edge = { x0: x, y0: y, cx, cy, x1, y1 };
429
+ x = x1;
430
+ y = y1;
431
+ }
432
+
433
+ // Map local 1-based style index → global 1-based into allFills/allLines
434
+ if (fill1 > 0) fills.push({ style: fillOffset + fill1, edge });
435
+ if (fill0 > 0) fills.push({ style: fillOffset + fill0, edge: reverseEdge(edge) });
436
+ if (line > 0) {
437
+ strokes.push({ style: lineOffset + line, edge, startsStroke });
438
+ startsStroke = false;
439
+ }
440
+ }
441
+
442
+ return { fillStyles: allFills, lineStyles: allLines, fills, strokes };
443
+ }
444
+
445
+ /**
446
+ * @param {Edge} e
447
+ * @returns {Edge}
448
+ */
449
+ function reverseEdge(e) {
450
+ if (e.cx != null && e.cy != null) {
451
+ return { x0: e.x1, y0: e.y1, cx: e.cx, cy: e.cy, x1: e.x0, y1: e.y0 };
452
+ }
453
+ return { x0: e.x1, y0: e.y1, x1: e.x0, y1: e.y0 };
454
+ }
455
+
456
+ /**
457
+ * @param {{ fillStyles: FillStyle[], lineStyles: LineStyle[], fills: {style:number,edge:Edge}[], strokes: StrokeEdge[] }} parsed
458
+ * @param {boolean} evenOdd
459
+ * @returns {ShapeDraw[]}
460
+ */
461
+ function buildDrawList(parsed, evenOdd) {
462
+ /** @type {ShapeDraw[]} */
463
+ const draws = [];
464
+ const { fillStyles, lineStyles, fills, strokes } = parsed;
465
+
466
+ /** @type {Map<number, Edge[]>} */
467
+ const byFill = new Map();
468
+ for (const { style, edge } of fills) {
469
+ if (!byFill.has(style)) byFill.set(style, []);
470
+ byFill.get(style).push(edge);
471
+ }
472
+
473
+ for (const idx of [...byFill.keys()].sort((a, b) => a - b)) {
474
+ const fs = fillStyles[idx - 1];
475
+ if (!fs) continue;
476
+ const path = edgesToPathCommands(byFill.get(idx), true);
477
+ if (!path.length) continue;
478
+ draws.push({ fill: serializeFill(fs), path, evenOdd });
479
+ }
480
+
481
+ /** @type {Map<number, StrokeEdge[]>} */
482
+ const byLine = new Map();
483
+ for (const stroke of strokes) {
484
+ if (!byLine.has(stroke.style)) byLine.set(stroke.style, []);
485
+ byLine.get(stroke.style).push(stroke);
486
+ }
487
+ for (const idx of [...byLine.keys()].sort((a, b) => a - b)) {
488
+ const ls = lineStyles[idx - 1];
489
+ if (!ls) continue;
490
+ const path = strokePathCommands(byLine.get(idx), !ls.noClose);
491
+ if (!path.length) continue;
492
+ draws.push({
493
+ stroke: { ...ls, width: ls.width / 20, fill: ls.fill ? serializeFill(ls.fill) : undefined },
494
+ path,
495
+ });
496
+ }
497
+
498
+ return draws;
499
+ }
500
+
501
+ /** Build each authored pen run without rejoining edges across a MoveTo or line-style change. */
502
+ function strokePathCommands(strokes, close) {
503
+ const path = [];
504
+ let first, last;
505
+ const finish = () => {
506
+ if (close && last && first.x0 === last.x1 && first.y0 === last.y1) path.push(['Z']);
507
+ };
508
+ for (const { edge, startsStroke } of strokes) {
509
+ if (startsStroke || !last || last.x1 !== edge.x0 || last.y1 !== edge.y0) {
510
+ finish();
511
+ first = edge;
512
+ path.push(['M', edge.x0 / 20, edge.y0 / 20]);
513
+ }
514
+ emitEdge(path, edge, 20);
515
+ last = edge;
516
+ }
517
+ finish();
518
+ return path;
519
+ }
520
+
521
+ /**
522
+ * @param {FillStyle} fs
523
+ * @returns {FillStyle}
524
+ */
525
+ function serializeFill(fs) {
526
+ if (fs.type === 'solid') return fs;
527
+ if (fs.type === 'linear' || fs.type === 'radial') {
528
+ return {
529
+ type: fs.type,
530
+ matrix: scaleMatrixToPixels(fs.matrix, 20),
531
+ stops: fs.stops,
532
+ focal: fs.focal,
533
+ spreadMode: fs.spreadMode,
534
+ interpolationMode: fs.interpolationMode,
535
+ };
536
+ }
537
+ if (fs.type === 'bitmap') {
538
+ return {
539
+ type: 'bitmap',
540
+ bitmapId: fs.bitmapId,
541
+ matrix: scaleMatrixToPixels(fs.matrix),
542
+ repeat: fs.repeat,
543
+ smoothed: fs.smoothed,
544
+ };
545
+ }
546
+ return fs;
547
+ }
548
+
549
+ /**
550
+ * Convert the destination from twips to pixels. The renderer uses pixels for
551
+ * both the gradient square and image samples. SWF gradient coordinates use
552
+ * twips, while SWF bitmap coordinates are already image pixels.
553
+ */
554
+ function scaleMatrixToPixels(m, sourceUnitsPerPixel = 1) {
555
+ if (!m) return { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 };
556
+ const divisor = 20 / sourceUnitsPerPixel;
557
+ return {
558
+ a: m.a / divisor,
559
+ b: m.b / divisor,
560
+ c: m.c / divisor,
561
+ d: m.d / divisor,
562
+ tx: m.tx / 20,
563
+ ty: m.ty / 20,
564
+ };
565
+ }
566
+
567
+ /**
568
+ * @param {Edge[]} edges
569
+ * @param {boolean} close
570
+ * @returns {PathCmd[]}
571
+ */
572
+ function edgesToPathCommands(edges, close, coordinateScale = 20) {
573
+ if (!edges || !edges.length) return [];
574
+ const used = new Uint8Array(edges.length);
575
+ /** @type {PathCmd[]} */
576
+ const cmds = [];
577
+
578
+ for (let start = 0; start < edges.length; start++) {
579
+ if (used[start]) continue;
580
+ used[start] = 1;
581
+ let e = edges[start];
582
+ cmds.push(['M', e.x0 / coordinateScale, e.y0 / coordinateScale]);
583
+ emitEdge(cmds, e, coordinateScale);
584
+ let x = e.x1;
585
+ let y = e.y1;
586
+ const sx = e.x0;
587
+ const sy = e.y0;
588
+ let guard = edges.length + 2;
589
+ while (guard-- > 0) {
590
+ if (close && approx(x, sx) && approx(y, sy)) {
591
+ cmds.push(['Z']);
592
+ break;
593
+ }
594
+ let next = -1;
595
+ for (let j = 0; j < edges.length; j++) {
596
+ if (used[j]) continue;
597
+ const cand = edges[j];
598
+ if (approx(cand.x0, x) && approx(cand.y0, y)) {
599
+ next = j;
600
+ break;
601
+ }
602
+ }
603
+ if (next < 0) break;
604
+ used[next] = 1;
605
+ e = edges[next];
606
+ emitEdge(cmds, e, coordinateScale);
607
+ x = e.x1;
608
+ y = e.y1;
609
+ }
610
+ }
611
+ return cmds;
612
+ }
613
+
614
+ /** Decode a DefineFont glyph SHAPE into EM-square path commands. */
615
+ export function decodeGlyphShape(rawData) {
616
+ const r = new BitReader(rawData);
617
+ let fillBits = r.readUB(4), lineBits = r.readUB(4);
618
+ let fill0 = 0, fill1 = 0, line = 0, x = 0, y = 0;
619
+ const fills = [];
620
+ while (!r.eof) {
621
+ const typeFlag = r.readUB(1);
622
+ if (!typeFlag) {
623
+ const newStyles = r.readUB(1), hasLine = r.readUB(1), hasFill1 = r.readUB(1), hasFill0 = r.readUB(1), hasMove = r.readUB(1);
624
+ if (!(newStyles || hasLine || hasFill1 || hasFill0 || hasMove)) break;
625
+ if (hasMove) { const bits = r.readUB(5); x = r.readSB(bits); y = r.readSB(bits); }
626
+ if (hasFill0) fill0 = r.readUB(fillBits);
627
+ if (hasFill1) fill1 = r.readUB(fillBits);
628
+ if (hasLine) line = r.readUB(lineBits);
629
+ if (newStyles) throw new Error('Glyph shapes cannot contain NewStyles records');
630
+ continue;
631
+ }
632
+ const straight = r.readUB(1), bits = r.readUB(4) + 2;
633
+ let edge;
634
+ if (straight) {
635
+ const general = r.readUB(1); let dx = 0, dy = 0;
636
+ if (general) { dx = r.readSB(bits); dy = r.readSB(bits); }
637
+ else if (r.readUB(1)) dy = r.readSB(bits); else dx = r.readSB(bits);
638
+ edge = { x0: x, y0: y, x1: x + dx, y1: y + dy }; x += dx; y += dy;
639
+ } else {
640
+ const cdx = r.readSB(bits), cdy = r.readSB(bits), adx = r.readSB(bits), ady = r.readSB(bits);
641
+ const cx = x + cdx, cy = y + cdy, x1 = cx + adx, y1 = cy + ady;
642
+ edge = { x0: x, y0: y, cx, cy, x1, y1 }; x = x1; y = y1;
643
+ }
644
+ if (fill1) fills.push(edge);
645
+ if (fill0) fills.push(reverseEdge(edge));
646
+ // Glyph SHAPEs have no line styles, but consume the record if one is present.
647
+ if (line) throw new Error('Glyph outline unexpectedly uses a line style');
648
+ }
649
+ const path = edgesToPathCommands(fills, true, 1);
650
+ return path.length ? { path } : null;
651
+ }
652
+
653
+ /** @param {PathCmd[]} cmds @param {Edge} e @param {number} TW */
654
+ function emitEdge(cmds, e, TW) {
655
+ if (e.cx != null && e.cy != null) {
656
+ cmds.push(['Q', e.cx / TW, e.cy / TW, e.x1 / TW, e.y1 / TW]);
657
+ } else {
658
+ cmds.push(['L', e.x1 / TW, e.y1 / TW]);
659
+ }
660
+ }
661
+
662
+ /** @param {number} a @param {number} b */
663
+ function approx(a, b) {
664
+ return Math.abs(a - b) < 0.1;
665
+ }
666
+
667
+ // --- low-level readers ---
668
+
669
+ /** @param {BitReader} r @param {number} version */
670
+ function readFillStyleArray(r, version) {
671
+ r.align();
672
+ let count = r.readUI8();
673
+ if (version >= 2 && count === 0xff) count = r.readUI16();
674
+ /** @type {FillStyle[]} */
675
+ const styles = [];
676
+ for (let i = 0; i < count; i++) styles.push(readFillStyle(r, version));
677
+ return styles;
678
+ }
679
+
680
+ /** @param {BitReader} r @param {number} version @returns {FillStyle} */
681
+ function readFillStyle(r, version) {
682
+ const type = r.readUI8();
683
+ if (type === 0x00) {
684
+ return { type: 'solid', color: colorToCss(readColor(r, version >= 3)) };
685
+ }
686
+ if (type === 0x10 || type === 0x12 || type === 0x13) {
687
+ const matrix = r.readMatrix();
688
+ const grad = readGradient(r, version, type === 0x13);
689
+ return {
690
+ type: type === 0x10 ? 'linear' : 'radial',
691
+ matrix,
692
+ stops: grad.stops,
693
+ focal: grad.focal,
694
+ spreadMode: grad.spreadMode,
695
+ interpolationMode: grad.interpolationMode,
696
+ };
697
+ }
698
+ if (type >= 0x40 && type <= 0x43) {
699
+ const bitmapId = r.readUI16();
700
+ const matrix = r.readMatrix();
701
+ return {
702
+ type: 'bitmap',
703
+ bitmapId,
704
+ matrix,
705
+ repeat: type === 0x40 || type === 0x42,
706
+ smoothed: type === 0x40 || type === 0x41,
707
+ };
708
+ }
709
+ return { type: 'solid', color: 'rgba(0,0,0,0)' };
710
+ }
711
+
712
+ /** @param {BitReader} r @param {number} version @param {boolean} focal */
713
+ function readGradient(r, version, focal) {
714
+ r.align();
715
+ const spreadMode = r.readUB(2);
716
+ const interpolationMode = r.readUB(2);
717
+ const n = r.readUB(4);
718
+ /** @type {{ ratio: number, color: string }[]} */
719
+ const stops = [];
720
+ for (let i = 0; i < n; i++) {
721
+ stops.push({ ratio: r.readUI8(), color: colorToCss(readColor(r, version >= 3)) });
722
+ }
723
+ const focalPos = focal ? r.readSI16() / 256 : 0;
724
+ return { stops, focal: focalPos, spreadMode, interpolationMode };
725
+ }
726
+
727
+ /** @param {BitReader} r @param {number} version */
728
+ function readLineStyleArray(r, version) {
729
+ r.align();
730
+ let count = r.readUI8();
731
+ if (version >= 2 && count === 0xff) count = r.readUI16();
732
+ /** @type {LineStyle[]} */
733
+ const styles = [];
734
+ for (let i = 0; i < count; i++) {
735
+ styles.push(version >= 4 ? readLineStyle2(r, version) : readLineStyle(r, version));
736
+ }
737
+ return styles;
738
+ }
739
+
740
+ /** @param {BitReader} r @param {number} version @returns {LineStyle} */
741
+ function readLineStyle(r, version) {
742
+ return { width: r.readUI16(), color: colorToCss(readColor(r, version >= 3)) };
743
+ }
744
+
745
+ /** @param {BitReader} r @param {number} version @returns {LineStyle} */
746
+ function readLineStyle2(r, version) {
747
+ const width = r.readUI16();
748
+ const startCap = r.readUB(2);
749
+ const joinStyle = r.readUB(2);
750
+ const hasFill = r.readUB(1);
751
+ const noHScale = !!r.readUB(1);
752
+ const noVScale = !!r.readUB(1);
753
+ const pixelHinting = !!r.readUB(1);
754
+ r.readUB(5);
755
+ const noClose = !!r.readUB(1);
756
+ const endCap = r.readUB(2);
757
+ const miterLimit = joinStyle === 2 ? r.readUI16() / 256 : undefined;
758
+ let color;
759
+ let fill;
760
+ if (hasFill) {
761
+ fill = readFillStyle(r, version);
762
+ if (fill.type === 'solid') color = fill.color;
763
+ } else {
764
+ color = colorToCss(readColor(r, true));
765
+ }
766
+ return { width, color, fill, noClose, startCap, endCap, joinStyle, miterLimit, noHScale, noVScale, pixelHinting };
767
+ }
768
+
769
+ /** @param {BitReader} r @param {boolean} withAlpha */
770
+ function readColor(r, withAlpha) {
771
+ if (withAlpha) {
772
+ const c = r.readRGBA();
773
+ return { r: c.r, g: c.g, b: c.b, a: c.a };
774
+ }
775
+ const c = r.readRGB();
776
+ return { r: c.r, g: c.g, b: c.b, a: 255 };
777
+ }
778
+
779
+ /** @param {{ r: number, g: number, b: number, a?: number }} c */
780
+ function colorToCss(c) {
781
+ const a = c.a != null ? c.a / 255 : 1;
782
+ if (a >= 1) {
783
+ return '#' + [c.r, c.g, c.b].map((v) => v.toString(16).padStart(2, '0')).join('');
784
+ }
785
+ return `rgba(${c.r},${c.g},${c.b},${+(a.toFixed(4))})`;
786
+ }