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