@haiyue/animation-spec 0.1.0 → 0.2.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 (77) hide show
  1. package/README.md +40 -6
  2. package/SPECIFICATION.md +12 -2
  3. package/bin/hya-live2d-convert.mjs +76 -0
  4. package/bin/{hya-convert.mjs → hya-lottie-convert.mjs} +1 -1
  5. package/dist/chunks/binary-DvuTJ_hy.js +1 -0
  6. package/dist/chunks/clip-baked-Dv-wjX9d.js +1 -0
  7. package/dist/chunks/errors-Bzs3GOD9.js +1 -0
  8. package/dist/chunks/expression-D1cKtNwM.js +1 -0
  9. package/dist/chunks/extensions-DxL4AxOC.js +1 -0
  10. package/dist/conversion.d.ts +1 -0
  11. package/dist/conversion.js +1 -0
  12. package/dist/cubism.d.ts +1 -0
  13. package/dist/cubism.js +1 -0
  14. package/dist/deformable2d.d.ts +1 -0
  15. package/dist/deformable2d.js +1 -0
  16. package/dist/index.d.ts +1 -10
  17. package/dist/index.js +1 -2927
  18. package/dist/live2d/clip-baked.d.ts +1 -0
  19. package/dist/live2d/clip-baked.js +1 -0
  20. package/dist/live2d.d.ts +1 -0
  21. package/dist/live2d.js +1 -0
  22. package/dist/lottie.d.ts +1 -62
  23. package/dist/lottie.js +1 -2642
  24. package/dist/native3d.d.ts +1 -2
  25. package/dist/native3d.js +1 -907
  26. package/dist/shared.d.ts +1493 -0
  27. package/package.json +30 -10
  28. package/schema/animation.schema.json +92 -0
  29. package/schema/deformable-mesh-2d-extension.schema.json +18 -0
  30. package/schema/deformable-mesh-2d.contract.json +58 -0
  31. package/schema/parameterized-rig-2d.contract.json +63 -0
  32. package/schema/parameterized-rig-2d.schema.json +57 -0
  33. package/schema/parameterized-rig-census-map.json +128 -0
  34. package/schema/responsive-layout-2d-census-map.json +49 -0
  35. package/schema/responsive-layout-2d.contract.json +58 -0
  36. package/schema/responsive-layout-2d.schema.json +34 -0
  37. package/schema/state-machine-v2-census-map.json +1 -0
  38. package/schema/state-machine-v2.contract.json +66 -0
  39. package/schema/state-machine-v2.schema.json +55 -0
  40. package/schema/vector-visual-census-map.json +120 -0
  41. package/schema/vector-visual.contract.json +47 -0
  42. package/schema/vector-visual.schema.json +72 -0
  43. package/dist/binary.d.ts +0 -7
  44. package/dist/chunks/types-l6nBVYwx.js +0 -8
  45. package/dist/chunks/types-l6nBVYwx.js.map +0 -1
  46. package/dist/errors.d.ts +0 -7
  47. package/dist/extensions.d.ts +0 -19
  48. package/dist/index.js.map +0 -1
  49. package/dist/lottie-merge-path.d.ts +0 -11
  50. package/dist/lottie.js.map +0 -1
  51. package/dist/native3d/Animation3DError.d.ts +0 -8
  52. package/dist/native3d/Animation3DParser.d.ts +0 -7
  53. package/dist/native3d/Animation3DTypes.d.ts +0 -285
  54. package/dist/native3d/index.d.ts +0 -5
  55. package/dist/native3d.js.map +0 -1
  56. package/dist/parser.d.ts +0 -2
  57. package/dist/state-machine.d.ts +0 -130
  58. package/dist/text-selector.d.ts +0 -2
  59. package/dist/types.d.ts +0 -419
  60. package/dist/validation.d.ts +0 -32
  61. package/src/binary.ts +0 -1441
  62. package/src/errors.ts +0 -18
  63. package/src/extensions.ts +0 -55
  64. package/src/index.ts +0 -90
  65. package/src/lottie-merge-path.ts +0 -204
  66. package/src/lottie.ts +0 -3073
  67. package/src/native3d/Animation3DError.ts +0 -20
  68. package/src/native3d/Animation3DParser.ts +0 -964
  69. package/src/native3d/Animation3DTypes.ts +0 -322
  70. package/src/native3d/index.ts +0 -14
  71. package/src/native3d.ts +0 -2
  72. package/src/parser.ts +0 -41
  73. package/src/state-machine.ts +0 -645
  74. package/src/text-selector.ts +0 -7
  75. package/src/types.ts +0 -483
  76. package/src/validation.ts +0 -1286
  77. package/test/fixtures/basic-lottie.json +0 -31
package/dist/lottie.js CHANGED
@@ -1,2642 +1 @@
1
- import { A as ANIMATION_VERSION, a as ANIMATION_FORMAT, b as ANIMATION_VECTOR_SHAPE_EXTENSION_ID } from './chunks/types-l6nBVYwx.js';
2
- import polygonClippingRuntime from 'polygon-clipping/dist/polygon-clipping.esm.js';
3
-
4
- // polygon-clipping publishes root declarations, but its ESM bundle subpath has
5
- // no adjacent .d.ts. Importing the ESM file avoids selecting the browser UMD
6
- // build while the public root types below keep the call surface checked.
7
- // @ts-expect-error The package does not map declarations for its ESM subpath.
8
- const polygonClipping = polygonClippingRuntime;
9
- /** Performs Lottie Merge/Add/Subtract/Intersect/Exclude on static path operands. */
10
- function mergeStaticVectorPaths(operands, mode) {
11
- const paths = operands.flat();
12
- if (mode === 1) {
13
- return paths.length === 0 ? null : {
14
- commands: paths.map(path => path.commands).join(''),
15
- values: paths.flatMap(path => Array.from(path.values)),
16
- };
17
- }
18
- const geometries = operands.map(pathsToMultiPolygon).filter(geometry => geometry.length > 0);
19
- if (geometries.length === 0)
20
- return null;
21
- const [first, ...rest] = geometries;
22
- const merged = mode === 2
23
- ? polygonClipping.union(first, ...rest)
24
- : mode === 3
25
- ? polygonClipping.difference(first, ...rest)
26
- : mode === 4
27
- ? polygonClipping.intersection(first, ...rest)
28
- : polygonClipping.xor(first, ...rest);
29
- return multiPolygonToPath(merged);
30
- }
31
- function identityMatrix() {
32
- return [1, 0, 0, 1, 0, 0];
33
- }
34
- function translationMatrix(x, y) {
35
- return [1, 0, 0, 1, x, y];
36
- }
37
- function transformMatrix(position, anchor, scale, rotation) {
38
- const scaleX = (scale[0] ?? 100) / 100;
39
- const scaleY = (scale[1] ?? 100) / 100;
40
- const cosine = Math.cos(rotation);
41
- const sine = Math.sin(rotation);
42
- const a = cosine * scaleX;
43
- const b = sine * scaleX;
44
- const c = -sine * scaleY;
45
- const d = cosine * scaleY;
46
- const anchorX = anchor[0] ?? 0;
47
- const anchorY = anchor[1] ?? 0;
48
- return [
49
- a, b, c, d,
50
- (position[0] ?? 0) - a * anchorX - c * anchorY,
51
- (position[1] ?? 0) - b * anchorX - d * anchorY,
52
- ];
53
- }
54
- function transformStaticPath(path, matrix) {
55
- const [a, b, c, d, e, f] = matrix;
56
- const values = [];
57
- for (let index = 0; index < path.values.length; index += 2) {
58
- const x = path.values[index] ?? 0;
59
- const y = path.values[index + 1] ?? 0;
60
- values.push(a * x + c * y + e, b * x + d * y + f);
61
- }
62
- return { commands: path.commands, values };
63
- }
64
- function pathsToMultiPolygon(paths) {
65
- const polygons = paths.flatMap(path => flattenStaticPath(path).map(ring => [ring]));
66
- if (polygons.length <= 1)
67
- return polygons;
68
- return polygonClipping.union(polygons[0], ...polygons.slice(1));
69
- }
70
- function flattenStaticPath(path, tolerance = 0.35) {
71
- const rings = [];
72
- let valuesIndex = 0;
73
- let ring = [];
74
- let current = [0, 0];
75
- const nextPair = () => [Number(path.values[valuesIndex++] ?? 0), Number(path.values[valuesIndex++] ?? 0)];
76
- const finish = () => {
77
- if (ring.length < 3) {
78
- ring = [];
79
- return;
80
- }
81
- if (!samePair$1(ring[0], ring.at(-1)))
82
- ring.push([...ring[0]]);
83
- if (Math.abs(signedRingArea(ring)) > 1e-8)
84
- rings.push(ring);
85
- ring = [];
86
- };
87
- for (const command of path.commands) {
88
- if (command === 'M') {
89
- finish();
90
- current = nextPair();
91
- ring.push(current);
92
- }
93
- else if (command === 'L') {
94
- current = nextPair();
95
- ring.push(current);
96
- }
97
- else if (command === 'C') {
98
- const control1 = nextPair();
99
- const control2 = nextPair();
100
- const end = nextPair();
101
- flattenCubic(current, control1, control2, end, tolerance, ring);
102
- current = end;
103
- }
104
- else if (command === 'Q') {
105
- const control = nextPair();
106
- const end = nextPair();
107
- flattenQuadratic(current, control, end, tolerance, ring);
108
- current = end;
109
- }
110
- else if (command === 'Z') {
111
- finish();
112
- }
113
- }
114
- finish();
115
- return rings;
116
- }
117
- function flattenCubic(start, control1, control2, end, tolerance, output, depth = 0) {
118
- if (depth >= 10 || Math.max(pointLineDistance(control1, start, end), pointLineDistance(control2, start, end)) <= tolerance) {
119
- output.push(end);
120
- return;
121
- }
122
- const a = midpoint(start, control1);
123
- const b = midpoint(control1, control2);
124
- const c = midpoint(control2, end);
125
- const d = midpoint(a, b);
126
- const e = midpoint(b, c);
127
- const middle = midpoint(d, e);
128
- flattenCubic(start, a, d, middle, tolerance, output, depth + 1);
129
- flattenCubic(middle, e, c, end, tolerance, output, depth + 1);
130
- }
131
- function flattenQuadratic(start, control, end, tolerance, output, depth = 0) {
132
- if (depth >= 10 || pointLineDistance(control, start, end) <= tolerance) {
133
- output.push(end);
134
- return;
135
- }
136
- const a = midpoint(start, control);
137
- const b = midpoint(control, end);
138
- const middle = midpoint(a, b);
139
- flattenQuadratic(start, a, middle, tolerance, output, depth + 1);
140
- flattenQuadratic(middle, b, end, tolerance, output, depth + 1);
141
- }
142
- function pointLineDistance(point, start, end) {
143
- const dx = end[0] - start[0];
144
- const dy = end[1] - start[1];
145
- const length = Math.hypot(dx, dy);
146
- if (length <= 1e-12)
147
- return Math.hypot(point[0] - start[0], point[1] - start[1]);
148
- return Math.abs(dy * point[0] - dx * point[1] + end[0] * start[1] - end[1] * start[0]) / length;
149
- }
150
- function midpoint(a, b) {
151
- return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
152
- }
153
- function signedRingArea(ring) {
154
- let area = 0;
155
- for (let index = 0; index + 1 < ring.length; index++) {
156
- area += ring[index][0] * ring[index + 1][1] - ring[index + 1][0] * ring[index][1];
157
- }
158
- return area / 2;
159
- }
160
- function multiPolygonToPath(geometry) {
161
- let commands = '';
162
- const values = [];
163
- for (const polygon of geometry) {
164
- for (const sourceRing of polygon) {
165
- const ring = sourceRing.length > 1 && samePair$1(sourceRing[0], sourceRing.at(-1))
166
- ? sourceRing.slice(0, -1)
167
- : sourceRing;
168
- if (ring.length < 3)
169
- continue;
170
- commands += `M${'L'.repeat(ring.length - 1)}Z`;
171
- values.push(...ring.flat());
172
- }
173
- }
174
- return commands ? { commands, values } : null;
175
- }
176
- function samePair$1(a, b) {
177
- return Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6;
178
- }
179
-
180
- const VECTOR_STROKE_EXTENSION = 'org.haiyue.vector-stroke@1';
181
- const VECTOR_PATH_MORPH_EXTENSION = 'org.haiyue.vector-path-morph@1';
182
- const DATA_LAYER_EXTENSION = 'org.haiyue.data-layer@1';
183
- // Animated paths dominate compressed delivery because arbitrary Float32 mantissas
184
- // defeat gzip even when neighbouring keyframes are visually almost identical.
185
- // A 1/64 canvas-unit grid bounds source error to 1/128 px while making the pool
186
- // substantially more compressible. Static paths keep their authored precision.
187
- const ANIMATED_PATH_QUANTIZATION = 1 / 64;
188
- const MAX_ANIMATED_PATH_SEGMENTS = 256;
189
- /** Converts the runtime-relevant Lottie subset without importing a Lottie player. */
190
- function convertLottie(source, options = {}) {
191
- const root = typeof source === 'string' ? parseLottieJson(source) : source;
192
- const frameRate = positive(root.fr, '$.fr');
193
- const inFrame = finite(root.ip ?? 0, '$.ip');
194
- const outFrame = finite(root.op, '$.op');
195
- if (outFrame <= inFrame)
196
- throw new TypeError('Lottie op must be greater than ip.');
197
- const width = positive(root.w, '$.w');
198
- const height = positive(root.h, '$.h');
199
- const duration = (outFrame - inFrame) / frameRate;
200
- const rootTimeline = {
201
- frameRate,
202
- secondsOffset: -inFrame / frameRate,
203
- secondsPerFrame: 1 / frameRate,
204
- };
205
- const fontInventory = inspectLottieFonts(root, options.fonts);
206
- const fontConversion = convertFonts(root.fonts, options);
207
- const state = {
208
- frameRate,
209
- duration,
210
- diagnostics: [],
211
- tracks: [],
212
- timeline: rootTimeline,
213
- shapeCounter: 0,
214
- convertedLayerCount: 0,
215
- skippedLayerCount: 0,
216
- usesStrokeExtension: false,
217
- usesPathMorphExtension: false,
218
- usesVectorShapeExtension: false,
219
- usesDataLayerExtension: false,
220
- fonts: fontConversion.fonts,
221
- warnedFontSubstitutions: new Set(),
222
- };
223
- const layerValues = list(root.layers);
224
- const assetValues = list(root.assets);
225
- const assetsById = new Map();
226
- for (let index = 0; index < assetValues.length; index++) {
227
- const value = object(assetValues[index]);
228
- if (typeof value.id === 'string')
229
- assetsById.set(value.id, { value, index });
230
- }
231
- const audioResourceIds = collectReferencedAssetIds([layerValues, ...assetValues.map(asset => list(object(asset).layers))], 6);
232
- const dataResourceIds = collectReferencedAssetIds([layerValues, ...assetValues.map(asset => list(object(asset).layers))], 15);
233
- const resources = [...convertAssets(root.assets, options, audioResourceIds, dataResourceIds), ...fontConversion.resources];
234
- const nodes = [];
235
- convertLayerList(layerValues, {
236
- listPath: '$.layers',
237
- idPrefix: '',
238
- timeline: rootTimeline,
239
- compositionWidth: width,
240
- compositionHeight: height,
241
- precompStack: [],
242
- });
243
- const document = {
244
- format: ANIMATION_FORMAT,
245
- version: ANIMATION_VERSION,
246
- name: options.name ?? (typeof root.nm === 'string' ? root.nm : 'Converted Lottie'),
247
- canvas: { width, height, coordinateSystem: 'screen-y-down' },
248
- duration,
249
- frameRate,
250
- endBehavior: 'loop',
251
- resources,
252
- nodes,
253
- tracks: state.tracks,
254
- ...((state.usesStrokeExtension || state.usesPathMorphExtension || state.usesVectorShapeExtension || state.usesDataLayerExtension) ? {
255
- extensionsUsed: [
256
- ...(state.usesStrokeExtension ? [VECTOR_STROKE_EXTENSION] : []),
257
- ...(state.usesPathMorphExtension ? [VECTOR_PATH_MORPH_EXTENSION] : []),
258
- ...(state.usesVectorShapeExtension ? [ANIMATION_VECTOR_SHAPE_EXTENSION_ID] : []),
259
- ...(state.usesDataLayerExtension ? [DATA_LAYER_EXTENSION] : []),
260
- ],
261
- } : {}),
262
- };
263
- if (options.strict && state.diagnostics.length > 0) {
264
- const first = state.diagnostics[0];
265
- throw new TypeError(`Lottie conversion failed: ${first.message} (${first.path})`);
266
- }
267
- return Object.freeze({
268
- document,
269
- diagnostics: Object.freeze(state.diagnostics),
270
- convertedLayerCount: state.convertedLayerCount,
271
- skippedLayerCount: state.skippedLayerCount,
272
- fonts: fontInventory,
273
- });
274
- function convertLayerList(layerList, context) {
275
- const previousTimeline = state.timeline;
276
- state.timeline = context.timeline;
277
- try {
278
- const retainedLayerIndices = collectRetainedLayerIndices(layerList, context.listPath);
279
- const layerIds = new Map();
280
- for (let index = 0; index < layerList.length; index++) {
281
- const layer = object(layerList[index]);
282
- const layerIndex = integer(layer.ind ?? index + 1, `${context.listPath}[${index}].ind`);
283
- if (!retainedLayerIndices.has(layerIndex))
284
- continue;
285
- layerIds.set(layerIndex, `${context.idPrefix}layer:${layerIndex}`);
286
- }
287
- for (let sourceIndex = layerList.length - 1; sourceIndex >= 0; sourceIndex--) {
288
- const layer = object(layerList[sourceIndex]);
289
- const path = `${context.listPath}[${sourceIndex}]`;
290
- const layerIndex = integer(layer.ind ?? sourceIndex + 1, `${path}.ind`);
291
- if (!retainedLayerIndices.has(layerIndex))
292
- continue;
293
- const id = layerIds.get(layerIndex);
294
- const type = integer(layer.ty, `${path}.ty`);
295
- const transformOnly = layer.hd === true;
296
- const parentIndex = layer.parent === undefined ? undefined : integer(layer.parent, `${path}.parent`);
297
- const localParent = parentIndex === undefined ? undefined : layerIds.get(parentIndex);
298
- if (parentIndex !== undefined && !localParent) {
299
- warn(state, 'W_LOTTIE_MISSING_PARENT', `${path}.parent`, `Parent layer ${parentIndex} was not found.`);
300
- }
301
- const parent = localParent ?? context.fallbackParent;
302
- const layerTimeline = type === 0
303
- ? context.timeline
304
- : createOrdinaryLayerTimeline(layer, path, context.timeline, state);
305
- state.timeline = layerTimeline;
306
- try {
307
- const effects = transformOnly ? [] : convertLayerEffects(layer.ef, path, state);
308
- const tint = null;
309
- if (!transformOnly)
310
- diagnoseUnsupportedLayerFeatures(layer, path, type, state);
311
- const transform = convertTransform(layer.ks, path, id, state);
312
- const startFrame = finite(layer.ip ?? 0, `${path}.ip`);
313
- const endFrame = finite(layer.op ?? startFrame + context.timeline.frameRate * state.duration, `${path}.op`);
314
- const timing = convertNodeTiming(startFrame, endFrame, context.timeline, state.duration);
315
- const composite = transformOnly
316
- ? { nodes: [] }
317
- : convertLayerComposite(layer, sourceIndex, layerList, layerIds, id, path, context.listPath, state, context.compositionWidth, context.compositionHeight);
318
- const baseNode = {
319
- id,
320
- name: typeof layer.nm === 'string' ? layer.nm : id,
321
- start: timing.start,
322
- duration: timing.duration,
323
- transform,
324
- ...(parent ? { parent } : {}),
325
- ...(composite.value ? { composite: composite.value } : {}),
326
- ...(effects.length > 0 ? { effects } : {}),
327
- };
328
- // Bodymovin may hide a null/shape layer while still using it as a
329
- // transform parent. Preserve that hierarchy node, but never convert
330
- // the hidden layer's visual content, effects or composites.
331
- if (transformOnly) {
332
- nodes.push(baseNode);
333
- state.convertedLayerCount++;
334
- continue;
335
- }
336
- if (type === 0) {
337
- nodes.push(baseNode);
338
- nodes.push(...composite.nodes);
339
- state.convertedLayerCount++;
340
- expandPrecomp(layer, id, path, context);
341
- continue;
342
- }
343
- if (type === 1) {
344
- const solidWidth = positive(layer.sw, `${path}.sw`);
345
- const solidHeight = positive(layer.sh, `${path}.sh`);
346
- nodes.push({
347
- ...baseNode,
348
- components: [{
349
- type: 'shape2d', shape: 'rect', size: [solidWidth, solidHeight],
350
- position: [solidWidth / 2, solidHeight / 2], fill: applyTint(parseHexColor(layer.sc, `${path}.sc`), tint),
351
- }],
352
- });
353
- nodes.push(...composite.nodes);
354
- state.convertedLayerCount++;
355
- continue;
356
- }
357
- if (type === 2) {
358
- const refId = typeof layer.refId === 'string' ? layer.refId : '';
359
- const resource = resources.find(candidate => candidate.id === refId);
360
- if (!resource || resource.type !== 'image') {
361
- warn(state, 'W_LOTTIE_MISSING_IMAGE', `${path}.refId`, `Image asset "${refId}" was not found.`);
362
- nodes.push(baseNode);
363
- }
364
- else {
365
- const size = [
366
- resource.width ?? context.compositionWidth,
367
- resource.height ?? context.compositionHeight,
368
- ];
369
- nodes.push({ ...baseNode, components: [{ type: 'sprite2d', resource: refId, size, position: [size[0] / 2, size[1] / 2] }] });
370
- }
371
- nodes.push(...composite.nodes);
372
- state.convertedLayerCount++;
373
- continue;
374
- }
375
- if (type === 3) {
376
- nodes.push(baseNode);
377
- nodes.push(...composite.nodes);
378
- state.convertedLayerCount++;
379
- continue;
380
- }
381
- if (type === 4) {
382
- nodes.push(baseNode);
383
- const shapes = convertShapes(layer.shapes, id, path, state, tint);
384
- nodes.push(...shapes);
385
- nodes.push(...composite.nodes);
386
- if (!shapes.some(node => (node.components?.length ?? 0) > 0)
387
- && !hasOnlyIntentionallyInvisiblePaints(layer.shapes)
388
- && !hasOnlyIntentionallyEmptyPaths(layer.shapes)) {
389
- warn(state, 'W_LOTTIE_EMPTY_SHAPE', `${path}.shapes`, 'No supported filled vector shape was found.');
390
- }
391
- state.convertedLayerCount++;
392
- continue;
393
- }
394
- if (type === 5) {
395
- const text = convertText(layer.t, path, context.compositionWidth, state, tint);
396
- nodes.push(text ? { ...baseNode, components: [text] } : baseNode);
397
- nodes.push(...composite.nodes);
398
- if (!text)
399
- state.skippedLayerCount++;
400
- else
401
- state.convertedLayerCount++;
402
- continue;
403
- }
404
- if (type === 6) {
405
- const refId = typeof layer.refId === 'string' ? layer.refId : '';
406
- const resource = resources.find(candidate => candidate.id === refId);
407
- if (!resource || resource.type !== 'audio') {
408
- warn(state, 'W_LOTTIE_MISSING_AUDIO', `${path}.refId`, `Audio asset "${refId}" was not found.`);
409
- nodes.push(baseNode);
410
- }
411
- else {
412
- nodes.push({ ...baseNode, components: [{ type: 'audio', resource: refId, volume: 1, loop: false }] });
413
- }
414
- nodes.push(...composite.nodes);
415
- state.convertedLayerCount++;
416
- continue;
417
- }
418
- if (type === 15) {
419
- const refId = typeof layer.refId === 'string' ? layer.refId : '';
420
- const resource = resources.find(candidate => candidate.id === refId);
421
- if (!resource || resource.type !== 'binary') {
422
- warn(state, 'W_LOTTIE_MISSING_DATA', `${path}.refId`, `Data asset "${refId}" was not found.`);
423
- nodes.push(baseNode);
424
- }
425
- else {
426
- state.usesDataLayerExtension = true;
427
- nodes.push({
428
- ...baseNode,
429
- extensions: {
430
- [DATA_LAYER_EXTENSION]: {
431
- resource: refId,
432
- mediaType: resource.mimeType ?? 'application/octet-stream',
433
- },
434
- },
435
- });
436
- }
437
- nodes.push(...composite.nodes);
438
- state.convertedLayerCount++;
439
- continue;
440
- }
441
- nodes.push(baseNode);
442
- nodes.push(...composite.nodes);
443
- state.skippedLayerCount++;
444
- warn(state, 'W_LOTTIE_UNSUPPORTED_LAYER', `${path}.ty`, `Layer type ${type} is preserved as a transform-only node.`);
445
- }
446
- finally {
447
- state.timeline = context.timeline;
448
- }
449
- }
450
- }
451
- finally {
452
- state.timeline = previousTimeline;
453
- }
454
- }
455
- function expandPrecomp(layer, layerId, path, parentContext) {
456
- const refId = typeof layer.refId === 'string' ? layer.refId : '';
457
- const entry = assetsById.get(refId);
458
- if (!entry || !Array.isArray(entry.value.layers)) {
459
- state.skippedLayerCount++;
460
- warn(state, 'W_LOTTIE_MISSING_PRECOMP', `${path}.refId`, `Precomposition asset "${refId}" was not found.`);
461
- return;
462
- }
463
- if (parentContext.precompStack.includes(refId)) {
464
- state.skippedLayerCount++;
465
- warn(state, 'W_LOTTIE_PRECOMP_CYCLE', `${path}.refId`, `Precomposition cycle detected for asset "${refId}".`);
466
- return;
467
- }
468
- const stretch = finite(layer.sr ?? 1, `${path}.sr`);
469
- if (stretch <= 0) {
470
- state.skippedLayerCount++;
471
- warn(state, 'W_LOTTIE_INVALID_TIME_STRETCH', `${path}.sr`, 'Precomposition time stretch must be greater than zero.');
472
- return;
473
- }
474
- const startFrame = finite(layer.st ?? 0, `${path}.st`);
475
- const assetFrameRate = positive(entry.value.fr ?? parentContext.timeline.frameRate, `$.assets[${entry.index}].fr`);
476
- const timeline = {
477
- frameRate: assetFrameRate,
478
- secondsOffset: frameToSeconds(parentContext.timeline, startFrame),
479
- secondsPerFrame: parentContext.timeline.secondsPerFrame
480
- * parentContext.timeline.frameRate / assetFrameRate * stretch,
481
- };
482
- const contentTimeline = layer.tm === undefined || !isAnimated(layer.tm)
483
- ? timeline
484
- : createTimeRemappedTimeline(layer.tm, parentContext.timeline, assetFrameRate, `${path}.tm`, state) ?? timeline;
485
- convertLayerList(list(entry.value.layers), {
486
- listPath: `$.assets[${entry.index}].layers`,
487
- idPrefix: `${layerId}/`,
488
- fallbackParent: layerId,
489
- timeline: contentTimeline,
490
- compositionWidth: positive(entry.value.w ?? layer.w ?? parentContext.compositionWidth, `$.assets[${entry.index}].w`),
491
- compositionHeight: positive(entry.value.h ?? layer.h ?? parentContext.compositionHeight, `$.assets[${entry.index}].h`),
492
- precompStack: [...parentContext.precompStack, refId],
493
- });
494
- }
495
- }
496
- /** Returns the complete authored-font delivery inventory without converting geometry. */
497
- function inspectLottieFonts(source, mappings = {}) {
498
- const root = typeof source === 'string' ? parseLottieJson(source) : source;
499
- const usage = new Map();
500
- const visit = (value) => {
501
- if (!value || typeof value !== 'object')
502
- return;
503
- if (Array.isArray(value)) {
504
- for (const entry of value)
505
- visit(entry);
506
- return;
507
- }
508
- const record = value;
509
- if (typeof record.f === 'string' && typeof record.t === 'string') {
510
- usage.set(record.f, (usage.get(record.f) ?? 0) + 1);
511
- }
512
- for (const entry of Object.values(record))
513
- visit(entry);
514
- };
515
- visit(root.layers);
516
- visit(root.assets);
517
- const entries = list(object(root.fonts).list).map(object);
518
- const declared = new Set(entries.map(entry => typeof entry.fName === 'string' ? entry.fName : '').filter(Boolean));
519
- for (const used of usage.keys()) {
520
- if (!declared.has(used))
521
- entries.push({ fName: used, fFamily: used, fStyle: 'Regular' });
522
- }
523
- return Object.freeze(entries.flatMap(entry => {
524
- if (typeof entry.fName !== 'string' || !entry.fName)
525
- return [];
526
- const configured = mappings?.[entry.fName];
527
- const mapping = typeof configured === 'string' ? { uri: configured } : configured;
528
- const authoredFamily = typeof entry.fFamily === 'string' && entry.fFamily ? entry.fFamily : entry.fName;
529
- const authoredStyle = typeof entry.fStyle === 'string' ? entry.fStyle : 'Regular';
530
- const normalizedStyle = authoredStyle.toLowerCase();
531
- return [Object.freeze({
532
- name: entry.fName,
533
- authoredFamily,
534
- authoredStyle,
535
- ...(typeof entry.ascent === 'number' && Number.isFinite(entry.ascent) ? { authoredAscent: entry.ascent } : {}),
536
- usageCount: usage.get(entry.fName) ?? 0,
537
- mapped: mapping !== undefined,
538
- resolvedFamily: mapping?.family ?? authoredFamily,
539
- resolvedStyle: mapping?.style ?? (normalizedStyle.includes('italic') ? 'italic' : 'normal'),
540
- resolvedWeight: mapping?.weight ?? (normalizedStyle.includes('bold') || normalizedStyle.includes('demi') ? 700 : 400),
541
- ...(mapping ? { uri: mapping.uri, mimeType: mapping.mimeType ?? 'font/woff2' } : {}),
542
- ...(mapping?.integrity === undefined ? {} : { integrity: mapping.integrity }),
543
- ...(mapping?.metrics === undefined ? {} : { metrics: Object.freeze({ ...mapping.metrics }) }),
544
- })];
545
- }));
546
- }
547
- function convertLottieDocument(source, options = {}) {
548
- return convertLottie(source, options).document;
549
- }
550
- function convertFonts(value, options) {
551
- const fonts = new Map();
552
- const resources = [];
553
- for (const entry of list(object(value).list).map(object)) {
554
- if (typeof entry.fName !== 'string' || !entry.fName)
555
- continue;
556
- const configured = options.fonts?.[entry.fName];
557
- const configuration = typeof configured === 'string' ? { uri: configured } : configured;
558
- const authoredStyle = typeof entry.fStyle === 'string' ? entry.fStyle.toLowerCase() : '';
559
- const descriptor = {
560
- name: entry.fName,
561
- family: configuration?.family ?? (typeof entry.fFamily === 'string' && entry.fFamily ? entry.fFamily : entry.fName),
562
- style: configuration?.style ?? (authoredStyle.includes('italic') ? 'italic' : 'normal'),
563
- weight: configuration?.weight ?? (authoredStyle.includes('bold') ? 700 : 400),
564
- ...(configuration ? { resourceId: `font:${entry.fName}` } : {}),
565
- };
566
- fonts.set(entry.fName, descriptor);
567
- if (configuration)
568
- resources.push({
569
- id: descriptor.resourceId, type: 'binary', uri: configuration.uri,
570
- mimeType: configuration.mimeType ?? 'font/woff2',
571
- ...(configuration.integrity === undefined ? {} : { integrity: configuration.integrity }),
572
- });
573
- }
574
- return { fonts, resources };
575
- }
576
- function convertAssets(value, options, audioResourceIds, dataResourceIds) {
577
- const assets = [];
578
- const values = list(value);
579
- for (let index = 0; index < values.length; index++) {
580
- const asset = object(values[index]);
581
- if (typeof asset.id !== 'string' || typeof asset.p !== 'string')
582
- continue;
583
- const prefix = typeof asset.u === 'string' ? asset.u : '';
584
- const uri = asset.p.startsWith('data:') ? asset.p : resolveUri(options.imageBaseUrl ?? '', `${prefix}${asset.p}`);
585
- if (audioResourceIds.has(asset.id)) {
586
- assets.push({ id: asset.id, type: 'audio', uri });
587
- }
588
- else if (dataResourceIds.has(asset.id)) {
589
- const mimeType = asset.t === 3 || /\.json(?:$|[?#])/i.test(asset.p) ? 'application/json' : 'application/octet-stream';
590
- assets.push({ id: asset.id, type: 'binary', uri, mimeType });
591
- }
592
- else {
593
- assets.push({
594
- id: asset.id,
595
- type: 'image',
596
- uri,
597
- ...(typeof asset.w === 'number' && asset.w > 0 ? { width: asset.w } : {}),
598
- ...(typeof asset.h === 'number' && asset.h > 0 ? { height: asset.h } : {}),
599
- });
600
- }
601
- }
602
- return assets;
603
- }
604
- function collectReferencedAssetIds(layerLists, layerType) {
605
- const result = new Set();
606
- for (const layerList of layerLists) {
607
- for (const layerValue of layerList) {
608
- const layer = object(layerValue);
609
- if (layer.ty === layerType && typeof layer.refId === 'string')
610
- result.add(layer.refId);
611
- }
612
- }
613
- return result;
614
- }
615
- function convertText(value, path, canvasWidth, state, tint) {
616
- const textRoot = object(value);
617
- const textExpression = object(textRoot.d).x;
618
- if (typeof textExpression === 'string' && textExpression.trim().length > 0) {
619
- warn(state, 'W_LOTTIE_TEXT_EXPRESSION', `${path}.t.d.x`, 'Text document expressions are preserved as a precise diagnostic; HYA does not execute source scripts at runtime.');
620
- }
621
- const keyframes = list(object(textRoot.d).k).map(object);
622
- const documents = [];
623
- for (let index = 0; index < keyframes.length; index++) {
624
- const keyframe = keyframes[index];
625
- const document = object(keyframe.s);
626
- if (typeof document.t !== 'string') {
627
- warn(state, 'W_LOTTIE_INVALID_TEXT', `${path}.t.d.k[${index}].s`, 'Text document has no string value.');
628
- continue;
629
- }
630
- const converted = convertTextDocument(document, frameToSeconds(state.timeline, finite(keyframe.t ?? 0, `${path}.t.d.k[${index}].t`)), state, tint, `${path}.t.d.k[${index}].s`);
631
- if (documents.length > 0 && converted.time <= documents[documents.length - 1].time) {
632
- warn(state, 'W_LOTTIE_TEXT_DOCUMENT_TIME', `${path}.t.d.k[${index}].t`, 'Duplicate or reversed text document time was omitted.');
633
- continue;
634
- }
635
- documents.push(converted);
636
- }
637
- const first = documents[0];
638
- if (!first) {
639
- warn(state, 'W_LOTTIE_INVALID_TEXT', `${path}.t.d`, 'Text layer has no usable text document.');
640
- return null;
641
- }
642
- const source = object(keyframes[0]?.s);
643
- const declaredSize = numberList(source.sz);
644
- const width = declaredSize[0] && declaredSize[0] > 0
645
- ? declaredSize[0]
646
- : Math.min(canvasWidth, Math.max(64, Math.max(...documents.map(document => document.text.length)) * (first.fontSize ?? 32) * 0.7));
647
- const height = declaredSize[1] && declaredSize[1] > 0 ? declaredSize[1] : (first.lineHeight ?? (first.fontSize ?? 32) * 1.2) * 1.35;
648
- const animators = convertTextAnimators(textRoot.a, first.fontSize ?? 32, `${path}.t.a`, state);
649
- return {
650
- type: 'text2d', text: first.text, size: [width, height],
651
- ...(first.fontFamily === undefined ? {} : { fontFamily: first.fontFamily }),
652
- ...(first.fontSize === undefined ? {} : { fontSize: first.fontSize }),
653
- ...(first.fontWeight === undefined ? {} : { fontWeight: first.fontWeight }),
654
- ...(first.fontStyle === undefined ? {} : { fontStyle: first.fontStyle }),
655
- ...(first.fontResource === undefined ? {} : { fontResource: first.fontResource }),
656
- ...(first.lineHeight === undefined ? {} : { lineHeight: first.lineHeight }),
657
- ...(first.tracking === undefined ? {} : { tracking: first.tracking }),
658
- ...(first.textAlign === undefined ? {} : { textAlign: first.textAlign }),
659
- verticalAlign: 'middle', color: first.color ?? [1, 1, 1, 1],
660
- ...(documents.length > 1 ? { documents } : {}),
661
- ...(animators.length > 0 ? { animators } : {}),
662
- };
663
- }
664
- function convertTextDocument(document, time, state, tint, path) {
665
- const fontSize = typeof document.s === 'number' && document.s > 0 ? document.s : 32;
666
- const authoredFont = typeof document.f === 'string' ? document.f : '';
667
- const font = state.fonts.get(authoredFont);
668
- if (authoredFont && !font?.resourceId && !state.warnedFontSubstitutions.has(authoredFont)) {
669
- state.warnedFontSubstitutions.add(authoredFont);
670
- warn(state, 'W_LOTTIE_FONT_SUBSTITUTION', `${path}.f`, `Font "${authoredFont}" has no mapped web-font resource; runtime fallback metrics may differ.`);
671
- }
672
- const fill = numberList(document.fc);
673
- const justification = typeof document.j === 'number' ? document.j : 2;
674
- return {
675
- time: Math.max(0, time), text: document.t,
676
- fontFamily: font?.family ?? (authoredFont || 'sans-serif'), fontSize,
677
- fontWeight: font?.weight ?? 400, fontStyle: font?.style ?? 'normal',
678
- ...(font?.resourceId === undefined ? {} : { fontResource: font.resourceId }),
679
- lineHeight: typeof document.lh === 'number' && document.lh > 0 ? document.lh : fontSize * 1.2,
680
- tracking: finite(document.tr ?? 0, `${path}.tr`) * fontSize / 1000,
681
- textAlign: justification === 0 ? 'left' : justification === 1 ? 'right' : 'center',
682
- color: applyTint([
683
- clamp(fill[0] ?? 1, 0, 1), clamp(fill[1] ?? 1, 0, 1), clamp(fill[2] ?? 1, 0, 1), 1,
684
- ]),
685
- };
686
- }
687
- function convertTextAnimators(value, fontSize, path, state) {
688
- const result = [];
689
- const animators = list(value).map(object);
690
- for (let index = 0; index < animators.length; index++) {
691
- const source = animators[index];
692
- const animatorPath = `${path}[${index}]`;
693
- const selector = object(source.s);
694
- const selectorType = selector.t === undefined ? 0 : integer(selector.t, `${animatorPath}.s.t`);
695
- const basedOn = selector.b === undefined ? 1 : integer(selector.b, `${animatorPath}.s.b`);
696
- if (selectorType !== 0) {
697
- warn(state, 'W_LOTTIE_TEXT_SELECTOR', `${animatorPath}.s.t`, 'Expression text selectors are not executed; use an offline bake or a range selector.');
698
- continue;
699
- }
700
- const basedOnValue = [undefined, 'characters', 'characters-excluding-spaces', 'words', 'lines'][basedOn];
701
- if (!basedOnValue) {
702
- warn(state, 'W_LOTTIE_TEXT_SELECTOR', `${animatorPath}.s.b`, `Text selector based-on mode ${basedOn} is not supported.`);
703
- continue;
704
- }
705
- const animatedSelectorControl = [
706
- ['xe', selector.xe], ['ne', selector.ne], ['sm', selector.sm],
707
- ].find(([, property]) => isAnimated(property));
708
- if (animatedSelectorControl) {
709
- warn(state, 'W_LOTTIE_TEXT_SELECTOR', `${animatorPath}.s.${animatedSelectorControl[0]}`, 'Animated selector easing or smoothness requires offline baking.');
710
- continue;
711
- }
712
- const units = selector.r === 2 ? 'index' : 'percent';
713
- const normalizeSelector = (values) => [units === 'percent' ? (values[0] ?? 0) / 100 : values[0] ?? 0];
714
- const startProperty = selector.s;
715
- const endProperty = selector.e;
716
- const offsetProperty = selector.o;
717
- const amountProperty = selector.a;
718
- const start = normalizeSelector([readStaticScalar(startProperty, 0)])[0];
719
- const end = normalizeSelector([readStaticScalar(endProperty, units === 'percent' ? 100 : 0)])[0];
720
- const offset = normalizeSelector([readStaticScalar(offsetProperty, 0)])[0];
721
- const amount = clamp(readStaticScalar(amountProperty, 100) / 100, -1, 1);
722
- const shapeCode = selector.sh === undefined ? 1 : integer(selector.sh, `${animatorPath}.s.sh`);
723
- const shape = ['square', 'square', 'ramp-up', 'ramp-down', 'triangle', 'round', 'smooth'][shapeCode];
724
- if (!shape) {
725
- warn(state, 'W_LOTTIE_TEXT_SELECTOR', `${animatorPath}.s.sh`, `Range selector shape ${shapeCode} is not supported.`);
726
- continue;
727
- }
728
- const easeHigh = clamp(readStaticScalar(selector.xe, 0), -100, 100) / 100;
729
- const easeLow = clamp(readStaticScalar(selector.ne, 0), -100, 100) / 100;
730
- const easing = [
731
- easeLow > 0 ? easeLow : 0,
732
- easeLow < 0 ? -easeLow : 0,
733
- easeHigh > 0 ? 1 - easeHigh : 1,
734
- easeHigh < 0 ? 1 + easeHigh : 1,
735
- ];
736
- const smoothness = clamp(readStaticScalar(selector.sm, 100) / 100, 0, 1);
737
- const randomSeed = selector.rn === 1 ? stableUint32(animatorPath) : undefined;
738
- const animator = object(source.a);
739
- const position = readStaticVector(animator.p, [0, 0]);
740
- const scale = readStaticVector(animator.s, [100, 100]);
741
- const fill = readStaticVector(animator.fc, [1, 1, 1]);
742
- const startTrack = createInlineTrack(startProperty, state, `${animatorPath}.s.s`, normalizeSelector);
743
- const endTrack = createInlineTrack(endProperty, state, `${animatorPath}.s.e`, normalizeSelector);
744
- const offsetTrack = createInlineTrack(offsetProperty, state, `${animatorPath}.s.o`, normalizeSelector);
745
- const amountTrack = createInlineTrack(amountProperty, state, `${animatorPath}.s.a`, values => [clamp((values[0] ?? 100) / 100, -1, 1)]);
746
- const positionTrack = createInlineTrack(animator.p, state, `${animatorPath}.a.p`, values => [values[0] ?? 0, values[1] ?? 0]);
747
- const scaleTrack = createInlineTrack(animator.s, state, `${animatorPath}.a.s`, values => [(values[0] ?? 100) / 100, (values[1] ?? 100) / 100]);
748
- const rotationTrack = createInlineTrack(animator.r, state, `${animatorPath}.a.r`, values => [degreesToRadians(values[0] ?? 0)]);
749
- const opacityTrack = createInlineTrack(animator.o, state, `${animatorPath}.a.o`, values => [clamp((values[0] ?? 100) / 100, 0, 1)]);
750
- const fillColorTrack = createInlineTrack(animator.fc, state, `${animatorPath}.a.fc`, values => [
751
- clamp(values[0] ?? 1, 0, 1), clamp(values[1] ?? 1, 0, 1), clamp(values[2] ?? 1, 0, 1), 1,
752
- ]);
753
- const trackingTrack = createInlineTrack(animator.t, state, `${animatorPath}.a.t`, values => [(values[0] ?? 0) * fontSize / 1000]);
754
- result.push({
755
- selector: {
756
- start, end, offset, units, amount, shape, basedOn: basedOnValue,
757
- ...(easing[0] === 0 && easing[1] === 0 && easing[2] === 1 && easing[3] === 1 ? {} : { easing }),
758
- ...(smoothness === 1 ? {} : { smoothness }),
759
- ...(randomSeed === undefined ? {} : { randomSeed }),
760
- ...(startTrack ? { startTrack } : {}),
761
- ...(endTrack ? { endTrack } : {}),
762
- ...(offsetTrack ? { offsetTrack } : {}),
763
- ...(amountTrack ? { amountTrack } : {}),
764
- },
765
- ...(animator.p === undefined ? {} : { position: [position[0] ?? 0, position[1] ?? 0] }),
766
- ...(animator.s === undefined ? {} : { scale: [(scale[0] ?? 100) / 100, (scale[1] ?? 100) / 100] }),
767
- ...(animator.r === undefined ? {} : { rotation: degreesToRadians(readStaticScalar(animator.r, 0)) }),
768
- ...(animator.o === undefined ? {} : { opacity: clamp(readStaticScalar(animator.o, 100) / 100, 0, 1) }),
769
- ...(animator.fc === undefined ? {} : { fillColor: [clamp(fill[0] ?? 1, 0, 1), clamp(fill[1] ?? 1, 0, 1), clamp(fill[2] ?? 1, 0, 1), 1] }),
770
- ...(animator.t === undefined ? {} : { tracking: readStaticScalar(animator.t, 0) * fontSize / 1000 }),
771
- ...(positionTrack ? { positionTrack } : {}),
772
- ...(scaleTrack ? { scaleTrack } : {}),
773
- ...(rotationTrack ? { rotationTrack } : {}),
774
- ...(opacityTrack ? { opacityTrack } : {}),
775
- ...(fillColorTrack ? { fillColorTrack } : {}),
776
- ...(trackingTrack ? { trackingTrack } : {}),
777
- });
778
- }
779
- return result;
780
- }
781
- function convertTransform(value, path, node, state) {
782
- return convertTransformProperties(object(value), `${path}.ks`, node, state);
783
- }
784
- function collectRetainedLayerIndices(layerList, listPath) {
785
- const layersByIndex = new Map();
786
- const retained = new Set();
787
- for (let sourceIndex = 0; sourceIndex < layerList.length; sourceIndex++) {
788
- const layer = object(layerList[sourceIndex]);
789
- const layerIndex = integer(layer.ind ?? sourceIndex + 1, `${listPath}[${sourceIndex}].ind`);
790
- layersByIndex.set(layerIndex, { layer, sourceIndex });
791
- if (layer.hd !== true)
792
- retained.add(layerIndex);
793
- }
794
- // A hidden layer may still be the authored transform parent of a visible
795
- // layer. Retain the complete ancestor chain; unrelated hidden visual layers
796
- // remain omitted from the HYA document.
797
- const pending = [...retained];
798
- for (let cursor = 0; cursor < pending.length; cursor++) {
799
- const layerIndex = pending[cursor];
800
- const record = layersByIndex.get(layerIndex);
801
- if (!record || record.layer.parent === undefined)
802
- continue;
803
- const parentIndex = integer(record.layer.parent, `${listPath}[${record.sourceIndex}].parent`);
804
- if (!layersByIndex.has(parentIndex) || retained.has(parentIndex))
805
- continue;
806
- retained.add(parentIndex);
807
- pending.push(parentIndex);
808
- }
809
- return retained;
810
- }
811
- function convertTransformProperties(ks, path, node, state) {
812
- const position = readStaticVector(ks.p, [0, 0]);
813
- const scale = readStaticVector(ks.s, [100, 100]);
814
- const anchor = readStaticVector(ks.a, [0, 0]);
815
- const rotation = readStaticScalar(ks.r ?? ks.rz, 0);
816
- const opacity = readStaticScalar(ks.o, 100);
817
- appendTrack(ks.p, node, 'position', state, values => [values[0] ?? 0, values[1] ?? 0], `${path}.p`);
818
- appendTrack(ks.s, node, 'scale', state, values => [(values[0] ?? 100) / 100, (values[1] ?? 100) / 100], `${path}.s`);
819
- appendTrack(ks.r ?? ks.rz, node, 'rotation', state, values => [degreesToRadians(values[0] ?? 0)], `${path}.r`);
820
- appendTrack(ks.o, node, 'opacity', state, values => [clamp((values[0] ?? 100) / 100, 0, 1)], `${path}.o`);
821
- if (isAnimated(ks.a))
822
- warn(state, 'W_LOTTIE_ANIMATED_ANCHOR', `${path}.a`, 'Animated anchor points are sampled at their initial value.');
823
- return {
824
- position: [position[0] ?? 0, position[1] ?? 0],
825
- rotation: degreesToRadians(rotation),
826
- scale: [(scale[0] ?? 100) / 100, (scale[1] ?? 100) / 100],
827
- anchor: [anchor[0] ?? 0, anchor[1] ?? 0],
828
- opacity: clamp(opacity / 100, 0, 1),
829
- };
830
- }
831
- function convertShapes(value, parent, path, state, tint) {
832
- const result = [];
833
- visitShapeList(list(value), [], [], parent, `${path}.shapes`);
834
- return result;
835
- function visitShapeList(values, inheritedPaints, inheritedModifiers, nodeParent, listPath) {
836
- const localPaints = [];
837
- const localModifiers = [];
838
- for (let index = 0; index < values.length; index++) {
839
- const shape = object(values[index]);
840
- if (shape.hd === true)
841
- continue;
842
- if (shape.ty === 'fl') {
843
- localPaints.push({ index, paint: {
844
- kind: 'fill', fill: convertSolidFillStyle(shape, `${listPath}[${index}]`, state),
845
- fillRule: shape.r === 2 ? 'evenodd' : 'nonzero',
846
- } });
847
- }
848
- if (shape.ty === 'gf')
849
- localPaints.push({ index, paint: {
850
- kind: 'fill', fill: convertGradientFillStyle(shape, `${listPath}[${index}]`, state),
851
- fillRule: shape.r === 2 ? 'evenodd' : 'nonzero',
852
- } });
853
- if (shape.ty === 'st') {
854
- const stroke = convertStrokeStyle(shape, `${listPath}[${index}]`, state);
855
- if (stroke)
856
- localPaints.push({ index, paint: { kind: 'stroke', stroke } });
857
- }
858
- if (shape.ty === 'gs') {
859
- const stroke = convertGradientStrokeStyle(shape, `${listPath}[${index}]`, state);
860
- if (stroke)
861
- localPaints.push({ index, paint: { kind: 'stroke', stroke } });
862
- }
863
- const modifier = convertShapeModifier(shape, `${listPath}[${index}]`, state);
864
- if (modifier)
865
- localModifiers.push({ index, modifier });
866
- }
867
- const paintsFor = (shapeIndex) => [
868
- ...inheritedPaints,
869
- ...localPaints.filter(entry => entry.index > shapeIndex).map(entry => entry.paint),
870
- ];
871
- const modifiersFor = (shapeIndex) => [
872
- ...localModifiers.filter(entry => entry.index > shapeIndex).map(entry => entry.modifier),
873
- ...inheritedModifiers,
874
- ];
875
- const mergePlans = prepareStaticMergePlans(values, listPath, state);
876
- const mergedInputIndices = new Set([...mergePlans.values()].flatMap(plan => plan.inputIndices));
877
- for (let index = 0; index < values.length; index++) {
878
- const shape = object(values[index]);
879
- const shapePath = `${listPath}[${index}]`;
880
- if (shape.hd === true)
881
- continue;
882
- if (mergedInputIndices.has(index))
883
- continue;
884
- if (shape.ty === 'mm') {
885
- const plan = mergePlans.get(index);
886
- if (!plan)
887
- continue;
888
- const components = paintsFor(index).flatMap(paint => plan.prepared
889
- ? createPaintedPath(plan.prepared, paint, modifiersFor(index), state)
890
- : plan.path
891
- ? createPaintedStaticPath(plan.path, paint, modifiersFor(index), state)
892
- : []);
893
- if (components.length === 0)
894
- continue;
895
- const id = `${parent}:shape:${state.shapeCounter++}`;
896
- result.push({ id, name: typeof shape.nm === 'string' ? shape.nm : id, parent: nodeParent, components });
897
- continue;
898
- }
899
- if (shape.ty === 'gr') {
900
- const items = list(shape.it);
901
- const transformIndex = items.findIndex(item => object(item).ty === 'tr');
902
- const groupId = `${parent}:group:${state.shapeCounter++}`;
903
- const groupNode = {
904
- id: groupId,
905
- name: typeof shape.nm === 'string' ? shape.nm : groupId,
906
- parent: nodeParent,
907
- };
908
- if (transformIndex >= 0) {
909
- const transform = object(items[transformIndex]);
910
- groupNode.transform = convertTransformProperties(transform, `${shapePath}.it[${transformIndex}]`, groupId, state);
911
- if (isAnimated(transform.sk) || isAnimated(transform.sa)
912
- || Math.abs(readStaticScalar(transform.sk, 0)) > 1e-6
913
- || Math.abs(readStaticScalar(transform.sa, 0)) > 1e-6) {
914
- warn(state, 'W_LOTTIE_GROUP_SKEW', `${shapePath}.it[${transformIndex}]`, 'Shape group skew is not converted.');
915
- }
916
- }
917
- result.push(groupNode);
918
- visitShapeList(items, paintsFor(index), modifiersFor(index), groupId, `${shapePath}.it`);
919
- continue;
920
- }
921
- if (shape.ty === 'sh') {
922
- const prepared = preparePaintedPath(shape.ks, `${shapePath}.ks`, state);
923
- const components = prepared ? paintsFor(index).flatMap(paint => (createPaintedPath(prepared, paint, modifiersFor(index), state))) : [];
924
- if (components.length === 0)
925
- continue;
926
- const id = `${parent}:shape:${state.shapeCounter++}`;
927
- result.push({ id, name: typeof shape.nm === 'string' ? shape.nm : id, parent: nodeParent, components });
928
- continue;
929
- }
930
- if (shape.ty === 'sr') {
931
- const paints = paintsFor(index);
932
- if (paints.length === 0)
933
- continue;
934
- const pathData = convertPolystarPath(shape, shapePath, state);
935
- if (!pathData)
936
- continue;
937
- const id = `${parent}:shape:${state.shapeCounter++}`;
938
- const position = readStaticVector(shape.p, [0, 0]);
939
- const rotation = readStaticScalar(shape.r, 0);
940
- appendTrack(shape.p, id, 'position', state, values => [values[0] ?? 0, values[1] ?? 0], `${shapePath}.p`);
941
- appendTrack(shape.r, id, 'rotation', state, values => [degreesToRadians(values[0] ?? 0)], `${shapePath}.r`);
942
- result.push({
943
- id,
944
- name: typeof shape.nm === 'string' ? shape.nm : id,
945
- parent: nodeParent,
946
- transform: { position: [position[0] ?? 0, position[1] ?? 0], rotation: degreesToRadians(rotation) },
947
- components: paints.flatMap(paint => createPaintedStaticPath(pathData, paint, modifiersFor(index), state)),
948
- });
949
- continue;
950
- }
951
- if (shape.ty !== 'rc' && shape.ty !== 'el') {
952
- if (!['fl', 'gf', 'st', 'gs', 'tr', 'tm', 'rd', 'mm'].includes(String(shape.ty)))
953
- warn(state, 'W_LOTTIE_UNSUPPORTED_SHAPE', `${shapePath}.ty`, `Shape operator "${String(shape.ty)}" is not converted.`);
954
- continue;
955
- }
956
- const paints = paintsFor(index);
957
- if (paints.length === 0)
958
- continue;
959
- const size = readFirstPositiveVector(shape.s, 2) ?? readStaticVector(shape.s, [0, 0]);
960
- const position = readStaticVector(shape.p, [0, 0]);
961
- if ((size[0] ?? 0) <= 0 || (size[1] ?? 0) <= 0) {
962
- warn(state, 'W_LOTTIE_INVALID_SHAPE_SIZE', `${shapePath}.s`, 'Shape has no positive static size.');
963
- continue;
964
- }
965
- const id = `${parent}:shape:${state.shapeCounter++}`;
966
- const radius = shape.ty === 'rc' ? Math.max(0, readStaticScalar(shape.r, 0)) : 0;
967
- const pathData = shape.ty === 'rc'
968
- ? roundedRectanglePath(size[0], size[1], radius)
969
- : ellipsePath(size[0] / 2, size[1] / 2);
970
- const components = paints.flatMap(paint => createPaintedStaticPath(pathData, paint, modifiersFor(index), state));
971
- appendTrack(shape.p, id, 'position', state, values => [values[0] ?? 0, values[1] ?? 0], `${shapePath}.p`);
972
- appendTrack(shape.s, id, 'scale', state, values => [
973
- (values[0] ?? size[0]) / size[0],
974
- (values[1] ?? size[1]) / size[1],
975
- ], `${shapePath}.s`);
976
- if (shape.ty === 'rc' && isAnimated(shape.r))
977
- warn(state, 'W_LOTTIE_ANIMATED_ROUNDED_RECT', `${shapePath}.r`, 'Animated corner radius is sampled at its initial value.');
978
- result.push({
979
- id,
980
- name: typeof shape.nm === 'string' ? shape.nm : id,
981
- parent: nodeParent,
982
- transform: { position: [position[0] ?? 0, position[1] ?? 0] },
983
- components,
984
- });
985
- }
986
- }
987
- }
988
- function hasOnlyIntentionallyInvisiblePaints(value) {
989
- const paints = [];
990
- const visit = (items) => {
991
- for (const entry of items) {
992
- const shape = object(entry);
993
- if (shape.hd === true)
994
- continue;
995
- if (shape.ty === 'gr')
996
- visit(list(shape.it));
997
- else if (shape.ty === 'fl' || shape.ty === 'gf' || shape.ty === 'st' || shape.ty === 'gs')
998
- paints.push(shape);
999
- }
1000
- };
1001
- visit(list(value));
1002
- if (paints.length === 0)
1003
- return false;
1004
- return paints.every(paint => {
1005
- const opacityVisible = (readFirstPositiveVector(paint.o, 1)?.[0] ?? readStaticScalar(paint.o, 100)) > 0;
1006
- if (!opacityVisible)
1007
- return true;
1008
- if (paint.ty === 'st' || paint.ty === 'gs') {
1009
- return readFirstPositiveVector(paint.w, 1) === undefined;
1010
- }
1011
- if (paint.ty === 'fl') {
1012
- const color = readStaticVector(paint.c, [1, 1, 1, 1]);
1013
- return (color[3] ?? 1) <= 0;
1014
- }
1015
- return false;
1016
- });
1017
- }
1018
- function hasOnlyIntentionallyEmptyPaths(value) {
1019
- let pathCount = 0;
1020
- let hasRenderableGeometry = false;
1021
- const visit = (items) => {
1022
- for (const entry of items) {
1023
- const shape = object(entry);
1024
- if (shape.hd === true)
1025
- continue;
1026
- if (shape.ty === 'gr') {
1027
- visit(list(shape.it));
1028
- continue;
1029
- }
1030
- if (shape.ty === 'sh') {
1031
- pathCount++;
1032
- if (!isIntentionallyEmptyPathProperty(shape.ks))
1033
- hasRenderableGeometry = true;
1034
- continue;
1035
- }
1036
- if (shape.ty === 'rc' || shape.ty === 'el' || shape.ty === 'sr' || shape.ty === 'mm') {
1037
- hasRenderableGeometry = true;
1038
- }
1039
- }
1040
- };
1041
- visit(list(value));
1042
- return pathCount > 0 && !hasRenderableGeometry;
1043
- }
1044
- function isIntentionallyEmptyPathProperty(value) {
1045
- const property = object(value);
1046
- if (!isAnimated(property))
1047
- return isIntentionallyEmptyShape(readStaticShape(value));
1048
- const shapes = [];
1049
- for (const keyframe of list(property.k).map(object)) {
1050
- for (const candidate of [keyframe.s, keyframe.e]) {
1051
- if (candidate === undefined)
1052
- continue;
1053
- const shape = object(list(candidate)[0] ?? candidate);
1054
- if (Object.keys(shape).length > 0)
1055
- shapes.push(shape);
1056
- }
1057
- }
1058
- return shapes.length > 0 && shapes.every(isIntentionallyEmptyShape);
1059
- }
1060
- function isIntentionallyEmptyShape(shape) {
1061
- return Array.isArray(shape.v) && shape.v.length === 0
1062
- && Array.isArray(shape.i) && shape.i.length === 0
1063
- && Array.isArray(shape.o) && shape.o.length === 0;
1064
- }
1065
- function prepareStaticMergePlans(values, listPath, state) {
1066
- const plans = new Map();
1067
- let boundary = 0;
1068
- for (let index = 0; index < values.length; index++) {
1069
- const operator = object(values[index]);
1070
- if (operator.ty !== 'mm' || operator.hd === true)
1071
- continue;
1072
- const operatorPath = `${listPath}[${index}]`;
1073
- const inputIndices = [];
1074
- let unsupportedModifier;
1075
- for (let inputIndex = boundary; inputIndex < index; inputIndex++) {
1076
- const input = object(values[inputIndex]);
1077
- if (input.hd === true)
1078
- continue;
1079
- if (isMergeGeometryShape(input.ty))
1080
- inputIndices.push(inputIndex);
1081
- else if (['tm', 'rd', 'rp', 'pb', 'zz', 'op', 'tw'].includes(String(input.ty))) {
1082
- unsupportedModifier = String(input.ty);
1083
- }
1084
- }
1085
- boundary = index + 1;
1086
- if (inputIndices.length === 0) {
1087
- warn(state, 'W_LOTTIE_MERGE_PATH_INPUT', operatorPath, 'Merge Paths has no preceding path geometry to combine.');
1088
- continue;
1089
- }
1090
- if (unsupportedModifier) {
1091
- warn(state, 'W_LOTTIE_MERGE_PATH_INPUT', operatorPath, `Merge Paths cannot yet bake the preceding "${unsupportedModifier}" modifier.`);
1092
- continue;
1093
- }
1094
- const mode = typeof operator.mm === 'number' && Number.isInteger(operator.mm) ? operator.mm : 1;
1095
- if (mode < 1 || mode > 5) {
1096
- warn(state, 'W_LOTTIE_MERGE_PATH_INPUT', `${operatorPath}.mm`, `Unknown Merge Paths mode "${String(operator.mm)}".`);
1097
- continue;
1098
- }
1099
- const operands = inputIndices.map(inputIndex => collectStaticMergeOperand(object(values[inputIndex]), `${listPath}[${inputIndex}]`, state));
1100
- if (operands.some(operand => operand.animated)) {
1101
- const prepared = mode === 1
1102
- ? prepareAnimatedCompoundMerge(values, inputIndices, listPath, state)
1103
- : undefined;
1104
- if (prepared)
1105
- plans.set(index, { inputIndices, prepared });
1106
- else
1107
- warn(state, 'W_LOTTIE_ANIMATED_MERGE_PATH', operatorPath, mode === 1
1108
- ? 'Animated Merge Paths could not be baked into a stable compound morph.'
1109
- : `Animated Merge Paths mode ${mode} requires time-varying boolean topology and remains unmerged.`);
1110
- continue;
1111
- }
1112
- const unsupported = operands.find(operand => operand.unsupportedReason)?.unsupportedReason;
1113
- if (unsupported) {
1114
- warn(state, 'W_LOTTIE_MERGE_PATH_INPUT', operatorPath, unsupported);
1115
- continue;
1116
- }
1117
- try {
1118
- plans.set(index, {
1119
- inputIndices,
1120
- ...(mergeStaticOperands(operands, mode) ?? {}),
1121
- });
1122
- }
1123
- catch (error) {
1124
- warn(state, 'W_LOTTIE_MERGE_PATH_GEOMETRY', operatorPath, `Static Merge Paths boolean failed: ${error instanceof Error ? error.message : String(error)}`);
1125
- }
1126
- }
1127
- return plans;
1128
- }
1129
- function prepareAnimatedCompoundMerge(values, inputIndices, listPath, state) {
1130
- const paths = [];
1131
- for (const inputIndex of inputIndices) {
1132
- const shape = object(values[inputIndex]);
1133
- // Mode 1 is a source-order compound path. Direct path operands preserve
1134
- // that contract exactly. Animated primitives and group transforms need a
1135
- // separate transform sampler and therefore retain the precise diagnostic.
1136
- if (shape.ty !== 'sh')
1137
- return undefined;
1138
- const path = preparePaintedPath(shape.ks, `${listPath}[${inputIndex}].ks`, state);
1139
- if (!path)
1140
- return undefined;
1141
- paths.push(path);
1142
- }
1143
- if (paths.length === 0)
1144
- return undefined;
1145
- const commands = paths.map(path => path.commands).join('');
1146
- const dynamic = paths.filter(path => path.morph !== undefined);
1147
- if (dynamic.length === 0)
1148
- return {
1149
- sourcePath: listPath,
1150
- commands,
1151
- values: paths.flatMap(path => path.values),
1152
- closed: paths.every(path => path.closed),
1153
- };
1154
- const firstTime = Math.min(...dynamic.map(path => path.morph.times[0]));
1155
- const lastTime = Math.max(...dynamic.map(path => path.morph.times.at(-1)));
1156
- const sampleTimes = new Set();
1157
- for (const path of dynamic)
1158
- for (const time of path.morph.times)
1159
- sampleTimes.add(Math.fround(time));
1160
- // A compound morph owns one interpolation mode while its source paths may
1161
- // have unrelated easings. Bake at the authored frame cadence: every rendered
1162
- // source frame remains exact and linear reconstruction spans at most one
1163
- // frame rather than assigning a false shared easing curve.
1164
- const frameDuration = 1 / Math.max(1, state.frameRate);
1165
- const firstFrame = Math.ceil(firstTime / frameDuration - 1e-6);
1166
- const lastFrame = Math.floor(lastTime / frameDuration + 1e-6);
1167
- if (lastFrame - firstFrame + 1 > 1024)
1168
- return undefined;
1169
- for (let frame = firstFrame; frame <= lastFrame; frame++) {
1170
- sampleTimes.add(Math.fround(clamp(frame * frameDuration, 0, state.duration)));
1171
- }
1172
- const times = [...sampleTimes]
1173
- .filter(time => time >= 0 && time <= state.duration)
1174
- .sort((a, b) => a - b)
1175
- .filter((time, index, entries) => index === 0 || time > entries[index - 1]);
1176
- if (times.length === 0)
1177
- return undefined;
1178
- const packedValues = [];
1179
- for (const time of times) {
1180
- for (const path of paths) {
1181
- packedValues.push(...(path.morph ? sampleLottieVectorTrack(path.morph, time) : path.values));
1182
- }
1183
- }
1184
- const valueSize = paths.reduce((sum, path) => sum + path.values.length, 0);
1185
- return {
1186
- sourcePath: listPath,
1187
- commands,
1188
- values: packedValues.slice(0, valueSize),
1189
- closed: paths.every(path => path.closed),
1190
- morph: { times, values: packedValues, valueSize, interpolation: 'linear' },
1191
- };
1192
- }
1193
- function sampleLottieVectorTrack(track, time) {
1194
- const times = track.times;
1195
- let frame = 0;
1196
- if (time >= times[times.length - 1])
1197
- frame = times.length - 1;
1198
- else
1199
- while (frame + 1 < times.length && time >= times[frame + 1])
1200
- frame++;
1201
- const next = Math.min(frame + 1, times.length - 1);
1202
- let progress = 0;
1203
- if (next !== frame && track.interpolation !== 'step') {
1204
- progress = clamp((time - times[frame]) / Math.max(1e-8, times[next] - times[frame]), 0, 1);
1205
- if (track.interpolation === 'cubic-bezier' && track.easings) {
1206
- const offset = frame * 4;
1207
- progress = cubicBezierProgress(progress, track.easings[offset] ?? 0.333, track.easings[offset + 1] ?? 0.333, track.easings[offset + 2] ?? 0.667, track.easings[offset + 3] ?? 0.667);
1208
- }
1209
- }
1210
- const result = new Array(track.valueSize);
1211
- const offset = frame * track.valueSize;
1212
- const nextOffset = next * track.valueSize;
1213
- for (let component = 0; component < track.valueSize; component++) {
1214
- const from = track.values[offset + component] ?? 0;
1215
- result[component] = from + ((track.values[nextOffset + component] ?? from) - from) * progress;
1216
- }
1217
- return result;
1218
- }
1219
- function isMergeGeometryShape(type) {
1220
- return type === 'sh' || type === 'rc' || type === 'el' || type === 'sr' || type === 'gr';
1221
- }
1222
- function collectStaticMergeOperand(shape, path, state) {
1223
- if (shape.ty === 'sh') {
1224
- if (isAnimated(shape.ks))
1225
- return { paths: [], animated: true };
1226
- const converted = convertShapePath(readStaticShape(shape.ks), `${path}.ks`, state, false, false);
1227
- return converted
1228
- ? { paths: [converted], animated: false }
1229
- : { paths: [], animated: false, unsupportedReason: `Merge Paths input at ${path} is not valid path geometry.` };
1230
- }
1231
- if (shape.ty === 'rc' || shape.ty === 'el') {
1232
- if ([shape.s, shape.p, ...(shape.ty === 'rc' ? [shape.r] : [])].some(isAnimated)) {
1233
- return { paths: [], animated: true };
1234
- }
1235
- const size = readStaticVector(shape.s, [0, 0]);
1236
- if ((size[0] ?? 0) <= 0 || (size[1] ?? 0) <= 0) {
1237
- return { paths: [], animated: false, unsupportedReason: `Merge Paths primitive at ${path} has no positive size.` };
1238
- }
1239
- const generated = shape.ty === 'rc'
1240
- ? roundedRectanglePath(size[0], size[1], Math.max(0, readStaticScalar(shape.r, 0)))
1241
- : ellipsePath(size[0] / 2, size[1] / 2);
1242
- const position = readStaticVector(shape.p, [0, 0]);
1243
- return { paths: [transformStaticPath(generated, translationMatrix(position[0] ?? 0, position[1] ?? 0))], animated: false };
1244
- }
1245
- if (shape.ty === 'sr') {
1246
- if ([shape.pt, shape.or, shape.ir, shape.is, shape.os, shape.p, shape.r].some(isAnimated)) {
1247
- return { paths: [], animated: true };
1248
- }
1249
- const generated = convertPolystarPath(shape, path, state);
1250
- if (!generated)
1251
- return { paths: [], animated: false, unsupportedReason: `Merge Paths polystar at ${path} is invalid.` };
1252
- const position = readStaticVector(shape.p, [0, 0]);
1253
- const rotation = degreesToRadians(readStaticScalar(shape.r, 0));
1254
- return {
1255
- paths: [transformStaticPath(generated, transformMatrix(position, [0, 0], [100, 100], rotation))],
1256
- animated: false,
1257
- };
1258
- }
1259
- if (shape.ty === 'gr') {
1260
- const items = list(shape.it);
1261
- const transformEntry = items.map(object).find(item => item.ty === 'tr');
1262
- if (transformEntry && [
1263
- transformEntry.p, transformEntry.a, transformEntry.s, transformEntry.r ?? transformEntry.rz,
1264
- transformEntry.sk, transformEntry.sa,
1265
- ].some(isAnimated))
1266
- return { paths: [], animated: true };
1267
- if (transformEntry && (Math.abs(readStaticScalar(transformEntry.sk, 0)) > 1e-6
1268
- || Math.abs(readStaticScalar(transformEntry.sa, 0)) > 1e-6)) {
1269
- return { paths: [], animated: false, unsupportedReason: `Merge Paths group at ${path} uses skew, which is not safe to bake.` };
1270
- }
1271
- const childShapes = items.map((item, index) => ({ item: object(item), index }))
1272
- .filter(entry => entry.item.hd !== true && isMergeGeometryShape(entry.item.ty));
1273
- const unsupportedOperator = items.map(object).find(item => item.hd !== true
1274
- && ['mm', 'tm', 'rd', 'rp', 'pb', 'zz', 'op', 'tw'].includes(String(item.ty)));
1275
- if (unsupportedOperator) {
1276
- return { paths: [], animated: false, unsupportedReason: `Nested Merge Paths input at ${path} contains the "${String(unsupportedOperator.ty)}" operator.` };
1277
- }
1278
- const children = childShapes.map(child => collectStaticMergeOperand(child.item, `${path}.it[${child.index}]`, state));
1279
- if (children.some(child => child.animated))
1280
- return { paths: [], animated: true };
1281
- const unsupportedReason = children.find(child => child.unsupportedReason)?.unsupportedReason;
1282
- if (unsupportedReason)
1283
- return { paths: [], animated: false, unsupportedReason };
1284
- const matrix = transformEntry
1285
- ? transformMatrix(readStaticVector(transformEntry.p, [0, 0]), readStaticVector(transformEntry.a, [0, 0]), readStaticVector(transformEntry.s, [100, 100]), degreesToRadians(readStaticScalar(transformEntry.r ?? transformEntry.rz, 0)))
1286
- : identityMatrix();
1287
- return {
1288
- paths: children.flatMap(child => child.paths).map(child => transformStaticPath(child, matrix)),
1289
- animated: false,
1290
- };
1291
- }
1292
- return { paths: [], animated: false, unsupportedReason: `Merge Paths input at ${path} is not supported.` };
1293
- }
1294
- function mergeStaticOperands(operands, mode) {
1295
- const path = mergeStaticVectorPaths(operands.map(operand => operand.paths), mode);
1296
- return path ? { path } : null;
1297
- }
1298
- function convertSolidFillStyle(shape, path, state, tint) {
1299
- const color = readStaticVector(shape.c, [1, 1, 1, 1]);
1300
- const opacity = clamp(readStaticScalar(shape.o, 100) / 100, 0, 1);
1301
- const base = applyTint([
1302
- clamp(color[0] ?? 1, 0, 1), clamp(color[1] ?? 1, 0, 1), clamp(color[2] ?? 1, 0, 1),
1303
- clamp(color[3] ?? 1, 0, 1),
1304
- ]);
1305
- const colorTrack = createInlineTrack(shape.c, state, `${path}.c`, values => {
1306
- const converted = applyTint([
1307
- clamp(values[0] ?? 1, 0, 1), clamp(values[1] ?? 1, 0, 1), clamp(values[2] ?? 1, 0, 1), clamp(values[3] ?? 1, 0, 1),
1308
- ]);
1309
- return [...converted];
1310
- });
1311
- const opacityTrack = createInlineTrack(shape.o, state, `${path}.o`, values => [clamp((values[0] ?? 100) / 100, 0, 1)]);
1312
- return { kind: 'solid', color: base, opacity, ...(colorTrack ? { colorTrack } : {}), ...(opacityTrack ? { opacityTrack } : {}) };
1313
- }
1314
- function convertGradientFillStyle(shape, path, state, tint) {
1315
- const gradient = object(shape.g);
1316
- if (shape.t === 2 && (isAnimated(shape.h) || isAnimated(shape.a)
1317
- || Math.abs(readStaticScalar(shape.h, 0)) > 1e-6
1318
- || Math.abs(readStaticScalar(shape.a, 0)) > 1e-6)) {
1319
- warn(state, 'W_LOTTIE_GRADIENT_HIGHLIGHT', path, 'Radial gradient highlight length and angle are not converted.');
1320
- }
1321
- const authoredStopCount = Math.max(2, integer(gradient.p ?? 2, `${path}.g.p`));
1322
- const stopCount = Math.min(8, authoredStopCount);
1323
- if (authoredStopCount > 8) {
1324
- warn(state, 'W_LOTTIE_GRADIENT_STOP_LIMIT', `${path}.g.p`, 'Gradient is resampled to the eight-stop HYA runtime budget.');
1325
- }
1326
- const property = gradient.k;
1327
- const opacity = clamp(readStaticScalar(shape.o, 100) / 100, 0, 1);
1328
- const stops = convertGradientStops(readStaticVector(property, []), authoredStopCount, stopCount);
1329
- const start = readStaticVector(shape.s, [0, 0]);
1330
- const end = readStaticVector(shape.e, [100, 0]);
1331
- const stopsTrack = createInlineTrack(property, state, `${path}.g.k`, values => convertGradientStops(values, authoredStopCount, stopCount));
1332
- const startTrack = createInlineTrack(shape.s, state, `${path}.s`, values => [values[0] ?? 0, values[1] ?? 0]);
1333
- const endTrack = createInlineTrack(shape.e, state, `${path}.e`, values => [values[0] ?? 0, values[1] ?? 0]);
1334
- const opacityTrack = createInlineTrack(shape.o, state, `${path}.o`, values => [clamp((values[0] ?? 100) / 100, 0, 1)]);
1335
- return {
1336
- kind: shape.t === 2 ? 'radial-gradient' : 'linear-gradient',
1337
- start: [start[0] ?? 0, start[1] ?? 0],
1338
- end: [end[0] ?? 100, end[1] ?? 0],
1339
- stops,
1340
- opacity,
1341
- ...(startTrack ? { startTrack } : {}),
1342
- ...(endTrack ? { endTrack } : {}),
1343
- ...(stopsTrack ? { stopsTrack } : {}),
1344
- ...(opacityTrack ? { opacityTrack } : {}),
1345
- };
1346
- }
1347
- function convertGradientStops(values, authoredStopCount, stopCount, tint) {
1348
- const colorStopCount = Math.min(authoredStopCount, Math.floor(values.length / 4));
1349
- const opacityValues = values.slice(colorStopCount * 4);
1350
- const opacityAt = (offset) => {
1351
- if (opacityValues.length < 2)
1352
- return 1;
1353
- let cursor = 0;
1354
- while (cursor + 3 < opacityValues.length && opacityValues[cursor + 2] <= offset)
1355
- cursor += 2;
1356
- const fromOffset = opacityValues[Math.max(0, cursor)] ?? 0;
1357
- const fromOpacity = (opacityValues[Math.max(0, cursor) + 1] ?? 1);
1358
- const toOffset = opacityValues[Math.min(opacityValues.length - 2, cursor + 2)] ?? fromOffset;
1359
- const toOpacity = opacityValues[Math.min(opacityValues.length - 1, cursor + 3)] ?? fromOpacity;
1360
- const progress = toOffset <= fromOffset ? 0 : clamp((offset - fromOffset) / (toOffset - fromOffset), 0, 1);
1361
- return clamp(fromOpacity + (toOpacity - fromOpacity) * progress, 0, 1);
1362
- };
1363
- const colorAt = (offset) => {
1364
- if (colorStopCount === 0)
1365
- return [1, 1, 1];
1366
- let from = 0;
1367
- while (from + 1 < colorStopCount && (values[(from + 1) * 4] ?? 1) <= offset)
1368
- from++;
1369
- const to = Math.min(colorStopCount - 1, from + 1);
1370
- const fromOffset = values[from * 4] ?? 0;
1371
- const toOffset = values[to * 4] ?? fromOffset;
1372
- const progress = toOffset <= fromOffset ? 0 : clamp((offset - fromOffset) / (toOffset - fromOffset), 0, 1);
1373
- return [1, 2, 3].map(channel => clamp((values[from * 4 + channel] ?? 1)
1374
- + ((values[to * 4 + channel] ?? values[from * 4 + channel] ?? 1) - (values[from * 4 + channel] ?? 1)) * progress, 0, 1));
1375
- };
1376
- const result = [];
1377
- for (let index = 0; index < stopCount; index++) {
1378
- const source = stopCount === colorStopCount ? index : -1;
1379
- const offset = clamp(source >= 0 ? values[source * 4] ?? 0 : index / Math.max(1, stopCount - 1), 0, 1);
1380
- const sampled = colorAt(offset);
1381
- const converted = applyTint([
1382
- sampled[0], sampled[1], sampled[2],
1383
- opacityAt(offset),
1384
- ]);
1385
- result.push(offset, ...converted);
1386
- }
1387
- return result;
1388
- }
1389
- function convertGradientStrokeStyle(shape, path, state, tint) {
1390
- const base = convertStrokeStyle({ ...shape, c: { a: 0, k: [1, 1, 1, 1] } }, path, state);
1391
- if (!base)
1392
- return null;
1393
- return { ...base, gradient: convertGradientFillStyle(shape, path, state) };
1394
- }
1395
- function preparePaintedPath(value, path, state) {
1396
- if (isAnimated(value)) {
1397
- const morph = convertAnimatedPathData(value, path, state, false);
1398
- if (morph)
1399
- return {
1400
- sourcePath: path,
1401
- commands: morph.commands,
1402
- values: morph.values.slice(0, morph.valueSize),
1403
- closed: morph.commands.endsWith('Z'),
1404
- morph: {
1405
- times: morph.times,
1406
- values: morph.values,
1407
- valueSize: morph.valueSize,
1408
- interpolation: morph.interpolation,
1409
- ...(morph.easings ? { easings: morph.easings } : {}),
1410
- },
1411
- };
1412
- }
1413
- const shape = readStaticShape(value);
1414
- const converted = convertShapePath(shape, path, state, false, false);
1415
- return converted ? { sourcePath: path, commands: converted.commands, values: Array.from(converted.values), closed: shape.c !== false } : null;
1416
- }
1417
- function createPaintedPath(prepared, paint, modifiers, state) {
1418
- const renderPath = paint.kind === 'fill' ? closePreparedPath(prepared, state) : prepared;
1419
- const relativeMorph = renderPath.morph
1420
- ? makeRelativeMorphTrack(renderPath.morph, renderPath.values)
1421
- : undefined;
1422
- const advanced = prepared.morph !== undefined || modifiers.length > 0
1423
- || (paint.kind === 'fill' && (paint.fill.kind !== 'solid' || paint.fill.colorTrack !== undefined || paint.fill.opacityTrack !== undefined))
1424
- || (paint.kind === 'stroke' && hasAnimatedStrokeStyle(paint.stroke));
1425
- if (!advanced) {
1426
- if (paint.kind === 'fill' && paint.fill.kind === 'solid')
1427
- return [{
1428
- type: 'path2d', commands: renderPath.commands, values: renderPath.values,
1429
- fill: [
1430
- paint.fill.color[0], paint.fill.color[1], paint.fill.color[2],
1431
- paint.fill.color[3] * (paint.fill.opacity ?? 1),
1432
- ],
1433
- fillRule: paint.fillRule,
1434
- }];
1435
- if (paint.kind === 'stroke') {
1436
- return [createStrokeExtensionComponent(renderPath.commands, renderPath.values, paint.stroke, state)];
1437
- }
1438
- }
1439
- state.usesVectorShapeExtension = true;
1440
- return [{
1441
- type: ANIMATION_VECTOR_SHAPE_EXTENSION_ID,
1442
- commands: renderPath.commands,
1443
- values: renderPath.values,
1444
- ...(relativeMorph ? { morph: relativeMorph, morphRelative: true } : {}),
1445
- ...(paint.kind === 'fill' ? { fill: paint.fill } : { stroke: toVectorStrokePaint(paint.stroke) }),
1446
- ...(modifiers.length > 0 ? { modifiers } : {}),
1447
- fillRule: paint.kind === 'fill' ? paint.fillRule : 'nonzero',
1448
- tolerance: 0.35,
1449
- }];
1450
- }
1451
- /**
1452
- * Store animated path samples as deltas from the component base pose. Lottie
1453
- * paths commonly repeat most coordinates between frames, so this preserves
1454
- * the runtime ABI while producing long zero runs that compress efficiently.
1455
- */
1456
- function makeRelativeMorphTrack(morph, baseValues) {
1457
- const values = Array.from(morph.values, (value, index) => (quantizeAnimatedPathCoordinate(value - (baseValues[index % morph.valueSize] ?? 0))));
1458
- return {
1459
- times: morph.times,
1460
- values,
1461
- valueSize: morph.valueSize,
1462
- interpolation: morph.interpolation,
1463
- ...(morph.easings ? { easings: morph.easings } : {}),
1464
- };
1465
- }
1466
- function closePreparedPath(prepared, state) {
1467
- if (prepared.closed)
1468
- return prepared;
1469
- warn(state, 'W_LOTTIE_OPEN_FILLED_PATH', prepared.sourcePath, 'Open filled path is closed with a straight segment.');
1470
- const closeValues = (values) => [...values, values[0] ?? 0, values[1] ?? 0];
1471
- if (!prepared.morph)
1472
- return {
1473
- commands: `${prepared.commands}LZ`,
1474
- values: closeValues(prepared.values),
1475
- closed: true,
1476
- sourcePath: prepared.sourcePath,
1477
- };
1478
- const values = [];
1479
- for (let frame = 0; frame < prepared.morph.times.length; frame++) {
1480
- const start = frame * prepared.morph.valueSize;
1481
- values.push(...closeValues(Array.from(prepared.morph.values).slice(start, start + prepared.morph.valueSize)));
1482
- }
1483
- return {
1484
- commands: `${prepared.commands}LZ`,
1485
- values: closeValues(prepared.values),
1486
- closed: true,
1487
- sourcePath: prepared.sourcePath,
1488
- morph: {
1489
- ...prepared.morph,
1490
- values,
1491
- valueSize: prepared.morph.valueSize + 2,
1492
- },
1493
- };
1494
- }
1495
- function createPaintedStaticPath(path, paint, modifiers, state) {
1496
- return createPaintedPath({ sourcePath: '$generated', commands: path.commands, values: Array.from(path.values), closed: path.commands.endsWith('Z') }, paint, modifiers, state);
1497
- }
1498
- function convertShapeModifier(shape, path, state) {
1499
- if (shape.ty === 'tm') {
1500
- const startTrack = createInlineTrack(shape.s, state, `${path}.s`, values => [(values[0] ?? 0) / 100]);
1501
- const endTrack = createInlineTrack(shape.e, state, `${path}.e`, values => [(values[0] ?? 100) / 100]);
1502
- const offsetTrack = createInlineTrack(shape.o, state, `${path}.o`, values => [(values[0] ?? 0) / 360]);
1503
- return {
1504
- kind: 'trim-path',
1505
- start: readStaticScalar(shape.s, 0) / 100,
1506
- end: readStaticScalar(shape.e, 100) / 100,
1507
- offset: readStaticScalar(shape.o, 0) / 360,
1508
- mode: shape.m === 2 ? 'individual' : 'simultaneous',
1509
- ...(startTrack ? { startTrack } : {}),
1510
- ...(endTrack ? { endTrack } : {}),
1511
- ...(offsetTrack ? { offsetTrack } : {}),
1512
- };
1513
- }
1514
- if (shape.ty === 'rd') {
1515
- const radiusTrack = createInlineTrack(shape.r, state, `${path}.r`, values => [Math.max(0, values[0] ?? 0)]);
1516
- return {
1517
- kind: 'round-corners',
1518
- radius: Math.max(0, readStaticScalar(shape.r, 0)),
1519
- ...(radiusTrack ? { radiusTrack } : {}),
1520
- };
1521
- }
1522
- return null;
1523
- }
1524
- function hasAnimatedStrokeStyle(stroke) {
1525
- return stroke.colorTrack !== undefined || stroke.opacityTrack !== undefined || stroke.widthTrack !== undefined
1526
- || stroke.dash !== undefined || stroke.dashOffsetTrack !== undefined || stroke.gradient !== undefined;
1527
- }
1528
- function toVectorStrokePaint(stroke) {
1529
- const gradient = stroke.gradient;
1530
- return {
1531
- color: stroke.color,
1532
- width: stroke.width,
1533
- opacity: stroke.opacity,
1534
- lineCap: stroke.lineCap === 2 ? 'round' : stroke.lineCap === 3 ? 'square' : 'butt',
1535
- lineJoin: stroke.lineJoin === 2 ? 'round' : stroke.lineJoin === 3 ? 'bevel' : 'miter',
1536
- miterLimit: stroke.miterLimit,
1537
- ...(gradient ? { gradient } : {}),
1538
- ...(stroke.dash ? { dash: stroke.dash } : {}),
1539
- ...(stroke.dashOffset === undefined ? {} : { dashOffset: stroke.dashOffset }),
1540
- ...(stroke.colorTrack ? { colorTrack: stroke.colorTrack } : {}),
1541
- ...(stroke.opacityTrack ? { opacityTrack: stroke.opacityTrack } : {}),
1542
- ...(stroke.widthTrack ? { widthTrack: stroke.widthTrack } : {}),
1543
- ...(stroke.dashOffsetTrack ? { dashOffsetTrack: stroke.dashOffsetTrack } : {}),
1544
- };
1545
- }
1546
- function convertStrokeStyle(shape, path, state) {
1547
- const color = readStaticVector(shape.c, [0, 0, 0, 1]);
1548
- const opacity = clamp(readStaticScalar(shape.o, 100) / 100, 0, 1);
1549
- const initialWidth = readStaticScalar(shape.w, 0);
1550
- const positiveWidth = readFirstPositiveVector(shape.w, 1)?.[0];
1551
- if (initialWidth < 0 || (positiveWidth !== undefined && positiveWidth < 0)) {
1552
- warn(state, 'W_LOTTIE_INVALID_STROKE', `${path}.w`, 'Stroke width cannot be negative.');
1553
- return null;
1554
- }
1555
- // Zero is a valid, intentionally invisible stroke width. For an animated
1556
- // zero-to-positive stroke, keep a positive base width for validation while
1557
- // the inline track preserves the authored zero sample exactly.
1558
- const width = initialWidth > 0 ? initialWidth : positiveWidth;
1559
- if (width === undefined)
1560
- return null;
1561
- const colorTrack = createInlineTrack(shape.c, state, `${path}.c`, values => [
1562
- clamp(values[0] ?? 0, 0, 1), clamp(values[1] ?? 0, 0, 1), clamp(values[2] ?? 0, 0, 1), clamp(values[3] ?? 1, 0, 1),
1563
- ]);
1564
- const opacityTrack = createInlineTrack(shape.o, state, `${path}.o`, values => [clamp((values[0] ?? 100) / 100, 0, 1)]);
1565
- const widthTrack = createInlineTrack(shape.w, state, `${path}.w`, values => [Math.max(0, values[0] ?? width)]);
1566
- const dashEntries = list(shape.d).map(object);
1567
- const dash = dashEntries.filter(entry => entry.n !== 'o').map((entry, index) => {
1568
- if (isAnimated(entry.v))
1569
- warn(state, 'W_LOTTIE_ANIMATED_STROKE_DASH', `${path}.d[${index}].v`, 'Animated dash lengths are sampled at their initial value.');
1570
- return Math.max(0, readStaticScalar(entry.v, 0));
1571
- }).filter(value => value > 0);
1572
- const offsetEntry = dashEntries.find(entry => entry.n === 'o');
1573
- const dashOffset = offsetEntry ? readStaticScalar(offsetEntry.v, 0) : undefined;
1574
- const dashOffsetTrack = offsetEntry ? createInlineTrack(offsetEntry.v, state, `${path}.d`, values => [values[0] ?? 0]) : undefined;
1575
- return {
1576
- color: [
1577
- clamp(color[0] ?? 0, 0, 1),
1578
- clamp(color[1] ?? 0, 0, 1),
1579
- clamp(color[2] ?? 0, 0, 1),
1580
- clamp(color[3] ?? 1, 0, 1),
1581
- ],
1582
- width,
1583
- opacity,
1584
- lineCap: shape.lc === 2 || shape.lc === 3 ? shape.lc : 1,
1585
- lineJoin: shape.lj === 2 || shape.lj === 3 ? shape.lj : 1,
1586
- miterLimit: Math.max(1, typeof shape.ml === 'number' && Number.isFinite(shape.ml) ? shape.ml : 4),
1587
- ...(colorTrack ? { colorTrack } : {}),
1588
- ...(opacityTrack ? { opacityTrack } : {}),
1589
- ...(widthTrack ? { widthTrack } : {}),
1590
- ...(dash.length > 0 ? { dash } : {}),
1591
- ...(dashOffset === undefined ? {} : { dashOffset }),
1592
- ...(dashOffsetTrack ? { dashOffsetTrack } : {}),
1593
- };
1594
- }
1595
- function createStrokeExtensionComponent(commands, values, stroke, state, sourceComponent) {
1596
- state.usesStrokeExtension = true;
1597
- return {
1598
- type: VECTOR_STROKE_EXTENSION,
1599
- ...({ commands, values } ),
1600
- color: [stroke.color[0], stroke.color[1], stroke.color[2], stroke.color[3] * stroke.opacity],
1601
- width: stroke.width,
1602
- lineCap: stroke.lineCap === 2 ? 'round' : stroke.lineCap === 3 ? 'square' : 'butt',
1603
- lineJoin: stroke.lineJoin === 2 ? 'round' : stroke.lineJoin === 3 ? 'bevel' : 'miter',
1604
- miterLimit: stroke.miterLimit,
1605
- tolerance: 0.2,
1606
- };
1607
- }
1608
- function roundedRectanglePath(width, height, authoredRadius) {
1609
- const halfWidth = width / 2;
1610
- const halfHeight = height / 2;
1611
- const radius = Math.min(Math.max(0, authoredRadius), halfWidth, halfHeight);
1612
- if (radius <= 1e-6)
1613
- return {
1614
- commands: 'MLLLZ',
1615
- values: [-halfWidth, -halfHeight, halfWidth, -halfHeight, halfWidth, halfHeight, -halfWidth, halfHeight],
1616
- };
1617
- const k = radius * 0.5522847498307936;
1618
- return {
1619
- commands: 'MLCLCLCLCZ',
1620
- values: [
1621
- -halfWidth + radius, -halfHeight,
1622
- halfWidth - radius, -halfHeight,
1623
- halfWidth - radius + k, -halfHeight, halfWidth, -halfHeight + radius - k, halfWidth, -halfHeight + radius,
1624
- halfWidth, halfHeight - radius,
1625
- halfWidth, halfHeight - radius + k, halfWidth - radius + k, halfHeight, halfWidth - radius, halfHeight,
1626
- -halfWidth + radius, halfHeight,
1627
- -halfWidth + radius - k, halfHeight, -halfWidth, halfHeight - radius + k, -halfWidth, halfHeight - radius,
1628
- -halfWidth, -halfHeight + radius,
1629
- -halfWidth, -halfHeight + radius - k, -halfWidth + radius - k, -halfHeight, -halfWidth + radius, -halfHeight,
1630
- ],
1631
- };
1632
- }
1633
- function ellipsePath(radiusX, radiusY) {
1634
- const kx = radiusX * 0.5522847498307936;
1635
- const ky = radiusY * 0.5522847498307936;
1636
- return {
1637
- commands: 'MCCCCZ',
1638
- values: [
1639
- 0, -radiusY,
1640
- kx, -radiusY, radiusX, -ky, radiusX, 0,
1641
- radiusX, ky, kx, radiusY, 0, radiusY,
1642
- -kx, radiusY, -radiusX, ky, -radiusX, 0,
1643
- -radiusX, -ky, -kx, -radiusY, 0, -radiusY,
1644
- ],
1645
- };
1646
- }
1647
- function convertPolystarPath(shape, path, state) {
1648
- const points = Math.round(readStaticScalar(shape.pt, 0));
1649
- const outerRadius = readStaticScalar(shape.or, 0);
1650
- const star = shape.sy !== 2;
1651
- const innerRadius = star ? readStaticScalar(shape.ir, 0) : outerRadius;
1652
- if (points < 3 || outerRadius <= 0 || (star && innerRadius <= 0)) {
1653
- warn(state, 'W_LOTTIE_INVALID_POLYSTAR', path, 'Polystar requires at least three points and positive radii.');
1654
- return null;
1655
- }
1656
- if ([shape.pt, shape.or, shape.ir].some(isAnimated)) {
1657
- warn(state, 'W_LOTTIE_ANIMATED_POLYSTAR_GEOMETRY', path, 'Animated polystar points and radii are sampled at their initial value.');
1658
- }
1659
- const innerRoundness = clamp(readStaticScalar(shape.is, 0) / 100, 0, 1);
1660
- const outerRoundness = clamp(readStaticScalar(shape.os, 0) / 100, 0, 1);
1661
- if (isAnimated(shape.is) || isAnimated(shape.os))
1662
- warn(state, 'W_LOTTIE_ANIMATED_POLYSTAR_ROUNDNESS', path, 'Animated polystar roundness is sampled at its initial value.');
1663
- const vertexCount = star ? points * 2 : points;
1664
- const direction = shape.d === 3 ? -1 : 1;
1665
- const vertices = [];
1666
- const roundness = [];
1667
- for (let index = 0; index < vertexCount; index++) {
1668
- const inner = star && (index & 1) === 1;
1669
- const radius = inner ? innerRadius : outerRadius;
1670
- const angle = -Math.PI / 2 + direction * index * Math.PI * 2 / vertexCount;
1671
- vertices.push([Math.cos(angle) * radius, Math.sin(angle) * radius]);
1672
- roundness.push(inner ? innerRoundness : outerRoundness);
1673
- }
1674
- if (roundness.every(value => value <= 1e-6)) {
1675
- return { commands: `M${'L'.repeat(vertexCount - 1)}Z`, values: vertices.flat() };
1676
- }
1677
- const entries = vertices.map((vertex, index) => {
1678
- const previous = vertices[(index - 1 + vertexCount) % vertexCount];
1679
- const next = vertices[(index + 1) % vertexCount];
1680
- const factor = roundness[index] * 0.25;
1681
- return {
1682
- vertex,
1683
- enter: [vertex[0] + (previous[0] - vertex[0]) * factor, vertex[1] + (previous[1] - vertex[1]) * factor],
1684
- exit: [vertex[0] + (next[0] - vertex[0]) * factor, vertex[1] + (next[1] - vertex[1]) * factor],
1685
- };
1686
- });
1687
- let commands = 'M';
1688
- const values = [...entries[0].enter];
1689
- for (let index = 0; index < entries.length; index++) {
1690
- const current = entries[index];
1691
- if (index > 0) {
1692
- commands += 'L';
1693
- values.push(...current.enter);
1694
- }
1695
- commands += 'Q';
1696
- values.push(...current.vertex, ...current.exit);
1697
- }
1698
- commands += 'LZ';
1699
- values.push(...entries[0].enter);
1700
- return { commands, values };
1701
- }
1702
- function diagnoseUnsupportedLayerFeatures(layer, path, type, state) {
1703
- if (layer.ddd === 1)
1704
- warn(state, 'W_LOTTIE_3D_LAYER', `${path}.ddd`, '3D layer transforms are flattened to the supported 2D transform subset.');
1705
- if (typeof layer.bm === 'number' && layer.bm !== 0) {
1706
- warn(state, 'W_LOTTIE_BLEND_MODE', `${path}.bm`, `Layer blend mode ${layer.bm} is not represented by the HYA 2D renderer.`);
1707
- }
1708
- if (layer.ao === 1)
1709
- warn(state, 'W_LOTTIE_AUTO_ORIENT', `${path}.ao`, 'Auto-orient along a motion path is not converted.');
1710
- if (layer.tm !== undefined && (type !== 0 || !isAnimated(layer.tm))) {
1711
- warn(state, 'W_LOTTIE_TIME_REMAP', `${path}.tm`, type !== 0
1712
- ? 'Time remapping is only supported for precomposition layers.'
1713
- : 'Static time remapping cannot be represented by ordinary HYA transform tracks.');
1714
- }
1715
- const position = object(object(layer.ks).p);
1716
- if (position.s === true || position.x !== undefined || position.y !== undefined) {
1717
- warn(state, 'W_LOTTIE_SPLIT_POSITION', `${path}.ks.p`, 'Separated position dimensions are sampled as the default position.');
1718
- }
1719
- const transform = object(layer.ks);
1720
- if (isAnimated(transform.sk) || isAnimated(transform.sa)
1721
- || Math.abs(readStaticScalar(transform.sk, 0)) > 1e-6
1722
- || Math.abs(readStaticScalar(transform.sa, 0)) > 1e-6) {
1723
- warn(state, 'W_LOTTIE_LAYER_SKEW', `${path}.ks`, 'Layer skew and skew axis are not converted.');
1724
- }
1725
- }
1726
- function convertLayerEffects(value, layerPath, state) {
1727
- const result = [];
1728
- const effects = list(value).map(object);
1729
- for (let index = 0; index < effects.length; index++) {
1730
- const effect = effects[index];
1731
- const effectPath = `${layerPath}.ef[${index}]`;
1732
- const name = normalizeEffectName(effect.nm ?? effect.mn);
1733
- const parameters = list(effect.ef).map(object);
1734
- if (name === 'tint') {
1735
- const blackProperty = effectParameter(parameters, ['map black to', 'adbe tint-0001']);
1736
- const whiteProperty = effectParameter(parameters, ['map white to', 'adbe tint-0002']);
1737
- const amountProperty = effectParameter(parameters, ['amount to tint', 'adbe tint-0003']);
1738
- if (!blackProperty || !whiteProperty || !amountProperty) {
1739
- warn(state, 'W_LOTTIE_EFFECT_PARAM', effectPath, 'Tint requires Map Black To, Map White To and Amount to Tint parameters.');
1740
- continue;
1741
- }
1742
- const black = readStaticVector(blackProperty, [0, 0, 0]);
1743
- const white = readStaticVector(whiteProperty, [1, 1, 1]);
1744
- const blackTrack = createInlineTrack(blackProperty, state, `${effectPath}.black`, values => rgb(values, [0, 0, 0]));
1745
- const whiteTrack = createInlineTrack(whiteProperty, state, `${effectPath}.white`, values => rgb(values, [1, 1, 1]));
1746
- const amountTrack = createInlineTrack(amountProperty, state, `${effectPath}.amount`, values => [clamp((values[0] ?? 100) / 100, 0, 1)]);
1747
- result.push({
1748
- kind: 'tint', black: rgb(black, [0, 0, 0]), white: rgb(white, [1, 1, 1]),
1749
- amount: clamp(readStaticScalar(amountProperty, 100) / 100, 0, 1),
1750
- ...(blackTrack ? { blackTrack } : {}), ...(whiteTrack ? { whiteTrack } : {}), ...(amountTrack ? { amountTrack } : {}),
1751
- });
1752
- continue;
1753
- }
1754
- if (name === 'fill') {
1755
- const colorProperty = effectParameter(parameters, ['color', 'adbe fill-0002']);
1756
- const opacityProperty = effectParameter(parameters, ['opacity', 'adbe fill-0007']);
1757
- if (!colorProperty) {
1758
- warn(state, 'W_LOTTIE_EFFECT_PARAM', effectPath, 'Fill requires a Color parameter.');
1759
- continue;
1760
- }
1761
- const initial = readStaticVector(colorProperty, [1, 1, 1, 1]);
1762
- const colorTrack = createInlineTrack(colorProperty, state, `${effectPath}.color`, values => rgba(values));
1763
- const opacityTrack = createInlineTrack(opacityProperty, state, `${effectPath}.opacity`, values => [clamp((values[0] ?? 100) / 100, 0, 1)]);
1764
- result.push({
1765
- kind: 'fill', color: rgba(initial),
1766
- opacity: clamp(readStaticScalar(opacityProperty, 100) / 100, 0, 1),
1767
- ...(colorTrack ? { colorTrack } : {}), ...(opacityTrack ? { opacityTrack } : {}),
1768
- });
1769
- continue;
1770
- }
1771
- if (name.includes('gaussian blur') || name.includes('fast box blur') || name === 'blur') {
1772
- const blurProperty = effectParameter(parameters, ['blurriness', 'blur', 'adbe gaussian blur 2-0001', 'adbe fast blur-0001']);
1773
- const dimensions = Math.round(readStaticScalar(effectParameter(parameters, ['blur dimensions', 'dimensions']), 1));
1774
- if (!blurProperty) {
1775
- warn(state, 'W_LOTTIE_EFFECT_PARAM', effectPath, 'Blur requires a Blurriness parameter.');
1776
- continue;
1777
- }
1778
- const toRadius = (values) => dimensions === 2
1779
- ? [0, Math.max(0, values[0] ?? 0)]
1780
- : dimensions === 3 ? [Math.max(0, values[0] ?? 0), 0] : [Math.max(0, values[0] ?? 0), Math.max(0, values[0] ?? 0)];
1781
- const radiusTrack = createInlineTrack(blurProperty, state, `${effectPath}.blur`, toRadius);
1782
- result.push({ kind: 'blur', radius: toRadius([readStaticScalar(blurProperty, 0)]), ...(radiusTrack ? { radiusTrack } : {}) });
1783
- continue;
1784
- }
1785
- if (name === 'drop shadow' || name.includes('drop shadow')) {
1786
- const colorProperty = effectParameter(parameters, ['shadow color', 'color', 'adbe drop shadow-0001']);
1787
- const opacityProperty = effectParameter(parameters, ['opacity', 'adbe drop shadow-0002']);
1788
- const directionProperty = effectParameter(parameters, ['direction', 'adbe drop shadow-0003']);
1789
- const distanceProperty = effectParameter(parameters, ['distance', 'adbe drop shadow-0004']);
1790
- const blurProperty = effectParameter(parameters, ['softness', 'blur', 'adbe drop shadow-0005']);
1791
- if (!colorProperty) {
1792
- warn(state, 'W_LOTTIE_EFFECT_PARAM', effectPath, 'Drop Shadow requires a Shadow Color parameter.');
1793
- continue;
1794
- }
1795
- if (isAnimated(directionProperty) || isAnimated(distanceProperty)) {
1796
- warn(state, 'W_LOTTIE_EFFECT_PARAM', effectPath, 'Animated Drop Shadow direction/distance requires coupled sampling and is held at its first value.');
1797
- }
1798
- const direction = degreesToRadians(readStaticScalar(directionProperty, 135));
1799
- const distance = Math.max(0, readStaticScalar(distanceProperty, 0));
1800
- const initial = readStaticVector(colorProperty, [0, 0, 0, 1]);
1801
- const colorTrack = createInlineTrack(colorProperty, state, `${effectPath}.color`, values => rgba(values, [0, 0, 0, 1]));
1802
- const opacityTrack = createInlineTrack(opacityProperty, state, `${effectPath}.opacity`, values => [clamp((values[0] ?? 100) / 100, 0, 1)]);
1803
- const blurTrack = createInlineTrack(blurProperty, state, `${effectPath}.blur`, values => [Math.max(0, values[0] ?? 0)]);
1804
- result.push({
1805
- kind: 'drop-shadow', color: rgba(initial, [0, 0, 0, 1]),
1806
- opacity: clamp(readStaticScalar(opacityProperty, 100) / 100, 0, 1),
1807
- offset: [Math.cos(direction) * distance, Math.sin(direction) * distance],
1808
- blur: Math.max(0, readStaticScalar(blurProperty, 0)),
1809
- ...(colorTrack ? { colorTrack } : {}), ...(opacityTrack ? { opacityTrack } : {}), ...(blurTrack ? { blurTrack } : {}),
1810
- });
1811
- continue;
1812
- }
1813
- if (name === 'opacity') {
1814
- const opacityProperty = effectParameter(parameters, ['opacity', 'amount']);
1815
- if (!opacityProperty) {
1816
- warn(state, 'W_LOTTIE_EFFECT_PARAM', effectPath, 'Opacity effect requires an Opacity parameter.');
1817
- continue;
1818
- }
1819
- const opacityTrack = createInlineTrack(opacityProperty, state, `${effectPath}.opacity`, values => [clamp((values[0] ?? 100) / 100, 0, 1)]);
1820
- result.push({ kind: 'opacity', opacity: clamp(readStaticScalar(opacityProperty, 100) / 100, 0, 1), ...(opacityTrack ? { opacityTrack } : {}) });
1821
- continue;
1822
- }
1823
- if (name === 'color matrix') {
1824
- const matrixProperty = effectParameter(parameters, ['matrix', 'color matrix']);
1825
- const matrix = readStaticVector(matrixProperty, []);
1826
- if (matrix.length !== 20) {
1827
- warn(state, 'W_LOTTIE_EFFECT_PARAM', effectPath, 'Color Matrix requires exactly 20 values.');
1828
- continue;
1829
- }
1830
- const matrixTrack = createInlineTrack(matrixProperty, state, `${effectPath}.matrix`, values => values.slice(0, 20));
1831
- result.push({ kind: 'color-matrix', matrix: matrix.slice(0, 20), ...(matrixTrack ? { matrixTrack } : {}) });
1832
- continue;
1833
- }
1834
- warn(state, 'W_LOTTIE_EFFECT', effectPath, `Layer effect "${typeof effect.nm === 'string' ? effect.nm : String(effect.ty)}" is not converted.`);
1835
- }
1836
- return result;
1837
- }
1838
- function normalizeEffectName(value) {
1839
- return typeof value === 'string' ? value.trim().toLowerCase() : '';
1840
- }
1841
- function effectParameter(parameters, names) {
1842
- const normalized = names.map(name => name.toLowerCase());
1843
- return parameters.find(parameter => {
1844
- const name = normalizeEffectName(parameter.nm);
1845
- const matchName = normalizeEffectName(parameter.mn);
1846
- return normalized.includes(name) || normalized.includes(matchName);
1847
- })?.v;
1848
- }
1849
- function rgb(values, fallback) {
1850
- return [
1851
- clamp(values[0] ?? fallback[0], 0, 1),
1852
- clamp(values[1] ?? fallback[1], 0, 1),
1853
- clamp(values[2] ?? fallback[2], 0, 1),
1854
- ];
1855
- }
1856
- function rgba(values, fallback = [1, 1, 1, 1]) {
1857
- return [
1858
- clamp(values[0] ?? fallback[0], 0, 1), clamp(values[1] ?? fallback[1], 0, 1),
1859
- clamp(values[2] ?? fallback[2], 0, 1), clamp(values[3] ?? fallback[3], 0, 1),
1860
- ];
1861
- }
1862
- function applyTint(color, tint) {
1863
- return color;
1864
- }
1865
- function convertLayerComposite(layer, sourceIndex, layerValues, layerIds, layerId, path, listPath, state, compositionWidth, compositionHeight) {
1866
- const matteType = layer.tt === undefined ? 0 : integer(layer.tt, `${path}.tt`);
1867
- const masks = convertMasks(layer.masksProperties, layerId, path, state, matteType > 0 ? 7 : 8, compositionWidth, compositionHeight);
1868
- if (matteType === 0)
1869
- return masks;
1870
- if (matteType < 1 || matteType > 4) {
1871
- warn(state, 'W_LOTTIE_UNSUPPORTED_MATTE', `${path}.tt`, `Track matte type ${matteType} is not supported.`);
1872
- return masks;
1873
- }
1874
- const explicitSource = layer.tp === undefined ? undefined : integer(layer.tp, `${path}.tp`);
1875
- const sourceLayer = object(layerValues[sourceIndex - 1]);
1876
- const sourceLayerIndex = explicitSource ?? (sourceIndex > 0
1877
- ? integer(sourceLayer.ind ?? sourceIndex, `${listPath}[${sourceIndex - 1}].ind`)
1878
- : undefined);
1879
- const source = sourceLayerIndex === undefined ? undefined : layerIds.get(sourceLayerIndex);
1880
- if (!source) {
1881
- warn(state, 'W_LOTTIE_MISSING_MATTE_SOURCE', `${path}.tt`, 'Track matte source layer was not found immediately before the target layer.');
1882
- return masks;
1883
- }
1884
- const matte = {
1885
- kind: 'matte',
1886
- source,
1887
- mode: matteType === 2 ? 'alpha-inverted' : matteType === 3 ? 'luma' : matteType === 4 ? 'luma-inverted' : 'alpha',
1888
- operation: masks.value ? 'intersect' : 'add',
1889
- };
1890
- const layers = [...compositeLayers(masks.value), matte];
1891
- return { value: compactComposite(layers), nodes: masks.nodes };
1892
- }
1893
- function convertMasks(value, layerId, path, state, layerBudget, compositionWidth, compositionHeight) {
1894
- const masks = list(value).map((entry, sourceIndex) => ({ mask: object(entry), sourceIndex }))
1895
- .filter(entry => entry.mask.hd !== true && entry.mask.mode !== 'n');
1896
- if (masks.length === 0)
1897
- return { nodes: [] };
1898
- const supported = masks.filter(({ mask, sourceIndex }) => {
1899
- if (mask.mode === undefined || ['a', 's', 'i', 'f'].includes(String(mask.mode)))
1900
- return true;
1901
- warn(state, 'W_LOTTIE_MASK_MODE', `${path}.masksProperties[${sourceIndex}].mode`, `Mask mode "${String(mask.mode)}" is not recognized.`);
1902
- return false;
1903
- });
1904
- if (supported.length === 0)
1905
- return { nodes: [] };
1906
- const nodes = [];
1907
- const layers = [];
1908
- for (let index = 0; index < supported.length; index++) {
1909
- const { mask, sourceIndex } = supported[index];
1910
- const maskPath = `${path}.masksProperties[${sourceIndex}]`;
1911
- const source = `${layerId}:mask:${state.shapeCounter++}`;
1912
- const opacity = clamp(readStaticScalar(mask.o, 100) / 100, 0, 1);
1913
- const feather = readStaticVector(mask.f, [0, 0]);
1914
- const expansion = readStaticScalar(mask.x, 0);
1915
- const expansionTrack = createInlineTrack(mask.x, state, `${maskPath}.x`, values => [values[0] ?? 0]);
1916
- if (isAnimated(mask.f))
1917
- warn(state, 'W_LOTTIE_ANIMATED_MASK_FEATHER', `${maskPath}.f`, 'Animated mask feather is sampled at its initial value.');
1918
- const animatedPath = isAnimated(mask.pt);
1919
- const animatedOpacity = isAnimated(mask.o);
1920
- const components = [];
1921
- const childNodes = [];
1922
- if (!animatedPath && !animatedOpacity) {
1923
- const component = convertPathComponent(mask.pt, [1, 1, 1, opacity], `${maskPath}.pt`, state);
1924
- if (component)
1925
- components.push(component);
1926
- }
1927
- else {
1928
- const maskNodeId = `${layerId}:mask-entry:${state.shapeCounter++}`;
1929
- const maskNode = {
1930
- id: maskNodeId,
1931
- name: `${layerId} mask ${index}`,
1932
- parent: source,
1933
- transform: { opacity },
1934
- };
1935
- if (animatedOpacity) {
1936
- appendTrack(mask.o, maskNodeId, 'opacity', state, values => [clamp((values[0] ?? 100) / 100, 0, 1)], `${maskPath}.o`);
1937
- }
1938
- const component = convertPathComponent(mask.pt, [1, 1, 1, 1], `${maskPath}.pt`, state);
1939
- if (component)
1940
- maskNode.components = [component];
1941
- childNodes.push(maskNode);
1942
- }
1943
- if (components.length === 0 && childNodes.length === 0)
1944
- continue;
1945
- nodes.push({ id: source, name: `${layerId} mask ${index}`, parent: layerId, ...(components.length > 0 ? { components } : {}) }, ...childNodes);
1946
- layers.push({
1947
- kind: 'mask',
1948
- source,
1949
- mode: mask.inv === true ? 'alpha-inverted' : 'alpha',
1950
- operation: mask.mode === 's' ? 'subtract' : mask.mode === 'i' ? 'intersect' : mask.mode === 'f' ? 'difference' : 'add',
1951
- ...(feather.some(value => Math.abs(value) > 1e-6) ? { feather: [Math.abs(feather[0] ?? 0), Math.abs(feather[1] ?? feather[0] ?? 0)] } : {}),
1952
- ...(Math.abs(expansion) > 1e-6 ? { expansion } : {}),
1953
- ...(expansionTrack ? { expansionTrack } : {}),
1954
- });
1955
- }
1956
- if (layers.length === 0)
1957
- return { nodes: [] };
1958
- const nested = nestCompositeLayers(layers, layerBudget, layerId, state, compositionWidth, compositionHeight);
1959
- nodes.push(...nested.nodes);
1960
- return { value: compactComposite(nested.layers), nodes };
1961
- }
1962
- function nestCompositeLayers(sourceLayers, finalLayerBudget, layerId, state, compositionWidth, compositionHeight) {
1963
- const remaining = [...sourceLayers];
1964
- const nodes = [];
1965
- let previousSource;
1966
- while (remaining.length + (previousSource ? 1 : 0) > finalLayerBudget) {
1967
- const capacity = previousSource ? 7 : 8;
1968
- const chunk = remaining.splice(0, capacity);
1969
- const compositeLayers = [
1970
- ...(previousSource ? [{
1971
- kind: 'mask',
1972
- source: previousSource,
1973
- mode: 'alpha',
1974
- operation: 'add',
1975
- }] : []),
1976
- ...chunk,
1977
- ];
1978
- const id = `${layerId}:mask-stack:${state.shapeCounter++}`;
1979
- nodes.push({
1980
- id,
1981
- name: `${layerId} mask stack`,
1982
- composite: compactComposite(compositeLayers),
1983
- components: [{
1984
- type: 'shape2d',
1985
- shape: 'rect',
1986
- size: [compositionWidth, compositionHeight],
1987
- position: [compositionWidth / 2, compositionHeight / 2],
1988
- fill: [1, 1, 1, 1],
1989
- }],
1990
- });
1991
- previousSource = id;
1992
- }
1993
- return {
1994
- layers: [
1995
- ...(previousSource ? [{
1996
- kind: 'mask',
1997
- source: previousSource,
1998
- mode: 'alpha',
1999
- operation: 'add',
2000
- }] : []),
2001
- ...remaining,
2002
- ],
2003
- nodes,
2004
- };
2005
- }
2006
- function compactComposite(layers) {
2007
- if (layers.length !== 1)
2008
- return { layers };
2009
- const layer = layers[0];
2010
- return layer.operation === undefined || layer.operation === 'add'
2011
- ? {
2012
- kind: layer.kind,
2013
- source: layer.source,
2014
- mode: layer.mode,
2015
- ...(layer.feather ? { feather: layer.feather } : {}),
2016
- ...(layer.expansion === undefined ? {} : { expansion: layer.expansion }),
2017
- ...(layer.expansionTrack === undefined ? {} : { expansionTrack: layer.expansionTrack }),
2018
- }
2019
- : layer;
2020
- }
2021
- function compositeLayers(value) {
2022
- if (!value)
2023
- return [];
2024
- return 'layers' in value ? value.layers : [value];
2025
- }
2026
- function convertPathComponent(value, fill, path, state) {
2027
- if (isAnimated(value)) {
2028
- const diagnosticStart = state.diagnostics.length;
2029
- const morph = convertAnimatedPathData(value, path, state);
2030
- if (morph) {
2031
- state.usesPathMorphExtension = true;
2032
- return {
2033
- type: VECTOR_PATH_MORPH_EXTENSION,
2034
- ...morph,
2035
- fill,
2036
- fillRule: 'nonzero',
2037
- };
2038
- }
2039
- if (!state.diagnostics.slice(diagnosticStart).some(diagnostic => diagnostic.code === 'W_LOTTIE_PATH_TOPOLOGY')) {
2040
- warn(state, 'W_LOTTIE_ANIMATED_PATH', path, 'Animated path cannot be represented and is sampled at its initial value.');
2041
- }
2042
- }
2043
- const shape = readStaticShape(value);
2044
- const converted = convertShapePath(shape, path, state);
2045
- if (!converted)
2046
- return null;
2047
- return { type: 'path2d', ...converted, fill, fillRule: 'nonzero' };
2048
- }
2049
- function convertAnimatedPathData(value, path, state, closeOpen = true) {
2050
- const keyframes = list(object(value).k).map(object);
2051
- const times = [];
2052
- const shapes = [];
2053
- const sourceFrames = [];
2054
- let previousShape = null;
2055
- for (let index = 0; index < keyframes.length; index++) {
2056
- const keyframe = keyframes[index];
2057
- const rawShape = list(keyframe.s)[0] ?? keyframe.s ?? list(keyframes[index - 1]?.e)[0] ?? previousShape;
2058
- const shape = object(rawShape);
2059
- if (Object.keys(shape).length === 0)
2060
- continue;
2061
- // HYA stores timeline data as Float32. De-duplicate after the storage
2062
- // conversion so composition-boundary keyframes cannot collapse into an
2063
- // invalid equal-time pair during binary validation.
2064
- const time = Math.fround(clamp(frameToSeconds(state.timeline, finite(keyframe.t, `${path}.k[${index}].t`)), 0, state.duration));
2065
- if (times.length > 0 && time <= times.at(-1))
2066
- continue;
2067
- times.push(time);
2068
- shapes.push(shape);
2069
- sourceFrames.push(keyframe);
2070
- previousShape = object(list(keyframe.e)[0] ?? keyframe.e ?? shape);
2071
- }
2072
- if (times.length === 0)
2073
- return null;
2074
- const normalized = normalizeAnimatedPathTopology(shapes, path, state, closeOpen);
2075
- if (!normalized)
2076
- return null;
2077
- const values = normalized.frames.flatMap(frame => frame.map(quantizeAnimatedPathCoordinate));
2078
- const commands = normalized.commands;
2079
- const valueSize = normalized.frames[0].length;
2080
- const allHold = sourceFrames.length > 1 && sourceFrames.slice(0, -1).every(frame => frame.h === 1);
2081
- const interpolation = allHold ? 'step' : times.length > 1 ? 'cubic-bezier' : 'linear';
2082
- const easings = [];
2083
- if (interpolation === 'cubic-bezier') {
2084
- for (let index = 0; index < times.length - 1; index++) {
2085
- const frame = sourceFrames[index];
2086
- const outgoing = object(frame.o);
2087
- const incoming = object(frame.i);
2088
- easings.push(clamp(firstNumber(outgoing.x, 0.333), 0, 1), firstNumber(outgoing.y, 0.333), clamp(firstNumber(incoming.x, 0.667), 0, 1), firstNumber(incoming.y, 0.667));
2089
- }
2090
- }
2091
- return {
2092
- commands,
2093
- times,
2094
- values,
2095
- valueSize,
2096
- interpolation,
2097
- ...(easings.length > 0 ? { easings } : {}),
2098
- tolerance: 0.35,
2099
- };
2100
- }
2101
- /**
2102
- * Lottie permits a segment to switch between a line and a cubic curve while
2103
- * keeping the same authored vertices. HYA morph tracks intentionally have one
2104
- * command stream, so every segment is represented canonically as a cubic. If
2105
- * exporters genuinely change the vertex count, exact de Casteljau subdivision
2106
- * raises every frame to the largest segment count without flattening curves.
2107
- */
2108
- function normalizeAnimatedPathTopology(shapes, path, state, closeOpen) {
2109
- const contours = [];
2110
- for (let index = 0; index < shapes.length; index++) {
2111
- const contour = lottieShapeToCubicContour(shapes[index], closeOpen);
2112
- if (!contour) {
2113
- warn(state, 'W_LOTTIE_INVALID_PATH', `${path}.k[${index}].s`, 'Animated path requires matching vertices and tangent arrays.');
2114
- return null;
2115
- }
2116
- contours.push(contour);
2117
- }
2118
- const closed = contours[0].closed;
2119
- if (contours.some(contour => contour.closed !== closed)) {
2120
- warn(state, 'W_LOTTIE_PATH_TOPOLOGY', path, 'Animated path changes between open and closed topology.');
2121
- return null;
2122
- }
2123
- const segmentCount = Math.max(...contours.map(contour => contour.segments.length));
2124
- if (segmentCount < 1 || segmentCount > MAX_ANIMATED_PATH_SEGMENTS) {
2125
- warn(state, 'W_LOTTIE_PATH_TOPOLOGY', path, `Animated path requires ${segmentCount} canonical segments; the safe budget is ${MAX_ANIMATED_PATH_SEGMENTS}.`);
2126
- return null;
2127
- }
2128
- const normalized = contours.map(contour => subdivideContour(contour, segmentCount));
2129
- const reference = normalized[0];
2130
- for (let index = 1; index < normalized.length; index++) {
2131
- normalized[index] = alignCubicContour(normalized[index], reference);
2132
- }
2133
- return {
2134
- commands: `M${'C'.repeat(segmentCount)}${closed ? 'Z' : ''}`,
2135
- frames: normalized.map(contour => [
2136
- ...contour.segments[0].start,
2137
- ...contour.segments.flatMap(segment => [...segment.control1, ...segment.control2, ...segment.end]),
2138
- ]),
2139
- };
2140
- }
2141
- function lottieShapeToCubicContour(shape, closeOpen) {
2142
- const vertices = pointList(shape.v);
2143
- const incoming = normalizedTangents(shape.i, vertices.length);
2144
- const outgoing = normalizedTangents(shape.o, vertices.length);
2145
- if (vertices.length < 2 || incoming.length !== vertices.length || outgoing.length !== vertices.length)
2146
- return null;
2147
- const authoredClosed = shape.c !== false;
2148
- const closed = authoredClosed || closeOpen;
2149
- const segmentCount = closed ? vertices.length : vertices.length - 1;
2150
- const segments = [];
2151
- for (let index = 0; index < segmentCount; index++) {
2152
- const next = (index + 1) % vertices.length;
2153
- const start = vertices[index];
2154
- const end = vertices[next];
2155
- const authoredSegment = authoredClosed || next !== 0;
2156
- segments.push({
2157
- start,
2158
- control1: authoredSegment
2159
- ? [start[0] + outgoing[index][0], start[1] + outgoing[index][1]]
2160
- : start,
2161
- control2: authoredSegment
2162
- ? [end[0] + incoming[next][0], end[1] + incoming[next][1]]
2163
- : end,
2164
- end,
2165
- });
2166
- }
2167
- return { closed, segments };
2168
- }
2169
- function subdivideContour(contour, segmentCount) {
2170
- const segments = [...contour.segments];
2171
- while (segments.length < segmentCount) {
2172
- let longest = 0;
2173
- let longestLength = -Infinity;
2174
- for (let index = 0; index < segments.length; index++) {
2175
- const segment = segments[index];
2176
- const length = pointDistance(segment.start, segment.control1)
2177
- + pointDistance(segment.control1, segment.control2)
2178
- + pointDistance(segment.control2, segment.end);
2179
- if (length > longestLength) {
2180
- longest = index;
2181
- longestLength = length;
2182
- }
2183
- }
2184
- segments.splice(longest, 1, ...splitCubicSegment(segments[longest]));
2185
- }
2186
- return { closed: contour.closed, segments };
2187
- }
2188
- function splitCubicSegment(segment) {
2189
- const a = midpointPair(segment.start, segment.control1);
2190
- const b = midpointPair(segment.control1, segment.control2);
2191
- const c = midpointPair(segment.control2, segment.end);
2192
- const d = midpointPair(a, b);
2193
- const e = midpointPair(b, c);
2194
- const middle = midpointPair(d, e);
2195
- return [
2196
- { start: segment.start, control1: a, control2: d, end: middle },
2197
- { start: middle, control1: e, control2: c, end: segment.end },
2198
- ];
2199
- }
2200
- function alignCubicContour(contour, reference) {
2201
- let candidate = contour;
2202
- if (contour.closed) {
2203
- if (Math.sign(cubicContourArea(candidate)) !== Math.sign(cubicContourArea(reference))) {
2204
- candidate = reverseCubicContour(candidate);
2205
- }
2206
- let bestOffset = 0;
2207
- let bestDistance = Infinity;
2208
- for (let offset = 0; offset < candidate.segments.length; offset++) {
2209
- let distance = 0;
2210
- for (let index = 0; index < reference.segments.length; index++) {
2211
- distance += squaredPointDistance(reference.segments[index].start, candidate.segments[(index + offset) % candidate.segments.length].start);
2212
- }
2213
- if (distance < bestDistance) {
2214
- bestDistance = distance;
2215
- bestOffset = offset;
2216
- }
2217
- }
2218
- if (bestOffset > 0)
2219
- candidate = {
2220
- closed: true,
2221
- segments: [...candidate.segments.slice(bestOffset), ...candidate.segments.slice(0, bestOffset)],
2222
- };
2223
- return candidate;
2224
- }
2225
- const forward = squaredPointDistance(reference.segments[0].start, candidate.segments[0].start)
2226
- + squaredPointDistance(reference.segments.at(-1).end, candidate.segments.at(-1).end);
2227
- const reversed = squaredPointDistance(reference.segments[0].start, candidate.segments.at(-1).end)
2228
- + squaredPointDistance(reference.segments.at(-1).end, candidate.segments[0].start);
2229
- return reversed < forward ? reverseCubicContour(candidate) : candidate;
2230
- }
2231
- function reverseCubicContour(contour) {
2232
- return {
2233
- closed: contour.closed,
2234
- segments: [...contour.segments].reverse().map(segment => ({
2235
- start: segment.end,
2236
- control1: segment.control2,
2237
- control2: segment.control1,
2238
- end: segment.start,
2239
- })),
2240
- };
2241
- }
2242
- function cubicContourArea(contour) {
2243
- let area = 0;
2244
- for (const segment of contour.segments) {
2245
- area += segment.start[0] * segment.end[1] - segment.end[0] * segment.start[1];
2246
- }
2247
- return area / 2;
2248
- }
2249
- function midpointPair(a, b) {
2250
- return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
2251
- }
2252
- function pointDistance(a, b) {
2253
- return Math.hypot(a[0] - b[0], a[1] - b[1]);
2254
- }
2255
- function squaredPointDistance(a, b) {
2256
- const x = a[0] - b[0];
2257
- const y = a[1] - b[1];
2258
- return x * x + y * y;
2259
- }
2260
- function quantizeAnimatedPathCoordinate(value) {
2261
- return Math.round(value / ANIMATED_PATH_QUANTIZATION) * ANIMATED_PATH_QUANTIZATION;
2262
- }
2263
- function convertShapePath(shape, path, state, diagnose = true, closeOpen = true) {
2264
- const vertices = pointList(shape.v);
2265
- const incoming = normalizedTangents(shape.i, vertices.length);
2266
- const outgoing = normalizedTangents(shape.o, vertices.length);
2267
- // Two cubic vertices can form a valid closed lens/oval. Older Bodymovin
2268
- // exporters use this compact form heavily for masks.
2269
- if (vertices.length < 2 || incoming.length !== vertices.length || outgoing.length !== vertices.length) {
2270
- if (diagnose)
2271
- warn(state, 'W_LOTTIE_INVALID_PATH', path, 'Path requires matching vertex, incoming-tangent and outgoing-tangent arrays.');
2272
- return null;
2273
- }
2274
- let commands = 'M';
2275
- const values = [...vertices[0]];
2276
- const closed = shape.c !== false;
2277
- const segmentCount = closed ? vertices.length : vertices.length - 1;
2278
- for (let segment = 0; segment < segmentCount; segment++) {
2279
- const fromIndex = segment;
2280
- const toIndex = (segment + 1) % vertices.length;
2281
- const from = vertices[fromIndex];
2282
- const to = vertices[toIndex];
2283
- const control1 = [from[0] + outgoing[fromIndex][0], from[1] + outgoing[fromIndex][1]];
2284
- const control2 = [to[0] + incoming[toIndex][0], to[1] + incoming[toIndex][1]];
2285
- if (samePair(control1, from) && samePair(control2, to)) {
2286
- commands += 'L';
2287
- values.push(...to);
2288
- }
2289
- else {
2290
- commands += 'C';
2291
- values.push(...control1, ...control2, ...to);
2292
- }
2293
- }
2294
- if (!closed && closeOpen) {
2295
- if (diagnose)
2296
- warn(state, 'W_LOTTIE_OPEN_FILLED_PATH', path, 'Open filled path is closed with a straight segment.');
2297
- commands += 'L';
2298
- values.push(...vertices[0]);
2299
- }
2300
- if (closed || closeOpen)
2301
- commands += 'Z';
2302
- return { commands, values };
2303
- }
2304
- function readStaticShape(value) {
2305
- const property = object(value);
2306
- if (isAnimated(property)) {
2307
- const first = object(list(property.k)[0]);
2308
- const start = list(first.s)[0];
2309
- return object(start ?? first.s);
2310
- }
2311
- return object(property.k ?? value);
2312
- }
2313
- function pointList(value) {
2314
- return list(value).map(item => {
2315
- const pair = numberList(item);
2316
- return [pair[0] ?? 0, pair[1] ?? 0];
2317
- });
2318
- }
2319
- function normalizedTangents(value, vertexCount) {
2320
- const points = pointList(value);
2321
- if (points.length === 0 && vertexCount > 0) {
2322
- return Array.from({ length: vertexCount }, () => [0, 0]);
2323
- }
2324
- return points;
2325
- }
2326
- function samePair(a, b) {
2327
- return Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6;
2328
- }
2329
- function appendTrack(property, node, target, state, mapValue, path) {
2330
- const track = createInlineTrack(property, state, path, mapValue);
2331
- if (track)
2332
- state.tracks.push({
2333
- node,
2334
- property: target,
2335
- interpolation: track.interpolation,
2336
- times: track.times,
2337
- values: track.values,
2338
- ...(track.easings ? { easings: track.easings } : {}),
2339
- ...(target === 'position' && track.spatialTangents ? { spatialTangents: track.spatialTangents } : {}),
2340
- });
2341
- }
2342
- function createInlineTrack(property, state, path, mapValue) {
2343
- if (!isAnimated(property))
2344
- return undefined;
2345
- const descriptor = object(property);
2346
- const keyframes = list(descriptor.k).map(object);
2347
- const times = [];
2348
- const values = [];
2349
- const sourceFrames = [];
2350
- let previousValue = null;
2351
- for (let index = 0; index < keyframes.length; index++) {
2352
- const keyframe = keyframes[index];
2353
- const frame = finite(keyframe.t, `${path}.k[${index}].t`);
2354
- const startValue = numberList(keyframe.s);
2355
- const raw = startValue.length > 0
2356
- ? startValue
2357
- : previousValue ?? numberList(keyframes[index - 1]?.e);
2358
- if (raw.length === 0)
2359
- continue;
2360
- const time = Math.fround(clamp(frameToSeconds(state.timeline, frame), 0, state.duration));
2361
- if (times.length > 0 && time <= times[times.length - 1])
2362
- continue;
2363
- const mapped = mapValue(raw);
2364
- times.push(time);
2365
- values.push(...mapped);
2366
- sourceFrames.push(keyframe);
2367
- previousValue = numberList(keyframe.e).length > 0 ? numberList(keyframe.e) : raw;
2368
- }
2369
- if (times.length < 1) {
2370
- warn(state, 'W_LOTTIE_EMPTY_TRACK', path, 'Animated property contains no usable keyframes.');
2371
- return undefined;
2372
- }
2373
- const allHold = sourceFrames.length > 1 && sourceFrames.slice(0, -1).every(frame => frame.h === 1);
2374
- if (allHold) {
2375
- return { times, values, valueSize: values.length / times.length, interpolation: 'step' };
2376
- }
2377
- const easings = [];
2378
- const spatialTangents = [];
2379
- let hasSpatialTangents = false;
2380
- for (let index = 0; index < times.length - 1; index++) {
2381
- const frame = sourceFrames[index];
2382
- const outgoing = object(frame.o);
2383
- const incoming = object(frame.i);
2384
- easings.push(clamp(firstNumber(outgoing.x, 0.333), 0, 1), firstNumber(outgoing.y, 0.333), clamp(firstNumber(incoming.x, 0.667), 0, 1), firstNumber(incoming.y, 0.667));
2385
- if (values.length / times.length === 2) {
2386
- const outgoingSpatial = numberList(frame.to);
2387
- const incomingSpatial = numberList(frame.ti);
2388
- const authored = [...outgoingSpatial, ...incomingSpatial].some(value => Math.abs(value) > 1e-8);
2389
- hasSpatialTangents ||= authored;
2390
- if (authored) {
2391
- spatialTangents.push(outgoingSpatial[0] ?? 0, outgoingSpatial[1] ?? 0, incomingSpatial[0] ?? 0, incomingSpatial[1] ?? 0);
2392
- }
2393
- else {
2394
- const offset = index * 2;
2395
- const dx = ((values[offset + 2] ?? values[offset] ?? 0) - (values[offset] ?? 0)) / 3;
2396
- const dy = ((values[offset + 3] ?? values[offset + 1] ?? 0) - (values[offset + 1] ?? 0)) / 3;
2397
- spatialTangents.push(dx, dy, -dx, -dy);
2398
- }
2399
- }
2400
- }
2401
- return {
2402
- times,
2403
- values,
2404
- valueSize: values.length / times.length,
2405
- interpolation: times.length > 1 ? 'cubic-bezier' : 'linear',
2406
- ...(times.length > 1 ? { easings } : {}),
2407
- ...(times.length > 1 && hasSpatialTangents ? { spatialTangents } : {}),
2408
- };
2409
- }
2410
- function frameToSeconds(timeline, frame) {
2411
- return timeline.mapFrameToSeconds?.(frame) ?? timeline.secondsOffset + frame * timeline.secondsPerFrame;
2412
- }
2413
- function createTimeRemappedTimeline(property, parentTimeline, assetFrameRate, path, state) {
2414
- if (!isAnimated(property)) {
2415
- warn(state, 'W_LOTTIE_TIME_REMAP', path, 'Static time remapping cannot be represented by ordinary HYA transform tracks.');
2416
- return null;
2417
- }
2418
- const keyframes = list(object(property).k).map(object);
2419
- if (keyframes.length < 2) {
2420
- warn(state, 'W_LOTTIE_TIME_REMAP', path, 'Time remapping requires at least two scalar keyframes.');
2421
- return null;
2422
- }
2423
- const samples = [];
2424
- for (let index = 0; index < keyframes.length; index++) {
2425
- const keyframe = keyframes[index];
2426
- if (typeof keyframe.t !== 'number' || !Number.isFinite(keyframe.t)) {
2427
- warn(state, 'W_LOTTIE_TIME_REMAP', `${path}.k[${index}].t`, 'Time-remap keyframe time must be finite.');
2428
- return null;
2429
- }
2430
- const value = firstNumber(keyframe.s, Number.NaN);
2431
- if (Number.isFinite(value))
2432
- samples.push({ frame: keyframe.t, value });
2433
- }
2434
- if (samples.length < 1) {
2435
- warn(state, 'W_LOTTIE_TIME_REMAP', path, 'Time remapping contains no scalar keyframe values.');
2436
- return null;
2437
- }
2438
- const finalFrame = finite(keyframes.at(-1).t, `${path}.k[${keyframes.length - 1}].t`);
2439
- const lastSegment = keyframes[Math.max(0, keyframes.length - 2)];
2440
- const finalValue = firstNumber(keyframes.at(-1).s, firstNumber(lastSegment.e, samples.at(-1).value));
2441
- if (finalFrame > samples.at(-1).frame)
2442
- samples.push({ frame: finalFrame, value: finalValue });
2443
- for (let index = 1; index < samples.length; index++) {
2444
- if (samples[index].frame <= samples[index - 1].frame || samples[index].value + 1e-6 < samples[index - 1].value) {
2445
- warn(state, 'W_LOTTIE_TIME_REMAP', path, 'Non-monotonic time remapping requires runtime time-warp support and was not converted.');
2446
- return null;
2447
- }
2448
- }
2449
- const first = samples[0];
2450
- const last = samples.at(-1);
2451
- const sourceSecondsAtParentFrame = (frame) => {
2452
- if (frame <= first.frame)
2453
- return first.value;
2454
- if (frame >= last.frame)
2455
- return last.value;
2456
- let segment = 0;
2457
- while (segment + 1 < samples.length && frame >= samples[segment + 1].frame)
2458
- segment++;
2459
- const from = samples[segment];
2460
- const to = samples[segment + 1];
2461
- const keyframe = keyframes[Math.min(segment, keyframes.length - 1)];
2462
- if (keyframe.h === 1 || to.frame <= from.frame)
2463
- return from.value;
2464
- const linearProgress = clamp((frame - from.frame) / (to.frame - from.frame), 0, 1);
2465
- const progress = cubicBezierProgress(linearProgress, clamp(firstNumber(object(keyframe.o).x, 0.333), 0, 1), firstNumber(object(keyframe.o).y, 0.333), clamp(firstNumber(object(keyframe.i).x, 0.667), 0, 1), firstNumber(object(keyframe.i).y, 0.667));
2466
- return from.value + (to.value - from.value) * progress;
2467
- };
2468
- const parentFrameForSourceSeconds = (sourceSeconds) => {
2469
- if (sourceSeconds <= first.value)
2470
- return first.frame;
2471
- if (sourceSeconds >= last.value)
2472
- return last.frame;
2473
- let low = first.frame;
2474
- let high = last.frame;
2475
- for (let iteration = 0; iteration < 28; iteration++) {
2476
- const middle = (low + high) / 2;
2477
- if (sourceSecondsAtParentFrame(middle) < sourceSeconds)
2478
- low = middle;
2479
- else
2480
- high = middle;
2481
- }
2482
- return (low + high) / 2;
2483
- };
2484
- return {
2485
- frameRate: assetFrameRate,
2486
- secondsOffset: frameToSeconds(parentTimeline, first.frame),
2487
- secondsPerFrame: parentTimeline.secondsPerFrame,
2488
- mapFrameToSeconds: frame => frameToSeconds(parentTimeline, parentFrameForSourceSeconds(frame / assetFrameRate)),
2489
- };
2490
- }
2491
- function cubicBezierProgress(progress, x1, y1, x2, y2) {
2492
- let low = 0;
2493
- let high = 1;
2494
- for (let iteration = 0; iteration < 16; iteration++) {
2495
- const parameter = (low + high) / 2;
2496
- if (cubicBezierCoordinate(parameter, x1, x2) < progress)
2497
- low = parameter;
2498
- else
2499
- high = parameter;
2500
- }
2501
- return cubicBezierCoordinate((low + high) / 2, y1, y2);
2502
- }
2503
- function cubicBezierCoordinate(parameter, firstControl, secondControl) {
2504
- const inverse = 1 - parameter;
2505
- return 3 * inverse * inverse * parameter * firstControl
2506
- + 3 * inverse * parameter * parameter * secondControl
2507
- + parameter * parameter * parameter;
2508
- }
2509
- function createOrdinaryLayerTimeline(layer, path, parentTimeline, state) {
2510
- const stretch = finite(layer.sr ?? 1, `${path}.sr`);
2511
- if (Math.abs(stretch - 1) < 1e-8)
2512
- return parentTimeline;
2513
- if (stretch <= 0) {
2514
- warn(state, 'W_LOTTIE_INVALID_TIME_STRETCH', `${path}.sr`, 'Layer time stretch must be greater than zero.');
2515
- return parentTimeline;
2516
- }
2517
- const startFrame = finite(layer.st ?? layer.ip ?? 0, `${path}.st`);
2518
- const mapFrameToSeconds = (frame) => frameToSeconds(parentTimeline, startFrame + (frame - startFrame) * stretch);
2519
- return {
2520
- frameRate: parentTimeline.frameRate,
2521
- secondsOffset: mapFrameToSeconds(0),
2522
- secondsPerFrame: parentTimeline.secondsPerFrame * stretch,
2523
- mapFrameToSeconds,
2524
- };
2525
- }
2526
- function convertNodeTiming(startFrame, endFrame, timeline, animationDuration) {
2527
- const minimumDuration = Math.min(animationDuration, Math.max(1e-6, timeline.secondsPerFrame));
2528
- const rawStart = frameToSeconds(timeline, startFrame);
2529
- const rawEnd = frameToSeconds(timeline, endFrame);
2530
- const start = clamp(rawStart, 0, Math.max(0, animationDuration - minimumDuration));
2531
- const end = clamp(rawEnd, start + minimumDuration, animationDuration);
2532
- return { start, duration: Math.max(minimumDuration, end - start) };
2533
- }
2534
- function isAnimated(value) {
2535
- const property = object(value);
2536
- if (!Array.isArray(property.k))
2537
- return false;
2538
- if (property.a === 1)
2539
- return true;
2540
- // Older Bodymovin exporters omit the `a` flag and encode animation solely as
2541
- // a keyframe array. Treating that form as a static array drops paths and
2542
- // transforms instead of merely degrading their animation.
2543
- const first = object(property.k[0]);
2544
- return typeof first.t === 'number'
2545
- && Number.isFinite(first.t)
2546
- && (first.s !== undefined || first.e !== undefined);
2547
- }
2548
- function readStaticVector(value, fallback) {
2549
- const property = object(value);
2550
- if (isAnimated(property))
2551
- return numberList(object(list(property.k)[0]).s).length > 0 ? numberList(object(list(property.k)[0]).s) : fallback;
2552
- const values = numberList(property.k);
2553
- return values.length > 0 ? values : fallback;
2554
- }
2555
- function readFirstPositiveVector(value, valueSize) {
2556
- const property = object(value);
2557
- const candidates = isAnimated(property)
2558
- ? list(property.k).flatMap(entry => {
2559
- const keyframe = object(entry);
2560
- return [numberList(keyframe.s), numberList(keyframe.e)];
2561
- })
2562
- : [numberList(property.k)];
2563
- return candidates.find(candidate => candidate.length >= valueSize
2564
- && candidate.slice(0, valueSize).every(component => component > 0));
2565
- }
2566
- function readStaticScalar(value, fallback) {
2567
- return readStaticVector(value, [fallback])[0] ?? fallback;
2568
- }
2569
- function parseHexColor(value, path) {
2570
- if (typeof value !== 'string' || !/^#[0-9a-f]{6}$/i.test(value))
2571
- throw new TypeError(`Expected #RRGGBB at ${path}.`);
2572
- const packed = Number.parseInt(value.slice(1), 16);
2573
- return [((packed >> 16) & 255) / 255, ((packed >> 8) & 255) / 255, (packed & 255) / 255, 1];
2574
- }
2575
- function resolveUri(base, path) {
2576
- if (!base)
2577
- return path;
2578
- try {
2579
- return new URL(path, base).toString();
2580
- }
2581
- catch {
2582
- return `${base.replace(/\/$/, '')}/${path.replace(/^\//, '')}`;
2583
- }
2584
- }
2585
- function parseLottieJson(source) {
2586
- const value = JSON.parse(source);
2587
- return object(value);
2588
- }
2589
- function object(value) {
2590
- return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
2591
- }
2592
- function list(value) {
2593
- return Array.isArray(value) ? value : [];
2594
- }
2595
- function numberList(value) {
2596
- if (typeof value === 'number' && Number.isFinite(value))
2597
- return [value];
2598
- if (!Array.isArray(value))
2599
- return [];
2600
- const flattened = value.length === 1 && Array.isArray(value[0]) ? value[0] : value;
2601
- return flattened.filter((item) => typeof item === 'number' && Number.isFinite(item));
2602
- }
2603
- function firstNumber(value, fallback) {
2604
- return numberList(value)[0] ?? fallback;
2605
- }
2606
- function finite(value, path) {
2607
- if (typeof value !== 'number' || !Number.isFinite(value))
2608
- throw new TypeError(`Expected a finite number at ${path}.`);
2609
- return value;
2610
- }
2611
- function positive(value, path) {
2612
- const result = finite(value, path);
2613
- if (result <= 0)
2614
- throw new TypeError(`Expected a positive number at ${path}.`);
2615
- return result;
2616
- }
2617
- function integer(value, path) {
2618
- const result = finite(value, path);
2619
- if (!Number.isSafeInteger(result))
2620
- throw new TypeError(`Expected an integer at ${path}.`);
2621
- return result;
2622
- }
2623
- function degreesToRadians(value) {
2624
- return value * Math.PI / 180;
2625
- }
2626
- function clamp(value, min, max) {
2627
- return Math.min(max, Math.max(min, value));
2628
- }
2629
- function stableUint32(value) {
2630
- let hash = 0x811c9dc5;
2631
- for (let index = 0; index < value.length; index++) {
2632
- hash ^= value.charCodeAt(index);
2633
- hash = Math.imul(hash, 0x01000193);
2634
- }
2635
- return hash >>> 0;
2636
- }
2637
- function warn(state, code, path, message) {
2638
- state.diagnostics.push(Object.freeze({ severity: 'warning', code, path, message }));
2639
- }
2640
-
2641
- export { convertLottie, convertLottieDocument, inspectLottieFonts };
2642
- //# sourceMappingURL=lottie.js.map
1
+ import{p as e,H as t,A as n,a as o,b as s}from"./chunks/expression-D1cKtNwM.js";import r from"polygon-clipping/dist/polygon-clipping.esm.js";import"./chunks/errors-Bzs3GOD9.js";const i=r;function a(e,t){const n=e.flat();if(1===t)return 0===n.length?null:{commands:n.map(e=>e.commands).join(""),values:n.flatMap(e=>Array.from(e.values))};const o=e.map(u).filter(e=>e.length>0);if(0===o.length)return null;const[s,...r]=o;return function(e){let t="";const n=[];for(const o of e)for(const e of o){const o=e.length>1&&h(e[0],e.at(-1))?e.slice(0,-1):e;o.length<3||(t+=`M${"L".repeat(o.length-1)}Z`,n.push(...o.flat()))}return t?{commands:t,values:n}:null}(2===t?i.union(s,...r):3===t?i.difference(s,...r):4===t?i.intersection(s,...r):i.xor(s,...r))}function c(e,t,n,o){const s=(n[0]??100)/100,r=(n[1]??100)/100,i=Math.cos(o),a=Math.sin(o),c=i*s,l=a*s,u=-a*r,f=i*r,p=t[0]??0,d=t[1]??0;return[c,l,u,f,(e[0]??0)-c*p-u*d,(e[1]??0)-l*p-f*d]}function l(e,t){const[n,o,s,r,i,a]=t,c=[];for(let t=0;t<e.values.length;t+=2){const l=e.values[t]??0,u=e.values[t+1]??0;c.push(n*l+s*u+i,o*l+r*u+a)}return{commands:e.commands,values:c}}function u(e){const t=e.flatMap(e=>function(e,t=.35){const n=[];let o=0,s=[],r=[0,0];const i=()=>[Number(e.values[o++]??0),Number(e.values[o++]??0)],a=()=>{s.length<3||(h(s[0],s.at(-1))||s.push([...s[0]]),Math.abs(function(e){let t=0;for(let n=0;n+1<e.length;n++)t+=e[n][0]*e[n+1][1]-e[n+1][0]*e[n][1];return t/2}(s))>1e-8&&n.push(s)),s=[]};for(const n of e.commands)if("M"===n)a(),r=i(),s.push(r);else if("L"===n)r=i(),s.push(r);else if("C"===n){const e=i(),n=i(),o=i();f(r,e,n,o,t,s),r=o}else if("Q"===n){const e=i(),n=i();p(r,e,n,t,s),r=n}else"Z"===n&&a();return a(),n}(e).map(e=>[e]));return t.length<=1?t:i.union(t[0],...t.slice(1))}function f(e,t,n,o,s,r,i=0){if(i>=10||Math.max(d(t,e,o),d(n,e,o))<=s)return void r.push(o);const a=m(e,t),c=m(t,n),l=m(n,o),u=m(a,c),p=m(c,l),h=m(u,p);f(e,a,u,h,s,r,i+1),f(h,p,l,o,s,r,i+1)}function p(e,t,n,o,s,r=0){if(r>=10||d(t,e,n)<=o)return void s.push(n);const i=m(e,t),a=m(t,n),c=m(i,a);p(e,i,c,o,s,r+1),p(c,a,n,o,s,r+1)}function d(e,t,n){const o=n[0]-t[0],s=n[1]-t[1],r=Math.hypot(o,s);return r<=1e-12?Math.hypot(e[0]-t[0],e[1]-t[1]):Math.abs(s*e[0]-o*e[1]+n[0]*t[1]-n[1]*t[0])/r}function m(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2]}function h(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6}class g extends Error{offset;constructor(e,t){super(e),this.offset=t,this.name="LottieTextExpressionCompileError"}}function y(e,t,n){if("identifier"===e.kind)return t.get(e.name)??null;if("member"===e.kind){const o=y(e.object,t,n);return o?"sourceData"===e.property?o:{resource:o.resource,path:[...o.path,e.property]}:null}if("call"!==e.kind)return null;if("member"===e.callee.kind&&"layer"===e.callee.property&&"identifier"===e.callee.object.kind&&"thisComp"===e.callee.object.name){const t=v(e,"thisComp.layer"),o=n.resolveDataLayer(t);if(!o)throw b(`Expression references unknown or non-data layer "${t}".`,e.offset);return{resource:o,path:[]}}const o=y(e.callee,t,n);if(!o)return null;const s=v(e,"Data Layer selector");return"Data"!==s&&"Outline"!==s||0!==o.path.length?{resource:o.resource,path:[...o.path,T(s)]}:o}function v(e,t){if(1!==e.arguments.length||"literal"!==e.arguments[0]?.kind||"string"!=typeof e.arguments[0].value)throw b(`${t} requires one static string argument.`,e.offset);return e.arguments[0].value}function T(e){const t=/^(.*) (\d+)$/.exec(e);return t&&t[1]?`${t[1]} ${t[2]}`:e}function k(e,t){const n={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"remainder","<":"less","<=":"less-equal",">":"greater",">=":"greater-equal","===":"equal","!==":"not-equal"}[e];if(!n)throw b(`Operator "${e}" is not supported.`,t);return n}class ${tokens;index=0;constructor(e){this.tokens=function(e){const t=[];let n=0;for(;n<e.length;){const o=e[n];if(/\s/.test(o)){n++;continue}if("/"===o&&"/"===e[n+1]){for(n+=2;n<e.length&&"\n"!==e[n];)n++;continue}if("/"===o&&"*"===e[n+1]){const t=e.indexOf("*/",n+2);if(t<0)throw b("Unterminated block comment.",n);n=t+2;continue}if(/[A-Za-z_$]/.test(o)){const o=n++;for(;n<e.length&&/[A-Za-z0-9_$]/.test(e[n]);)n++;t.push({kind:"identifier",value:e.slice(o,n),offset:o});continue}if(/\d/.test(o)||"."===o&&/\d/.test(e[n+1]??"")){const o=n++;for(;n<e.length&&/[0-9.eE+-]/.test(e[n]);){const t=e.slice(o,n+1);if(!/^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d*)?$/.test(t))break;n++}const s=Number(e.slice(o,n));if(!Number.isFinite(s))throw b("Invalid numeric literal.",o);t.push({kind:"number",value:s,offset:o});continue}if('"'===o||"'"===o){const s=n++;let r="";for(;n<e.length&&e[n]!==o;){const t=e[n++];if("\\"!==t){r+=t;continue}if(n>=e.length)throw b("Unterminated string escape.",s);const o=e[n++],i={n:"\n",r:"\r",t:"\t",b:"\b",f:"\f",v:"\v",0:"\0","\\":"\\","'":"'",'"':'"'};if(o in i)r+=i[o];else{if("x"===o||"u"===o){const t="x"===o?2:4,s=e.slice(n,n+t);if(!new RegExp(`^[0-9a-fA-F]{${t}}$`).test(s))throw b("Invalid hexadecimal string escape.",n);r+=String.fromCharCode(Number.parseInt(s,16)),n+=t;continue}r+=o}}if(e[n]!==o)throw b("Unterminated string literal.",s);n++,t.push({kind:"string",value:r,offset:s});continue}const s=["===","!==","<=",">=","==","!=","&&","||"].find(t=>e.startsWith(t,n));if(s)t.push({kind:"operator",value:s,offset:n}),n+=s.length;else if("+-*/%<>=!".includes(o))t.push({kind:"operator",value:o,offset:n++});else{if(!"().,;?:".includes(o))throw b(`Token "${o}" is not permitted in safe expressions.`,n);t.push({kind:"punctuation",value:o,offset:n++})}}return t.push({kind:"eof",value:"",offset:e.length}),t}(e)}parseProgram(){const e=[];for(;"eof"!==this.peek().kind;)if("identifier"===this.peek().kind&&E.has(String(this.peek().value))?e.push(this.parseVariableStatement()):e.push({kind:"expression",expression:this.parseAssignment()}),";"===this.peek().value)this.take();else if("eof"!==this.peek().kind)throw b("Expected semicolon between expression statements.",this.peek().offset);return e}parseVariableStatement(){this.take();const e=[];for(;;){const t=this.expect("identifier");let n;if("="===this.peek().value&&(this.take(),n=this.parseAssignment()),e.push({name:String(t.value),...n?{initializer:n}:{},offset:t.offset}),","!==this.peek().value)break;this.take()}return{kind:"variable",declarations:e}}parseAssignment(){const e=this.parseConditional();if("="!==this.peek().value)return e;const t=this.take();if("identifier"!==e.kind)throw b("Only local identifier assignment is supported.",t.offset);return{kind:"assignment",target:e.name,value:this.parseAssignment(),offset:t.offset}}parseConditional(){const e=this.parseBinary(0);if("?"!==this.peek().value)return e;const t=this.take(),n=this.parseAssignment();return this.expectValue(":"),{kind:"conditional",test:e,consequent:n,alternate:this.parseAssignment(),offset:t.offset}}parseBinary(e){let t=this.parseUnary();for(;;){const n=this.peek(),o="string"==typeof n.value?_[n.value]:void 0;if(void 0===o||o<e)break;this.take(),t={kind:"binary",operator:String(n.value),left:t,right:this.parseBinary(o+1),offset:n.offset}}return t}parseUnary(){const e=this.peek();return"+"===e.value||"-"===e.value||"!"===e.value?(this.take(),{kind:"unary",operator:e.value,argument:this.parseUnary(),offset:e.offset}):this.parsePostfix()}parsePostfix(){let e=this.parsePrimary();for(;;){const t=this.peek();if("."===t.value){this.take();const n=this.expect("identifier");e={kind:"member",object:e,property:String(n.value),offset:t.offset};continue}if("("===t.value){this.take();const n=[];if(")"!==this.peek().value)for(;;){if(n.push(this.parseAssignment()),","!==this.peek().value)break;this.take()}this.expectValue(")"),e={kind:"call",callee:e,arguments:n,offset:t.offset};continue}return e}}parsePrimary(){const e=this.take();if("number"===e.kind||"string"===e.kind)return{kind:"literal",value:e.value,offset:e.offset};if("identifier"===e.kind)return"true"===e.value||"false"===e.value||"null"===e.value?{kind:"literal",value:"null"===e.value?null:"true"===e.value,offset:e.offset}:{kind:"identifier",name:String(e.value),offset:e.offset};if("("===e.value){const e=this.parseAssignment();return this.expectValue(")"),e}throw b(`Unexpected token "${String(e.value)}".`,e.offset)}peek(){return this.tokens[this.index]}take(){return this.tokens[this.index++]}expect(e){const t=this.take();if(t.kind!==e)throw b(`Expected ${e}.`,t.offset);return t}expectValue(e){const t=this.take();if(t.value!==e)throw b(`Expected "${e}".`,t.offset)}}const _={"||":1,"&&":2,"==":3,"!=":3,"===":3,"!==":3,"<":4,"<=":4,">":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},E=new Set(["var","let","const"]);function b(e,t){return new g(e,t)}const M="org.haiyue.vector-stroke@1",x="org.haiyue.vector-path-morph@1",I="org.haiyue.data-layer@1",L=1/64,w=256;function A(e,t={}){const r="string"==typeof e?Be(e):e,i=tt(r.fr,"$.fr"),a=et(r.ip??0,"$.ip"),c=et(r.op,"$.op");if(c<=a)throw new TypeError("Lottie op must be greater than ip.");const l=tt(r.w,"$.w"),u=tt(r.h,"$.h"),f=(c-a)/i,p={frameRate:i,secondsOffset:-a/i,secondsPerFrame:1/i},d=O(r,t.fonts),m=function(e,t){const n=new Map,o=[];for(const s of Je(Xe(e).list).map(Xe)){if("string"!=typeof s.fName||!s.fName)continue;const e=t.fonts?.[s.fName],r="string"==typeof e?{uri:e}:e,i=P("string"==typeof s.fStyle?s.fStyle:"Regular"),a={name:s.fName,family:r?.family??("string"==typeof s.fFamily&&s.fFamily?s.fFamily:s.fName),style:r?.style??i.style,weight:r?.weight??i.weight,...r?{resourceId:`font:${s.fName}`}:{}};n.set(s.fName,a),r&&o.push({id:a.resourceId,type:"binary",uri:r.uri,mimeType:r.mimeType??"font/woff2",...void 0===r.integrity?{}:{integrity:r.integrity}})}return{fonts:n,resources:o}}(r.fonts,t),h={frameRate:i,duration:f,diagnostics:[],tracks:[],timeline:p,shapeCounter:0,convertedLayerCount:0,skippedLayerCount:0,usesStrokeExtension:!1,usesPathMorphExtension:!1,usesVectorShapeExtension:!1,usesDataLayerExtension:!1,fonts:m.fonts,warnedFontSubstitutions:new Set},g=Je(r.layers),y=Je(r.assets),v=new Map;for(let e=0;e<y.length;e++){const t=Xe(y[e]);"string"==typeof t.id&&v.set(t.id,{value:t,index:e})}const T=C([g,...y.map(e=>Je(Xe(e).layers))],6),k=C([g,...y.map(e=>Je(Xe(e).layers))],15),$=[...R(r.assets,t,T,k),...m.resources],_=[];b(g,{listPath:"$.layers",idPrefix:"",timeline:p,compositionWidth:l,compositionHeight:u,precompStack:[]});const E={format:o,version:n,name:t.name??("string"==typeof r.nm?r.nm:"Converted Lottie"),canvas:{width:l,height:u,coordinateSystem:"screen-y-down"},duration:f,frameRate:i,endBehavior:"loop",resources:$,nodes:_,tracks:h.tracks,...h.usesStrokeExtension||h.usesPathMorphExtension||h.usesVectorShapeExtension||h.usesDataLayerExtension?{extensionsUsed:[...h.usesStrokeExtension?[M]:[],...h.usesPathMorphExtension?[x]:[],...h.usesVectorShapeExtension?[s]:[],...h.usesDataLayerExtension?[I]:[]]}:{}};if(t.strict&&h.diagnostics.length>0){const e=h.diagnostics[0];throw new TypeError(`Lottie conversion failed: ${e.message} (${e.path})`)}return Object.freeze({document:E,diagnostics:Object.freeze(h.diagnostics),convertedLayerCount:h.convertedLayerCount,skippedLayerCount:h.skippedLayerCount,fonts:d});function b(e,t){const n=h.timeline;h.timeline=t.timeline;try{const n=function(e,t){const n=new Map,o=new Set;for(let s=0;s<e.length;s++){const r=Xe(e[s]),i=nt(r.ind??s+1,`${t}[${s}].ind`);n.set(i,{layer:r,sourceIndex:s}),!0!==r.hd&&o.add(i)}const s=[...o];for(let e=0;e<s.length;e++){const r=s[e],i=n.get(r);if(!i||void 0===i.layer.parent)continue;const a=nt(i.layer.parent,`${t}[${i.sourceIndex}].parent`);n.has(a)&&!o.has(a)&&(o.add(a),s.push(a))}return o}(e,t.listPath),o=new Map,s=new Map;for(let r=0;r<e.length;r++){const i=Xe(e[r]),a=nt(i.ind??r+1,`${t.listPath}[${r}].ind`);n.has(a)&&(o.set(a,`${t.idPrefix}layer:${a}`),15===i.ty&&"string"==typeof i.nm&&"string"==typeof i.refId&&$.some(e=>e.id===i.refId&&"binary"===e.type)&&s.set(i.nm,i.refId))}for(let r=e.length-1;r>=0;r--){const i=Xe(e[r]),a=`${t.listPath}[${r}]`,c=nt(i.ind??r+1,`${a}.ind`);if(!n.has(c))continue;const l=o.get(c),u=nt(i.ty,`${a}.ty`),f=!0===i.hd,p=void 0===i.parent?void 0:nt(i.parent,`${a}.parent`),d=void 0===p?void 0:o.get(p);void 0===p||d||it(h,"W_LOTTIE_MISSING_PARENT",`${a}.parent`,`Parent layer ${p} was not found.`);const m=d??t.fallbackParent,g=0===u?t.timeline:He(i,a,t.timeline,h);h.timeline=g;try{const n=f?[]:fe(i.ef,a,h),c=null;f||ue(i,a,u,h);const p=z(i.ks,a,l,h),d=et(i.ip??0,`${a}.ip`),g=je(d,et(i.op??d+t.timeline.frameRate*h.duration,`${a}.op`),t.timeline,h.duration),y=f?{nodes:[]}:ye(i,r,e,o,l,a,t.listPath,h,t.compositionWidth,t.compositionHeight),v={id:l,name:"string"==typeof i.nm?i.nm:l,start:g.start,duration:g.duration,transform:p,...m?{parent:m}:{},...y.value?{composite:y.value}:{},...n.length>0?{effects:n}:{}};if(f){_.push(v),h.convertedLayerCount++;continue}if(0===u){_.push(v),_.push(...y.nodes),h.convertedLayerCount++,L(i,l,a,t);continue}if(1===u){const e=tt(i.sw,`${a}.sw`),t=tt(i.sh,`${a}.sh`);_.push({...v,components:[{type:"shape2d",shape:"rect",size:[e,t],position:[e/2,t/2],fill:ge(Ye(i.sc,`${a}.sc`),c)}]}),_.push(...y.nodes),h.convertedLayerCount++;continue}if(2===u){const e="string"==typeof i.refId?i.refId:"",n=$.find(t=>t.id===e);if(n&&"image"===n.type){const o=[n.width??t.compositionWidth,n.height??t.compositionHeight];_.push({...v,components:[{type:"sprite2d",resource:e,size:o,position:[o[0]/2,o[1]/2]}]})}else it(h,"W_LOTTIE_MISSING_IMAGE",`${a}.refId`,`Image asset "${e}" was not found.`),_.push(v);_.push(...y.nodes),h.convertedLayerCount++;continue}if(3===u){_.push(v),_.push(...y.nodes),h.convertedLayerCount++;continue}if(4===u){_.push(v);const e=D(i.shapes,l,a,h,c);_.push(...e),_.push(...y.nodes),e.some(e=>(e.components?.length??0)>0)||H(i.shapes)||j(i.shapes)||it(h,"W_LOTTIE_EMPTY_SHAPE",`${a}.shapes`,"No supported filled vector shape was found."),h.convertedLayerCount++;continue}if(5===u){const e=W(i.t,a,t.compositionWidth,h,c,s);_.push(e?{...v,components:[e]}:v),_.push(...y.nodes),e?h.convertedLayerCount++:h.skippedLayerCount++;continue}if(6===u){const e="string"==typeof i.refId?i.refId:"",t=$.find(t=>t.id===e);t&&"audio"===t.type?_.push({...v,components:[{type:"audio",resource:e,volume:1,loop:!1}]}):(it(h,"W_LOTTIE_MISSING_AUDIO",`${a}.refId`,`Audio asset "${e}" was not found.`),_.push(v)),_.push(...y.nodes),h.convertedLayerCount++;continue}if(15===u){const e="string"==typeof i.refId?i.refId:"",t=$.find(t=>t.id===e);t&&"binary"===t.type?(h.usesDataLayerExtension=!0,_.push({...v,extensions:{[I]:{resource:e,mediaType:t.mimeType??"application/octet-stream"}}})):(it(h,"W_LOTTIE_MISSING_DATA",`${a}.refId`,`Data asset "${e}" was not found.`),_.push(v)),_.push(...y.nodes),h.convertedLayerCount++;continue}_.push(v),_.push(...y.nodes),h.skippedLayerCount++,it(h,"W_LOTTIE_UNSUPPORTED_LAYER",`${a}.ty`,`Layer type ${u} is preserved as a transform-only node.`)}finally{h.timeline=t.timeline}}}finally{h.timeline=n}}function L(e,t,n,o){const s="string"==typeof e.refId?e.refId:"",r=v.get(s);if(!r||!Array.isArray(r.value.layers))return h.skippedLayerCount++,void it(h,"W_LOTTIE_MISSING_PRECOMP",`${n}.refId`,`Precomposition asset "${s}" was not found.`);if(o.precompStack.includes(s))return h.skippedLayerCount++,void it(h,"W_LOTTIE_PRECOMP_CYCLE",`${n}.refId`,`Precomposition cycle detected for asset "${s}".`);const i=et(e.sr??1,`${n}.sr`);if(i<=0)return h.skippedLayerCount++,void it(h,"W_LOTTIE_INVALID_TIME_STRETCH",`${n}.sr`,"Precomposition time stretch must be greater than zero.");const a=et(e.st??0,`${n}.st`),c=tt(r.value.fr??o.timeline.frameRate,`$.assets[${r.index}].fr`),l={frameRate:c,secondsOffset:ze(o.timeline,a),secondsPerFrame:o.timeline.secondsPerFrame*o.timeline.frameRate/c*i},u=void 0!==e.tm&&qe(e.tm)?function(e,t,n,o,s){if(!qe(e))return it(s,"W_LOTTIE_TIME_REMAP",o,"Static time remapping cannot be represented by ordinary HYA transform tracks."),null;const r=Je(Xe(e).k).map(Xe);if(r.length<2)return it(s,"W_LOTTIE_TIME_REMAP",o,"Time remapping requires at least two scalar keyframes."),null;const i=[];for(let e=0;e<r.length;e++){const t=r[e];if("number"!=typeof t.t||!Number.isFinite(t.t))return it(s,"W_LOTTIE_TIME_REMAP",`${o}.k[${e}].t`,"Time-remap keyframe time must be finite."),null;const n=Qe(t.s,Number.NaN);Number.isFinite(n)&&i.push({frame:t.t,value:n})}if(i.length<1)return it(s,"W_LOTTIE_TIME_REMAP",o,"Time remapping contains no scalar keyframe values."),null;const a=et(r.at(-1).t,`${o}.k[${r.length-1}].t`),c=r[Math.max(0,r.length-2)],l=Qe(r.at(-1).s,Qe(c.e,i.at(-1).value));a>i.at(-1).frame&&i.push({frame:a,value:l});for(let e=1;e<i.length;e++)if(i[e].frame<=i[e-1].frame||i[e].value+1e-6<i[e-1].value)return it(s,"W_LOTTIE_TIME_REMAP",o,"Non-monotonic time remapping requires runtime time-warp support and was not converted."),null;const u=i[0],f=i.at(-1),p=e=>{if(e<=u.frame)return u.value;if(e>=f.frame)return f.value;let t=0;for(;t+1<i.length&&e>=i[t+1].frame;)t++;const n=i[t],o=i[t+1],s=r[Math.min(t,r.length-1)];if(1===s.h||o.frame<=n.frame)return n.value;const a=Fe(st((e-n.frame)/(o.frame-n.frame),0,1),st(Qe(Xe(s.o).x,.333),0,1),Qe(Xe(s.o).y,.333),st(Qe(Xe(s.i).x,.667),0,1),Qe(Xe(s.i).y,.667));return n.value+(o.value-n.value)*a},d=e=>{if(e<=u.value)return u.frame;if(e>=f.value)return f.frame;let t=u.frame,n=f.frame;for(let o=0;o<28;o++){const o=(t+n)/2;p(o)<e?t=o:n=o}return(t+n)/2};return{frameRate:n,secondsOffset:ze(t,u.frame),secondsPerFrame:t.secondsPerFrame,mapFrameToSeconds:e=>ze(t,d(e/n))}}(e.tm,o.timeline,c,`${n}.tm`,h)??l:l;b(Je(r.value.layers),{listPath:`$.assets[${r.index}].layers`,idPrefix:`${t}/`,fallbackParent:t,timeline:u,compositionWidth:tt(r.value.w??e.w??o.compositionWidth,`$.assets[${r.index}].w`),compositionHeight:tt(r.value.h??e.h??o.compositionHeight,`$.assets[${r.index}].h`),precompStack:[...o.precompStack,s]})}}function O(e,t={}){const n="string"==typeof e?Be(e):e,o=new Map,s=e=>{if(!e||"object"!=typeof e)return;if(Array.isArray(e)){for(const t of e)s(t);return}const t=e;"string"==typeof t.f&&"string"==typeof t.t&&o.set(t.f,(o.get(t.f)??0)+1);for(const e of Object.values(t))s(e)};s(n.layers),s(n.assets);const r=Je(Xe(n.fonts).list).map(Xe),i=new Set(r.map(e=>"string"==typeof e.fName?e.fName:"").filter(Boolean));for(const e of o.keys())i.has(e)||r.push({fName:e,fFamily:e,fStyle:"Regular"});return Object.freeze(r.flatMap(e=>{if("string"!=typeof e.fName||!e.fName)return[];const n=t?.[e.fName],s="string"==typeof n?{uri:n}:n,r="string"==typeof e.fFamily&&e.fFamily?e.fFamily:e.fName,i="string"==typeof e.fStyle?e.fStyle:"Regular",a=P(i);return[Object.freeze({name:e.fName,authoredFamily:r,authoredStyle:i,..."number"==typeof e.ascent&&Number.isFinite(e.ascent)?{authoredAscent:e.ascent}:{},usageCount:o.get(e.fName)??0,mapped:void 0!==s,resolvedFamily:s?.family??r,resolvedStyle:s?.style??a.style,resolvedWeight:s?.weight??a.weight,...s?{uri:s.uri,mimeType:s.mimeType??"font/woff2"}:{},...void 0===s?.integrity?{}:{integrity:s.integrity},...void 0===s?.metrics?{}:{metrics:Object.freeze({...s.metrics})}})]}))}function S(e,t={}){return A(e,t).document}function P(e){const t=e.toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim(),n=t.replace(/\s+/g,""),o=t.includes("italic")||t.includes("oblique")?"italic":"normal";let s=400;return/thin|hairline/.test(n)?s=100:/extralight|ultralight/.test(n)?s=200:/light/.test(n)?s=300:/extrabold|ultrabold/.test(n)?s=800:/semibold|demibold|demi/.test(n)?s=600:/bold/.test(n)?s=700:/black|heavy/.test(n)?s=900:/medium/.test(n)&&(s=500),{style:o,weight:s}}function R(e,t,n,o){const s=[],r=Je(e);for(let e=0;e<r.length;e++){const i=Xe(r[e]);if("string"!=typeof i.id||"string"!=typeof i.p)continue;const a="string"==typeof i.u?i.u:"",c=i.p.startsWith("data:")?i.p:Ze(t.imageBaseUrl??"",`${a}${i.p}`);if(n.has(i.id))s.push({id:i.id,type:"audio",uri:c});else if(o.has(i.id)){const e=3===i.t||/\.json(?:$|[?#])/i.test(i.p)?"application/json":"application/octet-stream";s.push({id:i.id,type:"binary",uri:c,mimeType:e})}else s.push({id:i.id,type:"image",uri:c,..."number"==typeof i.w&&i.w>0?{width:i.w}:{},..."number"==typeof i.h&&i.h>0?{height:i.h}:{}})}return s}function C(e,t){const n=new Set;for(const o of e)for(const e of o){const o=Xe(e);o.ty===t&&"string"==typeof o.refId&&n.add(o.refId)}return n}function W(n,o,s,r,i,a){const c=Xe(n),l=Xe(c.d).x;let u;if("string"==typeof l&&l.trim().length>0)try{u=function(n,o){const s=new $(n).parseProgram(),r=[],i=new Map,a=new Map;let c,l=-1;for(let e=s.length-1;e>=0;e--)if("expression"===s[e].kind){l=e;break}const u=(e,t)=>{const n=i.get(e);if(void 0!==n)return n;if(i.size>=16)throw b("Expression declares too many local variables.",t);const o=i.size;return i.set(e,o),o},f=e=>{const t=y(e,a,o);if(t){if(0===t.path.length)throw b("Data Layer references must select a primitive field.",e.offset);r.push({op:"data",resource:t.resource,path:t.path})}else switch(e.kind){case"literal":return void r.push({op:"constant",value:e.value});case"identifier":{if("time"===e.name)return void r.push({op:"time"});if("value"===e.name)return void r.push({op:"text"});const t=i.get(e.name);if(void 0===t)throw b(`Unknown expression identifier "${e.name}".`,e.offset);return void r.push({op:"local.get",index:t})}case"unary":return f(e.argument),void r.push({op:"unary",operator:"+"===e.operator?"positive":"-"===e.operator?"negative":"not"});case"binary":return f(e.left),f(e.right),void r.push({op:"binary",operator:k(e.operator,e.offset)});case"conditional":f(e.test);{const t=r.length;r.push({op:"branch.false",target:t+1}),f(e.consequent);const n=r.length;r.push({op:"jump",target:n+1}),r[t].target=r.length,f(e.alternate),r[n].target=r.length}return;case"call":return void p(e);case"assignment":throw b("Nested assignments are not supported.",e.offset);case"member":if("identifier"===e.object.kind&&"Math"===e.object.name&&("PI"===e.property||"E"===e.property))return void r.push({op:"constant",value:"PI"===e.property?Math.PI:Math.E});throw b(`Property "${e.property}" is not available in the safe expression profile.`,e.offset)}},p=e=>{if("identifier"===e.callee.kind&&"$bm_sum"===e.callee.name){if(2!==e.arguments.length)throw b("$bm_sum requires exactly two arguments.",e.offset);return f(e.arguments[0]),f(e.arguments[1]),void r.push({op:"binary",operator:"add"})}if("member"===e.callee.kind&&"toFixed"===e.callee.property){if(1!==e.arguments.length)throw b("toFixed requires exactly one digits argument.",e.offset);return f(e.callee.object),f(e.arguments[0]),void r.push({op:"call",function:"to-fixed",argc:2})}const t=function(e){return"identifier"===e.kind?e.name:"member"===e.kind&&"identifier"===e.object.kind&&"Math"===e.object.name?e.property:null}(e.callee),n=function(e){return e?{abs:"abs",min:"min",max:"max",clamp:"clamp",floor:"floor",ceil:"ceil",round:"round",sqrt:"sqrt",pow:"pow",sin:"sin",cos:"cos",tan:"tan",asin:"asin",acos:"acos",atan:"atan",atan2:"atan2",log:"log",exp:"exp",lerp:"lerp"}[e]??null:null}(t);if(!n)throw b(`Function "${t??"<dynamic>"}" is not available in the safe expression profile.`,e.offset);for(const t of e.arguments)f(t);r.push({op:"call",function:n,argc:e.arguments.length})};for(let e=0;e<s.length;e++){const t=s[e];if("variable"===t.kind){for(const e of t.declarations){if("$bm_rt"===e.name){c=u(e.name,e.offset),e.initializer&&(f(e.initializer),r.push({op:"local.set",index:c}));continue}if(e.initializer){const t=y(e.initializer,a,o);if(t){a.set(e.name,t);continue}}const t=u(e.name,e.offset);e.initializer?f(e.initializer):r.push({op:"constant",value:null}),r.push({op:"local.set",index:t})}continue}const n=t.expression;if("assignment"===n.kind){if("$bm_rt"===n.target){c=u(n.target,n.offset),f(n.value),r.push({op:"local.set",index:c});continue}const e=y(n.value,a,o);if(e){a.set(n.target,e);continue}const t=u(n.target,n.offset);f(n.value),r.push({op:"local.set",index:t});continue}f(n),e===l&&void 0===c||r.push({op:"pop"})}if(void 0!==c&&r.push({op:"local.get",index:c}),void 0===c&&l<0)throw b("Expression does not produce a result.",0);return r.push({op:"return"}),e({version:t,result:"text",localCount:i.size,instructions:r},"$.compiledExpression")}(l,{resolveDataLayer:e=>a.get(e)})}catch(e){it(r,"W_LOTTIE_TEXT_EXPRESSION",`${o}.t.d.x`,`Text document expression could not be lowered to safe HYA IR: ${e instanceof g?`${e.message} (source offset ${e.offset})`:e instanceof Error?e.message:String(e)}`)}const f=Je(Xe(c.d).k).map(Xe),p=[];for(let e=0;e<f.length;e++){const t=f[e],n=Xe(t.s);if("string"!=typeof n.t){it(r,"W_LOTTIE_INVALID_TEXT",`${o}.t.d.k[${e}].s`,"Text document has no string value.");continue}const s=N(n,ze(r.timeline,et(t.t??0,`${o}.t.d.k[${e}].t`)),r,i,`${o}.t.d.k[${e}].s`);p.length>0&&s.time<=p[p.length-1].time?it(r,"W_LOTTIE_TEXT_DOCUMENT_TIME",`${o}.t.d.k[${e}].t`,"Duplicate or reversed text document time was omitted."):p.push(s)}const d=p[0];if(!d)return it(r,"W_LOTTIE_INVALID_TEXT",`${o}.t.d`,"Text layer has no usable text document."),null;const m=Ke(Xe(f[0]?.s).sz),h=m[0]&&m[0]>0?m[0]:Math.min(s,Math.max(64,Math.max(...p.map(e=>e.text.length))*(d.fontSize??32)*.7)),v=m[1]&&m[1]>0?m[1]:1.35*(d.lineHeight??1.2*(d.fontSize??32)),T=function(e,t,n,o){const s=[],r=Je(e).map(Xe);for(let e=0;e<r.length;e++){const i=r[e],a=`${n}[${e}]`,c=Xe(i.s),l=void 0===c.t?0:nt(c.t,`${a}.s.t`),u=void 0===c.b?1:nt(c.b,`${a}.s.b`);if(0!==l){it(o,"W_LOTTIE_TEXT_SELECTOR",`${a}.s.t`,"Expression text selectors are not executed; use an offline bake or a range selector.");continue}const f=[void 0,"characters","characters-excluding-spaces","words","lines"][u];if(!f){it(o,"W_LOTTIE_TEXT_SELECTOR",`${a}.s.b`,`Text selector based-on mode ${u} is not supported.`);continue}const p=[["xe",c.xe],["ne",c.ne],["sm",c.sm]].find(([,e])=>qe(e));if(p){it(o,"W_LOTTIE_TEXT_SELECTOR",`${a}.s.${p[0]}`,"Animated selector easing or smoothness requires offline baking.");continue}const d=2===c.r?"index":"percent",m=e=>["percent"===d?(e[0]??0)/100:e[0]??0],h=c.s,g=c.e,y=c.o,v=c.a,T=m([Ve(h,0)])[0],k=m([Ve(g,"percent"===d?100:0)])[0],$=m([Ve(y,0)])[0],_=st(Ve(v,100)/100,-1,1),E=void 0===c.sh?1:nt(c.sh,`${a}.s.sh`),b=["square","square","ramp-up","ramp-down","triangle","round","smooth"][E];if(!b){it(o,"W_LOTTIE_TEXT_SELECTOR",`${a}.s.sh`,`Range selector shape ${E} is not supported.`);continue}const M=st(Ve(c.xe,0),-100,100)/100,x=st(Ve(c.ne,0),-100,100)/100,I=[x>0?x:0,x<0?-x:0,M>0?1-M:1,M<0?1+M:1],L=st(Ve(c.sm,100)/100,0,1),w=1===c.rn?rt(a):void 0,A=Xe(i.a),O=Ue(A.p,[0,0]),S=Ue(A.s,[100,100]),P=Ue(A.fc,[1,1,1]),R=Ne(h,o,`${a}.s.s`,m),C=Ne(g,o,`${a}.s.e`,m),W=Ne(y,o,`${a}.s.o`,m),N=Ne(v,o,`${a}.s.a`,e=>[st((e[0]??100)/100,-1,1)]),z=Ne(A.p,o,`${a}.a.p`,e=>[e[0]??0,e[1]??0]),F=Ne(A.s,o,`${a}.a.s`,e=>[(e[0]??100)/100,(e[1]??100)/100]),D=Ne(A.r,o,`${a}.a.r`,e=>[ot(e[0]??0)]),H=Ne(A.o,o,`${a}.a.o`,e=>[st((e[0]??100)/100,0,1)]),j=Ne(A.fc,o,`${a}.a.fc`,e=>[st(e[0]??1,0,1),st(e[1]??1,0,1),st(e[2]??1,0,1),1]),q=Ne(A.t,o,`${a}.a.t`,e=>[(e[0]??0)*t/1e3]);s.push({selector:{start:T,end:k,offset:$,units:d,amount:_,shape:b,basedOn:f,...0===I[0]&&0===I[1]&&1===I[2]&&1===I[3]?{}:{easing:I},...1===L?{}:{smoothness:L},...void 0===w?{}:{randomSeed:w},...R?{startTrack:R}:{},...C?{endTrack:C}:{},...W?{offsetTrack:W}:{},...N?{amountTrack:N}:{}},...void 0===A.p?{}:{position:[O[0]??0,O[1]??0]},...void 0===A.s?{}:{scale:[(S[0]??100)/100,(S[1]??100)/100]},...void 0===A.r?{}:{rotation:ot(Ve(A.r,0))},...void 0===A.o?{}:{opacity:st(Ve(A.o,100)/100,0,1)},...void 0===A.fc?{}:{fillColor:[st(P[0]??1,0,1),st(P[1]??1,0,1),st(P[2]??1,0,1),1]},...void 0===A.t?{}:{tracking:Ve(A.t,0)*t/1e3},...z?{positionTrack:z}:{},...F?{scaleTrack:F}:{},...D?{rotationTrack:D}:{},...H?{opacityTrack:H}:{},...j?{fillColorTrack:j}:{},...q?{trackingTrack:q}:{}})}return s}(c.a,d.fontSize??32,`${o}.t.a`,r);return{type:"text2d",text:d.text,size:[h,v],...void 0===d.fontFamily?{}:{fontFamily:d.fontFamily},...void 0===d.fontSize?{}:{fontSize:d.fontSize},...void 0===d.fontWeight?{}:{fontWeight:d.fontWeight},...void 0===d.fontStyle?{}:{fontStyle:d.fontStyle},...void 0===d.fontResource?{}:{fontResource:d.fontResource},...void 0===d.lineHeight?{}:{lineHeight:d.lineHeight},...void 0===d.tracking?{}:{tracking:d.tracking},...void 0===d.textAlign?{}:{textAlign:d.textAlign},verticalAlign:"middle",color:d.color??[1,1,1,1],...p.length>1?{documents:p}:{},...T.length>0?{animators:T}:{},...u?{expression:u}:{}}}function N(e,t,n,o,s){const r="number"==typeof e.s&&e.s>0?e.s:32,i="string"==typeof e.f?e.f:"",a=n.fonts.get(i);!i||a?.resourceId||n.warnedFontSubstitutions.has(i)||(n.warnedFontSubstitutions.add(i),it(n,"W_LOTTIE_FONT_SUBSTITUTION",`${s}.f`,`Font "${i}" has no mapped web-font resource; the original family, style and weight are preserved and the browser may use a system fallback.`));const c=Ke(e.fc),l="number"==typeof e.j?e.j:2;return{time:Math.max(0,t),text:e.t,fontFamily:a?.family??(i||"sans-serif"),fontSize:r,fontWeight:a?.weight??400,fontStyle:a?.style??"normal",...void 0===a?.resourceId?{}:{fontResource:a.resourceId},lineHeight:"number"==typeof e.lh&&e.lh>0?e.lh:1.2*r,tracking:et(e.tr??0,`${s}.tr`)*r/1e3,textAlign:0===l?"left":1===l?"right":"center",color:ge([st(c[0]??1,0,1),st(c[1]??1,0,1),st(c[2]??1,0,1),1])}}function z(e,t,n,o){return F(Xe(e),`${t}.ks`,n,o)}function F(e,t,n,o){const s=Ue(e.p,[0,0]),r=Ue(e.s,[100,100]),i=Ue(e.a,[0,0]),a=Ve(e.r??e.rz,0),c=Ve(e.o,100);return We(e.p,n,"position",o,e=>[e[0]??0,e[1]??0],`${t}.p`),We(e.s,n,"scale",o,e=>[(e[0]??100)/100,(e[1]??100)/100],`${t}.s`),We(e.r??e.rz,n,"rotation",o,e=>[ot(e[0]??0)],`${t}.r`),We(e.o,n,"opacity",o,e=>[st((e[0]??100)/100,0,1)],`${t}.o`),qe(e.a)&&it(o,"W_LOTTIE_ANIMATED_ANCHOR",`${t}.a`,"Animated anchor points are sampled at their initial value."),{position:[s[0]??0,s[1]??0],rotation:ot(a),scale:[(r[0]??100)/100,(r[1]??100)/100],anchor:[i[0]??0,i[1]??0],opacity:st(c/100,0,1)}}function D(e,t,n,o,s){const r=[];return function e(n,s,i,a,c){const l=[],u=[];for(let e=0;e<n.length;e++){const t=Xe(n[e]);if(!0===t.hd)continue;if("fl"===t.ty&&l.push({index:e,paint:{kind:"fill",fill:X(t,`${c}[${e}]`,o),fillRule:2===t.r?"evenodd":"nonzero"}}),"gf"===t.ty&&l.push({index:e,paint:{kind:"fill",fill:J(t,`${c}[${e}]`,o),fillRule:2===t.r?"evenodd":"nonzero"}}),"st"===t.ty){const n=re(t,`${c}[${e}]`,o);n&&l.push({index:e,paint:{kind:"stroke",stroke:n}})}if("gs"===t.ty){const n=Q(t,`${c}[${e}]`,o);n&&l.push({index:e,paint:{kind:"stroke",stroke:n}})}const s=oe(t,`${c}[${e}]`,o);s&&u.push({index:e,modifier:s})}const f=e=>[...s,...l.filter(t=>t.index>e).map(e=>e.paint)],p=e=>[...u.filter(t=>t.index>e).map(e=>e.modifier),...i],d=function(e,t,n){const o=new Map;let s=0;for(let r=0;r<e.length;r++){const i=Xe(e[r]);if("mm"!==i.ty||!0===i.hd)continue;const a=`${t}[${r}]`,c=[];let l;for(let t=s;t<r;t++){const n=Xe(e[t]);!0!==n.hd&&(Y(n.ty)?c.push(t):["tm","rd","rp","pb","zz","op","tw"].includes(String(n.ty))&&(l=String(n.ty)))}if(s=r+1,0===c.length){it(n,"W_LOTTIE_MERGE_PATH_INPUT",a,"Merge Paths has no preceding path geometry to combine.");continue}if(l){it(n,"W_LOTTIE_MERGE_PATH_INPUT",a,`Merge Paths cannot yet bake the preceding "${l}" modifier.`);continue}const u="number"==typeof i.mm&&Number.isInteger(i.mm)?i.mm:1;if(u<1||u>5){it(n,"W_LOTTIE_MERGE_PATH_INPUT",`${a}.mm`,`Unknown Merge Paths mode "${String(i.mm)}".`);continue}const f=c.map(o=>Z(Xe(e[o]),`${t}[${o}]`,n));if(f.some(e=>e.animated)){const s=1===u?G(e,c,t,n):void 0;s?o.set(r,{inputIndices:c,prepared:s}):it(n,"W_LOTTIE_ANIMATED_MERGE_PATH",a,1===u?"Animated Merge Paths could not be baked into a stable compound morph.":`Animated Merge Paths mode ${u} requires time-varying boolean topology and remains unmerged.`);continue}const p=f.find(e=>e.unsupportedReason)?.unsupportedReason;if(p)it(n,"W_LOTTIE_MERGE_PATH_INPUT",a,p);else try{o.set(r,{inputIndices:c,...B(f,u)??{}})}catch(e){it(n,"W_LOTTIE_MERGE_PATH_GEOMETRY",a,`Static Merge Paths boolean failed: ${e instanceof Error?e.message:String(e)}`)}}return o}(n,c,o),m=new Set([...d.values()].flatMap(e=>e.inputIndices));for(let s=0;s<n.length;s++){const i=Xe(n[s]),l=`${c}[${s}]`;if(!0===i.hd)continue;if(m.has(s))continue;if("mm"===i.ty){const e=d.get(s);if(!e)continue;const n=f(s).flatMap(t=>e.prepared?te(e.prepared,t,p(s),o):e.path?ne(e.path,t,p(s),o):[]);if(0===n.length)continue;const c=`${t}:shape:${o.shapeCounter++}`;r.push({id:c,name:"string"==typeof i.nm?i.nm:c,parent:a,components:n});continue}if("gr"===i.ty){const n=Je(i.it),c=n.findIndex(e=>"tr"===Xe(e).ty),u=`${t}:group:${o.shapeCounter++}`,d={id:u,name:"string"==typeof i.nm?i.nm:u,parent:a};if(c>=0){const e=Xe(n[c]);d.transform=F(e,`${l}.it[${c}]`,u,o),(qe(e.sk)||qe(e.sa)||Math.abs(Ve(e.sk,0))>1e-6||Math.abs(Ve(e.sa,0))>1e-6)&&it(o,"W_LOTTIE_GROUP_SKEW",`${l}.it[${c}]`,"Shape group skew is not converted.")}r.push(d),e(n,f(s),p(s),u,`${l}.it`);continue}if("sh"===i.ty){const e=ee(i.ks,`${l}.ks`,o),n=e?f(s).flatMap(t=>te(e,t,p(s),o)):[];if(0===n.length)continue;const c=`${t}:shape:${o.shapeCounter++}`;r.push({id:c,name:"string"==typeof i.nm?i.nm:c,parent:a,components:n});continue}if("sr"===i.ty){const e=f(s);if(0===e.length)continue;const n=le(i,l,o);if(!n)continue;const c=`${t}:shape:${o.shapeCounter++}`,u=Ue(i.p,[0,0]),d=Ve(i.r,0);We(i.p,c,"position",o,e=>[e[0]??0,e[1]??0],`${l}.p`),We(i.r,c,"rotation",o,e=>[ot(e[0]??0)],`${l}.r`),r.push({id:c,name:"string"==typeof i.nm?i.nm:c,parent:a,transform:{position:[u[0]??0,u[1]??0],rotation:ot(d)},components:e.flatMap(e=>ne(n,e,p(s),o))});continue}if("rc"!==i.ty&&"el"!==i.ty){["fl","gf","st","gs","tr","tm","rd","mm"].includes(String(i.ty))||it(o,"W_LOTTIE_UNSUPPORTED_SHAPE",`${l}.ty`,`Shape operator "${String(i.ty)}" is not converted.`);continue}const u=f(s);if(0===u.length)continue;const h=Ge(i.s,2)??Ue(i.s,[0,0]),g=Ue(i.p,[0,0]);if((h[0]??0)<=0||(h[1]??0)<=0){it(o,"W_LOTTIE_INVALID_SHAPE_SIZE",`${l}.s`,"Shape has no positive static size.");continue}const y=`${t}:shape:${o.shapeCounter++}`,v="rc"===i.ty?Math.max(0,Ve(i.r,0)):0,T="rc"===i.ty?ae(h[0],h[1],v):ce(h[0]/2,h[1]/2),k=u.flatMap(e=>ne(T,e,p(s),o));We(i.p,y,"position",o,e=>[e[0]??0,e[1]??0],`${l}.p`),We(i.s,y,"scale",o,e=>[(e[0]??h[0])/h[0],(e[1]??h[1])/h[1]],`${l}.s`),"rc"===i.ty&&qe(i.r)&&it(o,"W_LOTTIE_ANIMATED_ROUNDED_RECT",`${l}.r`,"Animated corner radius is sampled at its initial value."),r.push({id:y,name:"string"==typeof i.nm?i.nm:y,parent:a,transform:{position:[g[0]??0,g[1]??0]},components:k})}}(Je(e),[],[],t,`${n}.shapes`),r}function H(e){const t=[],n=e=>{for(const o of e){const e=Xe(o);!0!==e.hd&&("gr"===e.ty?n(Je(e.it)):"fl"!==e.ty&&"gf"!==e.ty&&"st"!==e.ty&&"gs"!==e.ty||t.push(e))}};return n(Je(e)),0!==t.length&&t.every(e=>{if(!((Ge(e.o,1)?.[0]??Ve(e.o,100))>0))return!0;if("st"===e.ty||"gs"===e.ty)return void 0===Ge(e.w,1);if("fl"===e.ty){return(Ue(e.c,[1,1,1,1])[3]??1)<=0}return!1})}function j(e){let t=0,n=!1;const o=e=>{for(const s of e){const e=Xe(s);!0!==e.hd&&("gr"!==e.ty?"sh"!==e.ty?"rc"!==e.ty&&"el"!==e.ty&&"sr"!==e.ty&&"mm"!==e.ty||(n=!0):(t++,q(e.ks)||(n=!0)):o(Je(e.it)))}};return o(Je(e)),t>0&&!n}function q(e){const t=Xe(e);if(!qe(t))return U(Se(e));const n=[];for(const e of Je(t.k).map(Xe))for(const t of[e.s,e.e]){if(void 0===t)continue;const e=Xe(Je(t)[0]??t);Object.keys(e).length>0&&n.push(e)}return n.length>0&&n.every(U)}function U(e){return Array.isArray(e.v)&&0===e.v.length&&Array.isArray(e.i)&&0===e.i.length&&Array.isArray(e.o)&&0===e.o.length}function G(e,t,n,o){const s=[];for(const r of t){const t=Xe(e[r]);if("sh"!==t.ty)return;const i=ee(t.ks,`${n}[${r}].ks`,o);if(!i)return;s.push(i)}if(0===s.length)return;const r=s.map(e=>e.commands).join(""),i=s.filter(e=>void 0!==e.morph);if(0===i.length)return{sourcePath:n,commands:r,values:s.flatMap(e=>e.values),closed:s.every(e=>e.closed)};const a=Math.min(...i.map(e=>e.morph.times[0])),c=Math.max(...i.map(e=>e.morph.times.at(-1))),l=new Set;for(const e of i)for(const t of e.morph.times)l.add(Math.fround(t));const u=1/Math.max(1,o.frameRate),f=Math.ceil(a/u-1e-6),p=Math.floor(c/u+1e-6);if(p-f+1>1024)return;for(let e=f;e<=p;e++)l.add(Math.fround(st(e*u,0,o.duration)));const d=[...l].filter(e=>e>=0&&e<=o.duration).sort((e,t)=>e-t).filter((e,t,n)=>0===t||e>n[t-1]);if(0===d.length)return;const m=[];for(const e of d)for(const t of s)m.push(...t.morph?V(t.morph,e):t.values);const h=s.reduce((e,t)=>e+t.values.length,0);return{sourcePath:n,commands:r,values:m.slice(0,h),closed:s.every(e=>e.closed),morph:{times:d,values:m,valueSize:h,interpolation:"linear"}}}function V(e,t){const n=e.times;let o=0;if(t>=n[n.length-1])o=n.length-1;else for(;o+1<n.length&&t>=n[o+1];)o++;const s=Math.min(o+1,n.length-1);let r=0;if(s!==o&&"step"!==e.interpolation&&(r=st((t-n[o])/Math.max(1e-8,n[s]-n[o]),0,1),"cubic-bezier"===e.interpolation&&e.easings)){const t=4*o;r=Fe(r,e.easings[t]??.333,e.easings[t+1]??.333,e.easings[t+2]??.667,e.easings[t+3]??.667)}const i=new Array(e.valueSize),a=o*e.valueSize,c=s*e.valueSize;for(let t=0;t<e.valueSize;t++){const n=e.values[a+t]??0;i[t]=n+((e.values[c+t]??n)-n)*r}return i}function Y(e){return"sh"===e||"rc"===e||"el"===e||"sr"===e||"gr"===e}function Z(e,t,n){if("sh"===e.ty){if(qe(e.ks))return{paths:[],animated:!0};const o=Oe(Se(e.ks),`${t}.ks`,n,!1,!1);return o?{paths:[o],animated:!1}:{paths:[],animated:!1,unsupportedReason:`Merge Paths input at ${t} is not valid path geometry.`}}if("rc"===e.ty||"el"===e.ty){if([e.s,e.p,..."rc"===e.ty?[e.r]:[]].some(qe))return{paths:[],animated:!0};const n=Ue(e.s,[0,0]);if((n[0]??0)<=0||(n[1]??0)<=0)return{paths:[],animated:!1,unsupportedReason:`Merge Paths primitive at ${t} has no positive size.`};const r="rc"===e.ty?ae(n[0],n[1],Math.max(0,Ve(e.r,0))):ce(n[0]/2,n[1]/2),i=Ue(e.p,[0,0]);return{paths:[l(r,(o=i[0]??0,s=i[1]??0,[1,0,0,1,o,s]))],animated:!1}}var o,s;if("sr"===e.ty){if([e.pt,e.or,e.ir,e.is,e.os,e.p,e.r].some(qe))return{paths:[],animated:!0};const o=le(e,t,n);if(!o)return{paths:[],animated:!1,unsupportedReason:`Merge Paths polystar at ${t} is invalid.`};return{paths:[l(o,c(Ue(e.p,[0,0]),[0,0],[100,100],ot(Ve(e.r,0))))],animated:!1}}if("gr"===e.ty){const o=Je(e.it),s=o.map(Xe).find(e=>"tr"===e.ty);if(s&&[s.p,s.a,s.s,s.r??s.rz,s.sk,s.sa].some(qe))return{paths:[],animated:!0};if(s&&(Math.abs(Ve(s.sk,0))>1e-6||Math.abs(Ve(s.sa,0))>1e-6))return{paths:[],animated:!1,unsupportedReason:`Merge Paths group at ${t} uses skew, which is not safe to bake.`};const r=o.map((e,t)=>({item:Xe(e),index:t})).filter(e=>!0!==e.item.hd&&Y(e.item.ty)),i=o.map(Xe).find(e=>!0!==e.hd&&["mm","tm","rd","rp","pb","zz","op","tw"].includes(String(e.ty)));if(i)return{paths:[],animated:!1,unsupportedReason:`Nested Merge Paths input at ${t} contains the "${String(i.ty)}" operator.`};const a=r.map(e=>Z(e.item,`${t}.it[${e.index}]`,n));if(a.some(e=>e.animated))return{paths:[],animated:!0};const u=a.find(e=>e.unsupportedReason)?.unsupportedReason;if(u)return{paths:[],animated:!1,unsupportedReason:u};const f=s?c(Ue(s.p,[0,0]),Ue(s.a,[0,0]),Ue(s.s,[100,100]),ot(Ve(s.r??s.rz,0))):[1,0,0,1,0,0];return{paths:a.flatMap(e=>e.paths).map(e=>l(e,f)),animated:!1}}return{paths:[],animated:!1,unsupportedReason:`Merge Paths input at ${t} is not supported.`}}function B(e,t){const n=a(e.map(e=>e.paths),t);return n?{path:n}:null}function X(e,t,n,o){const s=Ue(e.c,[1,1,1,1]),r=st(Ve(e.o,100)/100,0,1),i=ge([st(s[0]??1,0,1),st(s[1]??1,0,1),st(s[2]??1,0,1),st(s[3]??1,0,1)]),a=Ne(e.c,n,`${t}.c`,e=>[...ge([st(e[0]??1,0,1),st(e[1]??1,0,1),st(e[2]??1,0,1),st(e[3]??1,0,1)])]),c=Ne(e.o,n,`${t}.o`,e=>[st((e[0]??100)/100,0,1)]);return{kind:"solid",color:i,opacity:r,...a?{colorTrack:a}:{},...c?{opacityTrack:c}:{}}}function J(e,t,n,o){const s=Xe(e.g);2===e.t&&(qe(e.h)||qe(e.a)||Math.abs(Ve(e.h,0))>1e-6||Math.abs(Ve(e.a,0))>1e-6)&&it(n,"W_LOTTIE_GRADIENT_HIGHLIGHT",t,"Radial gradient highlight length and angle are not converted.");const r=Math.max(2,nt(s.p??2,`${t}.g.p`)),i=Math.min(8,r);r>8&&it(n,"W_LOTTIE_GRADIENT_STOP_LIMIT",`${t}.g.p`,"Gradient is resampled to the eight-stop HYA runtime budget.");const a=s.k,c=st(Ve(e.o,100)/100,0,1),l=K(Ue(a,[]),r,i),u=Ue(e.s,[0,0]),f=Ue(e.e,[100,0]),p=Ne(a,n,`${t}.g.k`,e=>K(e,r,i)),d=Ne(e.s,n,`${t}.s`,e=>[e[0]??0,e[1]??0]),m=Ne(e.e,n,`${t}.e`,e=>[e[0]??0,e[1]??0]),h=Ne(e.o,n,`${t}.o`,e=>[st((e[0]??100)/100,0,1)]);return{kind:2===e.t?"radial-gradient":"linear-gradient",start:[u[0]??0,u[1]??0],end:[f[0]??100,f[1]??0],stops:l,opacity:c,...d?{startTrack:d}:{},...m?{endTrack:m}:{},...p?{stopsTrack:p}:{},...h?{opacityTrack:h}:{}}}function K(e,t,n,o){const s=Math.min(t,Math.floor(e.length/4)),r=e.slice(4*s),i=e=>{if(r.length<2)return 1;let t=0;for(;t+3<r.length&&r[t+2]<=e;)t+=2;const n=r[Math.max(0,t)]??0,o=r[Math.max(0,t)+1]??1,s=r[Math.min(r.length-2,t+2)]??n,i=r[Math.min(r.length-1,t+3)]??o,a=s<=n?0:st((e-n)/(s-n),0,1);return st(o+(i-o)*a,0,1)},a=t=>{if(0===s)return[1,1,1];let n=0;for(;n+1<s&&(e[4*(n+1)]??1)<=t;)n++;const o=Math.min(s-1,n+1),r=e[4*n]??0,i=e[4*o]??r,a=i<=r?0:st((t-r)/(i-r),0,1);return[1,2,3].map(t=>st((e[4*n+t]??1)+((e[4*o+t]??e[4*n+t]??1)-(e[4*n+t]??1))*a,0,1))},c=[];for(let t=0;t<n;t++){const o=n===s?t:-1,r=st(o>=0?e[4*o]??0:t/Math.max(1,n-1),0,1),l=a(r),u=ge([l[0],l[1],l[2],i(r)]);c.push(r,...u)}return c}function Q(e,t,n,o){const s=re({...e,c:{a:0,k:[1,1,1,1]}},t,n);return s?{...s,gradient:J(e,t,n)}:null}function ee(e,t,n){if(qe(e)){const o=$e(e,t,n,!1);if(o)return{sourcePath:t,commands:o.commands,values:o.values.slice(0,o.valueSize),closed:o.commands.endsWith("Z"),morph:{times:o.times,values:o.values,valueSize:o.valueSize,interpolation:o.interpolation,...o.easings?{easings:o.easings}:{}}}}const o=Se(e),s=Oe(o,t,n,!1,!1);return s?{sourcePath:t,commands:s.commands,values:Array.from(s.values),closed:!1!==o.c}:null}function te(e,t,n,o){const r="fill"===t.kind?function(e,t){if(e.closed)return e;it(t,"W_LOTTIE_OPEN_FILLED_PATH",e.sourcePath,"Open filled path is closed with a straight segment.");const n=e=>[...e,e[0]??0,e[1]??0];if(!e.morph)return{commands:`${e.commands}LZ`,values:n(e.values),closed:!0,sourcePath:e.sourcePath};const o=[];for(let t=0;t<e.morph.times.length;t++){const s=t*e.morph.valueSize;o.push(...n(Array.from(e.morph.values).slice(s,s+e.morph.valueSize)))}return{commands:`${e.commands}LZ`,values:n(e.values),closed:!0,sourcePath:e.sourcePath,morph:{...e.morph,values:o,valueSize:e.morph.valueSize+2}}}(e,o):e,i=r.morph?function(e,t){const n=Array.from(e.values,(n,o)=>Ae(n-(t[o%e.valueSize]??0)));return{times:e.times,values:n,valueSize:e.valueSize,interpolation:e.interpolation,...e.easings?{easings:e.easings}:{}}}(r.morph,r.values):void 0;var a;if(!(void 0!==e.morph||n.length>0||"fill"===t.kind&&("solid"!==t.fill.kind||void 0!==t.fill.colorTrack||void 0!==t.fill.opacityTrack)||"stroke"===t.kind&&(void 0!==(a=t.stroke).colorTrack||void 0!==a.opacityTrack||void 0!==a.widthTrack||void 0!==a.dash||void 0!==a.dashOffsetTrack||void 0!==a.gradient))){if("fill"===t.kind&&"solid"===t.fill.kind)return[{type:"path2d",commands:r.commands,values:r.values,fill:[t.fill.color[0],t.fill.color[1],t.fill.color[2],t.fill.color[3]*(t.fill.opacity??1)],fillRule:t.fillRule}];if("stroke"===t.kind)return[ie(r.commands,r.values,t.stroke,o)]}return o.usesVectorShapeExtension=!0,[{type:s,commands:r.commands,values:r.values,...i?{morph:i,morphRelative:!0}:{},..."fill"===t.kind?{fill:t.fill}:{stroke:se(t.stroke)},...n.length>0?{modifiers:n}:{},fillRule:"fill"===t.kind?t.fillRule:"nonzero",tolerance:.35}]}function ne(e,t,n,o){return te({sourcePath:"$generated",commands:e.commands,values:Array.from(e.values),closed:e.commands.endsWith("Z")},t,n,o)}function oe(e,t,n){if("tm"===e.ty){const o=Ne(e.s,n,`${t}.s`,e=>[(e[0]??0)/100]),s=Ne(e.e,n,`${t}.e`,e=>[(e[0]??100)/100]),r=Ne(e.o,n,`${t}.o`,e=>[(e[0]??0)/360]);return{kind:"trim-path",start:Ve(e.s,0)/100,end:Ve(e.e,100)/100,offset:Ve(e.o,0)/360,mode:2===e.m?"individual":"simultaneous",...o?{startTrack:o}:{},...s?{endTrack:s}:{},...r?{offsetTrack:r}:{}}}if("rd"===e.ty){const o=Ne(e.r,n,`${t}.r`,e=>[Math.max(0,e[0]??0)]);return{kind:"round-corners",radius:Math.max(0,Ve(e.r,0)),...o?{radiusTrack:o}:{}}}return null}function se(e){const t=e.gradient;return{color:e.color,width:e.width,opacity:e.opacity,lineCap:2===e.lineCap?"round":3===e.lineCap?"square":"butt",lineJoin:2===e.lineJoin?"round":3===e.lineJoin?"bevel":"miter",miterLimit:e.miterLimit,...t?{gradient:t}:{},...e.dash?{dash:e.dash}:{},...void 0===e.dashOffset?{}:{dashOffset:e.dashOffset},...e.colorTrack?{colorTrack:e.colorTrack}:{},...e.opacityTrack?{opacityTrack:e.opacityTrack}:{},...e.widthTrack?{widthTrack:e.widthTrack}:{},...e.dashOffsetTrack?{dashOffsetTrack:e.dashOffsetTrack}:{}}}function re(e,t,n){const o=Ue(e.c,[0,0,0,1]),s=st(Ve(e.o,100)/100,0,1),r=Ve(e.w,0),i=Ge(e.w,1)?.[0];if(r<0||void 0!==i&&i<0)return it(n,"W_LOTTIE_INVALID_STROKE",`${t}.w`,"Stroke width cannot be negative."),null;const a=r>0?r:i;if(void 0===a)return null;const c=Ne(e.c,n,`${t}.c`,e=>[st(e[0]??0,0,1),st(e[1]??0,0,1),st(e[2]??0,0,1),st(e[3]??1,0,1)]),l=Ne(e.o,n,`${t}.o`,e=>[st((e[0]??100)/100,0,1)]),u=Ne(e.w,n,`${t}.w`,e=>[Math.max(0,e[0]??a)]),f=Je(e.d).map(Xe),p=f.filter(e=>"o"!==e.n).map((e,o)=>(qe(e.v)&&it(n,"W_LOTTIE_ANIMATED_STROKE_DASH",`${t}.d[${o}].v`,"Animated dash lengths are sampled at their initial value."),Math.max(0,Ve(e.v,0)))).filter(e=>e>0),d=f.find(e=>"o"===e.n),m=d?Ve(d.v,0):void 0,h=d?Ne(d.v,n,`${t}.d`,e=>[e[0]??0]):void 0;return{color:[st(o[0]??0,0,1),st(o[1]??0,0,1),st(o[2]??0,0,1),st(o[3]??1,0,1)],width:a,opacity:s,lineCap:2===e.lc||3===e.lc?e.lc:1,lineJoin:2===e.lj||3===e.lj?e.lj:1,miterLimit:Math.max(1,"number"==typeof e.ml&&Number.isFinite(e.ml)?e.ml:4),...c?{colorTrack:c}:{},...l?{opacityTrack:l}:{},...u?{widthTrack:u}:{},...p.length>0?{dash:p}:{},...void 0===m?{}:{dashOffset:m},...h?{dashOffsetTrack:h}:{}}}function ie(e,t,n,o,s){return o.usesStrokeExtension=!0,{type:M,commands:e,values:t,color:[n.color[0],n.color[1],n.color[2],n.color[3]*n.opacity],width:n.width,lineCap:2===n.lineCap?"round":3===n.lineCap?"square":"butt",lineJoin:2===n.lineJoin?"round":3===n.lineJoin?"bevel":"miter",miterLimit:n.miterLimit,tolerance:.2}}function ae(e,t,n){const o=e/2,s=t/2,r=Math.min(Math.max(0,n),o,s);if(r<=1e-6)return{commands:"MLLLZ",values:[-o,-s,o,-s,o,s,-o,s]};const i=.5522847498307936*r;return{commands:"MLCLCLCLCZ",values:[-o+r,-s,o-r,-s,o-r+i,-s,o,-s+r-i,o,-s+r,o,s-r,o,s-r+i,o-r+i,s,o-r,s,-o+r,s,-o+r-i,s,-o,s-r+i,-o,s-r,-o,-s+r,-o,-s+r-i,-o+r-i,-s,-o+r,-s]}}function ce(e,t){const n=.5522847498307936*e,o=.5522847498307936*t;return{commands:"MCCCCZ",values:[0,-t,n,-t,e,-o,e,0,e,o,n,t,0,t,-n,t,-e,o,-e,0,-e,-o,-n,-t,0,-t]}}function le(e,t,n){const o=Math.round(Ve(e.pt,0)),s=Ve(e.or,0),r=2!==e.sy,i=r?Ve(e.ir,0):s;if(o<3||s<=0||r&&i<=0)return it(n,"W_LOTTIE_INVALID_POLYSTAR",t,"Polystar requires at least three points and positive radii."),null;[e.pt,e.or,e.ir].some(qe)&&it(n,"W_LOTTIE_ANIMATED_POLYSTAR_GEOMETRY",t,"Animated polystar points and radii are sampled at their initial value.");const a=st(Ve(e.is,0)/100,0,1),c=st(Ve(e.os,0)/100,0,1);(qe(e.is)||qe(e.os))&&it(n,"W_LOTTIE_ANIMATED_POLYSTAR_ROUNDNESS",t,"Animated polystar roundness is sampled at its initial value.");const l=r?2*o:o,u=3===e.d?-1:1,f=[],p=[];for(let e=0;e<l;e++){const t=r&&!(1&~e),n=t?i:s,o=-Math.PI/2+u*e*Math.PI*2/l;f.push([Math.cos(o)*n,Math.sin(o)*n]),p.push(t?a:c)}if(p.every(e=>e<=1e-6))return{commands:`M${"L".repeat(l-1)}Z`,values:f.flat()};const d=f.map((e,t)=>{const n=f[(t-1+l)%l],o=f[(t+1)%l],s=.25*p[t];return{vertex:e,enter:[e[0]+(n[0]-e[0])*s,e[1]+(n[1]-e[1])*s],exit:[e[0]+(o[0]-e[0])*s,e[1]+(o[1]-e[1])*s]}});let m="M";const h=[...d[0].enter];for(let e=0;e<d.length;e++){const t=d[e];e>0&&(m+="L",h.push(...t.enter)),m+="Q",h.push(...t.vertex,...t.exit)}return m+="LZ",h.push(...d[0].enter),{commands:m,values:h}}function ue(e,t,n,o){1===e.ddd&&it(o,"W_LOTTIE_3D_LAYER",`${t}.ddd`,"3D layer transforms are flattened to the supported 2D transform subset."),"number"==typeof e.bm&&0!==e.bm&&it(o,"W_LOTTIE_BLEND_MODE",`${t}.bm`,`Layer blend mode ${e.bm} is not represented by the HYA 2D renderer.`),1===e.ao&&it(o,"W_LOTTIE_AUTO_ORIENT",`${t}.ao`,"Auto-orient along a motion path is not converted."),void 0===e.tm||0===n&&qe(e.tm)||it(o,"W_LOTTIE_TIME_REMAP",`${t}.tm`,0!==n?"Time remapping is only supported for precomposition layers.":"Static time remapping cannot be represented by ordinary HYA transform tracks.");const s=Xe(Xe(e.ks).p);!0!==s.s&&void 0===s.x&&void 0===s.y||it(o,"W_LOTTIE_SPLIT_POSITION",`${t}.ks.p`,"Separated position dimensions are sampled as the default position.");const r=Xe(e.ks);(qe(r.sk)||qe(r.sa)||Math.abs(Ve(r.sk,0))>1e-6||Math.abs(Ve(r.sa,0))>1e-6)&&it(o,"W_LOTTIE_LAYER_SKEW",`${t}.ks`,"Layer skew and skew axis are not converted.")}function fe(e,t,n){const o=[],s=Je(e).map(Xe);for(let e=0;e<s.length;e++){const r=s[e],i=`${t}.ef[${e}]`,a=pe(r.nm??r.mn),c=Je(r.ef).map(Xe);if("tint"===a){const e=de(c,["map black to","adbe tint-0001"]),t=de(c,["map white to","adbe tint-0002"]),s=de(c,["amount to tint","adbe tint-0003"]);if(!e||!t||!s){it(n,"W_LOTTIE_EFFECT_PARAM",i,"Tint requires Map Black To, Map White To and Amount to Tint parameters.");continue}const r=Ue(e,[0,0,0]),a=Ue(t,[1,1,1]),l=Ne(e,n,`${i}.black`,e=>me(e,[0,0,0])),u=Ne(t,n,`${i}.white`,e=>me(e,[1,1,1])),f=Ne(s,n,`${i}.amount`,e=>[st((e[0]??100)/100,0,1)]);o.push({kind:"tint",black:me(r,[0,0,0]),white:me(a,[1,1,1]),amount:st(Ve(s,100)/100,0,1),...l?{blackTrack:l}:{},...u?{whiteTrack:u}:{},...f?{amountTrack:f}:{}});continue}if("fill"===a){const e=de(c,["color","adbe fill-0002"]),t=de(c,["opacity","adbe fill-0007"]);if(!e){it(n,"W_LOTTIE_EFFECT_PARAM",i,"Fill requires a Color parameter.");continue}const s=Ue(e,[1,1,1,1]),r=Ne(e,n,`${i}.color`,e=>he(e)),a=Ne(t,n,`${i}.opacity`,e=>[st((e[0]??100)/100,0,1)]);o.push({kind:"fill",color:he(s),opacity:st(Ve(t,100)/100,0,1),...r?{colorTrack:r}:{},...a?{opacityTrack:a}:{}});continue}if(a.includes("gaussian blur")||a.includes("fast box blur")||"blur"===a){const e=de(c,["blurriness","blur","adbe gaussian blur 2-0001","adbe fast blur-0001"]),t=Math.round(Ve(de(c,["blur dimensions","dimensions"]),1));if(!e){it(n,"W_LOTTIE_EFFECT_PARAM",i,"Blur requires a Blurriness parameter.");continue}const s=e=>2===t?[0,Math.max(0,e[0]??0)]:3===t?[Math.max(0,e[0]??0),0]:[Math.max(0,e[0]??0),Math.max(0,e[0]??0)],r=Ne(e,n,`${i}.blur`,s);o.push({kind:"blur",radius:s([Ve(e,0)]),...r?{radiusTrack:r}:{}});continue}if("drop shadow"===a||a.includes("drop shadow")){const e=de(c,["shadow color","color","adbe drop shadow-0001"]),t=de(c,["opacity","adbe drop shadow-0002"]),s=de(c,["direction","adbe drop shadow-0003"]),r=de(c,["distance","adbe drop shadow-0004"]),a=de(c,["softness","blur","adbe drop shadow-0005"]);if(!e){it(n,"W_LOTTIE_EFFECT_PARAM",i,"Drop Shadow requires a Shadow Color parameter.");continue}(qe(s)||qe(r))&&it(n,"W_LOTTIE_EFFECT_PARAM",i,"Animated Drop Shadow direction/distance requires coupled sampling and is held at its first value.");const l=ot(Ve(s,135)),u=Math.max(0,Ve(r,0)),f=Ue(e,[0,0,0,1]),p=Ne(e,n,`${i}.color`,e=>he(e,[0,0,0,1])),d=Ne(t,n,`${i}.opacity`,e=>[st((e[0]??100)/100,0,1)]),m=Ne(a,n,`${i}.blur`,e=>[Math.max(0,e[0]??0)]);o.push({kind:"drop-shadow",color:he(f,[0,0,0,1]),opacity:st(Ve(t,100)/100,0,1),offset:[Math.cos(l)*u,Math.sin(l)*u],blur:Math.max(0,Ve(a,0)),...p?{colorTrack:p}:{},...d?{opacityTrack:d}:{},...m?{blurTrack:m}:{}});continue}if("opacity"===a){const e=de(c,["opacity","amount"]);if(!e){it(n,"W_LOTTIE_EFFECT_PARAM",i,"Opacity effect requires an Opacity parameter.");continue}const t=Ne(e,n,`${i}.opacity`,e=>[st((e[0]??100)/100,0,1)]);o.push({kind:"opacity",opacity:st(Ve(e,100)/100,0,1),...t?{opacityTrack:t}:{}});continue}if("color matrix"===a){const e=de(c,["matrix","color matrix"]),t=Ue(e,[]);if(20!==t.length){it(n,"W_LOTTIE_EFFECT_PARAM",i,"Color Matrix requires exactly 20 values.");continue}const s=Ne(e,n,`${i}.matrix`,e=>e.slice(0,20));o.push({kind:"color-matrix",matrix:t.slice(0,20),...s?{matrixTrack:s}:{}});continue}it(n,"W_LOTTIE_EFFECT",i,`Layer effect "${"string"==typeof r.nm?r.nm:String(r.ty)}" is not converted.`)}return o}function pe(e){return"string"==typeof e?e.trim().toLowerCase():""}function de(e,t){const n=t.map(e=>e.toLowerCase());return e.find(e=>{const t=pe(e.nm),o=pe(e.mn);return n.includes(t)||n.includes(o)})?.v}function me(e,t){return[st(e[0]??t[0],0,1),st(e[1]??t[1],0,1),st(e[2]??t[2],0,1)]}function he(e,t=[1,1,1,1]){return[st(e[0]??t[0],0,1),st(e[1]??t[1],0,1),st(e[2]??t[2],0,1),st(e[3]??t[3],0,1)]}function ge(e,t){return e}function ye(e,t,n,o,s,r,i,a,c,l){const u=void 0===e.tt?0:nt(e.tt,`${r}.tt`),f=function(e,t,n,o,s,r,i){const a=Je(e).map((e,t)=>({mask:Xe(e),sourceIndex:t})).filter(e=>!0!==e.mask.hd&&"n"!==e.mask.mode);if(0===a.length)return{nodes:[]};const c=a.filter(({mask:e,sourceIndex:t})=>!(void 0!==e.mode&&!["a","s","i","f"].includes(String(e.mode)))||(it(o,"W_LOTTIE_MASK_MODE",`${n}.masksProperties[${t}].mode`,`Mask mode "${String(e.mode)}" is not recognized.`),!1));if(0===c.length)return{nodes:[]};const l=[],u=[];for(let e=0;e<c.length;e++){const{mask:s,sourceIndex:r}=c[e],i=`${n}.masksProperties[${r}]`,a=`${t}:mask:${o.shapeCounter++}`,f=st(Ve(s.o,100)/100,0,1),p=Ue(s.f,[0,0]),d=Ve(s.x,0),m=Ne(s.x,o,`${i}.x`,e=>[e[0]??0]);qe(s.f)&&it(o,"W_LOTTIE_ANIMATED_MASK_FEATHER",`${i}.f`,"Animated mask feather is sampled at its initial value.");const h=qe(s.pt),g=qe(s.o),y=[],v=[];if(h||g){const n=`${t}:mask-entry:${o.shapeCounter++}`,r={id:n,name:`${t} mask ${e}`,parent:a,transform:{opacity:f}};g&&We(s.o,n,"opacity",o,e=>[st((e[0]??100)/100,0,1)],`${i}.o`);const c=ke(s.pt,[1,1,1,1],`${i}.pt`,o);c&&(r.components=[c]),v.push(r)}else{const e=ke(s.pt,[1,1,1,f],`${i}.pt`,o);e&&y.push(e)}0===y.length&&0===v.length||(l.push({id:a,name:`${t} mask ${e}`,parent:t,...y.length>0?{components:y}:{}},...v),u.push({kind:"mask",source:a,mode:!0===s.inv?"alpha-inverted":"alpha",operation:"s"===s.mode?"subtract":"i"===s.mode?"intersect":"f"===s.mode?"difference":"add",...p.some(e=>Math.abs(e)>1e-6)?{feather:[Math.abs(p[0]??0),Math.abs(p[1]??p[0]??0)]}:{},...Math.abs(d)>1e-6?{expansion:d}:{},...m?{expansionTrack:m}:{}}))}if(0===u.length)return{nodes:[]};const f=function(e,t,n,o,s,r){const i=[...e],a=[];let c;for(;i.length+(c?1:0)>t;){const e=c?7:8,t=[...c?[{kind:"mask",source:c,mode:"alpha",operation:"add"}]:[],...i.splice(0,e)],l=`${n}:mask-stack:${o.shapeCounter++}`;a.push({id:l,name:`${n} mask stack`,composite:ve(t),components:[{type:"shape2d",shape:"rect",size:[s,r],position:[s/2,r/2],fill:[1,1,1,1]}]}),c=l}return{layers:[...c?[{kind:"mask",source:c,mode:"alpha",operation:"add"}]:[],...i],nodes:a}}(u,s,t,o,r,i);return l.push(...f.nodes),{value:ve(f.layers),nodes:l}}(e.masksProperties,s,r,a,u>0?7:8,c,l);if(0===u)return f;if(u<1||u>4)return it(a,"W_LOTTIE_UNSUPPORTED_MATTE",`${r}.tt`,`Track matte type ${u} is not supported.`),f;const p=void 0===e.tp?void 0:nt(e.tp,`${r}.tp`),d=Xe(n[t-1]),m=p??(t>0?nt(d.ind??t,`${i}[${t-1}].ind`):void 0),h=void 0===m?void 0:o.get(m);if(!h)return it(a,"W_LOTTIE_MISSING_MATTE_SOURCE",`${r}.tt`,"Track matte source layer was not found immediately before the target layer."),f;const g={kind:"matte",source:h,mode:2===u?"alpha-inverted":3===u?"luma":4===u?"luma-inverted":"alpha",operation:f.value?"intersect":"add"};return{value:ve([...Te(f.value),g]),nodes:f.nodes}}function ve(e){if(1!==e.length)return{layers:e};const t=e[0];return void 0===t.operation||"add"===t.operation?{kind:t.kind,source:t.source,mode:t.mode,...t.feather?{feather:t.feather}:{},...void 0===t.expansion?{}:{expansion:t.expansion},...void 0===t.expansionTrack?{}:{expansionTrack:t.expansionTrack}}:t}function Te(e){return e?"layers"in e?e.layers:[e]:[]}function ke(e,t,n,o){if(qe(e)){const s=o.diagnostics.length,r=$e(e,n,o);if(r)return o.usesPathMorphExtension=!0,{type:x,...r,fill:t,fillRule:"nonzero"};o.diagnostics.slice(s).some(e=>"W_LOTTIE_PATH_TOPOLOGY"===e.code)||it(o,"W_LOTTIE_ANIMATED_PATH",n,"Animated path cannot be represented and is sampled at its initial value.")}const s=Oe(Se(e),n,o);return s?{type:"path2d",...s,fill:t,fillRule:"nonzero"}:null}function $e(e,t,n,o=!0){const s=Je(Xe(e).k).map(Xe),r=[],i=[],a=[];let c=null;for(let e=0;e<s.length;e++){const o=s[e],l=Xe(Je(o.s)[0]??o.s??Je(s[e-1]?.e)[0]??c);if(0===Object.keys(l).length)continue;const u=Math.fround(st(ze(n.timeline,et(o.t,`${t}.k[${e}].t`)),0,n.duration));r.length>0&&u<=r.at(-1)||(r.push(u),i.push(l),a.push(o),c=Xe(Je(o.e)[0]??o.e??l))}if(0===r.length)return null;const l=function(e,t,n,o){const s=[];for(let r=0;r<e.length;r++){const i=_e(e[r],o);if(!i)return it(n,"W_LOTTIE_INVALID_PATH",`${t}.k[${r}].s`,"Animated path requires matching vertices and tangent arrays."),null;s.push(i)}const r=s[0].closed;if(s.some(e=>e.closed!==r))return it(n,"W_LOTTIE_PATH_TOPOLOGY",t,"Animated path changes between open and closed topology."),null;const i=Math.max(...s.map(e=>e.segments.length));if(i<1||i>w)return it(n,"W_LOTTIE_PATH_TOPOLOGY",t,`Animated path requires ${i} canonical segments; the safe budget is 256.`),null;const a=s.map(e=>function(e,t){const n=[...e.segments];for(;n.length<t;){let e=0,t=-1/0;for(let o=0;o<n.length;o++){const s=n[o],r=Le(s.start,s.control1)+Le(s.control1,s.control2)+Le(s.control2,s.end);r>t&&(e=o,t=r)}n.splice(e,1,...Ee(n[e]))}return{closed:e.closed,segments:n}}(e,i)),c=a[0];for(let e=1;e<a.length;e++)a[e]=be(a[e],c);return{commands:`M${"C".repeat(i)}${r?"Z":""}`,frames:a.map(e=>[...e.segments[0].start,...e.segments.flatMap(e=>[...e.control1,...e.control2,...e.end])])}}(i,t,n,o);if(!l)return null;const u=l.frames.flatMap(e=>e.map(Ae)),f=l.commands,p=l.frames[0].length,d=a.length>1&&a.slice(0,-1).every(e=>1===e.h)?"step":r.length>1?"cubic-bezier":"linear",m=[];if("cubic-bezier"===d)for(let e=0;e<r.length-1;e++){const t=a[e],n=Xe(t.o),o=Xe(t.i);m.push(st(Qe(n.x,.333),0,1),Qe(n.y,.333),st(Qe(o.x,.667),0,1),Qe(o.y,.667))}return{commands:f,times:r,values:u,valueSize:p,interpolation:d,...m.length>0?{easings:m}:{},tolerance:.35}}function _e(e,t){const n=Pe(e.v),o=Re(e.i,n.length),s=Re(e.o,n.length);if(n.length<2||o.length!==n.length||s.length!==n.length)return null;const r=!1!==e.c,i=r||t,a=i?n.length:n.length-1,c=[];for(let e=0;e<a;e++){const t=(e+1)%n.length,i=n[e],a=n[t],l=r||0!==t;c.push({start:i,control1:l?[i[0]+s[e][0],i[1]+s[e][1]]:i,control2:l?[a[0]+o[t][0],a[1]+o[t][1]]:a,end:a})}return{closed:i,segments:c}}function Ee(e){const t=Ie(e.start,e.control1),n=Ie(e.control1,e.control2),o=Ie(e.control2,e.end),s=Ie(t,n),r=Ie(n,o),i=Ie(s,r);return[{start:e.start,control1:t,control2:s,end:i},{start:i,control1:r,control2:o,end:e.end}]}function be(e,t){let n=e;if(e.closed){Math.sign(xe(n))!==Math.sign(xe(t))&&(n=Me(n));let e=0,o=1/0;for(let s=0;s<n.segments.length;s++){let r=0;for(let e=0;e<t.segments.length;e++)r+=we(t.segments[e].start,n.segments[(e+s)%n.segments.length].start);r<o&&(o=r,e=s)}return e>0&&(n={closed:!0,segments:[...n.segments.slice(e),...n.segments.slice(0,e)]}),n}const o=we(t.segments[0].start,n.segments[0].start)+we(t.segments.at(-1).end,n.segments.at(-1).end);return we(t.segments[0].start,n.segments.at(-1).end)+we(t.segments.at(-1).end,n.segments[0].start)<o?Me(n):n}function Me(e){return{closed:e.closed,segments:[...e.segments].reverse().map(e=>({start:e.end,control1:e.control2,control2:e.control1,end:e.start}))}}function xe(e){let t=0;for(const n of e.segments)t+=n.start[0]*n.end[1]-n.end[0]*n.start[1];return t/2}function Ie(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2]}function Le(e,t){return Math.hypot(e[0]-t[0],e[1]-t[1])}function we(e,t){const n=e[0]-t[0],o=e[1]-t[1];return n*n+o*o}function Ae(e){return Math.round(e/L)*L}function Oe(e,t,n,o=!0,s=!0){const r=Pe(e.v),i=Re(e.i,r.length),a=Re(e.o,r.length);if(r.length<2||i.length!==r.length||a.length!==r.length)return o&&it(n,"W_LOTTIE_INVALID_PATH",t,"Path requires matching vertex, incoming-tangent and outgoing-tangent arrays."),null;let c="M";const l=[...r[0]],u=!1!==e.c,f=u?r.length:r.length-1;for(let e=0;e<f;e++){const t=e,n=(e+1)%r.length,o=r[t],s=r[n],u=[o[0]+a[t][0],o[1]+a[t][1]],f=[s[0]+i[n][0],s[1]+i[n][1]];Ce(u,o)&&Ce(f,s)?(c+="L",l.push(...s)):(c+="C",l.push(...u,...f,...s))}return!u&&s&&(o&&it(n,"W_LOTTIE_OPEN_FILLED_PATH",t,"Open filled path is closed with a straight segment."),c+="L",l.push(...r[0])),(u||s)&&(c+="Z"),{commands:c,values:l}}function Se(e){const t=Xe(e);if(qe(t)){const e=Xe(Je(t.k)[0]);return Xe(Je(e.s)[0]??e.s)}return Xe(t.k??e)}function Pe(e){return Je(e).map(e=>{const t=Ke(e);return[t[0]??0,t[1]??0]})}function Re(e,t){const n=Pe(e);return 0===n.length&&t>0?Array.from({length:t},()=>[0,0]):n}function Ce(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6}function We(e,t,n,o,s,r){const i=Ne(e,o,r,s);i&&o.tracks.push({node:t,property:n,interpolation:i.interpolation,times:i.times,values:i.values,...i.easings?{easings:i.easings}:{},..."position"===n&&i.spatialTangents?{spatialTangents:i.spatialTangents}:{}})}function Ne(e,t,n,o){if(!qe(e))return;const s=Je(Xe(e).k).map(Xe),r=[],i=[],a=[];let c=null;for(let e=0;e<s.length;e++){const l=s[e],u=et(l.t,`${n}.k[${e}].t`),f=Ke(l.s),p=f.length>0?f:c??Ke(s[e-1]?.e);if(0===p.length)continue;const d=Math.fround(st(ze(t.timeline,u),0,t.duration));if(r.length>0&&d<=r[r.length-1])continue;const m=o(p);r.push(d),i.push(...m),a.push(l),c=Ke(l.e).length>0?Ke(l.e):p}if(r.length<1)return void it(t,"W_LOTTIE_EMPTY_TRACK",n,"Animated property contains no usable keyframes.");if(a.length>1&&a.slice(0,-1).every(e=>1===e.h))return{times:r,values:i,valueSize:i.length/r.length,interpolation:"step"};const l=[],u=[];let f=!1;for(let e=0;e<r.length-1;e++){const t=a[e],n=Xe(t.o),o=Xe(t.i);if(l.push(st(Qe(n.x,.333),0,1),Qe(n.y,.333),st(Qe(o.x,.667),0,1),Qe(o.y,.667)),i.length/r.length===2){const n=Ke(t.to),o=Ke(t.ti),s=[...n,...o].some(e=>Math.abs(e)>1e-8);if(f||=s,s)u.push(n[0]??0,n[1]??0,o[0]??0,o[1]??0);else{const t=2*e,n=((i[t+2]??i[t]??0)-(i[t]??0))/3,o=((i[t+3]??i[t+1]??0)-(i[t+1]??0))/3;u.push(n,o,-n,-o)}}}return{times:r,values:i,valueSize:i.length/r.length,interpolation:r.length>1?"cubic-bezier":"linear",...r.length>1?{easings:l}:{},...r.length>1&&f?{spatialTangents:u}:{}}}function ze(e,t){return e.mapFrameToSeconds?.(t)??e.secondsOffset+t*e.secondsPerFrame}function Fe(e,t,n,o,s){let r=0,i=1;for(let n=0;n<16;n++){const n=(r+i)/2;De(n,t,o)<e?r=n:i=n}return De((r+i)/2,n,s)}function De(e,t,n){const o=1-e;return 3*o*o*e*t+3*o*e*e*n+e*e*e}function He(e,t,n,o){const s=et(e.sr??1,`${t}.sr`);if(Math.abs(s-1)<1e-8)return n;if(s<=0)return it(o,"W_LOTTIE_INVALID_TIME_STRETCH",`${t}.sr`,"Layer time stretch must be greater than zero."),n;const r=et(e.st??e.ip??0,`${t}.st`),i=e=>ze(n,r+(e-r)*s);return{frameRate:n.frameRate,secondsOffset:i(0),secondsPerFrame:n.secondsPerFrame*s,mapFrameToSeconds:i}}function je(e,t,n,o){const s=Math.min(o,Math.max(1e-6,n.secondsPerFrame)),r=ze(n,e),i=ze(n,t),a=st(r,0,Math.max(0,o-s)),c=st(i,a+s,o);return{start:a,duration:Math.max(s,c-a)}}function qe(e){const t=Xe(e);if(!Array.isArray(t.k))return!1;if(1===t.a)return!0;const n=Xe(t.k[0]);return"number"==typeof n.t&&Number.isFinite(n.t)&&(void 0!==n.s||void 0!==n.e)}function Ue(e,t){const n=Xe(e);if(qe(n))return Ke(Xe(Je(n.k)[0]).s).length>0?Ke(Xe(Je(n.k)[0]).s):t;const o=Ke(n.k);return o.length>0?o:t}function Ge(e,t){const n=Xe(e);return(qe(n)?Je(n.k).flatMap(e=>{const t=Xe(e);return[Ke(t.s),Ke(t.e)]}):[Ke(n.k)]).find(e=>e.length>=t&&e.slice(0,t).every(e=>e>0))}function Ve(e,t){return Ue(e,[t])[0]??t}function Ye(e,t){if("string"!=typeof e||!/^#[0-9a-f]{6}$/i.test(e))throw new TypeError(`Expected #RRGGBB at ${t}.`);const n=Number.parseInt(e.slice(1),16);return[(n>>16&255)/255,(n>>8&255)/255,(255&n)/255,1]}function Ze(e,t){if(!e)return t;try{return new URL(t,e).toString()}catch{return`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`}}function Be(e){return Xe(JSON.parse(e))}function Xe(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Je(e){return Array.isArray(e)?e:[]}function Ke(e){if("number"==typeof e&&Number.isFinite(e))return[e];if(!Array.isArray(e))return[];return(1===e.length&&Array.isArray(e[0])?e[0]:e).filter(e=>"number"==typeof e&&Number.isFinite(e))}function Qe(e,t){return Ke(e)[0]??t}function et(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError(`Expected a finite number at ${t}.`);return e}function tt(e,t){const n=et(e,t);if(n<=0)throw new TypeError(`Expected a positive number at ${t}.`);return n}function nt(e,t){const n=et(e,t);if(!Number.isSafeInteger(n))throw new TypeError(`Expected an integer at ${t}.`);return n}function ot(e){return e*Math.PI/180}function st(e,t,n){return Math.min(n,Math.max(t,e))}function rt(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function it(e,t,n,o){e.diagnostics.push(Object.freeze({severity:"warning",code:t,path:n,message:o}))}export{A as convertLottie,S as convertLottieDocument,O as inspectLottieFonts};//# sourceMappingURL=lottie.js.map