swf2js 0.1.2 → 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.
Files changed (416) hide show
  1. package/README.md +81 -14
  2. package/package.json +11 -7
  3. package/studio/actionscript-roundtrip.test.js +54 -0
  4. package/studio/actionscript-scripts.test.js +169 -0
  5. package/studio/animated-image.test.js +137 -0
  6. package/studio/arithmetic.test.js +16 -0
  7. package/studio/as3-import.test.js +110 -0
  8. package/studio/audio-info.test.js +44 -0
  9. package/studio/components.test.js +152 -0
  10. package/studio/document-editing.test.js +92 -0
  11. package/studio/examples/01-space-mission.json +1628 -0
  12. package/studio/examples/02-clockwork-vault.json +1079 -0
  13. package/studio/examples/03-neon-synth.json +1364 -0
  14. package/studio/examples/04-kinetic-poster.json +923 -0
  15. package/studio/examples/05-signal-relay.json +1131 -0
  16. package/studio/examples/06-calculator.json +564 -0
  17. package/studio/frame-editing.test.js +129 -0
  18. package/studio/frame-events.test.js +117 -0
  19. package/studio/groups.test.js +88 -0
  20. package/studio/index.html +962 -0
  21. package/studio/interaction-triggers.test.js +37 -0
  22. package/studio/linked-actions.test.js +48 -0
  23. package/studio/lottie.test.js +208 -0
  24. package/studio/masks.test.js +43 -0
  25. package/studio/media-assets.test.js +62 -0
  26. package/studio/paint-tools.test.js +60 -0
  27. package/studio/playback.test.js +17 -0
  28. package/studio/project-io.test.js +405 -0
  29. package/studio/project-preview.test.js +475 -0
  30. package/studio/scene-transition.test.js +32 -0
  31. package/studio/server/archive-companions.js +27 -0
  32. package/studio/server/as3-library.js +91 -0
  33. package/studio/server/assets.js +162 -0
  34. package/studio/server/audio-info.js +82 -0
  35. package/studio/server/font-files.js +332 -0
  36. package/studio/server/http.js +135 -0
  37. package/studio/server/linked-actions.js +93 -0
  38. package/studio/server/png-decode.js +1 -0
  39. package/studio/server/project-movie.js +1164 -0
  40. package/studio/server/project-preview.js +152 -0
  41. package/studio/server/projects.js +370 -0
  42. package/studio/server/report.js +29 -0
  43. package/studio/server/routes.js +93 -0
  44. package/studio/server/swf-authoring.js +90 -0
  45. package/studio/server/swf-control-runtime.as +513 -0
  46. package/studio/server/swf-controls.js +119 -0
  47. package/studio/server/swf-export.js +293 -0
  48. package/studio/server/swf-import.js +1675 -0
  49. package/studio/server/swf-morphs.js +64 -0
  50. package/studio/server/swf-routes.js +42 -0
  51. package/studio/server/swf-streams.js +80 -0
  52. package/studio/server/swf-transition-runtime.as +52 -0
  53. package/studio/server/tween-recovery.js +106 -0
  54. package/studio/server-api.test.js +283 -0
  55. package/studio/server.js +320 -0
  56. package/studio/src/animated-image.js +423 -0
  57. package/studio/src/appearance-inspector.js +63 -0
  58. package/studio/src/arithmetic.js +50 -0
  59. package/studio/src/authored-controls.js +42 -0
  60. package/studio/src/busy.js +41 -0
  61. package/studio/src/canvas.js +430 -0
  62. package/studio/src/clipper-browser.js +2 -0
  63. package/studio/src/color-transform.js +38 -0
  64. package/studio/src/component-inspector.js +126 -0
  65. package/studio/src/components.js +268 -0
  66. package/studio/src/display-frame.js +262 -0
  67. package/studio/src/document-editing.js +69 -0
  68. package/studio/src/event-editor.js +150 -0
  69. package/studio/src/frame-editing.js +150 -0
  70. package/studio/src/frame-events.js +128 -0
  71. package/studio/src/frame-image.js +28 -0
  72. package/studio/src/groups.js +125 -0
  73. package/studio/src/handler-editor.js +122 -0
  74. package/studio/src/history.js +83 -0
  75. package/studio/src/imported-paths.js +99 -0
  76. package/studio/src/index.js +3582 -0
  77. package/studio/src/interaction-triggers.js +42 -0
  78. package/studio/src/json-patch.js +77 -0
  79. package/studio/src/layer-icons.js +25 -0
  80. package/studio/src/lottie-export.js +948 -0
  81. package/studio/src/lottie-import.js +1138 -0
  82. package/studio/src/masks.js +69 -0
  83. package/studio/src/media-assets.js +188 -0
  84. package/studio/src/media-library.js +193 -0
  85. package/studio/src/model.js +431 -0
  86. package/studio/src/numeric-fields.js +46 -0
  87. package/studio/src/object-list.js +57 -0
  88. package/studio/src/paint-tools.js +76 -0
  89. package/studio/src/placement-effects.js +74 -0
  90. package/studio/src/playback.js +10 -0
  91. package/studio/src/preview-audio.js +64 -0
  92. package/studio/src/preview-interactions.js +106 -0
  93. package/studio/src/preview-recorder.js +335 -0
  94. package/studio/src/preview-surface.js +338 -0
  95. package/studio/src/project-io.js +905 -0
  96. package/studio/src/project-session.js +375 -0
  97. package/studio/src/projects-dialog.js +319 -0
  98. package/studio/src/scene-transition.js +129 -0
  99. package/studio/src/script-editor.js +175 -0
  100. package/studio/src/script-references.js +74 -0
  101. package/studio/src/scripted-controls.js +146 -0
  102. package/studio/src/scripts.js +185 -0
  103. package/studio/src/stage-guides.js +101 -0
  104. package/studio/src/svg-animation.js +416 -0
  105. package/studio/src/svg-context.js +522 -0
  106. package/studio/src/svg-frame.js +413 -0
  107. package/studio/src/svg-import.js +1208 -0
  108. package/studio/src/swf-recording.js +104 -0
  109. package/studio/src/symbol-library.js +39 -0
  110. package/studio/src/symbols.js +62 -0
  111. package/studio/src/text-fields.js +58 -0
  112. package/studio/src/theme.js +43 -0
  113. package/studio/src/timeline.js +321 -0
  114. package/studio/src/vector-cut.js +103 -0
  115. package/studio/src/vector-geometry.js +254 -0
  116. package/studio/src/vector-style.js +146 -0
  117. package/studio/src/video-encode.js +84 -0
  118. package/studio/src/video-export.js +331 -0
  119. package/studio/src/video-mux.js +339 -0
  120. package/studio/src/video-playback.js +281 -0
  121. package/studio/src/workspace.js +344 -0
  122. package/studio/stroke-style.test.js +119 -0
  123. package/studio/styles.css +1547 -0
  124. package/studio/svg-export.test.js +162 -0
  125. package/studio/svg-import.test.js +318 -0
  126. package/studio/swf-authoring.test.js +140 -0
  127. package/studio/swf-export.test.js +324 -0
  128. package/studio/swf-import.test.js +489 -0
  129. package/studio/symbols.test.js +68 -0
  130. package/studio/tests/accessibility-interactions.mjs +138 -0
  131. package/studio/tests/appearance-interactions.mjs +103 -0
  132. package/studio/tests/control-interactions.mjs +60 -0
  133. package/studio/tests/event-interactions.mjs +117 -0
  134. package/studio/tests/external-resources.mjs +174 -0
  135. package/studio/tests/frame-image.mjs +71 -0
  136. package/studio/tests/html-export.mjs +68 -0
  137. package/studio/tests/import-files.mjs +131 -0
  138. package/studio/tests/lottie.mjs +125 -0
  139. package/studio/tests/mask-interactions.mjs +148 -0
  140. package/studio/tests/media-interactions.mjs +109 -0
  141. package/studio/tests/paint-interactions.mjs +64 -0
  142. package/studio/tests/project-interactions.mjs +244 -0
  143. package/studio/tests/script-interactions.mjs +178 -0
  144. package/studio/tests/scripted-control-interactions.mjs +107 -0
  145. package/studio/tests/svg-export.mjs +149 -0
  146. package/studio/tests/text-field-interactions.mjs +64 -0
  147. package/studio/tests/theme-interactions.mjs +53 -0
  148. package/studio/tests/timeline-browser.mjs +507 -0
  149. package/studio/tests/transition-interactions.mjs +94 -0
  150. package/studio/tests/trigger-interactions.mjs +93 -0
  151. package/studio/tests/video-export.mjs +243 -0
  152. package/studio/tests/workspace-interactions.mjs +226 -0
  153. package/studio/tween-recovery.test.js +31 -0
  154. package/studio/vector-style.test.js +56 -0
  155. package/studio/video-export.test.js +326 -0
  156. package/studiospec/actionscript.md +88 -0
  157. package/studiospec/architecture.md +378 -0
  158. package/studiospec/controls.md +100 -0
  159. package/studiospec/file-support.md +268 -0
  160. package/studiospec/lottie.md +69 -0
  161. package/studiospec/requirements.md +135 -0
  162. package/studiospec/stroke-style.md +95 -0
  163. package/studiospec/svg-export.md +83 -0
  164. package/studiospec/svg-import.md +139 -0
  165. package/studiospec/swooflib-integration.md +115 -0
  166. package/studiospec/tasks.md +573 -0
  167. package/studiospec/video-export.md +127 -0
  168. package/swf2js/__tests__/actionscript.test.js +1609 -0
  169. package/swf2js/__tests__/adpcm-audio.test.js +43 -0
  170. package/swf2js/__tests__/as2-compiler.test.js +153 -0
  171. package/swf2js/__tests__/as3-mixed-depth.test.js +498 -0
  172. package/swf2js/__tests__/authored-sprite-hit.test.js +118 -0
  173. package/swf2js/__tests__/authored-sprite-sizing.test.js +164 -0
  174. package/swf2js/__tests__/avm1-action-prefix.test.js +134 -0
  175. package/swf2js/__tests__/avm1-attach-movie.test.js +1151 -0
  176. package/swf2js/__tests__/avm1-boxhead-budget.test.js +73 -0
  177. package/swf2js/__tests__/avm1-cfg-bubble-tanks.test.js +101 -0
  178. package/swf2js/__tests__/avm1-cfg-mario-kart.test.js +184 -0
  179. package/swf2js/__tests__/avm1-cfg-mario.test.js +31 -0
  180. package/swf2js/__tests__/avm1-cfg-pacman.test.js +49 -0
  181. package/swf2js/__tests__/avm1-checkers-gameplay.test.js +122 -0
  182. package/swf2js/__tests__/avm1-clip-actions.test.js +2002 -0
  183. package/swf2js/__tests__/avm1-clone-drag.test.js +626 -0
  184. package/swf2js/__tests__/avm1-decompiler.test.js +102 -0
  185. package/swf2js/__tests__/avm1-dynamic-locals.test.js +159 -0
  186. package/swf2js/__tests__/avm1-formal-parameters.test.js +71 -0
  187. package/swf2js/__tests__/avm1-key-events.test.js +52 -0
  188. package/swf2js/__tests__/avm1-load-bitmap.test.js +75 -0
  189. package/swf2js/__tests__/avm1-loading-host-actions.test.js +764 -0
  190. package/swf2js/__tests__/avm1-multibyte-strings.test.js +63 -0
  191. package/swf2js/__tests__/avm1-pacman-gameplay.test.js +115 -0
  192. package/swf2js/__tests__/avm1-shape-hittest.test.js +311 -0
  193. package/swf2js/__tests__/avm1-shared-bodies.test.js +57 -0
  194. package/swf2js/__tests__/avm1-shared-runtime.test.js +1364 -0
  195. package/swf2js/__tests__/avm1-snake-gameplay.test.js +139 -0
  196. package/swf2js/__tests__/avm1-super.test.js +70 -0
  197. package/swf2js/__tests__/avm1-target-path.test.js +325 -0
  198. package/swf2js/__tests__/avm1-try.test.js +229 -0
  199. package/swf2js/__tests__/avm2-activation-closures.test.js +65 -0
  200. package/swf2js/__tests__/avm2-applytype.test.js +180 -0
  201. package/swf2js/__tests__/avm2-call-ops.test.js +232 -0
  202. package/swf2js/__tests__/avm2-callsuperid.test.js +231 -0
  203. package/swf2js/__tests__/avm2-class-initializer.test.js +219 -0
  204. package/swf2js/__tests__/avm2-custom-namespace.test.js +139 -0
  205. package/swf2js/__tests__/avm2-describe-type.test.js +96 -0
  206. package/swf2js/__tests__/avm2-dictionary.test.js +96 -0
  207. package/swf2js/__tests__/avm2-domain-memory.test.js +332 -0
  208. package/swf2js/__tests__/avm2-e4x.test.js +326 -0
  209. package/swf2js/__tests__/avm2-exceptions.test.js +81 -0
  210. package/swf2js/__tests__/avm2-findprop.test.js +110 -0
  211. package/swf2js/__tests__/avm2-getlex.test.js +166 -0
  212. package/swf2js/__tests__/avm2-global-slot.test.js +106 -0
  213. package/swf2js/__tests__/avm2-interface.test.js +95 -0
  214. package/swf2js/__tests__/avm2-multiname-precedence.test.js +148 -0
  215. package/swf2js/__tests__/avm2-named-namespace-types.test.js +106 -0
  216. package/swf2js/__tests__/avm2-optional-args.test.js +100 -0
  217. package/swf2js/__tests__/avm2-outer-scopes.test.js +101 -0
  218. package/swf2js/__tests__/avm2-package-internal-class.test.js +106 -0
  219. package/swf2js/__tests__/avm2-protected-namespace.test.js +105 -0
  220. package/swf2js/__tests__/avm2-protected.test.js +214 -0
  221. package/swf2js/__tests__/avm2-qwop-gameplay.test.js +116 -0
  222. package/swf2js/__tests__/avm2-runtime-namespaces.test.js +159 -0
  223. package/swf2js/__tests__/avm2-script-traits.test.js +89 -0
  224. package/swf2js/__tests__/avm2-shared-runtime.test.js +52 -0
  225. package/swf2js/__tests__/avm2-slot-ops.test.js +117 -0
  226. package/swf2js/__tests__/avm2-type-ops.test.js +224 -0
  227. package/swf2js/__tests__/bevel-filter.test.js +116 -0
  228. package/swf2js/__tests__/bitmap-button-mask.test.js +106 -0
  229. package/swf2js/__tests__/bitmap-data-draw.test.js +388 -0
  230. package/swf2js/__tests__/bitmap-decoder.test.js +108 -0
  231. package/swf2js/__tests__/bitmapdata-color-bounds.test.js +70 -0
  232. package/swf2js/__tests__/bitmapdata-copy-channel.test.js +91 -0
  233. package/swf2js/__tests__/bitmapdata-copy-pixels.test.js +136 -0
  234. package/swf2js/__tests__/bitmapdata-fill-compare.test.js +241 -0
  235. package/swf2js/__tests__/bitmapdata-filter.test.js +232 -0
  236. package/swf2js/__tests__/bitmapdata-hit-test.test.js +71 -0
  237. package/swf2js/__tests__/bitmapdata-merge.test.js +84 -0
  238. package/swf2js/__tests__/bitmapdata-palette-map.test.js +92 -0
  239. package/swf2js/__tests__/bitmapdata-pixels-io.test.js +198 -0
  240. package/swf2js/__tests__/bitmapdata-threshold.test.js +97 -0
  241. package/swf2js/__tests__/bitmapdata-vector.test.js +82 -0
  242. package/swf2js/__tests__/blur-filter.test.js +48 -0
  243. package/swf2js/__tests__/bundle-emitter.test.js +394 -0
  244. package/swf2js/__tests__/button-actions.test.js +370 -0
  245. package/swf2js/__tests__/button-color-transform.test.js +48 -0
  246. package/swf2js/__tests__/button-decoder.test.js +106 -0
  247. package/swf2js/__tests__/button-hit-test.test.js +825 -0
  248. package/swf2js/__tests__/button-scaling-grid.test.js +124 -0
  249. package/swf2js/__tests__/button-sound.test.js +105 -0
  250. package/swf2js/__tests__/bytearray-coercion.test.js +23 -0
  251. package/swf2js/__tests__/bytearray-object-serialization.test.js +380 -0
  252. package/swf2js/__tests__/cfg-switch-loop.test.js +103 -0
  253. package/swf2js/__tests__/clip-depth-mask.test.js +119 -0
  254. package/swf2js/__tests__/clipped-bitmap-fill.test.js +118 -0
  255. package/swf2js/__tests__/companion-swf.test.js +638 -0
  256. package/swf2js/__tests__/context-menu.test.js +149 -0
  257. package/swf2js/__tests__/convolution-filter.test.js +74 -0
  258. package/swf2js/__tests__/definefont4.test.js +280 -0
  259. package/swf2js/__tests__/display-displacement.test.js +161 -0
  260. package/swf2js/__tests__/display-list.test.js +80 -0
  261. package/swf2js/__tests__/display-mask-render.test.js +656 -0
  262. package/swf2js/__tests__/displayobject-stage.test.js +320 -0
  263. package/swf2js/__tests__/embedded-script-audio.test.js +131 -0
  264. package/swf2js/__tests__/embedded-swf.test.js +202 -0
  265. package/swf2js/__tests__/embedded-textfield.test.js +107 -0
  266. package/swf2js/__tests__/embedded-timeline-audio.test.js +182 -0
  267. package/swf2js/__tests__/embedded-timeline-input.test.js +420 -0
  268. package/swf2js/__tests__/embedded-timer-lifecycle.test.js +145 -0
  269. package/swf2js/__tests__/event-priority-order.test.js +125 -0
  270. package/swf2js/__tests__/event-weak-listeners.test.js +53 -0
  271. package/swf2js/__tests__/event-will-trigger.test.js +43 -0
  272. package/swf2js/__tests__/flash-text-engine-content.test.js +115 -0
  273. package/swf2js/__tests__/flash-text-engine-format.test.js +95 -0
  274. package/swf2js/__tests__/flash-text-engine-line.test.js +314 -0
  275. package/swf2js/__tests__/font-encoder.test.js +95 -0
  276. package/swf2js/__tests__/font-outline-text.test.js +659 -0
  277. package/swf2js/__tests__/glow-shadow-filter.test.js +68 -0
  278. package/swf2js/__tests__/graphics-bitmap-smoothing.test.js +32 -0
  279. package/swf2js/__tests__/graphics-fill-lifetime.test.js +36 -0
  280. package/swf2js/__tests__/graphics-gradient-matrix.test.js +53 -0
  281. package/swf2js/__tests__/graphics-stroke-hit-test.test.js +457 -0
  282. package/swf2js/__tests__/hit-test-primitives.test.js +414 -0
  283. package/swf2js/__tests__/input-events.test.js +714 -0
  284. package/swf2js/__tests__/integration/corpus.test.js +41 -0
  285. package/swf2js/__tests__/loader-embedded-swf.test.js +210 -0
  286. package/swf2js/__tests__/loader-info.test.js +81 -0
  287. package/swf2js/__tests__/local-connection.test.js +122 -0
  288. package/swf2js/__tests__/morph-focal-gradient.test.js +51 -0
  289. package/swf2js/__tests__/morph-topology.test.js +267 -0
  290. package/swf2js/__tests__/movie-data-codec.test.js +128 -0
  291. package/swf2js/__tests__/nellymoser-audio.test.js +84 -0
  292. package/swf2js/__tests__/opaque-background-cache.test.js +352 -0
  293. package/swf2js/__tests__/path-stream.test.js +81 -0
  294. package/swf2js/__tests__/place-object-filters.test.js +88 -0
  295. package/swf2js/__tests__/place-object3-decoder.test.js +116 -0
  296. package/swf2js/__tests__/place-object3-image.test.js +85 -0
  297. package/swf2js/__tests__/player-version.test.js +46 -0
  298. package/swf2js/__tests__/root-textfield.test.js +287 -0
  299. package/swf2js/__tests__/scaling-grid.test.js +183 -0
  300. package/swf2js/__tests__/shape-decoder.test.js +361 -0
  301. package/swf2js/__tests__/shape-line-style2.test.js +138 -0
  302. package/swf2js/__tests__/shape-nonscaling-stroke.test.js +131 -0
  303. package/swf2js/__tests__/shape-pixel-hint.test.js +101 -0
  304. package/swf2js/__tests__/simplebutton-pointer.test.js +1477 -0
  305. package/swf2js/__tests__/socket-offline.test.js +67 -0
  306. package/swf2js/__tests__/sound-avm1-stop.test.js +99 -0
  307. package/swf2js/__tests__/sound-envelope.test.js +110 -0
  308. package/swf2js/__tests__/sound-extract.test.js +168 -0
  309. package/swf2js/__tests__/sound-id3.test.js +283 -0
  310. package/swf2js/__tests__/sound-load.test.js +259 -0
  311. package/swf2js/__tests__/sound-mixer-spectrum.test.js +261 -0
  312. package/swf2js/__tests__/sound-stream-sprite.test.js +624 -0
  313. package/swf2js/__tests__/sound-transform.test.js +104 -0
  314. package/swf2js/__tests__/speex-audio.test.js +77 -0
  315. package/swf2js/__tests__/stage-noscale.test.js +45 -0
  316. package/swf2js/__tests__/swf-encoder.test.js +134 -0
  317. package/swf2js/__tests__/swflib-assemble.test.js +20 -0
  318. package/swf2js/__tests__/textfield-html-text.test.js +368 -0
  319. package/swf2js/__tests__/textfield-line-layout.test.js +339 -0
  320. package/swf2js/__tests__/textfield-programmatic-overlay.test.js +2506 -0
  321. package/swf2js/__tests__/textfield-scroll.test.js +79 -0
  322. package/swf2js/__tests__/textfield-selection.test.js +383 -0
  323. package/swf2js/__tests__/timeline-effect-surfaces.test.js +295 -0
  324. package/swf2js/__tests__/timeline-named-anchor.test.js +139 -0
  325. package/swf2js/__tests__/timeline-scenes.test.js +1723 -0
  326. package/swf2js/__tests__/urlloader-http-status.test.js +236 -0
  327. package/{src → swf2js}/cli.js +43 -11
  328. package/swf2js/compiler/as2-classes.js +156 -0
  329. package/swf2js/compiler/as2-parser.js +598 -0
  330. package/swf2js/compiler/avm1-codegen.js +897 -0
  331. package/swf2js/compiler/index.js +28 -0
  332. package/{src → swf2js}/decoder/button-decoder.js +3 -1
  333. package/swf2js/decoder/png.js +114 -0
  334. package/{src → swf2js}/decoder/shape-decoder.js +20 -10
  335. package/{src → swf2js}/decoder/tag-decoder.js +5 -3
  336. package/{src → swf2js}/decoder/tag-types.js +4 -0
  337. package/swf2js/decompiler/avm1-decompiler.js +1138 -0
  338. package/{src → swf2js}/emitter/asset-encoder.js +66 -113
  339. package/{src → swf2js}/emitter/bundle-emitter.js +209 -78
  340. package/swf2js/emitter/external-resources.js +39 -0
  341. package/swf2js/emitter/movie-data-codec.js +91 -0
  342. package/swf2js/encoder/bit-writer.js +182 -0
  343. package/swf2js/encoder/shape-encoder.js +310 -0
  344. package/swf2js/encoder/swf-builder.js +639 -0
  345. package/swf2js/encoder/swf-writer.js +55 -0
  346. package/{src/runtime/swflib/assemble.js → swf2js/runtime/assemble-swooflib.js} +4 -3
  347. package/{src → swf2js}/runtime/avm1-runtime.js +102 -63
  348. package/{src → swf2js}/runtime/index.js +1 -1
  349. package/{src → swf2js}/runtime/movie-runtime.js +28 -2
  350. package/{src → swf2js}/transpiler/actionscript.js +82 -19
  351. package/{src → swf2js}/transpiler/avm1/avm1-opcodes.js +5 -3
  352. package/{src → swf2js}/transpiler/avm1/avm1-transpiler.js +69 -6
  353. package/{src → swf2js}/transpiler/avm2/avm2-transpiler.js +1 -1
  354. package/{src → swf2js}/transpiler/timeline/display-list.js +41 -22
  355. package/{src → swf2js}/transpiler/timeline/timeline-codegen.js +97 -36
  356. package/swooflib/README.md +569 -0
  357. package/swooflib/adpcm.js +147 -0
  358. package/{src/runtime/swflib → swooflib}/builtins.js +6 -0
  359. package/{src/runtime/swflib → swooflib}/context-menu.js +7 -1
  360. package/swooflib/control-definitions.js +42 -0
  361. package/swooflib/control-widget.js +763 -0
  362. package/swooflib/controls.js +300 -0
  363. package/{src/runtime/swflib → swooflib}/display.js +16 -10
  364. package/{src/runtime/swflib → swooflib}/events.js +11 -0
  365. package/{src/runtime/swflib → swooflib}/flash.js +6 -5
  366. package/{src/runtime/swflib → swooflib}/graphics.js +81 -19
  367. package/{src/runtime/swflib → swooflib}/input.js +12 -14
  368. package/{src/runtime/swflib → swooflib}/loader.js +52 -22
  369. package/swooflib/movie-network.js +86 -0
  370. package/swooflib/path-stream.js +169 -0
  371. package/{src/runtime/swflib → swooflib}/render.js +3 -13
  372. package/{src/runtime/swflib → swooflib}/sound.js +25 -2
  373. package/{src/runtime/swflib → swooflib}/stage.js +3 -3
  374. package/swooflib/stream-time.js +21 -0
  375. package/{src/runtime/swflib → swooflib}/system.js +88 -37
  376. package/{src/runtime/swflib → swooflib}/text-paint.js +14 -3
  377. package/{src/runtime/swflib → swooflib}/text.js +8 -0
  378. package/swooflib/xml-node.js +53 -0
  379. package/src/emitter/timeline-data-codec.js +0 -58
  380. /package/{src → swf2js}/decoder/symbol-table.js +0 -0
  381. /package/{src → swf2js}/emitter/embedded-swf.js +0 -0
  382. /package/{src → swf2js}/emitter/font-encoder.js +0 -0
  383. /package/{src → swf2js}/model/swf-document.js +0 -0
  384. /package/{src → swf2js}/model/transpile-result.js +0 -0
  385. /package/{src → swf2js}/parser/bit-reader.js +0 -0
  386. /package/{src → swf2js}/parser/decompressor.js +0 -0
  387. /package/{src → swf2js}/parser/swf-parser.js +0 -0
  388. /package/{src → swf2js}/pretty-printer/pretty-printer.js +0 -0
  389. /package/{src → swf2js}/runtime/avm2-runtime.js +0 -0
  390. /package/{src → swf2js}/runtime/embedded-movie-runtime.js +0 -0
  391. /package/{src → swf2js}/transpiler/avm1/avm1-ir.js +0 -0
  392. /package/{src → swf2js}/transpiler/avm1/avm1-rewrite.js +0 -0
  393. /package/{src → swf2js}/transpiler/avm2/abc-reader.js +0 -0
  394. /package/{src → swf2js}/transpiler/cfg-structurer.js +0 -0
  395. /package/{src → swf2js}/util/diagnostics.js +0 -0
  396. /package/{src → swf2js}/util/logger.js +0 -0
  397. /package/{src/runtime/swflib → swooflib}/bitmap-image.js +0 -0
  398. /package/{src/runtime/swflib → swooflib}/bitmap.js +0 -0
  399. /package/{src/runtime/swflib → swooflib}/bytearray.js +0 -0
  400. /package/{src/runtime/swflib → swooflib}/compiled-swf.js +0 -0
  401. /package/{src/runtime/swflib → swooflib}/cursor-flag.js +0 -0
  402. /package/{src/runtime/swflib → swooflib}/dictionary.js +0 -0
  403. /package/{src/runtime/swflib → swooflib}/filters.js +0 -0
  404. /package/{src/runtime/swflib → swooflib}/geom.js +0 -0
  405. /package/{src/runtime/swflib → swooflib}/glyph-metrics.js +0 -0
  406. /package/{src/runtime/swflib → swooflib}/host.js +0 -0
  407. /package/{src/runtime/swflib → swooflib}/inherit.js +0 -0
  408. /package/{src/runtime/swflib → swooflib}/marks.js +0 -0
  409. /package/{src/runtime/swflib → swooflib}/matrix3d.js +0 -0
  410. /package/{src/runtime/swflib → swooflib}/pointer-bridge.js +0 -0
  411. /package/{src/runtime/swflib → swooflib}/projection.js +0 -0
  412. /package/{src/runtime/swflib → swooflib}/sprite-drag.js +0 -0
  413. /package/{src/runtime/swflib → swooflib}/stage-ref.js +0 -0
  414. /package/{src/runtime/swflib → swooflib}/text-field.js +0 -0
  415. /package/{src/runtime/swflib → swooflib}/transform.js +0 -0
  416. /package/{src/runtime/swflib → swooflib}/xml.js +0 -0
@@ -0,0 +1,1138 @@
1
+ // Lottie import (studiospec/lottie.md). A Lottie file becomes Studio project JSON, which then goes
2
+ // through parseProjectJson like any other project, so its checks and limits apply.
3
+ //
4
+ // A file Studio wrote, unchanged since, carries the project itself and imports exactly. Any
5
+ // other file is read from its Lottie content: each layer's transform is evaluated at every frame
6
+ // (parents included) and reduced to Studio keyframes; shapes become paths, rectangles and
7
+ // ellipses; precomps become symbols; mattes and masks become Studio masks. What Studio cannot
8
+ // hold is reported. Expressions are never run, and images are only read from data URIs.
9
+ import { gunzipBase64, lottieHash } from './lottie-export.js';
10
+ import { reduceTrack } from './svg-animation.js';
11
+ import { placementFilters } from './placement-effects.js';
12
+ import { applyEasing } from './model.js';
13
+
14
+ const MAX_DEPTH = 32;
15
+ const MAX_FRAMES = 0xffff;
16
+ const MAX_WORK = 2e6;
17
+ const round = value => Math.round(value * 1e4) / 1e4;
18
+ const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
19
+ // A solid's colour as Studio's #rrggbb: #rgb is expanded, anything else is black.
20
+ const solidColor = value => {
21
+ const text = String(value ?? '').trim().toLowerCase();
22
+ if (/^#[0-9a-f]{6}/.test(text)) return text.slice(0, 7);
23
+ if (/^#[0-9a-f]{3}$/.test(text)) return `#${[...text.slice(1)].map(c => c + c).join('')}`;
24
+ return '#000000';
25
+ };
26
+ const finite = (value, fallback = 0) => Number.isFinite(+value) ? +value : fallback;
27
+ // Colours are 0–1, except in files from bodymovin 4.0 and before, which used 0–255. The scale is
28
+ // decided once per file (`colorScale`), so a dark 0–255 colour is not read as a light 0–1 one.
29
+ let colorScale = 1;
30
+ const hex = color => {
31
+ const channels = [0, 1, 2].map(k => finite(Array.isArray(color) ? color[k] : 0));
32
+ return `#${channels.map(value => Math.round(clamp(value / colorScale, 0, 1) * 255).toString(16).padStart(2, '0')).join('')}`;
33
+ };
34
+ // 0–255 when any solid colour or fill or stroke colour in the file goes well past 1.
35
+ function fileColorScale(lottie) {
36
+ let large = false;
37
+ const visit = (value, depth) => {
38
+ if (large || depth > 64 || !value || typeof value !== 'object') return;
39
+ if (Array.isArray(value)) { for (const item of value) visit(item, depth + 1); return; }
40
+ if ((value.ty === 'fl' || value.ty === 'st') && value.c) {
41
+ const k = value.c.k;
42
+ const colors = Array.isArray(k) && typeof k[0] === 'object' ? k.flatMap(key => [key.s, key.e]) : [k];
43
+ if (colors.some(color => Array.isArray(color) && color.slice(0, 3).some(channel => +channel > 1.5))) large = true;
44
+ }
45
+ for (const key of Object.keys(value)) if (key !== 'c') visit(value[key], depth + 1);
46
+ };
47
+ visit(lottie.layers, 0);
48
+ visit(lottie.assets, 0);
49
+ return large ? 255 : 1;
50
+ }
51
+
52
+ // ---- Values ------------------------------------------------------------------------------------
53
+
54
+ const isKeyframed = property => property && Array.isArray(property.k) && property.k.length && typeof property.k[0] === 'object' && property.k[0] !== null && 't' in property.k[0];
55
+
56
+ // Cubic-bezier timing (as CSS): the curve's y at a given x.
57
+ function bezierEase(x1, y1, x2, y2, x) {
58
+ if (x <= 0) return 0;
59
+ if (x >= 1) return 1;
60
+ const cx = 3 * x1, bx = 3 * (x2 - x1) - cx, ax = 1 - cx - bx;
61
+ const cy = 3 * y1, by = 3 * (y2 - y1) - cy, ay = 1 - cy - by;
62
+ const sampleX = t => ((ax * t + bx) * t + cx) * t;
63
+ let t = x;
64
+ for (let i = 0; i < 8; i++) {
65
+ const error = sampleX(t) - x;
66
+ const slope = (3 * ax * t + 2 * bx) * t + cx;
67
+ if (Math.abs(error) < 1e-7) break;
68
+ if (Math.abs(slope) < 1e-6) break;
69
+ t -= error / slope;
70
+ }
71
+ if (t < 0 || t > 1 || Math.abs(sampleX(t) - x) > 1e-5) {
72
+ let lo = 0, hi = 1;
73
+ t = x;
74
+ for (let i = 0; i < 40; i++) {
75
+ if (sampleX(t) < x) lo = t; else hi = t;
76
+ t = (lo + hi) / 2;
77
+ }
78
+ }
79
+ return ((ay * t + by) * t + cy) * t;
80
+ }
81
+ const pick = (value, index) => Array.isArray(value) ? (value[index] ?? value[0]) : value;
82
+
83
+ function easeAt(key, dimension, progress) {
84
+ if (!key.o || !key.i) return progress;
85
+ return bezierEase(+pick(key.o.x, dimension) || 0, +pick(key.o.y, dimension) || 0, +pick(key.i.x, dimension) || 0, +pick(key.i.y, dimension) || 0, progress);
86
+ }
87
+
88
+ function lerpValue(a, b, t) {
89
+ if (typeof a === 'number') return a + ((typeof b === 'number' ? b : a) - a) * t;
90
+ if (Array.isArray(a)) return a.map((value, i) => lerpValue(value, Array.isArray(b) ? b[i] : value, t));
91
+ if (a && typeof a === 'object') {
92
+ const out = {};
93
+ for (const key of Object.keys(a)) out[key] = key === 'c' ? a.c : lerpValue(a[key], b?.[key], t);
94
+ return out;
95
+ }
96
+ return a;
97
+ }
98
+
99
+ // A point along a cubic from a to b with tangents (Lottie spatial keyframes), by arc length.
100
+ function spatialAt(a, b, out, inn, progress) {
101
+ const p1 = a.map((v, i) => v + (out[i] ?? 0)), p2 = b.map((v, i) => v + (inn[i] ?? 0));
102
+ const at = t => a.map((v, i) => (1 - t) ** 3 * v + 3 * (1 - t) ** 2 * t * p1[i] + 3 * (1 - t) * t * t * p2[i] + t ** 3 * b[i]);
103
+ const steps = 32, lengths = [0];
104
+ let previous = a;
105
+ for (let k = 1; k <= steps; k++) {
106
+ const point = at(k / steps);
107
+ lengths.push(lengths[k - 1] + Math.hypot(...point.map((v, i) => v - previous[i])));
108
+ previous = point;
109
+ }
110
+ const target = progress * lengths[steps];
111
+ let k = 1;
112
+ while (k < steps && lengths[k] < target) k++;
113
+ const span = lengths[k] - lengths[k - 1];
114
+ const t = (k - 1 + (span > 0 ? (target - lengths[k - 1]) / span : 0)) / steps;
115
+ return at(t);
116
+ }
117
+
118
+ /** A Lottie property's value at time t (frames). Expressions are not run: their static value is used. */
119
+ export function valueAt(property, t, report) {
120
+ if (!property) return undefined;
121
+ if (property.x && typeof property.x === 'string') report?.('Expressions (their recorded values are used)');
122
+ if (property.s === true && (property.x || property.y) && typeof property.x === 'object') {
123
+ // Separated dimensions (position as x and y).
124
+ return [valueAt(property.x, t, report), valueAt(property.y, t, report), ...(property.z ? [valueAt(property.z, t, report)] : [])];
125
+ }
126
+ if (!isKeyframed(property)) return property.k;
127
+ const keys = property.k;
128
+ const start = key => Array.isArray(key.s) && key.s.length === 1 && typeof key.s[0] === 'object' ? key.s[0] : Array.isArray(key.s) && key.s.length === 1 ? key.s[0] : key.s;
129
+ const end = (key, next) => next?.s !== undefined ? start(next) : (key.e !== undefined ? (Array.isArray(key.e) && key.e.length === 1 ? key.e[0] : key.e) : start(key));
130
+ if (t <= keys[0].t) return start(keys[0]);
131
+ let index = 0;
132
+ while (index + 1 < keys.length && keys[index + 1].t <= t) index++;
133
+ const key = keys[index], next = keys[index + 1];
134
+ if (!next) return key.s !== undefined ? start(key) : end(keys[index - 1] ?? key, key);
135
+ const a = start(key), b = end(key, next);
136
+ if (key.h === 1 || next.t <= key.t) return a;
137
+ const progress = (t - key.t) / (next.t - key.t);
138
+ if (key.to && key.ti && Array.isArray(a) && (key.to.some(Boolean) || key.ti.some(Boolean))) {
139
+ return spatialAt(a, b, key.to, key.ti, easeAt(key, 0, progress));
140
+ }
141
+ if (Array.isArray(a) && Array.isArray(key.o?.x) && key.o.x.length > 1) {
142
+ return a.map((value, i) => value + ((b[i] ?? value) - value) * easeAt(key, i, progress));
143
+ }
144
+ return lerpValue(a, b, easeAt(key, 0, progress));
145
+ }
146
+
147
+ // ---- Geometry ----------------------------------------------------------------------------------
148
+
149
+ const IDENTITY = [1, 0, 0, 1, 0, 0];
150
+ const POSE_DEFAULTS = { x: 0, y: 0, rotation: 0, skew: 0, scaleX: 1, scaleY: 1 };
151
+ const mul = (m, n) => [m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1], m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3],
152
+ m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5]];
153
+ const translate = (x, y) => [1, 0, 0, 1, x, y];
154
+ const apply = (m, [x, y]) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
155
+ const applyVector = (m, [x, y]) => [m[0] * x + m[2] * y, m[1] * x + m[3] * y];
156
+
157
+ /** Lottie's transform without the anchor: position, rotation, skew, scale. */
158
+ function transformParts(ks, t, report) {
159
+ const p = valueAt(ks?.p, t, report) ?? [0, 0];
160
+ const s = valueAt(ks?.s, t, report) ?? [100, 100];
161
+ const r = (valueAt(ks?.r, t, report) ?? valueAt(ks?.rz, t, report) ?? 0) * Math.PI / 180;
162
+ const sk = (valueAt(ks?.sk, t, report) ?? 0) * Math.PI / 180;
163
+ const sa = (valueAt(ks?.sa, t, report) ?? 0) * Math.PI / 180;
164
+ const anchor = valueAt(ks?.a, t, report) ?? [0, 0];
165
+ const rotate = angle => [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0, 0];
166
+ let matrix = mul(translate(+p[0] || 0, +p[1] || 0), rotate(r));
167
+ if (sk) matrix = mul(matrix, mul(rotate(sa), mul([1, 0, -Math.tan(sk), 1, 0, 0], rotate(-sa))));
168
+ matrix = mul(matrix, [(+s[0] || 0) / 100, 0, 0, (+(s[1] ?? s[0]) || 0) / 100, 0, 0]);
169
+ const opacity = valueAt(ks?.o, t, report);
170
+ return { matrix, anchor: [+anchor[0] || 0, +anchor[1] || 0], opacity: opacity == null ? 1 : clamp(opacity / 100, 0, 1) };
171
+ }
172
+
173
+ /** A matrix as Studio's pose: rotation, then a skew of the y axis, then positive scales; a flip is `mirror`. */
174
+ export function studioPose(matrix, previous) {
175
+ const [a, b, c, d, e, f] = matrix;
176
+ const det = a * d - b * c;
177
+ const flip = det < 0 ? -1 : 1;
178
+ const scaleX = Math.hypot(a, b);
179
+ let rotation = scaleX > 1e-9 ? Math.atan2(b, a) * 180 / Math.PI : previous?.rotation ?? 0;
180
+ const scaleY = Math.hypot(c, d);
181
+ let skew = scaleY > 1e-9 ? Math.atan2(-c * flip, d * flip) * 180 / Math.PI - rotation : 0;
182
+ skew = ((skew + 540) % 360) - 180;
183
+ if (previous) {
184
+ while (rotation - previous.rotation > 180) rotation -= 360;
185
+ while (rotation - previous.rotation < -180) rotation += 360;
186
+ }
187
+ const cos = Math.cos(skew * Math.PI / 180);
188
+ return { x: e, y: f, rotation, skew, scaleX, scaleY: Math.abs(cos) > 1e-6 ? det * flip / scaleX / cos : scaleY, mirror: flip < 0 };
189
+ }
190
+
191
+ /** Lottie bezier shapes ({ v, i, o, c }) as Studio contours. */
192
+ function contourPoints(shape, matrix = IDENTITY) {
193
+ const v = shape?.v ?? [];
194
+ return v.map((point, k) => {
195
+ const at = apply(matrix, point);
196
+ const inn = applyVector(matrix, shape.i?.[k] ?? [0, 0]);
197
+ const out = applyVector(matrix, shape.o?.[k] ?? [0, 0]);
198
+ return { x: at[0], y: at[1], handleIn: { x: inn[0], y: inn[1] }, handleOut: { x: out[0], y: out[1] } };
199
+ });
200
+ }
201
+
202
+ const KAPPA = 0.5522847498;
203
+ function ellipseShape([cx, cy], [w, h]) {
204
+ const rx = w / 2, ry = h / 2;
205
+ return { c: true, v: [[cx, cy - ry], [cx + rx, cy], [cx, cy + ry], [cx - rx, cy]],
206
+ i: [[-rx * KAPPA, 0], [0, -ry * KAPPA], [rx * KAPPA, 0], [0, ry * KAPPA]],
207
+ o: [[rx * KAPPA, 0], [0, ry * KAPPA], [-rx * KAPPA, 0], [0, -ry * KAPPA]] };
208
+ }
209
+ function rectShape([cx, cy], [w, h], radius = 0) {
210
+ const x0 = cx - w / 2, y0 = cy - h / 2, x1 = cx + w / 2, y1 = cy + h / 2;
211
+ const r = Math.min(radius, w / 2, h / 2);
212
+ if (r <= 0) return { c: true, v: [[x1, y0], [x1, y1], [x0, y1], [x0, y0]], i: [[0, 0], [0, 0], [0, 0], [0, 0]], o: [[0, 0], [0, 0], [0, 0], [0, 0]] };
213
+ const k = r * KAPPA;
214
+ return { c: true,
215
+ v: [[x1 - r, y0], [x1, y0 + r], [x1, y1 - r], [x1 - r, y1], [x0 + r, y1], [x0, y1 - r], [x0, y0 + r], [x0 + r, y0]],
216
+ i: [[0, 0], [-0, -k], [0, 0], [k, 0], [0, 0], [0, k], [0, 0], [-k, 0]],
217
+ o: [[k, 0], [0, 0], [0, k], [0, 0], [-k, 0], [0, 0], [0, -k], [0, 0]] };
218
+ }
219
+ function starShape(item, t, report) {
220
+ const points = Math.max(3, Math.round(valueAt(item.pt, t, report) ?? 5));
221
+ const [cx, cy] = valueAt(item.p, t, report) ?? [0, 0];
222
+ const rotation = (valueAt(item.r, t, report) ?? 0) * Math.PI / 180;
223
+ const outer = valueAt(item.or, t, report) ?? 10, inner = item.sy === 1 ? (valueAt(item.ir, t, report) ?? 5) : null;
224
+ if (valueAt(item.os, t, report) || valueAt(item.is, t, report)) report?.('Rounded star points (drawn sharp)');
225
+ const v = [];
226
+ const count = inner == null ? points : points * 2;
227
+ for (let k = 0; k < count; k++) {
228
+ const angle = rotation - Math.PI / 2 + k * Math.PI * 2 / count;
229
+ const radius = inner != null && k % 2 ? inner : outer;
230
+ v.push([cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius]);
231
+ }
232
+ return { c: true, v, i: v.map(() => [0, 0]), o: v.map(() => [0, 0]) };
233
+ }
234
+
235
+ const PAINTS = new Set(['fl', 'st', 'gf', 'gs']);
236
+ const GEOMETRY = new Set(['sh', 'rc', 'el', 'sr']);
237
+ const MODIFIERS = { tm: 'Trim paths', rd: 'Rounded corners', mm: 'Merge paths', rp: 'Repeaters', op: 'Offset paths', pb: 'Pucker and bloat', tw: 'Twist', zz: 'Zig zag' };
238
+
239
+ function groupMatrix(tr, t, report) {
240
+ if (!tr) return { matrix: IDENTITY, opacity: 1 };
241
+ const parts = transformParts(tr, t, report);
242
+ return { matrix: mul(parts.matrix, translate(-parts.anchor[0], -parts.anchor[1])), opacity: parts.opacity };
243
+ }
244
+
245
+ /**
246
+ * The draws of a shape layer at time t, bottom first. Each is one paint with the shapes it
247
+ * applies to, in the space of the group holding the paint (`matrix` maps that space into the
248
+ * layer): { paint, item, shapes: [{ kind, shape, rect }], matrix, opacity, path }.
249
+ */
250
+ export function shapeDraws(items, t, report, matrix = IDENTITY, opacity = 1, path = 'g') {
251
+ const list = (items ?? []).filter(item => !item.hd);
252
+ const tr = list.find(item => item.ty === 'tr');
253
+ const own = groupMatrix(tr, t, report);
254
+ const here = mul(matrix, own.matrix);
255
+ const alpha = opacity * own.opacity;
256
+ const draws = [];
257
+ for (let index = list.length - 1; index >= 0; index--) {
258
+ const item = list[index];
259
+ if (item.ty === 'gr') draws.push(...shapeDraws(item.it, t, report, here, alpha, `${path}/${index}`));
260
+ else if (MODIFIERS[item.ty]) report?.(`${MODIFIERS[item.ty]} (left out)`);
261
+ else if (PAINTS.has(item.ty)) {
262
+ // A paint applies to the shapes listed before it, in its group and in groups before it.
263
+ const shapes = [];
264
+ const collect = (entries, relative, base) => {
265
+ const own = entries.find(entry => entry.ty === 'tr');
266
+ const inner = own && relative ? mul(relative, groupMatrix(own, t, report).matrix) : relative;
267
+ entries.forEach((entry, k) => {
268
+ if (entry.hd) return;
269
+ if (entry.ty === 'gr') collect(entry.it ?? [], inner ?? IDENTITY, `${base}/${k}`);
270
+ else if (GEOMETRY.has(entry.ty)) shapes.push({ entry, matrix: inner ?? IDENTITY, key: `${base}/${k}` });
271
+ });
272
+ };
273
+ collect(list.slice(0, index), null, path);
274
+ if (shapes.length) draws.push({ paint: item, shapes, matrix: here, opacity: alpha, key: `${path}/${index}` });
275
+ }
276
+ }
277
+ return draws;
278
+ }
279
+
280
+ function shapeGeometry(entry, t, report) {
281
+ if (entry.ty === 'sh') return valueAt(entry.ks, t, report);
282
+ if (entry.ty === 'rc') return rectShape(valueAt(entry.p, t, report) ?? [0, 0], valueAt(entry.s, t, report) ?? [0, 0], valueAt(entry.r, t, report) ?? 0);
283
+ if (entry.ty === 'el') return ellipseShape(valueAt(entry.p, t, report) ?? [0, 0], valueAt(entry.s, t, report) ?? [0, 0]);
284
+ return starShape(entry, t, report);
285
+ }
286
+
287
+ // ---- Keyframes ---------------------------------------------------------------------------------
288
+
289
+ const TOLERANCE = { x: 0.05, y: 0.05, rotation: 0.05, skew: 0.05, scaleX: 0.0005, scaleY: 0.0005, opacity: 0.002, width: 0.05, height: 0.05 };
290
+
291
+ /**
292
+ * Studio keyframes from per-frame poses (index 0 is `first`). Each numeric field is reduced on
293
+ * its own; keyframes go where any field needs one, linear, held before a jump.
294
+ */
295
+ function poseKeyframes(poses, first, discrete = []) {
296
+ const frames = new Set([0, poses.length - 1]);
297
+ const holds = new Set();
298
+ for (const field of Object.keys(poses[0]).filter(name => typeof poses[0][name] === 'number')) {
299
+ const values = poses.map(pose => [pose[field]]);
300
+ if (values.every(value => Math.abs(value[0] - values[0][0]) <= (TOLERANCE[field] ?? 0.002))) continue;
301
+ for (const key of reduceTrack(values, [TOLERANCE[field] ?? 0.002])) {
302
+ frames.add(key.frame);
303
+ if (key.step && key.frame > 0) { frames.add(key.frame - 1); holds.add(key.frame - 1); }
304
+ }
305
+ }
306
+ for (const field of discrete) {
307
+ for (let k = 1; k < poses.length; k++) {
308
+ if (JSON.stringify(poses[k][field]) !== JSON.stringify(poses[k - 1][field])) { frames.add(k - 1); frames.add(k); holds.add(k - 1); }
309
+ }
310
+ }
311
+ return [...frames].sort((a, b) => a - b).map(k => {
312
+ const key = { frame: first + k };
313
+ for (const [name, value] of Object.entries(poses[k])) key[name] = typeof value === 'number' ? round(value) : value;
314
+ key.tween = holds.has(k) ? 'hold' : 'linear';
315
+ return key;
316
+ });
317
+ }
318
+
319
+ // ---- Import ------------------------------------------------------------------------------------
320
+
321
+ const BLEND = { 1: 3, 2: 4, 3: 13, 4: 6, 5: 5, 8: 14, 10: 7, 16: 8 };
322
+
323
+ /**
324
+ * Reads Lottie JSON text. Returns { json, notes, exact }: Studio project JSON for
325
+ * parseProjectJson, what was left out or approximated, and whether the file was Studio's own.
326
+ */
327
+ // Text metrics as a canvas gives them (width, fontBoundingBoxAscent); an estimate without one.
328
+ const estimate = (font, line) => {
329
+ const size = parseFloat(font.match(/(\d+(?:\.\d+)?)px/)?.[1]) || 12;
330
+ return { width: line.length * size * 0.55, fontBoundingBoxAscent: size * 0.9 };
331
+ };
332
+
333
+ export async function importLottie(text, { measure = estimate, layoutText = null } = {}) {
334
+ const lottie = typeof text === 'string' ? JSON.parse(text) : text;
335
+ if (!isLottie(lottie)) throw new Error('This is not a Lottie animation: it needs w, h, fr, op and layers');
336
+ const notes = new Set();
337
+ const report = note => notes.add(note);
338
+ const studio = lottie.studio;
339
+ if (studio?.format === 'swoof-studio-lottie' && typeof studio.project === 'string') {
340
+ if (studio.hash === lottieHash(lottie)) {
341
+ return { json: await gunzipBase64(studio.project), notes: [], exact: true };
342
+ }
343
+ report('This Lottie was changed after Studio wrote it: it is read from its Lottie content, without Studio\'s events, scripts and sounds');
344
+ }
345
+ colorScale = fileColorScale(lottie);
346
+ const project = convert(lottie, report, measure, layoutText);
347
+ return { json: JSON.stringify(project), notes: [...notes], exact: false };
348
+ }
349
+
350
+ /** The Lottie animation in `text`, or null when it is not one (a Studio project, say). */
351
+ export function readLottieText(text) {
352
+ if (typeof text !== 'string' || !/"layers"\s*:/.test(text)) return null;
353
+ let value;
354
+ try { value = JSON.parse(text); } catch { return null; }
355
+ return value?.format !== 'swoof-studio' && isLottie(value) ? value : null;
356
+ }
357
+
358
+ export function isLottie(value) {
359
+ return value && typeof value === 'object' && Number.isFinite(value.w) && Number.isFinite(value.h) && Number.isFinite(value.fr) &&
360
+ Number.isFinite(value.op) && Array.isArray(value.layers);
361
+ }
362
+
363
+ function convert(lottie, report, measure, layoutText) {
364
+ const fps = clamp(+lottie.fr || 24, 1 / 256, 255);
365
+ // A size outside Studio's stage limits is scaled to fit them, keeping its shape.
366
+ const lw = Math.max(1, +lottie.w), lh = Math.max(1, +lottie.h);
367
+ const fit = Math.min(Math.max(1, 160 / lw, 120 / lh), 2400 / lw, 1600 / lh);
368
+ const width = Math.round(clamp(lw * fit, 160, 2400)), height = Math.round(clamp(lh * fit, 120, 1600));
369
+ if (fit !== 1) report(`A ${Math.round(lw)} × ${Math.round(lh)} animation (scaled to ${width} × ${height})`);
370
+ const stageMatrix = [fit, 0, 0, fit, 0, 0];
371
+ const assetsById = new Map((lottie.assets ?? []).map(asset => [asset.id, asset]));
372
+ const assets = [], symbols = [];
373
+ const imageIds = new Map(), symbolIds = new Map();
374
+ let nextId = 1;
375
+ const newId = prefix => `${prefix}-${nextId++}`;
376
+ if (lottie.ddd) report('3D layers (drawn flat)');
377
+
378
+ function imageAsset(id) {
379
+ if (imageIds.has(id)) return imageIds.get(id);
380
+ const asset = assetsById.get(id);
381
+ let result = null;
382
+ const data = asset && (String(asset.u ?? '') + String(asset.p ?? ''));
383
+ if (asset && /^data:image\/(png|jpeg|gif|webp|svg\+xml);base64,/i.test(String(asset.p))) {
384
+ result = { id: newId('image'), name: asset.nm ?? asset.id, type: String(asset.p).slice(5, String(asset.p).indexOf(';')), kind: 'image', data: asset.p, width: asset.w, height: asset.h };
385
+ assets.push({ id: result.id, name: result.name, type: result.type, kind: 'image', data: result.data });
386
+ } else if (asset) report(`Images linked from outside the file (left out${data ? `: ${String(asset.p).slice(0, 40)}` : ''})`);
387
+ imageIds.set(id, result);
388
+ return result;
389
+ }
390
+
391
+ function compDuration(layers) {
392
+ return Math.max(1, Math.min(MAX_FRAMES, Math.round(Math.max(1, ...layers.map(layer => +layer.op || 0)))));
393
+ }
394
+
395
+ let work = 0;
396
+ const stack = [];
397
+ function symbolFor(refId, layer) {
398
+ // The cycle check comes first: a precomp being converted is already in the cache.
399
+ if (stack.includes(refId)) {
400
+ report('Precomps that contain themselves (left out)');
401
+ return null;
402
+ }
403
+ if (symbolIds.has(refId)) return symbolIds.get(refId);
404
+ const asset = assetsById.get(refId);
405
+ if (!asset?.layers || stack.length >= MAX_DEPTH) {
406
+ report(stack.includes(refId) ? 'Precomps that contain themselves (left out)' : 'Precomps nested too deep (left out)');
407
+ return null;
408
+ }
409
+ stack.push(refId);
410
+ const symbol = { id: newId('symbol'), name: asset.nm ?? String(refId), durationFrames: compDuration(asset.layers), startFrame: 1, loop: false,
411
+ width: Math.round(clamp(+layer.w || +asset.w || 160, 160, 2400)), height: Math.round(clamp(+layer.h || +asset.h || 120, 120, 1600)) };
412
+ symbolIds.set(refId, symbol);
413
+ const timeline = convertLayers(asset.layers, symbol.durationFrames, 0, newId("s"));
414
+ Object.assign(symbol, timeline);
415
+ symbols.push(symbol);
416
+ stack.pop();
417
+ return symbol;
418
+ }
419
+
420
+ // A timeline (scene or symbol) from Lottie layers. `offset`: the Lottie time of frame 1.
421
+ function convertLayers(layers, duration, offset, prefix, root = IDENTITY) {
422
+ const saved = currentDuration;
423
+ currentDuration = () => duration;
424
+ try { return convertTimeline(layers, duration, offset, prefix, root); } finally { currentDuration = saved; }
425
+ }
426
+ function convertTimeline(layers, duration, offset, prefix, root) {
427
+ // Every layer is evaluated at every frame: a file can ask for more work than a tab can do.
428
+ work += layers.length * duration;
429
+ if (work > MAX_WORK) throw new Error('This Lottie animation is too large to import: too many layers over too many frames');
430
+ const elements = [];
431
+ const byInd = new Map(layers.filter(layer => layer.ind != null).map(layer => [layer.ind, layer]));
432
+ const parentMatrix = (layer, t, depth = 0) => {
433
+ const parent = layer.parent != null ? byInd.get(layer.parent) : null;
434
+ if (!parent || depth > MAX_DEPTH) return root;
435
+ const parts = transformParts(parent.ks, t, report);
436
+ return mul(parentMatrix(parent, t, depth + 1), mul(parts.matrix, translate(-parts.anchor[0], -parts.anchor[1])));
437
+ };
438
+ // Masks drawn on a layer itself; `made` are the layer's Studio objects. Returns them.
439
+ const withMasks = (layer, made, first, last, isMatte = false) => {
440
+ // Masks drawn on the layer itself. Studio masks show what is inside one shape: a mask that
441
+ // adds (or intersects, alone) is one. One that cuts a hole is a hole in a solid; elsewhere it
442
+ // is left out, which shows more than intended rather than the opposite.
443
+ const masks = (layer.masksProperties ?? []).filter(mask => mask.mode !== 'n');
444
+ if (masks.length) {
445
+ // The first mask combines with nothing: lighten and difference then add too.
446
+ const showing = masks.filter((mask, k) => (mask.mode === 'a' || (k === 0 && ['f', 'l'].includes(mask.mode)) || (mask.mode === 'i' && masks.length === 1)) && !mask.inv);
447
+ const cutting = masks.filter(mask => (mask.mode === 's' && !mask.inv) || (mask.mode === 'a' && mask.inv && masks.length === 1));
448
+ if (showing.length > 1 || showing.length + cutting.length < masks.length) report('Layer masks that combine, intersect or invert (the first that adds is kept)');
449
+ const solid = layer.ty === 1 && made.length === 1 ? made[0] : null;
450
+ let holesKept = false;
451
+ if (solid && (showing.length || cutting.length)) {
452
+ // A solid seen through masks is the masks' shapes: a path for each that adds, with the
453
+ // ones that subtract as holes. Masks that move make the path change shape.
454
+ const w = solid.width, h = solid.height;
455
+ const corner = (x, y) => ({ x, y, handleIn: { x: 0, y: 0 }, handleOut: { x: 0, y: 0 } });
456
+ const rectangle = shiftContour([corner(0, 0), corner(w, 0), corner(w, h), corner(0, h)], -w / 2, -h / 2);
457
+ const contourAt = (mask, t) => shiftContour(contourPoints(valueAt(mask.pt, t, report) ?? { v: [] }), -w / 2, -h / 2);
458
+ // `outline`: one mask, or (for a matte, which must be one object) a list of them.
459
+ const shapeAt = (outline, t) => {
460
+ const holes = cutting.map(mask => contourAt(mask, t)).filter(points => points.length >= 3);
461
+ const several = Array.isArray(outline) && outline.length > 1;
462
+ // Several adding masks are one nonzero path: adds wind forwards, holes backwards, so
463
+ // overlapping adds stay covered (even-odd would cut their overlap out).
464
+ const wind = (points, forwards) => several && (signedArea(points) >= 0) !== forwards ? reverseContour(points) : points;
465
+ const [main, ...more] = (Array.isArray(outline) ? outline.map(mask => contourAt(mask, t)).filter(points => points.length >= 3) : [outline ? contourAt(outline, t) : rectangle])
466
+ .map(points => wind(points, true));
467
+ const subpaths = [...more, ...holes.map(points => wind(points, false))];
468
+ return { points: main ?? [], ...(subpaths.length ? { subpaths } : {}) };
469
+ };
470
+ const animated = [...showing, ...cutting].some(mask => isKeyframed(mask.pt));
471
+ const outlines = !showing.length ? [null] : isMatte && showing.length > 1 ? [showing] : showing;
472
+ const paths = outlines.map((outline, n) => {
473
+ const label = outlines.length > 1 ? `${solid.name} ${n + 1}` : solid.name;
474
+ const fields = { width: w, height: h, strokeWidth: 0, fill: solid.fill, closed: true, ...(Array.isArray(outline) && outline.length > 1 ? { fillRule: 'nonzero' } : {}) };
475
+ let path;
476
+ if (animated) {
477
+ const poses = track(layer, first, last, offset, parentMatrix, () => ({ matrix: translate(w / 2, h / 2) }), t => shapeAt(outline, t));
478
+ if (poses.some(pose => pose.points.length < 3)) report('Masks that shrink to nothing (drawn at their smallest)');
479
+ for (const pose of poses) if (pose.points.length < 3) pose.points = rectangle.map(point => ({ ...point, x: 0, y: 0 }));
480
+ path = element('path', label, poses, first, last, currentDuration(), fields, ['points', 'subpaths']);
481
+ } else {
482
+ const shape = shapeAt(outline, offset + first - 1);
483
+ if (shape.points.length < 3) return null;
484
+ path = { ...solid, id: newId('path'), name: label, type: 'path', closed: true, ...shape, keyframes: solid.keyframes.map(key => ({ ...key })) };
485
+ if (!shape.subpaths) delete path.subpaths;
486
+ if (Array.isArray(outline) && outline.length > 1) path.fillRule = 'nonzero';
487
+ }
488
+ if (solid.effect) path.effect = solid.effect;
489
+ if (solid.maskId) path.maskId = solid.maskId;
490
+ if (solid.keyframes[0]?.blendMode) path.keyframes[0].blendMode = solid.keyframes[0].blendMode;
491
+ if (solid.keyframes[0]?.filters) for (const key of path.keyframes) key.filters = solid.keyframes[0].filters;
492
+ return path;
493
+ }).filter(Boolean);
494
+ made.splice(0, made.length, ...paths);
495
+ if (paths.length > 1) {
496
+ const groupId = newId('group');
497
+ for (const path of paths) path.groupId = groupId;
498
+ }
499
+ } else if (showing.length && isMatte) {
500
+ report('Masks on layers used as mattes (left out)');
501
+ } else if (showing.length && made.some(element => element.maskId)) {
502
+ report('Layers with both a matte and a mask (the matte is kept)');
503
+ } else if (showing.length) {
504
+ const source = maskElement(layer, showing[0], first, last, offset, parentMatrix, prefix, showing.length === 1 ? cutting : []);
505
+ if (source) {
506
+ elements.push(source);
507
+ for (const element of made) element.maskId = source.id;
508
+ holesKept = showing.length === 1;
509
+ }
510
+ }
511
+ if (cutting.length && !solid && !holesKept) report('Masks that cut holes in shapes and precomps (left out)');
512
+ }
513
+ return made;
514
+ };
515
+ // Bottom layer first, as Studio draws.
516
+ const ordered = layers.map((layer, index) => ({ layer, index })).reverse();
517
+ for (const { layer, index } of ordered) {
518
+ if (layer.hd || layer.td) continue;
519
+ if (layer.ddd) report('3D layers (drawn flat)');
520
+ if (layer.sr && layer.sr !== 1 && layer.ty !== 0) report('Time-stretched layers (at normal speed)');
521
+ const frames = [];
522
+ for (let f = 1; f <= duration; f++) {
523
+ const t = offset + f - 1;
524
+ if (t >= (+layer.ip || 0) && t < (layer.op ?? Infinity)) frames.push(f);
525
+ }
526
+ if (!frames.length) continue;
527
+ const first = frames[0], last = frames.at(-1);
528
+ const made = convertLayer(layer, first, last, offset, parentMatrix, prefix, measure);
529
+ if (!made.length) continue;
530
+ // Mattes: the matte layer right above (or named by `tp`) masks this one.
531
+ // An inverted matte shows what is outside it, which a Studio mask cannot: it is left out,
532
+ // showing more rather than the opposite. A luma matte is drawn as an alpha matte.
533
+ if (layer.tt === 2 || layer.tt === 4) report('Inverted mattes (left out)');
534
+ else if (layer.tt) {
535
+ const matteLayer = layer.tp != null ? byInd.get(layer.tp) : layers[index - 1];
536
+ if (layer.tt === 3) report('Luma mattes (drawn as alpha mattes)');
537
+ if (matteLayer) {
538
+ const matte = withMasks(matteLayer, convertLayer({ ...matteLayer, td: 0, tt: 0 }, first, last, offset, parentMatrix, prefix, measure, true), first, last, true);
539
+ if (matte.length > 1) report('Mattes made of several shapes (the first one masks)');
540
+ if (matte[0]) {
541
+ elements.push(matte[0]);
542
+ for (const element of made) element.maskId = matte[0].id;
543
+ }
544
+ }
545
+ }
546
+ withMasks(layer, made, first, last);
547
+ elements.push(...made);
548
+ }
549
+ return { layers: [{ id: `${prefix}-layer`, name: 'Layer 1', visible: true, locked: false, order: 0 }],
550
+ elements: elements.map(element => ({ ...element, layerId: `${prefix}-layer` })) };
551
+ }
552
+
553
+ function layerMatrix(layer, t, parentMatrix) {
554
+ const parts = transformParts(layer.ks, t, report);
555
+ return { matrix: mul(parentMatrix(layer, t), mul(parts.matrix, translate(-parts.anchor[0], -parts.anchor[1]))), opacity: parts.opacity };
556
+ }
557
+
558
+ // Per-frame poses of an object whose own space maps into the layer by `inner(t)`.
559
+ function track(layer, first, last, offset, parentMatrix, inner, extra = () => ({})) {
560
+ const poses = [];
561
+ let previous = null;
562
+ for (let f = first; f <= last; f++) {
563
+ const t = offset + f - 1;
564
+ const { matrix, opacity } = layerMatrix(layer, t, parentMatrix);
565
+ const placed = inner(t);
566
+ const pose = studioPose(mul(matrix, placed.matrix ?? IDENTITY), previous);
567
+ // Degenerate matrices (a scale of 0) and wild values keep the last sound value.
568
+ for (const [key, fallback] of Object.entries(POSE_DEFAULTS)) pose[key] = finite(pose[key], previous?.[key] ?? fallback);
569
+ pose.x = clamp(pose.x, -100000, 100000);
570
+ pose.y = clamp(pose.y, -100000, 100000);
571
+ previous = pose;
572
+ const flip = pose.mirror;
573
+ delete pose.mirror;
574
+ poses.push({ ...pose, scaleX: clamp(pose.scaleX, 0.01, 100), scaleY: clamp(pose.scaleY, 0.01, 100), skew: clamp(pose.skew, -85, 85),
575
+ opacity: clamp(finite(opacity * (placed.opacity ?? 1), 1), 0, 1), ...(flip ? { mirror: true } : { mirror: false }), ...extra(t) });
576
+ }
577
+ return poses;
578
+ }
579
+
580
+ function element(type, name, poses, first, last, duration, fields = {}, discrete = []) {
581
+ const keys = poseKeyframes(poses, first, ['mirror', ...discrete]).map(key => {
582
+ if (!key.mirror) delete key.mirror;
583
+ return key;
584
+ });
585
+ const base = { ...keys[0] };
586
+ delete base.frame; delete base.tween;
587
+ const result = { id: newId(type), name, type, ...base, ...fields, keyframes: keys };
588
+ if (first > 1) result.keyframes.unshift({ ...keys[0], frame: 1, blank: true, tween: 'hold' });
589
+ if (last < duration) result.keyframes.push({ ...keys.at(-1), frame: last + 1, blank: true, tween: 'hold' });
590
+ if (result.keyframes.length === 1 && !result.keyframes[0].blank) result.keyframes[0].tween = 'linear';
591
+ return result;
592
+ }
593
+
594
+ function layerEffects(layer) {
595
+ const fields = {};
596
+ for (const effect of layer.ef ?? []) {
597
+ if (effect.en === 0) continue;
598
+ const value = name => valueAt(effect.ef?.find(item => item.nm === name || item.mn?.endsWith(name))?.v, 0, report);
599
+ if (effect.ty === 21) {
600
+ // Fill: the layer's paint in one colour.
601
+ fields.fillColor = hex(value('Color') ?? [0, 0, 0]);
602
+ if ((+value('Opacity') ?? 1) < 1) report('Fill effects that are partly transparent (opaque)');
603
+ continue;
604
+ }
605
+ if (effect.ty === 29 && !fields.effect) {
606
+ const sigma = (+value('Blurriness') || 0) * 0.3;
607
+ const blur = clamp(Math.sqrt(12 * sigma * sigma + 1), 0, 255);
608
+ fields.effect = { type: 'blur', blurX: round(blur), blurY: round(blur) };
609
+ } else if (effect.ty === 25 && !fields.effect) {
610
+ const sigma = (+value('Softness') || 0) / 4;
611
+ const blur = clamp(Math.sqrt(12 * sigma * sigma + 1), 0, 255);
612
+ // A shadow that does not move is a glow.
613
+ if (!(+value('Distance'))) {
614
+ fields.effect = { type: 'glow', color: hex(value('Shadow Color') ?? [0, 0, 0]), alpha: round(clamp((+value('Opacity') || 0) / 255, 0, 1)), blurX: round(blur), blurY: round(blur) };
615
+ continue;
616
+ }
617
+ fields.effect = { type: 'shadow', color: hex(value('Shadow Color') ?? [0, 0, 0]), alpha: round(clamp((+value('Opacity') || 0) / 255, 0, 1)),
618
+ angle: round(((+value('Direction') || 0) - 90 + 360) % 360), distance: round(clamp(+value('Distance') || 0, 0, 255)), blurX: round(blur), blurY: round(blur) };
619
+ } else if (fields.effect) report('Layers with several effects (the first is kept)');
620
+ else report(`The ${effect.nm ?? `type ${effect.ty}`} effect (left out)`);
621
+ }
622
+ if (fields.effect && fields.effect.angle > 360) fields.effect.angle -= 360;
623
+ return fields;
624
+ }
625
+
626
+ function withLayerFields(made, layer) {
627
+ const effects = layerEffects(layer);
628
+ const blend = layer.bm ? BLEND[layer.bm] : 0;
629
+ if (layer.bm && !blend) report('Blend modes Studio does not have (normal)');
630
+ for (const item of made) {
631
+ if (effects.fillColor) {
632
+ if (item.type === 'symbol' || item.type === 'bitmap') report('Fill effects on precomps and images (left out)');
633
+ for (const target of [item, ...item.keyframes]) {
634
+ for (const key of ['fill', 'stroke', 'textColor']) if (target[key] !== undefined) target[key] = effects.fillColor;
635
+ if (target.gradient) delete target.gradient;
636
+ }
637
+ }
638
+ // Shapes carry Studio's editable effect; other objects a placement filter on each keyframe.
639
+ if (effects.effect && item.type !== 'symbol' && item.type !== 'bitmap' && item.type !== 'text') item.effect = effects.effect;
640
+ else if (effects.effect) {
641
+ const filters = placementFilters({ effect: effects.effect });
642
+ for (const key of item.keyframes) key.filters = filters;
643
+ }
644
+ if (blend) item.keyframes[0].blendMode = blend;
645
+ }
646
+ return made;
647
+ }
648
+
649
+ function convertLayer(layer, first, last, offset, parentMatrix, prefix, measure, matte = false) {
650
+ const name = String(layer.nm ?? `Layer ${layer.ind ?? ''}`).slice(0, 120);
651
+ const timelineEnd = currentDuration;
652
+ if (layer.ty === 0) {
653
+ const symbol = symbolFor(layer.refId, layer);
654
+ if (!symbol) return [];
655
+ const poses = track(layer, first, last, offset, parentMatrix, () => ({ matrix: translate(symbol.width / 2, symbol.height / 2) }));
656
+ const fields = { symbolId: symbol.id, width: symbol.width, height: symbol.height };
657
+ // The precomp's own frame for each frame of this layer.
658
+ const child = [];
659
+ for (let f = first; f <= last; f++) {
660
+ const t = offset + f - 1;
661
+ const time = layer.tm ? (valueAt(layer.tm, t, report) ?? 0) * fps : (t - (+layer.st || 0)) / (+layer.sr || 1);
662
+ child.push(Math.round(time) + 1);
663
+ }
664
+ const start = clamp(child[0], 1, symbol.durationFrames);
665
+ if (child.every(value => value === child[0])) Object.assign(fields, { symbolMode: 'single', firstFrame: start });
666
+ else {
667
+ // Played once: straight on, then held on the last frame.
668
+ const plays = child.every((value, k) => value === child[0] + k || (value === symbol.durationFrames && child[k - 1] === value));
669
+ // A loop returns to the frame it started from when it reaches the end.
670
+ const loops = !plays && child.every((value, k) => !k || value === child[k - 1] + 1 || (value === child[0] && child[k - 1] === symbol.durationFrames));
671
+ if (loops) Object.assign(fields, { symbolMode: 'loop', firstFrame: start });
672
+ else if (!plays) {
673
+ // Any other time remapping: one placement per run that plays on or holds a frame. Each
674
+ // starts after a blank keyframe, so it starts from its own first frame.
675
+ const runs = [];
676
+ child.forEach((value, k) => {
677
+ const run = runs.at(-1);
678
+ const frame = clamp(value, 1, symbol.durationFrames);
679
+ if (run && ((run.kind !== 'hold' && frame === run.last + 1) || (run.kind !== 'play' && frame === run.last))) {
680
+ run.kind ??= frame === run.last ? 'hold' : 'play';
681
+ run.last = frame;
682
+ run.end = k;
683
+ } else runs.push({ start: k, end: k, first: frame, last: frame, kind: null });
684
+ });
685
+ if (runs.length <= 60) {
686
+ return withLayerFields(runs.map((run, n) => element('symbol', runs.length > 1 ? `${name} ${n + 1}` : name, poses.slice(run.start, run.end + 1),
687
+ first + run.start, first + run.end, timelineEnd(),
688
+ { ...fields, symbolMode: run.kind === 'play' ? 'once' : 'single', firstFrame: run.first })), layer);
689
+ }
690
+ report('Time remapping with many jumps (played straight through)');
691
+ if (start > 1) fields.firstFrame = start;
692
+ fields.symbolMode = 'once';
693
+ } else {
694
+ if (start > 1) fields.firstFrame = start;
695
+ fields.symbolMode = 'once';
696
+ }
697
+ }
698
+ return withLayerFields([element('symbol', name, poses, first, last, timelineEnd(), fields)], layer);
699
+ }
700
+ if (layer.ty === 2) {
701
+ const image = imageAsset(layer.refId);
702
+ if (!image) return [];
703
+ const w = +image.width || 1, h = +image.height || 1;
704
+ const poses = track(layer, first, last, offset, parentMatrix, () => ({ matrix: translate(w / 2, h / 2) }));
705
+ return withLayerFields([element('bitmap', name, poses, first, last, timelineEnd(), { assetId: image.id, width: w, height: h })], layer);
706
+ }
707
+ if (layer.ty === 1) {
708
+ const w = +layer.sw || 1, h = +layer.sh || 1;
709
+ const poses = track(layer, first, last, offset, parentMatrix, () => ({ matrix: translate(w / 2, h / 2) }));
710
+ return withLayerFields([element('rectangle', name, poses, first, last, timelineEnd(), { width: w, height: h, fill: solidColor(layer.sc), strokeWidth: 0 })], layer);
711
+ }
712
+ if (layer.ty === 5) return withLayerFields(textElement(layer, name, first, last, offset, parentMatrix, measure), layer);
713
+ if (layer.ty === 4) return withLayerFields(shapeElements(layer, name, first, last, offset, parentMatrix, matte), layer);
714
+ if (layer.ty !== 3) report(`Layers of type ${layer.ty} (left out)`);
715
+ return [];
716
+ }
717
+
718
+ let currentDuration = () => MAX_FRAMES;
719
+
720
+ function textElement(layer, name, first, last, offset, parentMatrix, measure) {
721
+ const docs = layer.t?.d?.k ?? [];
722
+ if (layer.t?.a?.length) report('Text animators (left out)');
723
+ const docAt = t => {
724
+ let doc = docs[0]?.s ?? {};
725
+ for (const key of docs) if ((key.t ?? 0) <= t) doc = key.s ?? doc;
726
+ return doc;
727
+ };
728
+ const fontOf = doc => (lottie.fonts?.list ?? []).find(font => font.fName === doc.f);
729
+ const firstDoc = docAt(offset + first - 1);
730
+ const size = +firstDoc.s || 12;
731
+ const fontSize = clamp(size, 6, 240);
732
+ const scale = size / fontSize;
733
+ const lines = String(firstDoc.t ?? '').split(/\r\n|\r|\n|\u0003/);
734
+ const font = fontOf(firstDoc);
735
+ const family = font?.fFamily ?? String(firstDoc.f ?? 'Arial').split('-')[0];
736
+ const bold = /bold|black|heavy|[6-9]00/i.test(`${font?.fStyle ?? ''} ${font?.fWeight ?? ''}`);
737
+ const lineHeight = +firstDoc.lh || size * 1.2;
738
+ const css = `${bold ? 'bold ' : ''}${fontSize}px ${family}`;
739
+ const widest = Math.max(1, ...lines.map(line => measure(css, line).width));
740
+ const boxWidth = Math.ceil(widest + 12), boxHeight = Math.ceil(lineHeight / scale * lines.length + 8);
741
+ const align = { 0: 'left', 1: 'right', 2: 'center' }[firstDoc.j] ?? 'left';
742
+ // swooflib's first baseline: the text's top (2 px in) plus the font's ascent.
743
+ const ascent = measure(css, 'Hg').fontBoundingBoxAscent ?? fontSize * 0.9;
744
+ // Studio lays text from its box's top left (2 px in); Lottie from the first line's baseline.
745
+ let ox = align === 'left' ? -boxWidth / 2 + 2 : align === 'right' ? boxWidth / 2 - 2 : 0;
746
+ let oy = -boxHeight / 2 + 2 + ascent;
747
+ // With Studio's renderer at hand, its own layout says where the first line lands.
748
+ const placed = layoutText?.({ text: lines.join('\n'), fontFamily: family, fontSize, bold, textAlign: align, width: boxWidth, height: boxHeight, textColor: '#000000' });
749
+ if (placed) { ox = placed.x; oy = placed.baseline; }
750
+ const poses = track(layer, first, last, offset, parentMatrix, () => ({ matrix: mul([scale, 0, 0, scale, 0, 0], translate(-ox, -oy)) }), t => {
751
+ const doc = docAt(t);
752
+ return { text: String(doc.t ?? '').split(/\r\n|\r|\u0003/).join('\n'), textColor: hex(doc.fc ?? [0, 0, 0]) };
753
+ });
754
+ if (firstDoc.sz) report('Text in boxes (laid out on its own lines)');
755
+ if (firstDoc.tr) report('Text tracking (left out)');
756
+ return [element('text', name, poses, first, last, currentDuration(), { width: boxWidth, height: boxHeight, fontSize: round(fontSize), fontFamily: family,
757
+ bold, textAlign: align, strokeWidth: 0 }, ['text', 'textColor'])];
758
+ }
759
+
760
+ // The signed area of a contour's corners (positive: clockwise on screen), and the contour backwards.
761
+ function signedArea(points) {
762
+ return points.reduce((sum, p, k) => { const q = points[(k + 1) % points.length]; return sum + p.x * q.y - q.x * p.y; }, 0) / 2;
763
+ }
764
+ function reverseContour(points) {
765
+ return [...points].reverse().map(p => ({ ...p, handleIn: p.handleOut, handleOut: p.handleIn }));
766
+ }
767
+
768
+ function maskElement(layer, mask, first, last, offset, parentMatrix, prefix, holes = []) {
769
+ const shapeAt = t => valueAt(mask.pt, t, report);
770
+ const shape = shapeAt(offset + first - 1);
771
+ if (!shape?.v?.length) return null;
772
+ const points = contourPoints(shape);
773
+ const box = bounds(points);
774
+ const cx = (box[0] + box[2]) / 2, cy = (box[1] + box[3]) / 2;
775
+ const poses = track(layer, first, last, offset, parentMatrix, () => ({ matrix: translate(cx, cy) }));
776
+ if ([mask, ...holes].some(item => isKeyframed(item.pt))) report('Animated masks (their first shape)');
777
+ // Masks that subtract are holes in it (Studio masks clip even-odd, as compound paths fill).
778
+ const subpaths = holes.map(hole => contourPoints(valueAt(hole.pt, offset + first - 1, report) ?? { v: [] })).filter(contour => contour.length >= 3)
779
+ .map(contour => contour.map(p => shiftPoint(p, -cx, -cy)));
780
+ return element('path', `${layer.nm ?? 'layer'} mask`, poses, first, last, currentDuration(), {
781
+ points: points.map(p => shiftPoint(p, -cx, -cy)), ...(subpaths.length ? { subpaths } : {}), closed: true, fill: '#000000', strokeWidth: 0,
782
+ width: clamp(round(box[2] - box[0]), 1, 10000), height: clamp(round(box[3] - box[1]), 1, 10000) });
783
+ }
784
+
785
+ function shapeElements(layer, name, first, last, offset, parentMatrix, matte) {
786
+ const t0 = offset + first - 1;
787
+ // A stroke right above a fill of the same outline is one Studio object with both.
788
+ const geometryOf = draw => JSON.stringify([draw.matrix, draw.opacity, draw.shapes.map(({ entry, matrix }) => [shapeGeometry(entry, t0, () => {}), matrix])]);
789
+ const draws = [];
790
+ for (const draw of shapeDraws(layer.shapes, t0, report)) {
791
+ const previous = draws.at(-1);
792
+ if (previous && !previous.outline && (previous.paint.ty === 'fl' || previous.paint.ty === 'gf') && draw.paint.ty === 'st' && !matte &&
793
+ geometryOf(previous) === geometryOf(draw)) {
794
+ previous.outline = draw;
795
+ continue;
796
+ }
797
+ draws.push({ ...draw });
798
+ }
799
+ // The layer's shape tree at a time, evaluated once for all its paints.
800
+ const evaluated = new Map();
801
+ const drawsAt = t => {
802
+ if (!evaluated.has(t)) evaluated.set(t, new Map(shapeDraws(layer.shapes, t, () => {}).map(item => [item.key, item])));
803
+ return evaluated.get(t);
804
+ };
805
+ const made = [];
806
+ draws.forEach((draw, n) => {
807
+ const paint = draw.paint;
808
+ if (matte && paint.ty !== 'fl' && paint.ty !== 'gf') return;
809
+ const drawAt = t => drawsAt(t).get(draw.key) ?? draw;
810
+ const label = draws.length > 1 ? `${name} ${n + 1}` : name;
811
+ const stroke = paint.ty === 'st' || paint.ty === 'gs';
812
+ // Paint values; animated colours and opacity are sampled with the pose.
813
+ const paintAt = t => {
814
+ const item = drawAt(t).paint;
815
+ const opacity = clamp((valueAt(item.o, t, report) ?? 100) / 100, 0, 1);
816
+ if (item.ty === 'fl' || item.ty === 'st') return { color: hex(valueAt(item.c, t, report) ?? [0, 0, 0]), opacity };
817
+ return { color: gradientColors(item, t).first, opacity };
818
+ };
819
+ if (paint.ty === 'gs') report('Gradient strokes (in their first colour)');
820
+ // Line ends, corners and dashes of the stroke (Lottie: 1 butt, 2 round, 3 square; 1 miter,
821
+ // 2 round, 3 bevel), as the element's; animated dashes keep their first lengths.
822
+ const lineStyle = result => {
823
+ const line = stroke ? paint : draw.outline;
824
+ if (!line) return;
825
+ const cap = { 1: 'butt', 3: 'square' }[line.lc ?? 2], join = { 1: 'miter', 3: 'bevel' }[line.lj ?? 2];
826
+ if (cap) result.lineCap = cap;
827
+ if (join) result.lineJoin = join;
828
+ if (join === 'miter') result.miterLimit = round(clamp(+(line.ml ?? 4) || 4, 1, 255));
829
+ const dashes = (line.d ?? []).filter(item => item.n === 'd' || item.n === 'g');
830
+ const lengths = dashes.map(item => +(valueAt(item.v, t0, report) ?? 0) * lineScale);
831
+ if (dashes.some(item => isKeyframed(item.v))) report('Animated dashes (their first lengths)');
832
+ if (lengths.length && lengths.length <= 64 && lengths.every(value => Number.isFinite(value) && value >= 0) && lengths.some(value => value > 0)) {
833
+ result.strokeDash = lengths.map(value => round(clamp(value, 0, 10000)));
834
+ const offset = line.d.find(item => item.n === 'o');
835
+ const shift = +(valueAt(offset?.v, t0, report) ?? 0) * lineScale;
836
+ if (shift) result.strokeDashOffset = round(clamp(shift, -100000, 100000));
837
+ }
838
+ };
839
+ const single = draw.shapes.length === 1 && (draw.shapes[0].entry.ty === 'rc' || draw.shapes[0].entry.ty === 'el') ? draw.shapes[0] : null;
840
+ const animatedShape = draw.shapes.some(({ entry }) => entry.ty === 'sh' ? isKeyframed(entry.ks) : ['p', 's', 'r', 'pt', 'or', 'ir'].some(k => isKeyframed(entry[k]))) ||
841
+ draw.shapes.some(({ matrix }) => matrix !== IDENTITY);
842
+ const base = { strokeWidth: 0 };
843
+ // A group transform Studio's pose cannot hold (Lottie gradients are often drawn as a
844
+ // 1638.4-unit square scaled to fit) is baked into the points, when it does not change.
845
+ const fits = m => [Math.hypot(m[0], m[1]), Math.hypot(m[2], m[3])].every(scale => scale >= 0.05 && scale <= 20);
846
+ const samples = Array.from({ length: Math.min(20, last - first + 1) }, (_, k) => offset + first - 1 + Math.round(k * (last - first) / Math.max(1, Math.min(19, last - first))));
847
+ const staticGroup = samples.every(t => drawAt(t).matrix.every((value, k) => Math.abs(value - draw.matrix[k]) < 1e-6));
848
+ const bake = staticGroup && !fits(draw.matrix) ? draw.matrix : null;
849
+ const lineScale = bake ? Math.sqrt(Math.abs(bake[0] * bake[3] - bake[1] * bake[2])) : 1;
850
+ const outlineAt = t => drawsAt(t).get(draw.outline.key)?.paint ?? draw.outline.paint;
851
+ const paintFields = t => {
852
+ const { color, opacity } = paintAt(t);
853
+ const width = stroke ? +(valueAt(drawAt(t).paint.w, t, report) ?? 1) * lineScale : 0;
854
+ if (stroke) return { stroke: color, strokeWidth: round(clamp(width, 0, 3276.75)), paintOpacity: opacity };
855
+ const fields = { fill: matte ? '#000000' : color, paintOpacity: matte ? 1 : opacity };
856
+ if (draw.outline) {
857
+ const line = outlineAt(t);
858
+ fields.stroke = hex(valueAt(line.c, t, report) ?? [0, 0, 0]);
859
+ fields.strokeWidth = round(clamp(+(valueAt(line.w, t, report) ?? 1) * lineScale, 0, 3276.75));
860
+ if ((valueAt(line.o, t, report) ?? 100) < 100) report('Stroke opacity (drawn opaque)');
861
+ }
862
+ return fields;
863
+ };
864
+ if (!stroke && single && !bake && fits(mul(draw.matrix, single.matrix)) && !isKeyframed(single.entry.p) && !isKeyframed(single.entry.r)) {
865
+ // Rectangles and ellipses stay rectangles and ellipses; their size can animate.
866
+ const entry = single.entry;
867
+ const position = valueAt(entry.p, t0, report) ?? [0, 0];
868
+ const radius = entry.ty === 'rc' ? +(valueAt(entry.r, t0, report) ?? 0) : 0;
869
+ const type = entry.ty === 'el' ? 'ellipse' : radius > 0 ? 'roundedRectangle' : 'rectangle';
870
+ const poses = track(layer, first, last, offset, parentMatrix, t => ({ matrix: mul(drawAt(t).matrix, mul(single.matrix, translate(position[0], position[1]))), opacity: drawAt(t).opacity }), t => {
871
+ const size = valueAt(drawAt(t).shapes[0]?.entry.s ?? entry.s, t, report) ?? [1, 1];
872
+ const fields = paintFields(t);
873
+ return { width: clamp(+size[0] || 1, 1, 10000), height: clamp(+size[1] || 1, 1, 10000), ...fields };
874
+ });
875
+ for (const pose of poses) { pose.opacity = round(clamp(pose.opacity * pose.paintOpacity, 0, 1)); delete pose.paintOpacity; }
876
+ const fields = { ...base, ...(stroke ? { fill: '#000000' } : {}), ...(radius > 0 ? { cornerRadius: round(radius) } : {}) };
877
+ const result = element(type, label, poses, first, last, currentDuration(), fields, ['fill', 'stroke']);
878
+ if (paint.ty === 'gf') result.gradient = studioGradient(paint, t0, [result.width, result.height], [position[0], position[1]], single.matrix);
879
+ lineStyle(result);
880
+ made.push(result);
881
+ return;
882
+ }
883
+ // Paths: contours in the paint's group space, centred on their bounds.
884
+ const contoursAt = t => drawAt(t).shapes.map(({ entry, matrix }) => contourPoints(shapeGeometry(entry, t, report), bake ? mul(bake, matrix) : matrix)
885
+ ).map((points, k) => ({ points, closed: !!(shapeGeometry(drawAt(t).shapes[k].entry, t, report)?.c ?? true) || draw.shapes[k].entry.ty !== 'sh' }));
886
+ const contours = contoursAt(t0).filter(contour => contour.points.length > 1);
887
+ if (!contours.length) return;
888
+ const box = bounds(contours.flatMap(contour => contour.points));
889
+ const cx = (box[0] + box[2]) / 2, cy = (box[1] + box[3]) / 2;
890
+ const groups = stroke ? contours.map(contour => [contour]) : groupContours(contours, paint.r === 2);
891
+ if (animatedShape) report('Shapes that change shape (frame by frame)');
892
+ groups.forEach((group, g) => {
893
+ const poses = track(layer, first, last, offset, parentMatrix, t => ({ matrix: mul(bake ? IDENTITY : drawAt(t).matrix, translate(cx, cy)), opacity: drawAt(t).opacity }), t => {
894
+ const fields = paintFields(t);
895
+ if (animatedShape) {
896
+ const now = contoursAt(t);
897
+ const pick = group.map(contour => now[contours.indexOf(contour)] ?? contour);
898
+ fields.points = shiftContour(stroke && pick[0].closed ? closeOpen(pick[0].points) : pick[0].points, -cx, -cy);
899
+ if (pick.length > 1) fields.subpaths = pick.slice(1).map(contour => shiftContour(contour.points, -cx, -cy));
900
+ }
901
+ return fields;
902
+ });
903
+ for (const pose of poses) { pose.opacity = round(clamp(pose.opacity * pose.paintOpacity, 0, 1)); delete pose.paintOpacity; }
904
+ const outline = group[0];
905
+ const points = shiftContour(stroke && outline.closed ? closeOpen(outline.points) : outline.points, -cx, -cy);
906
+ // Lottie fills close open outlines.
907
+ const closed = !stroke;
908
+ const fields = { ...base, points, closed, width: clamp(round(box[2] - box[0]), 1, 10000), height: clamp(round(box[3] - box[1]), 1, 10000), ...(stroke ? { fill: '#000000' } : {}) };
909
+ if (closed && group.length > 1) fields.subpaths = group.slice(1).map(contour => shiftContour(contour.points, -cx, -cy));
910
+ const result = element('path', groups.length > 1 ? `${label}.${g + 1}` : label, poses, first, last, currentDuration(), fields,
911
+ ['fill', 'stroke', ...(animatedShape ? ['points', 'subpaths'] : [])]);
912
+ if (!animatedShape) for (const key of result.keyframes) { delete key.points; delete key.subpaths; }
913
+ if (!stroke && paint.ty === 'gf') result.gradient = studioGradient(paint, t0, [result.width, result.height], [cx, cy], bake ?? IDENTITY);
914
+ // Lottie fills nonzero unless the fill says even-odd; Studio's compound paths are even-odd.
915
+ if (closed && group.length > 1 && paint.r !== 2) result.fillRule = 'nonzero';
916
+ lineStyle(result);
917
+ made.push(result);
918
+ });
919
+ });
920
+ if (made.length > 1 && !matte) {
921
+ const groupId = newId('group');
922
+ for (const item of made) item.groupId = groupId;
923
+ }
924
+ return made;
925
+ }
926
+
927
+ function gradientColors(item, t) {
928
+ const count = +item.g?.p || 2;
929
+ const values = valueAt(item.g?.k, t, report) ?? [];
930
+ const stops = [];
931
+ for (let k = 0; k < count; k++) stops.push({ ratio: clamp(+values[4 * k] || 0, 0, 1), color: hex([values[4 * k + 1], values[4 * k + 2], values[4 * k + 3]]) });
932
+ const alphas = [];
933
+ for (let k = 4 * count; k + 1 < values.length; k += 2) alphas.push([+values[k], +values[k + 1]]);
934
+ const alphaAt = ratio => {
935
+ if (!alphas.length) return 1;
936
+ if (ratio <= alphas[0][0]) return alphas[0][1];
937
+ for (let k = 1; k < alphas.length; k++) {
938
+ if (ratio <= alphas[k][0]) {
939
+ const [r0, a0] = alphas[k - 1], [r1, a1] = alphas[k];
940
+ return r1 > r0 ? a0 + (a1 - a0) * (ratio - r0) / (r1 - r0) : a1;
941
+ }
942
+ }
943
+ return alphas.at(-1)[1];
944
+ };
945
+ for (const stop of stops) stop.alpha = round(clamp(alphaAt(stop.ratio), 0, 1));
946
+ return { stops, first: stops[0]?.color ?? '#000000', last: stops.at(-1)?.color ?? '#ffffff' };
947
+ }
948
+
949
+ // A Lottie gradient as Studio's: Flash's gradient square (±819.2) placed by a matrix relative
950
+ // to the object's box. `center`: the box centre in the paint's space; `matrix`: shape to paint space.
951
+ function studioGradient(item, t, [w, h], center, matrix) {
952
+ if (isKeyframed(item.s) || isKeyframed(item.e) || isKeyframed(item.g?.k)) report('Animated gradients (their first frame)');
953
+ const { stops, first, last } = gradientColors(item, t);
954
+ // Built in the paint's own space, then mapped whole: a scaled group makes a radial gradient elliptical.
955
+ const s = valueAt(item.s, t, report) ?? [0, 0], e = valueAt(item.e, t, report) ?? [100, 0];
956
+ const dx = e[0] - s[0], dy = e[1] - s[1];
957
+ const length = Math.hypot(dx, dy) || 1;
958
+ const angle = Math.atan2(dy, dx);
959
+ let g;
960
+ const gradient = { type: item.t === 2 ? 'radial' : 'linear', endColor: last, stops };
961
+ if (item.t === 2) {
962
+ const highlight = clamp((+valueAt(item.h, t, report) || 0) / 100, -0.99, 0.99);
963
+ const turn = angle + (+valueAt(item.a, t, report) || 0) * Math.PI / 180;
964
+ const k = length / 819.2;
965
+ g = [Math.cos(turn) * k, Math.sin(turn) * k, -Math.sin(turn) * k, Math.cos(turn) * k, s[0], s[1]];
966
+ gradient.focus = round(highlight);
967
+ } else {
968
+ const k = length / 1638.4;
969
+ g = [Math.cos(angle) * k, Math.sin(angle) * k, -Math.sin(angle) * k, Math.cos(angle) * k, (s[0] + e[0]) / 2, (s[1] + e[1]) / 2];
970
+ gradient.angle = round(angle * 180 / Math.PI);
971
+ }
972
+ g = mul(translate(-center[0], -center[1]), mul(matrix, g));
973
+ gradient.matrix = { a: round(g[0] * 819.2 / w), b: round(g[1] * 819.2 / h), c: round(g[2] * 819.2 / w), d: round(g[3] * 819.2 / h), tx: round(g[4] / w), ty: round(g[5] / h) };
974
+ if (gradient.type === 'linear' && gradient.angle == null) gradient.angle = 0;
975
+ void first;
976
+ return gradient;
977
+ }
978
+
979
+ // ---- The movie ----
980
+
981
+ let background = '#ffffff';
982
+ let main = lottie.layers;
983
+ const bottom = main.at(-1);
984
+ if (bottom?.ty === 1 && Math.abs((+bottom.sw || 0) - lottie.w) < 1 && Math.abs((+bottom.sh || 0) - lottie.h) < 1 && !bottom.parent && !isKeyframed(bottom.ks?.p)
985
+ && (valueAt(bottom.ks?.o, 0) ?? 100) >= 100 && (+bottom.ip || 0) <= (+lottie.ip || 0) && bottom.op >= lottie.op && /^#[0-9a-f]{6}/i.test(bottom.sc ?? '')) {
986
+ background = bottom.sc.slice(0, 7).toLowerCase();
987
+ main = main.slice(0, -1);
988
+ }
989
+ const ip = +lottie.ip || 0;
990
+ const scenes = [];
991
+ // Studio's own files place each scene's precomp on the main timeline.
992
+ const scenePrecomps = main.filter(layer => !layer.td && !(layer.nm ?? '').endsWith('(transition)'));
993
+ if (scenePrecomps.length && scenePrecomps.every(layer => layer.ty === 0 && String(layer.refId).startsWith('scene_'))) {
994
+ const segments = [...scenePrecomps].sort((a, b) => a.ip - b.ip);
995
+ const sceneOf = new Map();
996
+ for (const { refId } of segments) {
997
+ const asset = assetsById.get(refId);
998
+ if (sceneOf.has(refId) || !asset?.layers) continue;
999
+ const duration = compDuration(asset.layers);
1000
+ const scene = { id: newId('scene'), name: asset.nm ?? refId, durationFrames: duration, startFrame: 1, loop: false, ...convertLayers(asset.layers, duration, 0, `c${scenes.length}`) };
1001
+ sceneOf.set(refId, scene);
1002
+ scenes.push(scene);
1003
+ }
1004
+ const sceneDurations = new Map(scenes.map(scene => [scene, scene.durationFrames]));
1005
+ sceneFlow(segments.filter(layer => sceneOf.has(layer.refId)), sceneOf, main, sceneDurations);
1006
+ }
1007
+ if (!scenes.length) {
1008
+ const duration = Math.max(1, Math.min(MAX_FRAMES, Math.round(lottie.op - ip)));
1009
+ scenes.push({ id: newId('scene'), name: lottie.nm ? String(lottie.nm).slice(0, 120) : 'Scene 1', durationFrames: duration, startFrame: 1, loop: true,
1010
+ ...convertLayers(main, duration, ip, 'c0', stageMatrix) });
1011
+ }
1012
+ // How Studio's scenes follow each other: each segment of the main timeline is a scene playing.
1013
+ // Where one hands over to the next, the scene gets a jump on its last frame shown, and the
1014
+ // incoming scene the transition drawn over it. Lottie players loop the whole file.
1015
+ function sceneFlow(segments, sceneOf, layers, sceneDurations) {
1016
+ const playheads = layer => {
1017
+ const list = [];
1018
+ for (let t = +layer.ip || 0; t < (+layer.op || 0); t++) {
1019
+ list.push(layer.tm ? Math.round((valueAt(layer.tm, t, report) ?? 0) * fps) + 1 : Math.round(t - (+layer.st || 0)) + 1);
1020
+ }
1021
+ return list;
1022
+ };
1023
+ // A jump on entering a frame happens before it is drawn: it goes on the frame after the last
1024
+ // one shown. After a scene's last frame, the scene gets one more frame to hold it.
1025
+ const jump = (scene, shown, target) => {
1026
+ let frame = shown + 1;
1027
+ if (frame > scene.durationFrames) {
1028
+ if (scene.durationFrames >= MAX_FRAMES) return;
1029
+ scene.durationFrames = frame;
1030
+ }
1031
+ scene.events ??= [];
1032
+ if (scene.events.some(event => event.frame === frame)) return;
1033
+ scene.events.push({ trigger: 'frameEnter', frame, actions: target.scene === scene && target.frame !== scene.startFrame
1034
+ ? [{ type: 'gotoFrame', target: target.frame, play: true }] : [{ type: 'gotoScene', target: target.scene.id, play: true }] });
1035
+ };
1036
+ segments.forEach((segment, k) => {
1037
+ const next = segments[k + 1];
1038
+ const shown = playheads(segment);
1039
+ // A playhead that skips inside a segment is a jump (a frame that holds is a transition or a stop).
1040
+ for (let j = 1; j < shown.length; j++) {
1041
+ if (shown[j] !== shown[j - 1] + 1 && shown[j] !== shown[j - 1]) jump(sceneOf.get(segment.refId), shown[j - 1], { scene: sceneOf.get(segment.refId), frame: shown[j] });
1042
+ }
1043
+ if (!next) return;
1044
+ jump(sceneOf.get(segment.refId), shown.at(-1), { scene: sceneOf.get(next.refId), frame: playheads(next)[0] ?? 1 });
1045
+ // The transition into `next` starts where it does.
1046
+ const index = layers.indexOf(layers.find(layer => (layer.nm ?? '').endsWith('(transition)') && layer.ip === next.ip));
1047
+ if (index < 0) return;
1048
+ const fade = layers[index];
1049
+ const edge = layers[index - 1]?.td ? layers[index - 1] : null;
1050
+ const frames = Math.round(fade.op - fade.ip);
1051
+ const progress = [];
1052
+ for (let t = fade.ip; t < fade.op; t++) {
1053
+ if (edge) {
1054
+ const rect = edge.shapes?.[0]?.it?.find(item => item.ty === 'rc');
1055
+ progress.push(((valueAt(rect?.p, t, report)?.[0] ?? lottie.w * 2) - lottie.w) / lottie.w);
1056
+ } else progress.push(1 - (valueAt(fade.ks?.o, t, report) ?? 0) / 100);
1057
+ }
1058
+ const easings = ['linear', 'easeIn', 'easeOut', 'easeInOut'];
1059
+ const error = easing => progress.reduce((sum, value, j) => sum + Math.abs(applyEasing(easing, j / frames) - value), 0);
1060
+ const easing = easings.reduce((best, item) => error(item) < error(best) ? item : best);
1061
+ sceneOf.get(next.refId).transition = { type: edge ? 'wipe' : 'crossfade', durationFrames: clamp(frames, 1, 600), easing };
1062
+ });
1063
+ // The repeat: from the `loop` marker, or (as Lottie players do) from the start, unless the
1064
+ // movie ends held still.
1065
+ const last = segments.at(-1), shown = playheads(last);
1066
+ const held = shown.length > 1 && shown.at(-1) === shown.at(-2);
1067
+ const marker = (lottie.markers ?? []).find(item => item.cm === 'loop');
1068
+ const from = marker ? segments.find(layer => layer.ip <= marker.tm && marker.tm < layer.op) : segments[0];
1069
+ // A movie that ends held stops on the frame it holds.
1070
+ if (held) {
1071
+ const scene = sceneOf.get(last.refId), frame = clamp(shown.at(-1), 1, scene.durationFrames);
1072
+ scene.events ??= [];
1073
+ if (!scene.events.some(event => event.frame === frame)) scene.events.push({ trigger: 'frameEnter', frame, actions: [{ type: 'stop' }] });
1074
+ return;
1075
+ }
1076
+ if (!from) return;
1077
+ const frame = playheads(from)[Math.round((marker?.tm ?? from.ip) - from.ip)] ?? 1;
1078
+ const scene = sceneOf.get(last.refId), target = sceneOf.get(from.refId);
1079
+ // Without a loop marker, a movie cut short by the export's length limit does not repeat.
1080
+ if (!marker && shown.at(-1) < sceneDurations.get(scene)) return;
1081
+ if (target === scene && frame === 1 && !scene.events?.length) scene.loop = true;
1082
+ else jump(scene, shown.at(-1), { scene: target, frame });
1083
+ }
1084
+
1085
+ // Symbols are converted while scenes are; their durations were set before their layers.
1086
+ for (const symbol of symbols) symbol.elements = symbol.elements.map(item => fitKeyframes(item, symbol.durationFrames));
1087
+ for (const scene of scenes) scene.elements = scene.elements.map(item => fitKeyframes(item, scene.durationFrames));
1088
+ return { format: 'swoof-studio', version: 1, stage: { width, height, frameRate: round(fps), background }, assets, scenes, symbols };
1089
+ }
1090
+
1091
+ // Keyframes past a timeline's end are dropped (Studio keys must lie inside it).
1092
+ function fitKeyframes(element, duration) {
1093
+ const keys = element.keyframes.filter(key => key.frame >= 1 && key.frame <= duration);
1094
+ return { ...element, keyframes: keys.length ? keys : [{ ...element.keyframes[0], frame: 1 }] };
1095
+ }
1096
+
1097
+ function bounds(points) {
1098
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
1099
+ for (const p of points) {
1100
+ for (const [x, y] of [[p.x, p.y], [p.x + p.handleIn.x, p.y + p.handleIn.y], [p.x + p.handleOut.x, p.y + p.handleOut.y]]) {
1101
+ x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y);
1102
+ }
1103
+ }
1104
+ return x0 === Infinity ? [0, 0, 0, 0] : [x0, y0, x1, y1];
1105
+ }
1106
+ const coordinate = value => round(clamp(finite(value), -100000, 100000));
1107
+ const shiftPoint = (p, dx, dy) => ({ x: coordinate(p.x + dx), y: coordinate(p.y + dy), handleIn: { x: coordinate(p.handleIn.x), y: coordinate(p.handleIn.y) },
1108
+ handleOut: { x: coordinate(p.handleOut.x), y: coordinate(p.handleOut.y) } });
1109
+ // Studio paths have at least three points: a two-point outline is split in the middle of its curve.
1110
+ export function threePoints(points) {
1111
+ if (points.length >= 3) return points;
1112
+ if (!points.length) return [];
1113
+ if (points.length === 1) return [points[0], { ...points[0] }, { ...points[0] }];
1114
+ const [a, b] = points;
1115
+ const p0 = [a.x, a.y], p1 = [a.x + a.handleOut.x, a.y + a.handleOut.y], p2 = [b.x + b.handleIn.x, b.y + b.handleIn.y], p3 = [b.x, b.y];
1116
+ const mid = (u, v) => [(u[0] + v[0]) / 2, (u[1] + v[1]) / 2];
1117
+ const q0 = mid(p0, p1), q1 = mid(p1, p2), q2 = mid(p2, p3), r0 = mid(q0, q1), r1 = mid(q1, q2), m = mid(r0, r1);
1118
+ return [{ ...a, handleOut: { x: q0[0] - a.x, y: q0[1] - a.y } },
1119
+ { x: m[0], y: m[1], handleIn: { x: r0[0] - m[0], y: r0[1] - m[1] }, handleOut: { x: r1[0] - m[0], y: r1[1] - m[1] } },
1120
+ { ...b, handleIn: { x: q2[0] - b.x, y: q2[1] - b.y } }];
1121
+ }
1122
+ const shiftContour = (points, dx, dy) => threePoints(points).map(p => shiftPoint(p, dx, dy));
1123
+ // A closed outline drawn as an open line ends where it started.
1124
+ const closeOpen = points => [...points, { ...points[0], handleOut: { x: 0, y: 0 } }];
1125
+
1126
+ // Contours that sit inside another are its holes (one compound path); others are separate.
1127
+ function groupContours(contours, evenOdd) {
1128
+ if (evenOdd || contours.length === 1) return [contours];
1129
+ const boxes = contours.map(contour => bounds(contour.points));
1130
+ const inside = (a, b) => a[0] >= b[0] && a[1] >= b[1] && a[2] <= b[2] && a[3] <= b[3];
1131
+ const groups = [];
1132
+ contours.forEach((contour, k) => {
1133
+ const host = groups.find(group => inside(boxes[k], bounds(group[0].points)));
1134
+ if (host) host.push(contour);
1135
+ else groups.push([contour]);
1136
+ });
1137
+ return groups;
1138
+ }