@anime-studio/lottie 0.0.0-stage → 0.4.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dener Fernandes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,76 @@
1
- # Temporary Holding Version
1
+ # @anime-studio/lottie
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@anime-studio/lottie)](https://www.npmjs.com/package/@anime-studio/lottie)
4
+ [![CI](https://github.com/denerFernandes/animeStudio/actions/workflows/ci.yml/badge.svg)](https://github.com/denerFernandes/animeStudio/actions/workflows/ci.yml)
5
+ [![MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/denerFernandes/animeStudio/blob/master/LICENSE)
6
+
7
+ Part of [animeStudio](https://github.com/denerFernandes/animeStudio), a deterministic 2D/2.5D cartoon animation engine: characters are
8
+ SVG art bound to skeletons, scenes are JSON documents, and every frame is a pure function of the
9
+ documents and the time.
10
+
11
+ Exports animeStudio characters and scenes as Lottie (bodymovin) JSON, for lottie-web, the
12
+ Lottie iOS / Android players, After Effects (via the bodymovin importer) and the many tools that
13
+ read Lottie.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install @anime-studio/core @anime-studio/lottie
19
+ # or
20
+ pnpm add @anime-studio/core @anime-studio/lottie
21
+ ```
22
+
23
+ Requires Node.js 22 or later (or a modern browser / bundler).
24
+
25
+ ## Usage
26
+
27
+ ```ts
28
+ import { readFileSync, writeFileSync } from "node:fs";
29
+ import { validateToon } from "@anime-studio/core";
30
+ import { lottieFromCharacter, validateLottie } from "@anime-studio/lottie";
31
+
32
+ const doc = validateToon(JSON.parse(readFileSync("pip.toon.json", "utf8"))).value!;
33
+ const { lottie, warnings } = lottieFromCharacter(doc, { clip: "walk", fps: 30 });
34
+ console.log(validateLottie(lottie)); // [] when the structure is sound
35
+ writeFileSync("pip-walk.json", JSON.stringify(lottie));
36
+ ```
37
+
38
+ `lottieFromScene(compileScene(sceneDoc, assets), { from, to, fps })` exports a scene. From the
39
+ command line: `toon lottie pip.toon.json --clip walk -o pip-walk.json` or
40
+ `toon lottie hello.scene.json -o hello.json`.
41
+
42
+ ## How it works
43
+
44
+ The engine's frames are sampled (so IK, springs, walks, physics and every script action come out
45
+ as they render) and written as nested layers: actors and groups become null layers, each actor's
46
+ parts hang on one null per bone, and transforms and opacity are keyframed per frame (keys a
47
+ straight line already gives are dropped; held values use hold keyframes).
48
+
49
+ - **Rigid** parts: their SVG art converted to Lottie shapes once, moved by their bone.
50
+ - **Switch** parts (eyes, mouths, hands): each variant is its own layer, shown in turn with
51
+ stepped opacity.
52
+ - **Morph, hose, skinned and 2.5D** parts, whose path changes every frame: an animated path when
53
+ the path's structure stays the same (paths whose vertex count changes are subdivided to match).
54
+ - **Embedded PNGs** (characters from `import-psd`): image assets.
55
+ - Fills (solid, linear and radial gradients), strokes (caps, joins, dashes), opacity and `<use>`.
56
+
57
+ ## Limits
58
+
59
+ Not exported, each warned about once: lighting overlays and cel shading, line boil, blur and
60
+ other SVG filters, masks and clip paths, text, CSS classes, and audio. A node that switches
61
+ between more than `maxVariants` (32) distinct drawings is left out. Every frame is sampled, so
62
+ long scenes make large files (a 3 s 2.5D walk is about 2.5 MB; prefer `from` / `to` and a lower
63
+ `fps`). Rigid-body props are exported as the engine renders them only when the scene was prepared
64
+ with `@anime-studio/rigid` (the CLI does this).
65
+
66
+ ## Documentation
67
+
68
+ - [Getting started and features](https://github.com/denerFernandes/animeStudio#readme)
69
+ - [Format specification](https://github.com/denerFernandes/animeStudio/blob/master/docs/FORMAT.md)
70
+ - [API reference](https://github.com/denerFernandes/animeStudio/blob/master/docs/API.md)
71
+ - [Authoring guide for AI agents](https://github.com/denerFernandes/animeStudio/blob/master/docs/AI_GUIDE.md)
72
+ - [Changelog](https://github.com/denerFernandes/animeStudio/blob/master/CHANGELOG.md)
73
+
74
+ ## License
75
+
76
+ MIT © Dener Fernandes
@@ -0,0 +1,55 @@
1
+ import { type CompiledScene, type ToonDoc } from "@anime-studio/core";
2
+ import type { LottieAnimation } from "./types.js";
3
+ export interface LottieOptions {
4
+ /** First second exported (default 0). */
5
+ from?: number;
6
+ /** Last second (exclusive; default the scene's duration). */
7
+ to?: number;
8
+ /** Frame rate (default the scene's). */
9
+ fps?: number;
10
+ /** The animation's `nm` (default `"animeStudio"`). */
11
+ name?: string;
12
+ /**
13
+ * Nest each actor's parts under one null layer per bone (default true): the bones carry the
14
+ * sampled motion and the parts sit still on them, as a rig in After Effects would. Off, every part
15
+ * carries its own sampled transform.
16
+ */
17
+ bones?: boolean;
18
+ /** How many distinct drawings one node may switch between before it is left out (default 32). */
19
+ maxVariants?: number;
20
+ }
21
+ export interface LottieResult {
22
+ lottie: LottieAnimation;
23
+ /** What could not be exported exactly (each message once). */
24
+ warnings: string[];
25
+ }
26
+ /**
27
+ * The frames of a compiled scene as a Lottie animation. Every frame is evaluated (`evaluateScene`)
28
+ * and sampled: each node of the render tree becomes a layer whose transform and opacity are
29
+ * keyframed per frame (keyframes a straight line already gives are dropped); groups become null
30
+ * layers that their children are parented to; actors' parts hang on one null per bone (see
31
+ * `bones`). Art is converted from SVG to Lottie shapes once per distinct drawing (a switch part's
32
+ * variants are separate layers shown in turn), a part whose path is recomputed every frame (skinned,
33
+ * hose, morph, the 2.5D solids) gets an animated path when its structure stays the same, and
34
+ * embedded PNG images become image assets. Lighting overlays, cel shading, line boil, blur and other
35
+ * filters, masks and clip paths, text and audio are not exported (each one warned about once).
36
+ */
37
+ export declare function lottieFromScene(scene: CompiledScene, opts?: LottieOptions): LottieResult;
38
+ export interface CharacterLottieOptions extends LottieOptions {
39
+ /** The clip to play (default the first clip). */
40
+ clip?: string;
41
+ /** Canvas size (default 512 × 512). */
42
+ width?: number;
43
+ height?: number;
44
+ /** Character scale (default: fitted to the canvas, as `previewScene` does). */
45
+ scale?: number;
46
+ /** Background colour (default none: transparent). */
47
+ background?: string;
48
+ }
49
+ /**
50
+ * A character's clip as a Lottie animation: the character stands in the middle of a `width` ×
51
+ * `height` canvas (fitted like `previewScene`), playing `clip` once — one cycle of a looping clip,
52
+ * so the Lottie loops seamlessly (with physics, the cycle after two cycles of settling).
53
+ */
54
+ export declare function lottieFromCharacter(doc: ToonDoc, opts?: CharacterLottieOptions): LottieResult;
55
+ //# sourceMappingURL=export.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"export.d.ts","sourceRoot":"","sources":["../src/export.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,aAAa,EAGlB,KAAK,OAAO,EAOb,MAAM,oBAAoB,CAAC;AAG5B,OAAO,KAAK,EAAE,eAAe,EAAwF,MAAM,SAAS,CAAC;AAErI,MAAM,WAAW,aAAa;IAC5B,yCAAyC;IACzC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,6DAA6D;IAC7D,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,wCAAwC;IACxC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,sDAAsD;IACtD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,iGAAiG;IACjG,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,eAAe,CAAC;IACxB,8DAA8D;IAC9D,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAqND;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,aAAa,EAAE,IAAI,GAAE,aAAkB,GAAG,YAAY,CA+B5F;AAiND,MAAM,WAAW,sBAAuB,SAAQ,aAAa;IAC3D,iDAAiD;IACjD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qDAAqD;IACrD,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,GAAE,sBAA2B,GAAG,YAAY,CAqBjG"}
package/dist/export.js ADDED
@@ -0,0 +1,456 @@
1
+ import { actorPose, evaluateScene, identity, invert, multiply, previewScene, } from "@anime-studio/core";
2
+ import { collectDefs, pathToBeziers, roundBezier, svgToPieces } from "./svg.js";
3
+ import { property, sampledTransform, staticTransform } from "./transform.js";
4
+ const det = (m) => m[0] * m[3] - m[1] * m[2];
5
+ /** Flattens one frame's render nodes into items, bottom first; actor parts re-parented onto bone nulls. */
6
+ function flatten(scene, t, nodes, bones, warn, skip) {
7
+ const items = [];
8
+ const poses = new Map();
9
+ const actorOf = (groupKey) => {
10
+ const m = /^actor-(.+?)(-hand|-behind)?$/.exec(groupKey);
11
+ if (!m)
12
+ return undefined;
13
+ const actor = scene.actors.find((a) => a.id === m[1]);
14
+ if (!actor)
15
+ return undefined;
16
+ return { actor, prefix: `${actor.id}-${m[2] === "-hand" ? "h-" : m[2] === "-behind" ? "b-" : ""}` };
17
+ };
18
+ const walk = (list, parent, opacity) => {
19
+ for (const n of list) {
20
+ const key = parent ? `${parent}/${n.key}` : n.key;
21
+ if (skip(n.key))
22
+ continue;
23
+ const op = opacity * (n.opacity ?? 1);
24
+ if ("filter" in n && n.filter)
25
+ warn(`${n.key}: screen-space filters (motion blur, depth of field) are not exported`);
26
+ if ("svgFilter" in n && n.svgFilter)
27
+ warn(`${n.key}: line boil is not exported`);
28
+ if (n.kind === "group") {
29
+ items.push({ key, parent, matrix: n.transform ?? identity(), opacity: op });
30
+ const who = bones ? actorOf(n.key) : undefined;
31
+ if (who)
32
+ walkActor(n.children, key, op, who.actor, who.prefix);
33
+ else
34
+ walk(n.children, key, op);
35
+ }
36
+ else if (n.kind === "markup")
37
+ items.push({ key, parent, matrix: n.transform ?? identity(), opacity: op, content: { markup: n.markup } });
38
+ else
39
+ items.push({ key, parent, matrix: identity(), opacity: op, content: { d: n.d, attrs: n.attrs } });
40
+ }
41
+ };
42
+ /** An actor's parts: each part drawn on one bone hangs under that bone's null. */
43
+ const walkActor = (list, group, opacity, actor, prefix) => {
44
+ let pose = poses.get(actor.id);
45
+ if (!pose) {
46
+ pose = actorPose(scene, actor, t);
47
+ poses.set(actor.id, pose);
48
+ }
49
+ const rig = actor.rig;
50
+ const added = new Set();
51
+ const boneKey = (i) => `${group}/bone:${rig.bones[i].id}`;
52
+ const addBone = (i) => {
53
+ if (added.has(i))
54
+ return;
55
+ const b = rig.bones[i];
56
+ if (b.parent >= 0)
57
+ addBone(b.parent);
58
+ added.add(i);
59
+ const world = pose.world[i];
60
+ const parentWorld = b.parent >= 0 ? pose.world[b.parent] : identity();
61
+ const ok = Math.abs(det(parentWorld)) > 1e-9;
62
+ items.push({ key: boneKey(i), parent: b.parent >= 0 ? boneKey(b.parent) : group, matrix: ok ? multiply(invert(parentWorld), world) : world, opacity });
63
+ };
64
+ for (const n of list) {
65
+ const partId = n.key.startsWith(prefix) ? n.key.slice(prefix.length) : undefined;
66
+ const part = partId !== undefined ? rig.parts.find((p) => p.id === partId) : undefined;
67
+ const bone = part && "bone" in part && typeof part.bone === "number" ? part.bone : undefined;
68
+ if (n.kind === "markup" && bone !== undefined && Math.abs(det(pose.world[bone])) > 1e-9) {
69
+ addBone(bone);
70
+ const op = opacity * (n.opacity ?? 1);
71
+ if (n.filter)
72
+ warn(`${n.key}: screen-space filters are not exported`);
73
+ items.push({
74
+ key: `${group}/${n.key}`,
75
+ parent: boneKey(bone),
76
+ matrix: multiply(invert(pose.world[bone]), n.transform ?? identity()),
77
+ opacity: op,
78
+ content: { markup: n.markup },
79
+ });
80
+ }
81
+ else
82
+ walk([n], group, opacity);
83
+ }
84
+ };
85
+ walk(nodes, undefined, 1);
86
+ return items;
87
+ }
88
+ /**
89
+ * Merges each frame's draw order into one layer order (Lottie cannot reorder layers over time).
90
+ * Every frame is matched against the order so far, bottom to top: a drawn item takes the first slot
91
+ * of its key above the last one matched, or a new slot is inserted there. A part that changes
92
+ * places in the stacking (a 2.5D rig's far arm going behind the body as it turns) so gets one
93
+ * layer per place, each shown in the frames it is drawn there. Items are renamed to their slot's
94
+ * key (`<key>~<n>` for the second and later slots); nulls draw nothing and keep their key.
95
+ */
96
+ function mergeOrder(frames) {
97
+ const order = [];
98
+ const created = new Map();
99
+ for (const items of frames) {
100
+ let cursor = -1;
101
+ for (const it of items) {
102
+ if (!it.content)
103
+ continue;
104
+ let j = -1;
105
+ for (let k = cursor + 1; k < order.length; k++)
106
+ if (order[k].key === it.key) {
107
+ j = k;
108
+ break;
109
+ }
110
+ if (j < 0) {
111
+ const n = created.get(it.key) ?? 0;
112
+ created.set(it.key, n + 1);
113
+ j = cursor + 1;
114
+ order.splice(j, 0, { key: it.key, id: n ? `${it.key}~${n}` : it.key });
115
+ }
116
+ cursor = j;
117
+ it.key = order[j].id;
118
+ }
119
+ }
120
+ const nulls = [...new Set(frames.flatMap((items) => items.filter((it) => !it.content).map((it) => it.key)))];
121
+ return [...nulls, ...order.map((o) => o.id)];
122
+ }
123
+ /** Same sub-path structure (vertex counts, closed flags): the shape can be keyframed. */
124
+ const sameStructure = (a, b) => a.length === b.length && a.every((p, i) => p.v.length === b[i].v.length && p.c === b[i].c);
125
+ /** Splits segment `j` of a sub-path in two at its middle (de Casteljau): the same curve, one more vertex. */
126
+ function splitSegment(b, j) {
127
+ const n = b.v.length;
128
+ const k = (j + 1) % n;
129
+ const p0 = b.v[j];
130
+ const p3 = b.v[k];
131
+ const c1 = [p0[0] + b.o[j][0], p0[1] + b.o[j][1]];
132
+ const c2 = [p3[0] + b.i[k][0], p3[1] + b.i[k][1]];
133
+ const mid = (a, c) => [(a[0] + c[0]) / 2, (a[1] + c[1]) / 2];
134
+ const q0 = mid(p0, c1);
135
+ const q1 = mid(c1, c2);
136
+ const q2 = mid(c2, p3);
137
+ const r0 = mid(q0, q1);
138
+ const r1 = mid(q1, q2);
139
+ const m = mid(r0, r1);
140
+ b.o[j] = [q0[0] - p0[0], q0[1] - p0[1]];
141
+ b.i[k] = [q2[0] - p3[0], q2[1] - p3[1]];
142
+ b.v.splice(j + 1, 0, m);
143
+ b.i.splice(j + 1, 0, [r0[0] - m[0], r0[1] - m[1]]);
144
+ b.o.splice(j + 1, 0, [r1[0] - m[0], r1[1] - m[1]]);
145
+ }
146
+ /**
147
+ * Gives every frame's path the same structure, when the frames only differ in vertex counts (a
148
+ * hose whose closing point merged in one frame, a path with more segments when bent): the
149
+ * sub-paths with fewer vertices get their longest segments split in two until they match. The
150
+ * drawing of each frame is unchanged. Undefined when the sub-path counts or closed flags differ.
151
+ */
152
+ function equalize(frames) {
153
+ const first = frames[0];
154
+ if (!frames.every((f) => f.length === first.length && f.every((p, i) => p.c === first[i].c)))
155
+ return undefined;
156
+ const target = first.map((_, i) => Math.max(...frames.map((f) => f[i].v.length)));
157
+ return frames.map((f) => f.map((p, i) => {
158
+ if (p.v.length === target[i])
159
+ return p;
160
+ const b = { c: p.c, v: p.v.map((x) => [...x]), i: p.i.map((x) => [...x]), o: p.o.map((x) => [...x]) };
161
+ while (b.v.length < target[i]) {
162
+ const segs = b.c ? b.v.length : b.v.length - 1;
163
+ if (segs < 1) {
164
+ // A lone point: repeat it.
165
+ b.v.push([...b.v[0]]);
166
+ b.i.push([0, 0]);
167
+ b.o.push([0, 0]);
168
+ continue;
169
+ }
170
+ let best = 0;
171
+ let len = -1;
172
+ for (let j = 0; j < segs; j++) {
173
+ const q = b.v[(j + 1) % b.v.length];
174
+ const l = Math.hypot(q[0] - b.v[j][0], q[1] - b.v[j][1]);
175
+ if (l > len) {
176
+ len = l;
177
+ best = j;
178
+ }
179
+ }
180
+ splitSegment(b, best);
181
+ }
182
+ return roundBezier(b);
183
+ }));
184
+ }
185
+ const flatBezier = (paths) => paths.flatMap((p) => [...p.v.flat(), ...p.i.flat(), ...p.o.flat()]);
186
+ const unflatBezier = (template, values) => {
187
+ let k = 0;
188
+ return template.map((p) => {
189
+ const take = () => p.v.map(() => [values[k++], values[k++]]);
190
+ const v = take();
191
+ const i = take();
192
+ const o = take();
193
+ return { c: p.c, v, i, o };
194
+ });
195
+ };
196
+ /**
197
+ * The frames of a compiled scene as a Lottie animation. Every frame is evaluated (`evaluateScene`)
198
+ * and sampled: each node of the render tree becomes a layer whose transform and opacity are
199
+ * keyframed per frame (keyframes a straight line already gives are dropped); groups become null
200
+ * layers that their children are parented to; actors' parts hang on one null per bone (see
201
+ * `bones`). Art is converted from SVG to Lottie shapes once per distinct drawing (a switch part's
202
+ * variants are separate layers shown in turn), a part whose path is recomputed every frame (skinned,
203
+ * hose, morph, the 2.5D solids) gets an animated path when its structure stays the same, and
204
+ * embedded PNG images become image assets. Lighting overlays, cel shading, line boil, blur and other
205
+ * filters, masks and clip paths, text and audio are not exported (each one warned about once).
206
+ */
207
+ export function lottieFromScene(scene, opts = {}) {
208
+ const warnings = new Set();
209
+ const warn = (m) => warnings.add(m);
210
+ const fps = opts.fps ?? scene.fps;
211
+ const from = opts.from ?? 0;
212
+ const to = Math.min(opts.to ?? scene.duration, scene.duration);
213
+ const total = Math.max(1, Math.round((to - from) * fps));
214
+ const bones = opts.bones ?? true;
215
+ const maxVariants = opts.maxVariants ?? 32;
216
+ const skip = (key) => {
217
+ if (key === "lighting" || key.startsWith("shade-")) {
218
+ warn("lighting and cel shading are not exported");
219
+ return true;
220
+ }
221
+ return false;
222
+ };
223
+ // Sample every frame.
224
+ const frames = [];
225
+ let defsMarkup = "";
226
+ let background;
227
+ for (let f = 0; f < total; f++) {
228
+ const t = from + f / fps;
229
+ const frame = evaluateScene(scene, t);
230
+ if (f === 0) {
231
+ defsMarkup = frame.defs;
232
+ background = frame.background;
233
+ }
234
+ frames.push(flatten(scene, t, frame.nodes, bones, warn, skip));
235
+ }
236
+ return assemble(frames, { width: scene.width, height: scene.height, fps, total, name: opts.name ?? "animeStudio", defs: defsMarkup, background, maxVariants, warn, warnings });
237
+ }
238
+ function assemble(frames, o) {
239
+ const { total, warn } = o;
240
+ const order = mergeOrder(frames);
241
+ const tracks = new Map();
242
+ frames.forEach((items, f) => {
243
+ for (const it of items) {
244
+ let tr = tracks.get(it.key);
245
+ if (!tr) {
246
+ tr = {
247
+ key: it.key,
248
+ parent: it.parent,
249
+ order: f,
250
+ matrix: new Array(total).fill(undefined),
251
+ opacity: new Array(total).fill(0),
252
+ content: new Array(total).fill(undefined),
253
+ paths: new Array(total).fill(undefined),
254
+ kind: !it.content ? "null" : "markup" in it.content ? "markup" : "path",
255
+ };
256
+ tracks.set(it.key, tr);
257
+ }
258
+ tr.matrix[f] = it.matrix;
259
+ tr.opacity[f] = it.opacity;
260
+ if (it.content && "markup" in it.content)
261
+ tr.content[f] = it.content.markup;
262
+ else if (it.content) {
263
+ tr.paths[f] = it.content;
264
+ tr.content[f] = JSON.stringify(it.content.attrs);
265
+ }
266
+ }
267
+ });
268
+ const ctx = { defs: collectDefs(o.defs), warn };
269
+ const layers = [];
270
+ const nulls = [];
271
+ const assets = [];
272
+ const assetIds = new Map();
273
+ let ind = 1;
274
+ const indOf = new Map();
275
+ const pieceCache = new Map();
276
+ for (const key of order)
277
+ indOf.set(key, ind++);
278
+ /** Holds each sample over the frames a key is missing in (so keyframes never jump while hidden). */
279
+ const filled = (m) => {
280
+ const first = m.find((x) => x !== undefined) ?? identity();
281
+ let last = first;
282
+ return m.map((x) => (last = x ?? last));
283
+ };
284
+ const base = (key, name, ks, parent) => ({
285
+ ddd: 0,
286
+ ind: indOf.get(key) ?? ind++,
287
+ nm: name,
288
+ ...(parent && indOf.has(parent) ? { parent: indOf.get(parent) } : {}),
289
+ ks,
290
+ ip: 0,
291
+ op: total,
292
+ st: 0,
293
+ sr: 1,
294
+ ao: 0,
295
+ bm: 0,
296
+ });
297
+ const assetFor = (href, w, h) => {
298
+ const k = `${w}x${h}:${href}`;
299
+ let id = assetIds.get(k);
300
+ if (!id) {
301
+ id = `image_${assets.length}`;
302
+ assetIds.set(k, id);
303
+ assets.push({ id, w, h, u: "", p: href, e: 1 });
304
+ }
305
+ return id;
306
+ };
307
+ /** Layers drawing some pieces under one parent, bottom first (the final list is reversed to top first). */
308
+ const pieceLayers = (pieces, name, ks, parentKey, ownKey) => {
309
+ if (pieces.length === 1 && pieces[0].kind === "shapes") {
310
+ return [{ ...base(ownKey, name, ks, parentKey), ty: 4, shapes: [...pieces[0].groups].reverse() }];
311
+ }
312
+ // Several pieces: a null carries the motion, each piece a child layer (opacity multiplied in).
313
+ const holder = { ...base(ownKey, name, { ...ks, o: { a: 0, k: 100 } }, parentKey), ty: 3 };
314
+ nulls.push(holder);
315
+ const out = [];
316
+ pieces.forEach((p, i) => {
317
+ const childKs = p.kind === "image" ? staticTransform(p.matrix, 100) : staticTransform(identity(), 100);
318
+ childKs.o = p.kind === "image" && p.opacity < 1 ? scaleOpacity(ks.o, p.opacity) : ks.o;
319
+ const layer = { ...base(`${ownKey}#${i}`, `${name} ${i}`, childKs), parent: holder.ind };
320
+ out.push(p.kind === "image" ? { ...layer, ty: 2, refId: assetFor(p.href, p.width, p.height) } : { ...layer, ty: 4, shapes: [...p.groups].reverse() });
321
+ });
322
+ return out;
323
+ };
324
+ for (const key of order) {
325
+ const tr = tracks.get(key);
326
+ const name = key.split("/").pop().replace(/~\d+$/, "");
327
+ const matrices = filled(tr.matrix);
328
+ if (tr.kind === "null") {
329
+ nulls.push({ ...base(key, name, sampledTransform(matrices, 0), tr.parent), ty: 3 });
330
+ continue;
331
+ }
332
+ // Distinct drawings of this key, in order of appearance.
333
+ const variants = [...new Set(tr.content.filter((c) => c !== undefined))];
334
+ if (tr.kind === "path") {
335
+ const paths = tr.paths.map((p) => (p ? pathToBeziers(p.d).map(roundBezier) : undefined));
336
+ const present = paths.filter((p) => !!p && p.length > 0);
337
+ if (!present.length)
338
+ continue;
339
+ const attrsList = tr.paths.find((p) => p).attrs;
340
+ if (variants.length > 1)
341
+ warn(`${name}: its paint changes over time; the first paint is used`);
342
+ const same = present.every((p) => sameStructure(p, present[0])) ? present : equalize(present);
343
+ if (same) {
344
+ const template = same[0];
345
+ let n = 0;
346
+ let last = template;
347
+ const values = paths.map((p) => flatBezier((last = p && p.length ? same[n++] : last)));
348
+ const prop = property(values, 0, 0.05);
349
+ // One `sh` per sub-path, static or keyframed on its own.
350
+ const subs = template.map((sub, si) => prop.a === 0
351
+ ? { ty: "sh", ks: { a: 0, k: sub } }
352
+ : { ty: "sh", ks: { a: 1, k: prop.k.map((kf) => ({ ...kf, s: [unflatBezier(template, kf.s)[si]] })) } });
353
+ const shapes = [{ ty: "gr", nm: name, it: [...subs, ...pathStyle(attrsList, ctx), { ty: "tr", ...staticTransform(identity()) }] }];
354
+ const opacity = tr.opacity.map((op, f) => (tr.paths[f] ? op : 0));
355
+ layers.push({ ...base(key, name, sampledTransform(matrices, 0, opacity), tr.parent), ty: 4, shapes });
356
+ }
357
+ else {
358
+ warn(`${name}: its path changes structure over time; drawn as one layer per drawing`);
359
+ const distinct = [...new Set(tr.paths.map((p) => p?.d).filter((d) => !!d))];
360
+ if (distinct.length > o.maxVariants) {
361
+ warn(`${name}: more than ${o.maxVariants} different drawings; left out`);
362
+ continue;
363
+ }
364
+ distinct.forEach((d, vi) => {
365
+ const opacity = tr.opacity.map((op, f) => (tr.paths[f]?.d === d ? op : 0));
366
+ const shapes = [{ ty: "gr", nm: name, it: [...pathToBeziers(d).map((p) => ({ ty: "sh", ks: { a: 0, k: roundBezier(p) } })), ...pathStyle(attrsList, ctx), { ty: "tr", ...staticTransform(identity()) }] }];
367
+ layers.push({ ...base(vi ? `${key}#v${vi}` : key, vi ? `${name} ${vi}` : name, sampledTransform(matrices, 0, opacity), tr.parent), ty: 4, shapes });
368
+ });
369
+ }
370
+ continue;
371
+ }
372
+ if (variants.length > o.maxVariants) {
373
+ warn(`${name}: more than ${o.maxVariants} different drawings; left out`);
374
+ continue;
375
+ }
376
+ variants.forEach((markup, vi) => {
377
+ let pieces = pieceCache.get(markup);
378
+ if (!pieces) {
379
+ pieces = svgToPieces(markup, { ...ctx, warn: (m) => warn(`${name}: ${m}`) });
380
+ pieceCache.set(markup, pieces);
381
+ }
382
+ if (!pieces.length)
383
+ return;
384
+ const opacity = tr.opacity.map((op, f) => (tr.content[f] === markup ? op : 0));
385
+ const ks = sampledTransform(matrices, 0, opacity);
386
+ const ownKey = vi ? `${key}#v${vi}` : key;
387
+ const variantName = variants.length > 1 ? `${name} [${vi}]` : name;
388
+ layers.push(...pieceLayers(pieces, variantName, ks, tr.parent, ownKey));
389
+ });
390
+ }
391
+ // Lottie lists the top layer first.
392
+ const out = [...layers.reverse(), ...nulls];
393
+ if (o.background) {
394
+ out.push({ ...base("#background", "background", staticTransform(identity())), ty: 1, sc: o.background, sw: o.width, sh: o.height });
395
+ }
396
+ // Every index unique, parents present.
397
+ const lottie = {
398
+ v: "5.7.4",
399
+ fr: o.fps,
400
+ ip: 0,
401
+ op: total,
402
+ w: o.width,
403
+ h: o.height,
404
+ nm: o.name,
405
+ ddd: 0,
406
+ assets,
407
+ layers: out,
408
+ meta: { g: "animeStudio" },
409
+ };
410
+ return { lottie, warnings: [...o.warnings] };
411
+ }
412
+ /** Multiplies an opacity property by a constant factor. */
413
+ function scaleOpacity(p, k) {
414
+ if (p.a === 0)
415
+ return { a: 0, k: p.k * k };
416
+ return { a: 1, k: p.k.map((kf) => ({ ...kf, s: kf.s.map((v) => v * k) })) };
417
+ }
418
+ /** A path node's attributes → Lottie fill / stroke items (stroke first: drawn on top). */
419
+ function pathStyle(attrs, ctx) {
420
+ const style = Object.entries(attrs)
421
+ .map(([k, v]) => `${k}="${String(v).replace(/"/g, "&quot;")}"`)
422
+ .join(" ");
423
+ const pieces = svgToPieces(`<path d="M0 0L1 0L1 1Z" ${style}/>`, ctx);
424
+ const group = pieces[0]?.kind === "shapes" ? pieces[0].groups[0] : undefined;
425
+ return group ? group.it.filter((s) => s.ty === "fl" || s.ty === "st" || s.ty === "gf") : [];
426
+ }
427
+ /**
428
+ * A character's clip as a Lottie animation: the character stands in the middle of a `width` ×
429
+ * `height` canvas (fitted like `previewScene`), playing `clip` once — one cycle of a looping clip,
430
+ * so the Lottie loops seamlessly (with physics, the cycle after two cycles of settling).
431
+ */
432
+ export function lottieFromCharacter(doc, opts = {}) {
433
+ const clip = opts.clip ?? Object.keys(doc.clips ?? {})[0];
434
+ if (clip && !doc.clips?.[clip])
435
+ throw new Error(`unknown clip "${clip}" (clips: ${Object.keys(doc.clips ?? {}).join(", ") || "none"})`);
436
+ const def = clip ? doc.clips[clip] : undefined;
437
+ const length = def?.duration ?? 1;
438
+ const settle = def?.loop && (doc.physics?.length ?? 0) > 0 ? 2 * length : 0;
439
+ const fps = opts.fps ?? 30;
440
+ const scene = previewScene(doc, {
441
+ clip,
442
+ width: opts.width ?? 512,
443
+ height: opts.height ?? 512,
444
+ fps,
445
+ duration: settle + length + 1 / fps,
446
+ ...(opts.scale !== undefined ? { scale: opts.scale } : {}),
447
+ ...(opts.background ? { background: opts.background } : { background: "none" }),
448
+ });
449
+ const from = opts.from ?? settle;
450
+ const to = opts.to ?? settle + length;
451
+ const result = lottieFromScene(scene, { ...opts, fps, from, to, name: opts.name ?? doc.name });
452
+ if (!opts.background)
453
+ result.lottie.layers = result.lottie.layers.filter((l) => l.nm !== "background");
454
+ return result;
455
+ }
456
+ //# sourceMappingURL=export.js.map