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.
- package/README.md +81 -14
- package/package.json +11 -7
- package/studio/actionscript-roundtrip.test.js +54 -0
- package/studio/actionscript-scripts.test.js +169 -0
- package/studio/animated-image.test.js +137 -0
- package/studio/arithmetic.test.js +16 -0
- package/studio/as3-import.test.js +110 -0
- package/studio/audio-info.test.js +44 -0
- package/studio/components.test.js +152 -0
- package/studio/document-editing.test.js +92 -0
- package/studio/examples/01-space-mission.json +1628 -0
- package/studio/examples/02-clockwork-vault.json +1079 -0
- package/studio/examples/03-neon-synth.json +1364 -0
- package/studio/examples/04-kinetic-poster.json +923 -0
- package/studio/examples/05-signal-relay.json +1131 -0
- package/studio/examples/06-calculator.json +564 -0
- package/studio/frame-editing.test.js +129 -0
- package/studio/frame-events.test.js +117 -0
- package/studio/groups.test.js +88 -0
- package/studio/index.html +962 -0
- package/studio/interaction-triggers.test.js +37 -0
- package/studio/linked-actions.test.js +48 -0
- package/studio/lottie.test.js +208 -0
- package/studio/masks.test.js +43 -0
- package/studio/media-assets.test.js +62 -0
- package/studio/paint-tools.test.js +60 -0
- package/studio/playback.test.js +17 -0
- package/studio/project-io.test.js +405 -0
- package/studio/project-preview.test.js +475 -0
- package/studio/scene-transition.test.js +32 -0
- package/studio/server/archive-companions.js +27 -0
- package/studio/server/as3-library.js +91 -0
- package/studio/server/assets.js +162 -0
- package/studio/server/audio-info.js +82 -0
- package/studio/server/font-files.js +332 -0
- package/studio/server/http.js +135 -0
- package/studio/server/linked-actions.js +93 -0
- package/studio/server/png-decode.js +1 -0
- package/studio/server/project-movie.js +1164 -0
- package/studio/server/project-preview.js +152 -0
- package/studio/server/projects.js +370 -0
- package/studio/server/report.js +29 -0
- package/studio/server/routes.js +93 -0
- package/studio/server/swf-authoring.js +90 -0
- package/studio/server/swf-control-runtime.as +513 -0
- package/studio/server/swf-controls.js +119 -0
- package/studio/server/swf-export.js +293 -0
- package/studio/server/swf-import.js +1675 -0
- package/studio/server/swf-morphs.js +64 -0
- package/studio/server/swf-routes.js +42 -0
- package/studio/server/swf-streams.js +80 -0
- package/studio/server/swf-transition-runtime.as +52 -0
- package/studio/server/tween-recovery.js +106 -0
- package/studio/server-api.test.js +283 -0
- package/studio/server.js +320 -0
- package/studio/src/animated-image.js +423 -0
- package/studio/src/appearance-inspector.js +63 -0
- package/studio/src/arithmetic.js +50 -0
- package/studio/src/authored-controls.js +42 -0
- package/studio/src/busy.js +41 -0
- package/studio/src/canvas.js +430 -0
- package/studio/src/clipper-browser.js +2 -0
- package/studio/src/color-transform.js +38 -0
- package/studio/src/component-inspector.js +126 -0
- package/studio/src/components.js +268 -0
- package/studio/src/display-frame.js +262 -0
- package/studio/src/document-editing.js +69 -0
- package/studio/src/event-editor.js +150 -0
- package/studio/src/frame-editing.js +150 -0
- package/studio/src/frame-events.js +128 -0
- package/studio/src/frame-image.js +28 -0
- package/studio/src/groups.js +125 -0
- package/studio/src/handler-editor.js +122 -0
- package/studio/src/history.js +83 -0
- package/studio/src/imported-paths.js +99 -0
- package/studio/src/index.js +3582 -0
- package/studio/src/interaction-triggers.js +42 -0
- package/studio/src/json-patch.js +77 -0
- package/studio/src/layer-icons.js +25 -0
- package/studio/src/lottie-export.js +948 -0
- package/studio/src/lottie-import.js +1138 -0
- package/studio/src/masks.js +69 -0
- package/studio/src/media-assets.js +188 -0
- package/studio/src/media-library.js +193 -0
- package/studio/src/model.js +431 -0
- package/studio/src/numeric-fields.js +46 -0
- package/studio/src/object-list.js +57 -0
- package/studio/src/paint-tools.js +76 -0
- package/studio/src/placement-effects.js +74 -0
- package/studio/src/playback.js +10 -0
- package/studio/src/preview-audio.js +64 -0
- package/studio/src/preview-interactions.js +106 -0
- package/studio/src/preview-recorder.js +335 -0
- package/studio/src/preview-surface.js +338 -0
- package/studio/src/project-io.js +905 -0
- package/studio/src/project-session.js +375 -0
- package/studio/src/projects-dialog.js +319 -0
- package/studio/src/scene-transition.js +129 -0
- package/studio/src/script-editor.js +175 -0
- package/studio/src/script-references.js +74 -0
- package/studio/src/scripted-controls.js +146 -0
- package/studio/src/scripts.js +185 -0
- package/studio/src/stage-guides.js +101 -0
- package/studio/src/svg-animation.js +416 -0
- package/studio/src/svg-context.js +522 -0
- package/studio/src/svg-frame.js +413 -0
- package/studio/src/svg-import.js +1208 -0
- package/studio/src/swf-recording.js +104 -0
- package/studio/src/symbol-library.js +39 -0
- package/studio/src/symbols.js +62 -0
- package/studio/src/text-fields.js +58 -0
- package/studio/src/theme.js +43 -0
- package/studio/src/timeline.js +321 -0
- package/studio/src/vector-cut.js +103 -0
- package/studio/src/vector-geometry.js +254 -0
- package/studio/src/vector-style.js +146 -0
- package/studio/src/video-encode.js +84 -0
- package/studio/src/video-export.js +331 -0
- package/studio/src/video-mux.js +339 -0
- package/studio/src/video-playback.js +281 -0
- package/studio/src/workspace.js +344 -0
- package/studio/stroke-style.test.js +119 -0
- package/studio/styles.css +1547 -0
- package/studio/svg-export.test.js +162 -0
- package/studio/svg-import.test.js +318 -0
- package/studio/swf-authoring.test.js +140 -0
- package/studio/swf-export.test.js +324 -0
- package/studio/swf-import.test.js +489 -0
- package/studio/symbols.test.js +68 -0
- package/studio/tests/accessibility-interactions.mjs +138 -0
- package/studio/tests/appearance-interactions.mjs +103 -0
- package/studio/tests/control-interactions.mjs +60 -0
- package/studio/tests/event-interactions.mjs +117 -0
- package/studio/tests/external-resources.mjs +174 -0
- package/studio/tests/frame-image.mjs +71 -0
- package/studio/tests/html-export.mjs +68 -0
- package/studio/tests/import-files.mjs +131 -0
- package/studio/tests/lottie.mjs +125 -0
- package/studio/tests/mask-interactions.mjs +148 -0
- package/studio/tests/media-interactions.mjs +109 -0
- package/studio/tests/paint-interactions.mjs +64 -0
- package/studio/tests/project-interactions.mjs +244 -0
- package/studio/tests/script-interactions.mjs +178 -0
- package/studio/tests/scripted-control-interactions.mjs +107 -0
- package/studio/tests/svg-export.mjs +149 -0
- package/studio/tests/text-field-interactions.mjs +64 -0
- package/studio/tests/theme-interactions.mjs +53 -0
- package/studio/tests/timeline-browser.mjs +507 -0
- package/studio/tests/transition-interactions.mjs +94 -0
- package/studio/tests/trigger-interactions.mjs +93 -0
- package/studio/tests/video-export.mjs +243 -0
- package/studio/tests/workspace-interactions.mjs +226 -0
- package/studio/tween-recovery.test.js +31 -0
- package/studio/vector-style.test.js +56 -0
- package/studio/video-export.test.js +326 -0
- package/studiospec/actionscript.md +88 -0
- package/studiospec/architecture.md +378 -0
- package/studiospec/controls.md +100 -0
- package/studiospec/file-support.md +268 -0
- package/studiospec/lottie.md +69 -0
- package/studiospec/requirements.md +135 -0
- package/studiospec/stroke-style.md +95 -0
- package/studiospec/svg-export.md +83 -0
- package/studiospec/svg-import.md +139 -0
- package/studiospec/swooflib-integration.md +115 -0
- package/studiospec/tasks.md +573 -0
- package/studiospec/video-export.md +127 -0
- package/swf2js/__tests__/actionscript.test.js +1609 -0
- package/swf2js/__tests__/adpcm-audio.test.js +43 -0
- package/swf2js/__tests__/as2-compiler.test.js +153 -0
- package/swf2js/__tests__/as3-mixed-depth.test.js +498 -0
- package/swf2js/__tests__/authored-sprite-hit.test.js +118 -0
- package/swf2js/__tests__/authored-sprite-sizing.test.js +164 -0
- package/swf2js/__tests__/avm1-action-prefix.test.js +134 -0
- package/swf2js/__tests__/avm1-attach-movie.test.js +1151 -0
- package/swf2js/__tests__/avm1-boxhead-budget.test.js +73 -0
- package/swf2js/__tests__/avm1-cfg-bubble-tanks.test.js +101 -0
- package/swf2js/__tests__/avm1-cfg-mario-kart.test.js +184 -0
- package/swf2js/__tests__/avm1-cfg-mario.test.js +31 -0
- package/swf2js/__tests__/avm1-cfg-pacman.test.js +49 -0
- package/swf2js/__tests__/avm1-checkers-gameplay.test.js +122 -0
- package/swf2js/__tests__/avm1-clip-actions.test.js +2002 -0
- package/swf2js/__tests__/avm1-clone-drag.test.js +626 -0
- package/swf2js/__tests__/avm1-decompiler.test.js +102 -0
- package/swf2js/__tests__/avm1-dynamic-locals.test.js +159 -0
- package/swf2js/__tests__/avm1-formal-parameters.test.js +71 -0
- package/swf2js/__tests__/avm1-key-events.test.js +52 -0
- package/swf2js/__tests__/avm1-load-bitmap.test.js +75 -0
- package/swf2js/__tests__/avm1-loading-host-actions.test.js +764 -0
- package/swf2js/__tests__/avm1-multibyte-strings.test.js +63 -0
- package/swf2js/__tests__/avm1-pacman-gameplay.test.js +115 -0
- package/swf2js/__tests__/avm1-shape-hittest.test.js +311 -0
- package/swf2js/__tests__/avm1-shared-bodies.test.js +57 -0
- package/swf2js/__tests__/avm1-shared-runtime.test.js +1364 -0
- package/swf2js/__tests__/avm1-snake-gameplay.test.js +139 -0
- package/swf2js/__tests__/avm1-super.test.js +70 -0
- package/swf2js/__tests__/avm1-target-path.test.js +325 -0
- package/swf2js/__tests__/avm1-try.test.js +229 -0
- package/swf2js/__tests__/avm2-activation-closures.test.js +65 -0
- package/swf2js/__tests__/avm2-applytype.test.js +180 -0
- package/swf2js/__tests__/avm2-call-ops.test.js +232 -0
- package/swf2js/__tests__/avm2-callsuperid.test.js +231 -0
- package/swf2js/__tests__/avm2-class-initializer.test.js +219 -0
- package/swf2js/__tests__/avm2-custom-namespace.test.js +139 -0
- package/swf2js/__tests__/avm2-describe-type.test.js +96 -0
- package/swf2js/__tests__/avm2-dictionary.test.js +96 -0
- package/swf2js/__tests__/avm2-domain-memory.test.js +332 -0
- package/swf2js/__tests__/avm2-e4x.test.js +326 -0
- package/swf2js/__tests__/avm2-exceptions.test.js +81 -0
- package/swf2js/__tests__/avm2-findprop.test.js +110 -0
- package/swf2js/__tests__/avm2-getlex.test.js +166 -0
- package/swf2js/__tests__/avm2-global-slot.test.js +106 -0
- package/swf2js/__tests__/avm2-interface.test.js +95 -0
- package/swf2js/__tests__/avm2-multiname-precedence.test.js +148 -0
- package/swf2js/__tests__/avm2-named-namespace-types.test.js +106 -0
- package/swf2js/__tests__/avm2-optional-args.test.js +100 -0
- package/swf2js/__tests__/avm2-outer-scopes.test.js +101 -0
- package/swf2js/__tests__/avm2-package-internal-class.test.js +106 -0
- package/swf2js/__tests__/avm2-protected-namespace.test.js +105 -0
- package/swf2js/__tests__/avm2-protected.test.js +214 -0
- package/swf2js/__tests__/avm2-qwop-gameplay.test.js +116 -0
- package/swf2js/__tests__/avm2-runtime-namespaces.test.js +159 -0
- package/swf2js/__tests__/avm2-script-traits.test.js +89 -0
- package/swf2js/__tests__/avm2-shared-runtime.test.js +52 -0
- package/swf2js/__tests__/avm2-slot-ops.test.js +117 -0
- package/swf2js/__tests__/avm2-type-ops.test.js +224 -0
- package/swf2js/__tests__/bevel-filter.test.js +116 -0
- package/swf2js/__tests__/bitmap-button-mask.test.js +106 -0
- package/swf2js/__tests__/bitmap-data-draw.test.js +388 -0
- package/swf2js/__tests__/bitmap-decoder.test.js +108 -0
- package/swf2js/__tests__/bitmapdata-color-bounds.test.js +70 -0
- package/swf2js/__tests__/bitmapdata-copy-channel.test.js +91 -0
- package/swf2js/__tests__/bitmapdata-copy-pixels.test.js +136 -0
- package/swf2js/__tests__/bitmapdata-fill-compare.test.js +241 -0
- package/swf2js/__tests__/bitmapdata-filter.test.js +232 -0
- package/swf2js/__tests__/bitmapdata-hit-test.test.js +71 -0
- package/swf2js/__tests__/bitmapdata-merge.test.js +84 -0
- package/swf2js/__tests__/bitmapdata-palette-map.test.js +92 -0
- package/swf2js/__tests__/bitmapdata-pixels-io.test.js +198 -0
- package/swf2js/__tests__/bitmapdata-threshold.test.js +97 -0
- package/swf2js/__tests__/bitmapdata-vector.test.js +82 -0
- package/swf2js/__tests__/blur-filter.test.js +48 -0
- package/swf2js/__tests__/bundle-emitter.test.js +394 -0
- package/swf2js/__tests__/button-actions.test.js +370 -0
- package/swf2js/__tests__/button-color-transform.test.js +48 -0
- package/swf2js/__tests__/button-decoder.test.js +106 -0
- package/swf2js/__tests__/button-hit-test.test.js +825 -0
- package/swf2js/__tests__/button-scaling-grid.test.js +124 -0
- package/swf2js/__tests__/button-sound.test.js +105 -0
- package/swf2js/__tests__/bytearray-coercion.test.js +23 -0
- package/swf2js/__tests__/bytearray-object-serialization.test.js +380 -0
- package/swf2js/__tests__/cfg-switch-loop.test.js +103 -0
- package/swf2js/__tests__/clip-depth-mask.test.js +119 -0
- package/swf2js/__tests__/clipped-bitmap-fill.test.js +118 -0
- package/swf2js/__tests__/companion-swf.test.js +638 -0
- package/swf2js/__tests__/context-menu.test.js +149 -0
- package/swf2js/__tests__/convolution-filter.test.js +74 -0
- package/swf2js/__tests__/definefont4.test.js +280 -0
- package/swf2js/__tests__/display-displacement.test.js +161 -0
- package/swf2js/__tests__/display-list.test.js +80 -0
- package/swf2js/__tests__/display-mask-render.test.js +656 -0
- package/swf2js/__tests__/displayobject-stage.test.js +320 -0
- package/swf2js/__tests__/embedded-script-audio.test.js +131 -0
- package/swf2js/__tests__/embedded-swf.test.js +202 -0
- package/swf2js/__tests__/embedded-textfield.test.js +107 -0
- package/swf2js/__tests__/embedded-timeline-audio.test.js +182 -0
- package/swf2js/__tests__/embedded-timeline-input.test.js +420 -0
- package/swf2js/__tests__/embedded-timer-lifecycle.test.js +145 -0
- package/swf2js/__tests__/event-priority-order.test.js +125 -0
- package/swf2js/__tests__/event-weak-listeners.test.js +53 -0
- package/swf2js/__tests__/event-will-trigger.test.js +43 -0
- package/swf2js/__tests__/flash-text-engine-content.test.js +115 -0
- package/swf2js/__tests__/flash-text-engine-format.test.js +95 -0
- package/swf2js/__tests__/flash-text-engine-line.test.js +314 -0
- package/swf2js/__tests__/font-encoder.test.js +95 -0
- package/swf2js/__tests__/font-outline-text.test.js +659 -0
- package/swf2js/__tests__/glow-shadow-filter.test.js +68 -0
- package/swf2js/__tests__/graphics-bitmap-smoothing.test.js +32 -0
- package/swf2js/__tests__/graphics-fill-lifetime.test.js +36 -0
- package/swf2js/__tests__/graphics-gradient-matrix.test.js +53 -0
- package/swf2js/__tests__/graphics-stroke-hit-test.test.js +457 -0
- package/swf2js/__tests__/hit-test-primitives.test.js +414 -0
- package/swf2js/__tests__/input-events.test.js +714 -0
- package/swf2js/__tests__/integration/corpus.test.js +41 -0
- package/swf2js/__tests__/loader-embedded-swf.test.js +210 -0
- package/swf2js/__tests__/loader-info.test.js +81 -0
- package/swf2js/__tests__/local-connection.test.js +122 -0
- package/swf2js/__tests__/morph-focal-gradient.test.js +51 -0
- package/swf2js/__tests__/morph-topology.test.js +267 -0
- package/swf2js/__tests__/movie-data-codec.test.js +128 -0
- package/swf2js/__tests__/nellymoser-audio.test.js +84 -0
- package/swf2js/__tests__/opaque-background-cache.test.js +352 -0
- package/swf2js/__tests__/path-stream.test.js +81 -0
- package/swf2js/__tests__/place-object-filters.test.js +88 -0
- package/swf2js/__tests__/place-object3-decoder.test.js +116 -0
- package/swf2js/__tests__/place-object3-image.test.js +85 -0
- package/swf2js/__tests__/player-version.test.js +46 -0
- package/swf2js/__tests__/root-textfield.test.js +287 -0
- package/swf2js/__tests__/scaling-grid.test.js +183 -0
- package/swf2js/__tests__/shape-decoder.test.js +361 -0
- package/swf2js/__tests__/shape-line-style2.test.js +138 -0
- package/swf2js/__tests__/shape-nonscaling-stroke.test.js +131 -0
- package/swf2js/__tests__/shape-pixel-hint.test.js +101 -0
- package/swf2js/__tests__/simplebutton-pointer.test.js +1477 -0
- package/swf2js/__tests__/socket-offline.test.js +67 -0
- package/swf2js/__tests__/sound-avm1-stop.test.js +99 -0
- package/swf2js/__tests__/sound-envelope.test.js +110 -0
- package/swf2js/__tests__/sound-extract.test.js +168 -0
- package/swf2js/__tests__/sound-id3.test.js +283 -0
- package/swf2js/__tests__/sound-load.test.js +259 -0
- package/swf2js/__tests__/sound-mixer-spectrum.test.js +261 -0
- package/swf2js/__tests__/sound-stream-sprite.test.js +624 -0
- package/swf2js/__tests__/sound-transform.test.js +104 -0
- package/swf2js/__tests__/speex-audio.test.js +77 -0
- package/swf2js/__tests__/stage-noscale.test.js +45 -0
- package/swf2js/__tests__/swf-encoder.test.js +134 -0
- package/swf2js/__tests__/swflib-assemble.test.js +20 -0
- package/swf2js/__tests__/textfield-html-text.test.js +368 -0
- package/swf2js/__tests__/textfield-line-layout.test.js +339 -0
- package/swf2js/__tests__/textfield-programmatic-overlay.test.js +2506 -0
- package/swf2js/__tests__/textfield-scroll.test.js +79 -0
- package/swf2js/__tests__/textfield-selection.test.js +383 -0
- package/swf2js/__tests__/timeline-effect-surfaces.test.js +295 -0
- package/swf2js/__tests__/timeline-named-anchor.test.js +139 -0
- package/swf2js/__tests__/timeline-scenes.test.js +1723 -0
- package/swf2js/__tests__/urlloader-http-status.test.js +236 -0
- package/{src → swf2js}/cli.js +43 -11
- package/swf2js/compiler/as2-classes.js +156 -0
- package/swf2js/compiler/as2-parser.js +598 -0
- package/swf2js/compiler/avm1-codegen.js +897 -0
- package/swf2js/compiler/index.js +28 -0
- package/{src → swf2js}/decoder/button-decoder.js +3 -1
- package/swf2js/decoder/png.js +114 -0
- package/{src → swf2js}/decoder/shape-decoder.js +20 -10
- package/{src → swf2js}/decoder/tag-decoder.js +5 -3
- package/{src → swf2js}/decoder/tag-types.js +4 -0
- package/swf2js/decompiler/avm1-decompiler.js +1138 -0
- package/{src → swf2js}/emitter/asset-encoder.js +66 -113
- package/{src → swf2js}/emitter/bundle-emitter.js +209 -78
- package/swf2js/emitter/external-resources.js +39 -0
- package/swf2js/emitter/movie-data-codec.js +91 -0
- package/swf2js/encoder/bit-writer.js +182 -0
- package/swf2js/encoder/shape-encoder.js +310 -0
- package/swf2js/encoder/swf-builder.js +639 -0
- package/swf2js/encoder/swf-writer.js +55 -0
- package/{src/runtime/swflib/assemble.js → swf2js/runtime/assemble-swooflib.js} +4 -3
- package/{src → swf2js}/runtime/avm1-runtime.js +102 -63
- package/{src → swf2js}/runtime/index.js +1 -1
- package/{src → swf2js}/runtime/movie-runtime.js +28 -2
- package/{src → swf2js}/transpiler/actionscript.js +82 -19
- package/{src → swf2js}/transpiler/avm1/avm1-opcodes.js +5 -3
- package/{src → swf2js}/transpiler/avm1/avm1-transpiler.js +69 -6
- package/{src → swf2js}/transpiler/avm2/avm2-transpiler.js +1 -1
- package/{src → swf2js}/transpiler/timeline/display-list.js +41 -22
- package/{src → swf2js}/transpiler/timeline/timeline-codegen.js +97 -36
- package/swooflib/README.md +569 -0
- package/swooflib/adpcm.js +147 -0
- package/{src/runtime/swflib → swooflib}/builtins.js +6 -0
- package/{src/runtime/swflib → swooflib}/context-menu.js +7 -1
- package/swooflib/control-definitions.js +42 -0
- package/swooflib/control-widget.js +763 -0
- package/swooflib/controls.js +300 -0
- package/{src/runtime/swflib → swooflib}/display.js +16 -10
- package/{src/runtime/swflib → swooflib}/events.js +11 -0
- package/{src/runtime/swflib → swooflib}/flash.js +6 -5
- package/{src/runtime/swflib → swooflib}/graphics.js +81 -19
- package/{src/runtime/swflib → swooflib}/input.js +12 -14
- package/{src/runtime/swflib → swooflib}/loader.js +52 -22
- package/swooflib/movie-network.js +86 -0
- package/swooflib/path-stream.js +169 -0
- package/{src/runtime/swflib → swooflib}/render.js +3 -13
- package/{src/runtime/swflib → swooflib}/sound.js +25 -2
- package/{src/runtime/swflib → swooflib}/stage.js +3 -3
- package/swooflib/stream-time.js +21 -0
- package/{src/runtime/swflib → swooflib}/system.js +88 -37
- package/{src/runtime/swflib → swooflib}/text-paint.js +14 -3
- package/{src/runtime/swflib → swooflib}/text.js +8 -0
- package/swooflib/xml-node.js +53 -0
- package/src/emitter/timeline-data-codec.js +0 -58
- /package/{src → swf2js}/decoder/symbol-table.js +0 -0
- /package/{src → swf2js}/emitter/embedded-swf.js +0 -0
- /package/{src → swf2js}/emitter/font-encoder.js +0 -0
- /package/{src → swf2js}/model/swf-document.js +0 -0
- /package/{src → swf2js}/model/transpile-result.js +0 -0
- /package/{src → swf2js}/parser/bit-reader.js +0 -0
- /package/{src → swf2js}/parser/decompressor.js +0 -0
- /package/{src → swf2js}/parser/swf-parser.js +0 -0
- /package/{src → swf2js}/pretty-printer/pretty-printer.js +0 -0
- /package/{src → swf2js}/runtime/avm2-runtime.js +0 -0
- /package/{src → swf2js}/runtime/embedded-movie-runtime.js +0 -0
- /package/{src → swf2js}/transpiler/avm1/avm1-ir.js +0 -0
- /package/{src → swf2js}/transpiler/avm1/avm1-rewrite.js +0 -0
- /package/{src → swf2js}/transpiler/avm2/abc-reader.js +0 -0
- /package/{src → swf2js}/transpiler/cfg-structurer.js +0 -0
- /package/{src → swf2js}/util/diagnostics.js +0 -0
- /package/{src → swf2js}/util/logger.js +0 -0
- /package/{src/runtime/swflib → swooflib}/bitmap-image.js +0 -0
- /package/{src/runtime/swflib → swooflib}/bitmap.js +0 -0
- /package/{src/runtime/swflib → swooflib}/bytearray.js +0 -0
- /package/{src/runtime/swflib → swooflib}/compiled-swf.js +0 -0
- /package/{src/runtime/swflib → swooflib}/cursor-flag.js +0 -0
- /package/{src/runtime/swflib → swooflib}/dictionary.js +0 -0
- /package/{src/runtime/swflib → swooflib}/filters.js +0 -0
- /package/{src/runtime/swflib → swooflib}/geom.js +0 -0
- /package/{src/runtime/swflib → swooflib}/glyph-metrics.js +0 -0
- /package/{src/runtime/swflib → swooflib}/host.js +0 -0
- /package/{src/runtime/swflib → swooflib}/inherit.js +0 -0
- /package/{src/runtime/swflib → swooflib}/marks.js +0 -0
- /package/{src/runtime/swflib → swooflib}/matrix3d.js +0 -0
- /package/{src/runtime/swflib → swooflib}/pointer-bridge.js +0 -0
- /package/{src/runtime/swflib → swooflib}/projection.js +0 -0
- /package/{src/runtime/swflib → swooflib}/sprite-drag.js +0 -0
- /package/{src/runtime/swflib → swooflib}/stage-ref.js +0 -0
- /package/{src/runtime/swflib → swooflib}/text-field.js +0 -0
- /package/{src/runtime/swflib → swooflib}/transform.js +0 -0
- /package/{src/runtime/swflib → swooflib}/xml.js +0 -0
|
@@ -0,0 +1,1675 @@
|
|
|
1
|
+
import { finalStopIndex, matchingSprites, readAuthoringMetadata } from './swf-authoring.js';
|
|
2
|
+
// Convert a SWF movie into an editable Studio project. Reads the swf2js parser and decoder
|
|
3
|
+
// output and reports everything it approximates or drops. ActionScript is kept as scripts at
|
|
4
|
+
// the place Flash attached it (see studiospec/actionscript.md); the transpiler only renders a
|
|
5
|
+
// readable copy of each script.
|
|
6
|
+
import { importedMorphFingerprint } from './swf-morphs.js';
|
|
7
|
+
import { recoverTweens } from './tween-recovery.js';
|
|
8
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
9
|
+
import { parse } from '../../swf2js/parser/swf-parser.js';
|
|
10
|
+
import { decode, decodeTag } from '../../swf2js/decoder/tag-decoder.js';
|
|
11
|
+
import { TAG } from '../../swf2js/decoder/tag-types.js';
|
|
12
|
+
import { decodeShape, decodeMorphShape } from '../../swf2js/decoder/shape-decoder.js';
|
|
13
|
+
import { decodeButton } from '../../swf2js/decoder/button-decoder.js';
|
|
14
|
+
import { buildFramesFromTags, buildSymbolClasses, buttonSupplementaryTags, scalingGrids } from '../../swf2js/transpiler/timeline/display-list.js';
|
|
15
|
+
import { morphDrawsFor } from '../../swf2js/transpiler/timeline/timeline-codegen.js';
|
|
16
|
+
import { encodeBitmap, mergeJpegAlpha, encodeSound, encodeSoundStreamSegments } from '../../swf2js/emitter/asset-encoder.js';
|
|
17
|
+
import { OP } from '../../swf2js/transpiler/avm1/avm1-opcodes.js';
|
|
18
|
+
import { transpileAvm1 } from '../../swf2js/transpiler/avm1/avm1-transpiler.js';
|
|
19
|
+
import { linkedActionSource } from '../../swf2js/transpiler/actionscript.js';
|
|
20
|
+
import { CLIP_EVENT_HANDLERS } from '../../swf2js/runtime/avm1-runtime.js';
|
|
21
|
+
import { DiagnosticsCollector } from '../../swf2js/util/diagnostics.js';
|
|
22
|
+
import { PROJECT_FORMAT, PROJECT_VERSION } from '../src/project-io.js';
|
|
23
|
+
import { numericPoseRange, POSITION_LIMIT, stageRanges, MAX_TIMELINE_FRAMES } from '../src/numeric-fields.js';
|
|
24
|
+
import { readColorTransform } from '../src/color-transform.js';
|
|
25
|
+
import { defineTextAdvancePixels, fontOutlineScale } from '../../swooflib/glyph-metrics.js';
|
|
26
|
+
import { createReport } from './report.js';
|
|
27
|
+
import { packClassLibrary } from './as3-library.js';
|
|
28
|
+
import { standaloneLinkedActions } from './linked-actions.js';
|
|
29
|
+
import { encodeBrowserFont } from '../../swf2js/emitter/font-encoder.js';
|
|
30
|
+
import { canMask } from '../src/masks.js';
|
|
31
|
+
import { readTransition } from '../src/scene-transition.js';
|
|
32
|
+
import { componentKind, decodeComponentParameters } from '../src/components.js';
|
|
33
|
+
|
|
34
|
+
const NAME_LIMIT = 48;
|
|
35
|
+
const round = (value, digits = 2) => Math.round(value * 10 ** digits) / 10 ** digits;
|
|
36
|
+
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
|
|
37
|
+
const poseSize = (boxSize, axis) => clamp(round(boxSize), ...numericPoseRange(axis));
|
|
38
|
+
const IDENTITY = { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 };
|
|
39
|
+
|
|
40
|
+
export class SwfImportError extends Error {
|
|
41
|
+
constructor(message, status = 422) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.status = status;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function shortName(text, fallback) {
|
|
48
|
+
const name = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
49
|
+
return (name || fallback).slice(0, NAME_LIMIT);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// --- Colors ----------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
function parseColor(value) {
|
|
55
|
+
if (value && typeof value === 'object') {
|
|
56
|
+
const hex = '#' + [value.r, value.g, value.b].map(n => clamp(n | 0, 0, 255).toString(16).padStart(2, '0')).join('');
|
|
57
|
+
return { hex, alpha: value.a === undefined ? 1 : value.a > 1 ? value.a / 255 : value.a };
|
|
58
|
+
}
|
|
59
|
+
const text = String(value ?? '#000000').trim();
|
|
60
|
+
let match = /^#([0-9a-f]{6})$/i.exec(text);
|
|
61
|
+
if (match) return { hex: '#' + match[1].toLowerCase(), alpha: 1 };
|
|
62
|
+
match = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec(text);
|
|
63
|
+
if (match) {
|
|
64
|
+
const hex = '#' + match.slice(1, 4).map(n => clamp(Math.round(Number(n)), 0, 255).toString(16).padStart(2, '0')).join('');
|
|
65
|
+
return { hex, alpha: match[4] === undefined ? 1 : clamp(Number(match[4]), 0, 1) };
|
|
66
|
+
}
|
|
67
|
+
return { hex: '#000000', alpha: 1 };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// --- Matrices --------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
function multiply(m, n) {
|
|
73
|
+
// Apply n first, then m.
|
|
74
|
+
return {
|
|
75
|
+
a: m.a * n.a + m.c * n.b, b: m.b * n.a + m.d * n.b,
|
|
76
|
+
c: m.a * n.c + m.c * n.d, d: m.b * n.c + m.d * n.d,
|
|
77
|
+
tx: m.a * n.tx + m.c * n.ty + m.tx, ty: m.b * n.tx + m.d * n.ty + m.ty,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const apply = (m, x, y) => ({ x: m.a * x + m.c * y + m.tx, y: m.b * x + m.d * y + m.ty });
|
|
81
|
+
|
|
82
|
+
function transformBounds(m, box) {
|
|
83
|
+
if (!box) return null;
|
|
84
|
+
const points = [[box.x, box.y], [box.x + box.w, box.y], [box.x, box.y + box.h], [box.x + box.w, box.y + box.h]]
|
|
85
|
+
.map(([x, y]) => apply(m, x, y));
|
|
86
|
+
const xs = points.map(p => p.x), ys = points.map(p => p.y);
|
|
87
|
+
return { x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function unionBounds(a, b) {
|
|
91
|
+
if (!a) return b;
|
|
92
|
+
if (!b) return a;
|
|
93
|
+
const x = Math.min(a.x, b.x), y = Math.min(a.y, b.y);
|
|
94
|
+
return { x, y, w: Math.max(a.x + a.w, b.x + b.w) - x, h: Math.max(a.y + a.h, b.y + b.h) - y };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Decompose a linear transform into Studio's rotation, skew, and positive scales. */
|
|
98
|
+
function decompose(m) {
|
|
99
|
+
const scaleX = Math.hypot(m.a, m.b), scaleY = Math.hypot(m.c, m.d);
|
|
100
|
+
const rotation = Math.atan2(m.b, m.a) * 180 / Math.PI;
|
|
101
|
+
let skew = Math.atan2(-m.c, m.d) * 180 / Math.PI - rotation;
|
|
102
|
+
skew = ((skew + 540) % 360) - 180;
|
|
103
|
+
return { scaleX, scaleY, rotation, skew, mirrored: m.a * m.d - m.b * m.c < 0 };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// --- Paths -----------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
/** Split a draw-list path into Studio contours with cubic handles. Coordinates are pixels. */
|
|
109
|
+
function contours(path) {
|
|
110
|
+
const result = [];
|
|
111
|
+
let current = null;
|
|
112
|
+
const close = () => {
|
|
113
|
+
if (!current) return;
|
|
114
|
+
const points = current.points;
|
|
115
|
+
if (points.length > 1) {
|
|
116
|
+
const first = points[0], last = points.at(-1);
|
|
117
|
+
if (Math.abs(first.x - last.x) < 0.01 && Math.abs(first.y - last.y) < 0.01) {
|
|
118
|
+
first.handleIn = last.handleIn;
|
|
119
|
+
points.pop();
|
|
120
|
+
current.closed = true;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (points.length >= 2) result.push(current);
|
|
124
|
+
current = null;
|
|
125
|
+
};
|
|
126
|
+
for (const command of path) {
|
|
127
|
+
const [op, ...args] = command;
|
|
128
|
+
if (op === 'M') {
|
|
129
|
+
close();
|
|
130
|
+
current = { points: [{ x: args[0], y: args[1], handleIn: { x: 0, y: 0 }, handleOut: { x: 0, y: 0 } }], closed: false };
|
|
131
|
+
} else if (op === 'L' && current) {
|
|
132
|
+
current.points.push({ x: args[0], y: args[1], handleIn: { x: 0, y: 0 }, handleOut: { x: 0, y: 0 } });
|
|
133
|
+
} else if (op === 'Q' && current) {
|
|
134
|
+
const previous = current.points.at(-1);
|
|
135
|
+
const [cx, cy, x, y] = args;
|
|
136
|
+
previous.handleOut = { x: (cx - previous.x) * 2 / 3, y: (cy - previous.y) * 2 / 3 };
|
|
137
|
+
current.points.push({ x, y, handleIn: { x: (cx - x) * 2 / 3, y: (cy - y) * 2 / 3 }, handleOut: { x: 0, y: 0 } });
|
|
138
|
+
} else if (op === 'C' && current) {
|
|
139
|
+
const previous = current.points.at(-1);
|
|
140
|
+
const [c1x, c1y, c2x, c2y, x, y] = args;
|
|
141
|
+
previous.handleOut = { x: c1x - previous.x, y: c1y - previous.y };
|
|
142
|
+
current.points.push({ x, y, handleIn: { x: c2x - x, y: c2y - y }, handleOut: { x: 0, y: 0 } });
|
|
143
|
+
} else if (op === 'Z' && current) {
|
|
144
|
+
const first = current.points[0], last = current.points.at(-1);
|
|
145
|
+
if (Math.abs(first.x - last.x) >= 0.01 || Math.abs(first.y - last.y) >= 0.01) {
|
|
146
|
+
current.points.push({ x: first.x, y: first.y, handleIn: { x: 0, y: 0 }, handleOut: { x: 0, y: 0 } });
|
|
147
|
+
}
|
|
148
|
+
close();
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
close();
|
|
152
|
+
return result;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The overlap of two boxes, or null when they do not overlap. */
|
|
156
|
+
function intersectBounds(a, b) {
|
|
157
|
+
const x = Math.max(a.x, b.x), y = Math.max(a.y, b.y);
|
|
158
|
+
const w = Math.min(a.x + a.w, b.x + b.w) - x, h = Math.min(a.y + a.h, b.y + b.h) - y;
|
|
159
|
+
return w > 0 && h > 0 ? { x, y, w, h } : null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** True for one closed contour of straight edges along the axes (an unrotated rectangle). */
|
|
163
|
+
function isRectangle(shapes) {
|
|
164
|
+
if (shapes.length !== 1) return false;
|
|
165
|
+
const points = shapes[0].points;
|
|
166
|
+
const box = contourBounds(points);
|
|
167
|
+
const edge = (value, a, b) => Math.abs(value - a) < 0.01 || Math.abs(value - b) < 0.01;
|
|
168
|
+
return points.length >= 4 && points.every(point => !point.handleIn.x && !point.handleIn.y && !point.handleOut.x && !point.handleOut.y
|
|
169
|
+
&& edge(point.x, box.x, box.x + box.w) && edge(point.y, box.y, box.y + box.h));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function contourBounds(points) {
|
|
173
|
+
let left = Infinity, top = Infinity, right = -Infinity, bottom = -Infinity;
|
|
174
|
+
for (const point of points) {
|
|
175
|
+
for (const [x, y] of [[point.x, point.y], [point.x + point.handleIn.x, point.y + point.handleIn.y],
|
|
176
|
+
[point.x + point.handleOut.x, point.y + point.handleOut.y]]) {
|
|
177
|
+
left = Math.min(left, x); right = Math.max(right, x);
|
|
178
|
+
top = Math.min(top, y); bottom = Math.max(bottom, y);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return { x: left, y: top, w: right - left, h: bottom - top };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const contains = (outer, inner) => inner.x >= outer.x - 0.01 && inner.y >= outer.y - 0.01 &&
|
|
185
|
+
inner.x + inner.w <= outer.x + outer.w + 0.01 && inner.y + inner.h <= outer.y + outer.h + 0.01;
|
|
186
|
+
|
|
187
|
+
// --- Images ----------------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
function imageSize(data) {
|
|
190
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
191
|
+
if (data.length > 24 && view.getUint32(0) === 0x89504e47) return { width: view.getUint32(16), height: view.getUint32(20) };
|
|
192
|
+
if (data.length > 10 && data[0] === 0x47 && data[1] === 0x49) return { width: view.getUint16(6, true), height: view.getUint16(8, true) };
|
|
193
|
+
if (data[0] === 0xff && data[1] === 0xd8) {
|
|
194
|
+
let offset = 2;
|
|
195
|
+
while (offset + 9 < data.length) {
|
|
196
|
+
if (data[offset] !== 0xff) { offset++; continue; }
|
|
197
|
+
const marker = data[offset + 1];
|
|
198
|
+
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
|
|
199
|
+
return { width: view.getUint16(offset + 7), height: view.getUint16(offset + 5) };
|
|
200
|
+
}
|
|
201
|
+
if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { offset += 2; continue; }
|
|
202
|
+
offset += 2 + view.getUint16(offset + 2);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// --- AVM1 ------------------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
/** Read a sequence of simple timeline actions; returns null when anything else appears. */
|
|
211
|
+
function simpleActions(bytes) {
|
|
212
|
+
const actions = [];
|
|
213
|
+
let offset = 0;
|
|
214
|
+
while (offset < bytes.length) {
|
|
215
|
+
const op = bytes[offset];
|
|
216
|
+
if (op === OP.End) break;
|
|
217
|
+
let length = 0;
|
|
218
|
+
if (op >= 0x80) {
|
|
219
|
+
if (offset + 3 > bytes.length) return null;
|
|
220
|
+
length = bytes[offset + 1] | (bytes[offset + 2] << 8);
|
|
221
|
+
}
|
|
222
|
+
const body = bytes.subarray(offset + 3, offset + 3 + length);
|
|
223
|
+
if (op === OP.Stop) actions.push({ op: 'stop' });
|
|
224
|
+
else if (op === OP.Play) actions.push({ op: 'play' });
|
|
225
|
+
else if (op === OP.GotoFrame) actions.push({ op: 'gotoFrame', frame: (body[0] | (body[1] << 8)) + 1 });
|
|
226
|
+
else if (op === OP.GotoLabel) actions.push({ op: 'gotoLabel', label: new TextDecoder().decode(body.subarray(0, Math.max(0, body.indexOf(0)))) });
|
|
227
|
+
else return null;
|
|
228
|
+
offset += op >= 0x80 ? 3 + length : 1;
|
|
229
|
+
}
|
|
230
|
+
// "goto then play" is the AS1 form of gotoAndPlay.
|
|
231
|
+
const merged = [];
|
|
232
|
+
for (const action of actions) {
|
|
233
|
+
const previous = merged.at(-1);
|
|
234
|
+
if (action.op === 'play' && previous && previous.op.startsWith('goto') && previous.play === undefined) previous.play = true;
|
|
235
|
+
else merged.push(action);
|
|
236
|
+
}
|
|
237
|
+
return merged;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Flash button transitions (BUTTONCONDACTION) by the handler name Flash's authoring tool used.
|
|
241
|
+
const BUTTON_CONDITIONS = [
|
|
242
|
+
['overUpToOverDown', 'press'], ['overDownToOverUp', 'release'], ['outDownToIdle', 'releaseOutside'],
|
|
243
|
+
['idleToOverUp', 'rollOver'], ['overUpToIdle', 'rollOut'], ['outDownToOverDown', 'dragOver'],
|
|
244
|
+
['overDownToOutDown', 'dragOut'], ['idleToOverDown', 'menuDragOver'], ['overDownToIdle', 'menuDragOut'],
|
|
245
|
+
];
|
|
246
|
+
|
|
247
|
+
/** Button trigger names for one condition record, plus its key code (0 = none). */
|
|
248
|
+
function buttonTriggers(conditions = {}) {
|
|
249
|
+
const on = BUTTON_CONDITIONS.filter(([bit]) => conditions[bit]).map(([, name]) => name);
|
|
250
|
+
if (conditions.keyPress) on.push('keyPress');
|
|
251
|
+
return { on, key: conditions.keyPress || 0 };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Clip event names (onClipEvent) for a CLIPEVENTFLAGS value. */
|
|
255
|
+
function clipTriggers(flags) {
|
|
256
|
+
return CLIP_EVENT_HANDLERS.filter(([bit]) => flags & bit).map(([, name]) => name[2].toLowerCase() + name.slice(3));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// --- Conversion ------------------------------------------------------------
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Convert SWF bytes. `storeMedia(data, { name, type })` stores extracted media and returns
|
|
263
|
+
* an asset entry (name, kind, type, hash, bytes, src). Returns { project, report, library }.
|
|
264
|
+
*/
|
|
265
|
+
export async function convertSwf(bytes, { name, storeMedia, decompressedLimit = 256 * 1024 * 1024, idPrefix, mode = 'project', maxObjects = 50000 }) {
|
|
266
|
+
if (bytes.length < 8 || !['FWS', 'CWS', 'ZWS'].includes(String.fromCharCode(bytes[0], bytes[1], bytes[2]))) {
|
|
267
|
+
throw new SwfImportError(`${name} is not a SWF file`);
|
|
268
|
+
}
|
|
269
|
+
const declared = (bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24)) >>> 0;
|
|
270
|
+
if (declared > decompressedLimit) throw new SwfImportError(`${name} expands beyond the ${Math.round(decompressedLimit / 1048576)} MB limit`);
|
|
271
|
+
|
|
272
|
+
const diagnostics = new DiagnosticsCollector();
|
|
273
|
+
let doc, tags, symbolTable;
|
|
274
|
+
try {
|
|
275
|
+
({ doc } = await parse(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength), diagnostics));
|
|
276
|
+
({ tags, symbolTable } = decode(doc, diagnostics));
|
|
277
|
+
} catch (error) {
|
|
278
|
+
throw new SwfImportError(`${name} could not be read: ${error.message}`);
|
|
279
|
+
}
|
|
280
|
+
if (!doc?.header) throw new SwfImportError(`${name} could not be read`);
|
|
281
|
+
|
|
282
|
+
const report = createReport(name);
|
|
283
|
+
function finishReport(summary) {
|
|
284
|
+
for (const issue of diagnostics.errors()) report.approximated('Parts of the file that could not be decoded', issue.message);
|
|
285
|
+
return report.finish(summary);
|
|
286
|
+
}
|
|
287
|
+
const prefix = idPrefix ?? `swf${randomBytes(3).toString('hex')}`;
|
|
288
|
+
let sequence = 0;
|
|
289
|
+
const makeId = kind => `${prefix}${kind}${++sequence}`;
|
|
290
|
+
// Very large movies would produce documents the editor cannot hold; stop early instead.
|
|
291
|
+
let objects = 0;
|
|
292
|
+
const countObject = () => {
|
|
293
|
+
if (++objects > maxObjects) {
|
|
294
|
+
throw new SwfImportError(`${name} is too large to edit in Studio: it converts to more than ${maxObjects.toLocaleString('en-US')} objects`, 413);
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
const header = doc.header;
|
|
298
|
+
const version = header.version;
|
|
299
|
+
// Whether any ActionScript can run: frame and init scripts (also inside clips), clip events, or
|
|
300
|
+
// button actions. Scripts can change what the import decides from the timeline alone.
|
|
301
|
+
const SCRIPT_TAGS = new Set([TAG.DoAction, TAG.DoInitAction, TAG.DoABC, TAG.DoABCDefine]);
|
|
302
|
+
const hasActionScript = tags.some(tag => SCRIPT_TAGS.has(tag.code) || ['DoAction', 'DoInitAction', 'DoABC'].includes(tag.type)
|
|
303
|
+
|| tag.clipActions?.length || tag.actions?.some?.(entry => entry.bytecode?.length)
|
|
304
|
+
|| (tag.tags ?? []).some(raw => SCRIPT_TAGS.has(raw.code)));
|
|
305
|
+
|
|
306
|
+
// Scripts are stored once per bytecode and SWF version, and referenced by ID.
|
|
307
|
+
const scripts = [];
|
|
308
|
+
const scriptIds = new Map();
|
|
309
|
+
const frameCarriers = new WeakMap();
|
|
310
|
+
function keepScript(bytes, name) {
|
|
311
|
+
const data = Buffer.from(bytes);
|
|
312
|
+
const carrier = frameCarriers.get(bytes);
|
|
313
|
+
const digest = createHash('sha256').update(String(version));
|
|
314
|
+
if (carrier) digest.update(`:${carrier.prefix.length}:${carrier.offset}:`).update(carrier.prefix);
|
|
315
|
+
const key = digest.update(data).digest('hex');
|
|
316
|
+
let id = scriptIds.get(key);
|
|
317
|
+
if (id) return id;
|
|
318
|
+
id = makeId('scr');
|
|
319
|
+
scriptIds.set(key, id);
|
|
320
|
+
let source = '';
|
|
321
|
+
try {
|
|
322
|
+
const linked = carrier && linkedActionSource(bytes, { code: 253, data: carrier.prefix }, carrier.offset);
|
|
323
|
+
source = transpileAvm1(linked?.bytecode ?? bytes, new DiagnosticsCollector(), { entryOffset: linked?.entryOffset ?? 0 });
|
|
324
|
+
} catch (error) {
|
|
325
|
+
source = `// Readable copy unavailable: ${error.message}`;
|
|
326
|
+
}
|
|
327
|
+
scripts.push({ id, name: shortName(name, 'Script'), language: 'avm1', swfVersion: version, bytecode: data.toString('base64'), source,
|
|
328
|
+
...(carrier && { linkedPrefix: Buffer.from(carrier.prefix).toString('base64') }) });
|
|
329
|
+
return id;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Some movies keep part of a handler in the preceding SWF record. Use the
|
|
333
|
+
// same validated entry point as swf2js before moving it to an editable timeline.
|
|
334
|
+
const buttonPrefixes = new Map();
|
|
335
|
+
function standaloneActions(bytes, previous, offset, length) {
|
|
336
|
+
const linked = linkedActionSource(bytes, previous, offset, length);
|
|
337
|
+
return standaloneLinkedActions(linked.bytecode, linked.entryOffset);
|
|
338
|
+
}
|
|
339
|
+
function resolveLinkedActions(decoded) {
|
|
340
|
+
for (let index = 1; index < decoded.length; index++) {
|
|
341
|
+
const previous = decoded[index - 1], tag = decoded[index];
|
|
342
|
+
if (previous?.code !== 253 || !tag) continue;
|
|
343
|
+
if (tag.type === 'DoAction' || tag.type === 'DoInitAction') {
|
|
344
|
+
const offset = tag.type === 'DoInitAction' ? 2 : 0;
|
|
345
|
+
const linked = linkedActionSource(tag.bytecode, previous, offset);
|
|
346
|
+
if (linked.entryOffset) frameCarriers.set(tag.bytecode, { prefix: previous.data, offset });
|
|
347
|
+
} else if (tag.type === 'Button') buttonPrefixes.set(tag.characterId, previous);
|
|
348
|
+
else for (const action of tag.clipActions ?? []) {
|
|
349
|
+
action.bytecode = standaloneActions(action.bytecode, previous, action.bytecodeOffset, tag.clipActionTagLength);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
resolveLinkedActions(tags);
|
|
354
|
+
|
|
355
|
+
// Stage settings within Studio's ranges.
|
|
356
|
+
const frameSize = header.frameSize;
|
|
357
|
+
const rawWidth = (frameSize.xMax - frameSize.xMin) / 20, rawHeight = (frameSize.yMax - frameSize.yMin) / 20;
|
|
358
|
+
const stage = {
|
|
359
|
+
width: clamp(Math.round(rawWidth), ...stageRanges.width),
|
|
360
|
+
height: clamp(Math.round(rawHeight), ...stageRanges.height),
|
|
361
|
+
frameRate: clamp(header.frameRate || 24, ...stageRanges.frameRate),
|
|
362
|
+
background: parseColor(tags.find(tag => tag?.type === 'SetBackgroundColor')?.color ?? '#ffffff').hex,
|
|
363
|
+
};
|
|
364
|
+
if (stage.width !== rawWidth || stage.height !== rawHeight) {
|
|
365
|
+
report.approximated(`Stage size ${rawWidth}×${rawHeight} adjusted to ${stage.width}×${stage.height}`);
|
|
366
|
+
}
|
|
367
|
+
if (stage.frameRate !== header.frameRate) report.approximated(`Frame rate ${round(header.frameRate)} fps rounded to ${stage.frameRate} fps`);
|
|
368
|
+
const ranges = { x: POSITION_LIMIT, y: POSITION_LIMIT };
|
|
369
|
+
|
|
370
|
+
const jpegTables = tags.find(tag => tag?.type === 'JPEGTables')?.data ?? null;
|
|
371
|
+
const assets = [];
|
|
372
|
+
const bitmapAssets = new Map(), soundAssets = new Map();
|
|
373
|
+
const symbols = [];
|
|
374
|
+
const classBindings = buildSymbolClasses(tags);
|
|
375
|
+
const classCharacters = new Set(classBindings.map(binding => binding.id));
|
|
376
|
+
const soundClassIds = new Map(classBindings.filter(binding => symbolTable.get(binding.id)?.type === 'Sound')
|
|
377
|
+
.map(({ name, id }) => [name.replace('::', '.'), id]));
|
|
378
|
+
const grids = scalingGrids(tags);
|
|
379
|
+
const { buttonSounds, buttonColorTransforms } = buttonSupplementaryTags(tags, symbolTable, diagnostics);
|
|
380
|
+
const buttonTransitions = new Map(buttonSounds.map(tag => [tag.buttonId, tag.sounds]));
|
|
381
|
+
const nestedAbc = [];
|
|
382
|
+
const generated = new Map(), baseSprites = new Map(), baseButtons = new Set();
|
|
383
|
+
const protectedIds = new Set(classCharacters);
|
|
384
|
+
for (const tag of tags) {
|
|
385
|
+
if (tag.type === 'DoInitAction') protectedIds.add(tag.spriteId);
|
|
386
|
+
if (tag.type === 'ExportAssets') for (const entry of tag.assets) protectedIds.add(entry.id);
|
|
387
|
+
}
|
|
388
|
+
const avm2Movie = classCharacters.size > 0 || tags.some(tag => tag.type === 'DoABC');
|
|
389
|
+
const authoringRows = version >= 8 && !avm2Movie ? readAuthoringMetadata(doc.tags) : [];
|
|
390
|
+
// Scenes of a SWF that Studio exported (AVM1 keeps no scene table).
|
|
391
|
+
const studioScenes = authoringRows.filter(row => row[0] === 'n');
|
|
392
|
+
for (const row of authoringRows) {
|
|
393
|
+
const [kind, id, base, loops, stop] = row;
|
|
394
|
+
if (kind === 'n') continue;
|
|
395
|
+
if (protectedIds.has(id) || grids.has(id) || buttonTransitions.has(id)) continue;
|
|
396
|
+
if (kind === 's') {
|
|
397
|
+
if (!matchingSprites(symbolTable.get(base), symbolTable.get(id), loops, stop)) continue;
|
|
398
|
+
baseSprites.set(base, { loops: !!loops, stop: !!stop });
|
|
399
|
+
} else if (kind === 'b') {
|
|
400
|
+
if (symbolTable.get(base)?.type !== 'Button' || symbolTable.get(id)?.type !== 'Button') continue;
|
|
401
|
+
baseButtons.add(base);
|
|
402
|
+
}
|
|
403
|
+
generated.set(id, row);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const nativeClasses = mode === 'project' && avm2Movie;
|
|
407
|
+
const fontIds = new Set(), fontFaces = new Map();
|
|
408
|
+
const libraryId = makeId('lib');
|
|
409
|
+
function keepFontLibrary() {
|
|
410
|
+
if (!nativeClasses && !fontIds.size) return;
|
|
411
|
+
const fontLibrary = { id: libraryId, language: 'swf-library', name: nativeClasses ? 'AS3 class library' : 'Embedded fonts',
|
|
412
|
+
swfVersion: version, bytecode: packClassLibrary(doc, nativeClasses ? null : fontIds) };
|
|
413
|
+
const faces = [...fontFaces.values()].filter(Boolean);
|
|
414
|
+
if (faces.length) fontLibrary.fontFaces = faces;
|
|
415
|
+
scripts.push(fontLibrary);
|
|
416
|
+
}
|
|
417
|
+
const symbolsByCharacter = new Map();
|
|
418
|
+
const partsCache = new Map();
|
|
419
|
+
const scriptedArtwork = new WeakMap();
|
|
420
|
+
const morphs = new Map();
|
|
421
|
+
const morphSources = new Map();
|
|
422
|
+
const morphVariants = new Map();
|
|
423
|
+
const boundsCache = new Map();
|
|
424
|
+
|
|
425
|
+
async function bitmapAsset(id) {
|
|
426
|
+
if (bitmapAssets.has(id)) return bitmapAssets.get(id);
|
|
427
|
+
const bitmap = symbolTable.get(id);
|
|
428
|
+
let result = null;
|
|
429
|
+
if (bitmap?.type === 'Bitmap') {
|
|
430
|
+
try {
|
|
431
|
+
let encoded = encodeBitmap(bitmap, jpegTables);
|
|
432
|
+
if (encoded.alphaData) {
|
|
433
|
+
// Studio images are single files: merge the JPEG's alpha plane into a PNG.
|
|
434
|
+
const merged = mergeJpegAlpha(encoded.data, encoded.alphaData);
|
|
435
|
+
if (merged) encoded = { mimeType: 'image/png', ext: 'png', data: merged };
|
|
436
|
+
else report.approximated('Transparency in JPEG images with invalid color or alpha data', `bitmap ${id}`);
|
|
437
|
+
}
|
|
438
|
+
if (/^image\/(png|jpeg|gif)$/.test(encoded.mimeType)) {
|
|
439
|
+
const size = imageSize(encoded.data) ?? { width: bitmap.width || 1, height: bitmap.height || 1 };
|
|
440
|
+
const stored = await storeMedia(Buffer.from(encoded.data), { name: `bitmap-${id}.${encoded.ext}`, type: encoded.mimeType });
|
|
441
|
+
const asset = { id: makeId('a'), ...stored };
|
|
442
|
+
assets.push(asset);
|
|
443
|
+
result = { asset, ...size };
|
|
444
|
+
} else {
|
|
445
|
+
report.dropped('Images in unsupported formats', `bitmap ${id}`);
|
|
446
|
+
}
|
|
447
|
+
} catch (error) {
|
|
448
|
+
report.dropped('Images that could not be decoded', `bitmap ${id}: ${error.message}`);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
bitmapAssets.set(id, result);
|
|
452
|
+
return result;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async function soundAsset(id) {
|
|
456
|
+
if (soundAssets.has(id)) return soundAssets.get(id);
|
|
457
|
+
const sound = symbolTable.get(id);
|
|
458
|
+
let result = null;
|
|
459
|
+
if (sound?.type === 'Sound') {
|
|
460
|
+
const encoded = encodeSound(sound);
|
|
461
|
+
if (/^audio\//.test(encoded.mimeType)) {
|
|
462
|
+
const stored = await storeMedia(Buffer.from(encoded.data), { name: `sound-${id}.${encoded.ext}`, type: encoded.mimeType });
|
|
463
|
+
const asset = { id: makeId('a'), ...stored };
|
|
464
|
+
assets.push(asset);
|
|
465
|
+
const sampleRate = encoded.sampleRate ?? sound.sampleRate;
|
|
466
|
+
const seconds = (encoded.sampleCount ?? sound.sampleCount) / sampleRate;
|
|
467
|
+
result = { asset, seconds, sampleRate };
|
|
468
|
+
} else {
|
|
469
|
+
report.dropped('Sounds in unsupported codecs', `sound ${id}`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
soundAssets.set(id, result);
|
|
473
|
+
return result;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Event sounds (`StartSound`) on frames `offset`… of a timeline become audio clips: from the
|
|
478
|
+
* frame that starts the sound for its length (times its loop count), within the timeline.
|
|
479
|
+
*/
|
|
480
|
+
async function frameSounds(timeline, frames, offset, where) {
|
|
481
|
+
for (let frame = 1; frame <= timeline.durationFrames; frame++) {
|
|
482
|
+
for (const sound of frames[offset + frame - 1]?.sounds ?? []) {
|
|
483
|
+
const id = sound.soundId ?? soundClassIds.get(sound.soundClassName?.replace('::', '.'));
|
|
484
|
+
if (id == null) { report.dropped('Sound class without a definition', sound.soundClassName ?? where); continue; }
|
|
485
|
+
const source = await soundAsset(id);
|
|
486
|
+
if (!source) continue;
|
|
487
|
+
const info = sound.soundInfo;
|
|
488
|
+
const startSeconds = (info.inPoint ?? 0) / source.sampleRate;
|
|
489
|
+
const endSeconds = Math.min(source.seconds, info.outPoint == null ? source.seconds : info.outPoint / source.sampleRate);
|
|
490
|
+
const duration = (endSeconds - startSeconds) * Math.max(1, info.loopCount ?? 1);
|
|
491
|
+
const end = info.syncStop ? frame : Math.min(timeline.durationFrames, frame + Math.max(0, Math.ceil(duration * stage.frameRate) - 1));
|
|
492
|
+
(timeline.audioClips ??= []).push({ id: makeId('c'), assetId: source.asset.id, start: frame, end,
|
|
493
|
+
loop: (info.loopCount ?? 0) > 1, soundInfo: info,
|
|
494
|
+
...(sound.soundClassName ? { soundClassName: sound.soundClassName } : {}) });
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// Stream headers can change within a timeline. Keep each encoded segment and its sample
|
|
500
|
+
// anchors, including the part of a root stream that continues into the next Studio scene.
|
|
501
|
+
async function streamSounds(streamTags, ranges, where) {
|
|
502
|
+
for (const { start, end, encoded, native } of encodeSoundStreamSegments(streamTags, true)) {
|
|
503
|
+
if (!encoded) continue;
|
|
504
|
+
if (!encoded.streamSync) { report.dropped('Streaming sound in unsupported codecs', where); continue; }
|
|
505
|
+
const sync = encoded.streamSync;
|
|
506
|
+
if (!sync.seekMap.length) continue;
|
|
507
|
+
let asset;
|
|
508
|
+
for (const { timeline, offset } of ranges) {
|
|
509
|
+
const first = Math.max(offset, start, sync.seekMap[0].frame);
|
|
510
|
+
const last = Math.min(offset + timeline.durationFrames, end ?? Infinity);
|
|
511
|
+
if (first >= last) continue;
|
|
512
|
+
if (!asset) {
|
|
513
|
+
const stored = await storeMedia(Buffer.from(encoded.data), { name: 'stream.' + encoded.ext, type: encoded.mimeType });
|
|
514
|
+
asset = { id: makeId('a'), ...stored };
|
|
515
|
+
assets.push(asset);
|
|
516
|
+
}
|
|
517
|
+
// Anchor frames are relative to the clip. Keep the preceding anchor for a scene
|
|
518
|
+
// entered midstream, with the same MP3 latency correction it had in the original.
|
|
519
|
+
const anchor = Math.max(0, sync.seekMap.findLastIndex(block => block.frame <= first));
|
|
520
|
+
const seekMap = [];
|
|
521
|
+
for (let i = anchor; i < sync.seekMap.length && sync.seekMap[i].frame < last; i++) {
|
|
522
|
+
const block = sync.seekMap[i];
|
|
523
|
+
seekMap.push({ ...block, frame: block.frame - first,
|
|
524
|
+
seekSamples: block.seekSamples + (i === anchor && i > 0 ? sync.latencySeek : 0) });
|
|
525
|
+
}
|
|
526
|
+
(timeline.audioClips ??= []).push({ id: makeId('c'), assetId: asset.id, start: first - offset + 1,
|
|
527
|
+
end: last - offset, loop: false, streamSync: { ...sync, seekMap },
|
|
528
|
+
nativeStream: { code: native.code, header: native.header, frame: native.frame - first,
|
|
529
|
+
packets: native.packets.filter(packet => packet.frame >= Math.max(start, offset) && packet.frame < last)
|
|
530
|
+
.map(packet => ({ ...packet, frame: packet.frame - first })) } });
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// Keep where a gradient sits in its shape, relative to the part's box (vector-style.js
|
|
536
|
+
// gradientPlacement), so offset and stretched glows look as authored.
|
|
537
|
+
function placedGradient(gradient, m, box) {
|
|
538
|
+
if (!m) return gradient;
|
|
539
|
+
const cx = box.x + box.w / 2, cy = box.y + box.h / 2;
|
|
540
|
+
// gradientPlacement scales these coefficients by the stored pose dimensions.
|
|
541
|
+
// For a subpixel contour those dimensions are 1 px, while its center stays exact.
|
|
542
|
+
const w = poseSize(box.w, 'width'), h = poseSize(box.h, 'height');
|
|
543
|
+
const r = value => Math.round(value * 1e5) / 1e5;
|
|
544
|
+
return { ...gradient, matrix: {
|
|
545
|
+
a: r(m.a * 819.2 / w), b: r(m.b * 819.2 / h), c: r(m.c * 819.2 / w), d: r(m.d * 819.2 / h),
|
|
546
|
+
tx: r((m.tx - cx) / w), ty: r((m.ty - cy) / h),
|
|
547
|
+
} };
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// A part is one Studio element in the character's own coordinate space.
|
|
551
|
+
function fillStyle(fill, where) {
|
|
552
|
+
if (!fill) return null;
|
|
553
|
+
if (fill.type === 'solid') {
|
|
554
|
+
const color = parseColor(fill.color);
|
|
555
|
+
return { fill: color.hex, alpha: color.alpha };
|
|
556
|
+
}
|
|
557
|
+
if (fill.type === 'linear' || fill.type === 'radial') {
|
|
558
|
+
const stops = fill.stops ?? [];
|
|
559
|
+
const first = parseColor(stops[0]?.color), last = parseColor(stops.at(-1)?.color);
|
|
560
|
+
const gradient = fill.type === 'linear'
|
|
561
|
+
? { type: 'linear', endColor: last.hex, angle: round(Math.atan2(fill.matrix?.b ?? 0, fill.matrix?.a ?? 1) * 180 / Math.PI) }
|
|
562
|
+
: { type: 'radial', endColor: last.hex, focus: clamp(round(fill.focal ?? 0), -1, 1) };
|
|
563
|
+
// Every stop, with its transparency (glows fade to clear).
|
|
564
|
+
const colors = stops.slice(0, 15).map(stop => ({ ...parseColor(stop.color), ratio: clamp((stop.ratio ?? 0) / 255, 0, 1) }));
|
|
565
|
+
if (stops.length > 15) report.approximated('Gradients with more than 15 colors', where);
|
|
566
|
+
if (fill.spreadMode) gradient.spreadMethod = fill.spreadMode === 1 ? 'reflect' : 'repeat';
|
|
567
|
+
if (fill.interpolationMode === 1) gradient.interpolationMethod = 'linearRGB';
|
|
568
|
+
if (colors.length > 2 || colors.length === 2 && (colors[0].ratio !== 0 || colors[1].ratio !== 1) || colors.some(stop => stop.alpha < 1)) {
|
|
569
|
+
let previous = 0;
|
|
570
|
+
gradient.stops = colors.map(stop => {
|
|
571
|
+
previous = Math.max(previous, round(stop.ratio, 4));
|
|
572
|
+
return { ratio: previous, color: stop.hex, alpha: round(stop.alpha, 4) };
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
return { fill: first.hex, alpha: 1, gradient };
|
|
576
|
+
}
|
|
577
|
+
return null;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
async function shapeParts(id, draws, where) {
|
|
581
|
+
const parts = [];
|
|
582
|
+
for (const draw of draws) {
|
|
583
|
+
const shapes = contours(draw.path ?? []);
|
|
584
|
+
if (draw.fill?.type === 'bitmap') {
|
|
585
|
+
const fill = draw.fill;
|
|
586
|
+
const source = await bitmapAsset(fill.bitmapId);
|
|
587
|
+
if (!source) continue;
|
|
588
|
+
const m = fill.matrix ?? IDENTITY;
|
|
589
|
+
const placed = transformBounds(m, { x: 0, y: 0, w: source.width, h: source.height });
|
|
590
|
+
const region = shapes.reduce((box, shape) => unionBounds(box, contourBounds(shape.points)), null);
|
|
591
|
+
if (!region || !region.w || !region.h) continue;
|
|
592
|
+
const straight = !m.b && !m.c && m.a > 0 && m.d > 0;
|
|
593
|
+
if (straight && isRectangle(shapes) && (!fill.repeat || contains(placed, region))) {
|
|
594
|
+
const visible = intersectBounds(region, placed);
|
|
595
|
+
if (!visible) continue;
|
|
596
|
+
const part = { kind: 'bitmap', box: visible, assetId: source.asset.id, smoothed: fill.smoothed, alpha: 1 };
|
|
597
|
+
if (!contains(visible, placed)) {
|
|
598
|
+
part.crop = { x: round((visible.x - m.tx) / m.a, 3), y: round((visible.y - m.ty) / m.d, 3),
|
|
599
|
+
width: round(visible.w / m.a, 3), height: round(visible.h / m.d, 3) };
|
|
600
|
+
}
|
|
601
|
+
parts.push(part);
|
|
602
|
+
} else {
|
|
603
|
+
// A tiled, transformed or shaped fill is an editable path. Keep the image matrix in
|
|
604
|
+
// the path's local space so separate shapes using the same bitmap stay clipped.
|
|
605
|
+
const contours = shapes.filter(shape => shape.points.length >= 3);
|
|
606
|
+
if (!contours.length) continue;
|
|
607
|
+
const matrix = { ...m, tx: m.tx - region.x - region.w / 2, ty: m.ty - region.y - region.h / 2 };
|
|
608
|
+
parts.push({ kind: 'path', box: region, closed: true, points: contours[0].points,
|
|
609
|
+
subpaths: contours.slice(1).map(shape => shape.points), alpha: 1,
|
|
610
|
+
style: { assetId: source.asset.id, bitmapFill: { matrix, repeat: !!fill.repeat, smoothed: !!fill.smoothed }, strokeWidth: 0 } });
|
|
611
|
+
}
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
if (draw.stroke) {
|
|
615
|
+
const paint = fillStyle(draw.stroke.fill, where);
|
|
616
|
+
const color = paint ? { hex: paint.fill, alpha: paint.alpha } : parseColor(draw.stroke.color);
|
|
617
|
+
const bitmap = draw.stroke.fill?.type === 'bitmap' && await bitmapAsset(draw.stroke.fill.bitmapId);
|
|
618
|
+
const width = draw.stroke.width || 1;
|
|
619
|
+
// Flash 8 line ends and corners (0 round, 1 none, 2 square; 0 round, 1 bevel, 2 miter).
|
|
620
|
+
const lineStyle = {};
|
|
621
|
+
const cap = { 1: 'butt', 2: 'square' }[draw.stroke.startCap], join = { 1: 'bevel', 2: 'miter' }[draw.stroke.joinStyle];
|
|
622
|
+
if (cap) lineStyle.lineCap = cap;
|
|
623
|
+
if (join) lineStyle.lineJoin = join;
|
|
624
|
+
if (join === 'miter' && Number.isFinite(draw.stroke.miterLimit)) lineStyle.miterLimit = Math.min(255, Math.max(1, draw.stroke.miterLimit));
|
|
625
|
+
if (draw.stroke.endCap !== undefined && draw.stroke.endCap !== draw.stroke.startCap) report.approximated('Different line ends at each end of a stroke (the start one is kept)', where);
|
|
626
|
+
for (const shape of shapes) {
|
|
627
|
+
// Studio fills closed paths, so outlines stay open and end on their first point. With
|
|
628
|
+
// corners that are not round, the first segment is drawn again so the start is a corner
|
|
629
|
+
// too, not two line ends.
|
|
630
|
+
const start = shape.points[0], second = shape.points[1];
|
|
631
|
+
const points = !shape.closed ? shape.points
|
|
632
|
+
: join && second ? [...shape.points, { x: start.x, y: start.y, handleIn: start.handleIn, handleOut: start.handleOut },
|
|
633
|
+
{ x: second.x, y: second.y, handleIn: second.handleIn, handleOut: { x: 0, y: 0 } }]
|
|
634
|
+
: [...shape.points, { x: start.x, y: start.y, handleIn: start.handleIn, handleOut: { x: 0, y: 0 } }];
|
|
635
|
+
const box = contourBounds(points);
|
|
636
|
+
const style = { fill: color.hex, stroke: color.hex, strokeWidth: round(width), ...lineStyle };
|
|
637
|
+
if (bitmap) {
|
|
638
|
+
const m = draw.stroke.fill.matrix ?? IDENTITY;
|
|
639
|
+
style.bitmapStroke = { assetId: bitmap.asset.id, repeat: !!draw.stroke.fill.repeat,
|
|
640
|
+
smoothed: !!draw.stroke.fill.smoothed, matrix: { ...m, tx: m.tx - box.x - box.w / 2, ty: m.ty - box.y - box.h / 2 } };
|
|
641
|
+
}
|
|
642
|
+
if (paint?.gradient) style.strokeGradient = placedGradient(paint.gradient, draw.stroke.fill.matrix, box);
|
|
643
|
+
parts.push({ kind: 'path', box, points, closed: false, style, alpha: color.alpha });
|
|
644
|
+
}
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
const style = fillStyle(draw.fill, where);
|
|
648
|
+
if (!style) continue;
|
|
649
|
+
const closedShapes = shapes.filter(shape => shape.points.length >= 3);
|
|
650
|
+
// Contours inside another contour of the same fill are its holes (or islands within
|
|
651
|
+
// holes): one compound path, filled even-odd as Flash does.
|
|
652
|
+
const bounds = closedShapes.map(shape => contourBounds(shape.points));
|
|
653
|
+
const area = box => box.w * box.h;
|
|
654
|
+
const outerOf = closedShapes.map((_, i) => {
|
|
655
|
+
let best = -1;
|
|
656
|
+
bounds.forEach((box, j) => {
|
|
657
|
+
if (j === i || !contains(box, bounds[i]) || area(box) <= area(bounds[i])) return;
|
|
658
|
+
if (best < 0 || area(box) < area(bounds[best])) best = j;
|
|
659
|
+
});
|
|
660
|
+
return best;
|
|
661
|
+
});
|
|
662
|
+
const topOf = i => { let at = i; while (outerOf[at] >= 0) at = outerOf[at]; return at; };
|
|
663
|
+
for (const [index, shape] of closedShapes.entries()) {
|
|
664
|
+
if (outerOf[index] >= 0) continue;
|
|
665
|
+
const subpaths = closedShapes.filter((_, j) => j !== index && topOf(j) === index).map(inner => inner.points);
|
|
666
|
+
const part = { kind: 'path', box: bounds[index], points: shape.points, closed: true,
|
|
667
|
+
style: { fill: style.fill, stroke: style.fill, strokeWidth: 0 }, alpha: style.alpha };
|
|
668
|
+
if (subpaths.length) part.subpaths = subpaths;
|
|
669
|
+
// SWF 8 shapes may fill nonzero (UsesFillWindingRule); Studio's compound paths are even-odd.
|
|
670
|
+
if (subpaths.length && draw.evenOdd === false) part.style.fillRule = 'nonzero';
|
|
671
|
+
if (style.gradient) part.style.gradient = placedGradient(style.gradient, draw.fill.matrix, part.box);
|
|
672
|
+
parts.push(part);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
return parts;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* Static text whose glyphs are all embedded outlines, drawn as Flash draws it: one compound
|
|
680
|
+
* path per text run, in the font's own shapes. Returns null when outlines are missing.
|
|
681
|
+
*/
|
|
682
|
+
function glyphTextParts(character) {
|
|
683
|
+
const records = character.records ?? [];
|
|
684
|
+
const outline = (record, glyph) => symbolTable.get(record.fontId)?.glyphs?.[glyph.glyphIndex]?.path;
|
|
685
|
+
if (!records.some(record => record.glyphs?.length)) return null;
|
|
686
|
+
for (const record of records) {
|
|
687
|
+
const font = symbolTable.get(record.fontId);
|
|
688
|
+
for (const glyph of record.glyphs ?? []) {
|
|
689
|
+
const code = font?.codes?.[glyph.glyphIndex];
|
|
690
|
+
if (!outline(record, glyph)?.length && !(code != null && /^\s$/u.test(String.fromCodePoint(code)))) return null;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
const m = character.matrix ?? IDENTITY;
|
|
694
|
+
const parts = [];
|
|
695
|
+
for (const record of records) {
|
|
696
|
+
const font = symbolTable.get(record.fontId);
|
|
697
|
+
const scale = fontOutlineScale(font, Math.max(1, (record.fontHeight || 240) / 20));
|
|
698
|
+
const runX = (record.x || 0) / 20, runY = (record.y || 0) / 20;
|
|
699
|
+
const path = [];
|
|
700
|
+
let cursor = 0;
|
|
701
|
+
for (const glyph of record.glyphs ?? []) {
|
|
702
|
+
const originX = runX + cursor;
|
|
703
|
+
for (const command of outline(record, glyph) ?? []) {
|
|
704
|
+
const out = [command[0]];
|
|
705
|
+
for (let i = 1; i + 1 < command.length; i += 2) {
|
|
706
|
+
const x = originX + command[i] * scale, y = runY + command[i + 1] * scale;
|
|
707
|
+
out.push(m.a * x + m.c * y + m.tx / 20, m.b * x + m.d * y + m.ty / 20);
|
|
708
|
+
}
|
|
709
|
+
path.push(out);
|
|
710
|
+
}
|
|
711
|
+
cursor += defineTextAdvancePixels(glyph.advance);
|
|
712
|
+
}
|
|
713
|
+
const shapes = contours(path).filter(shape => shape.points.length >= 3);
|
|
714
|
+
if (!shapes.length) continue;
|
|
715
|
+
const color = parseColor(record.color ?? '#000000');
|
|
716
|
+
const box = shapes.reduce((all, shape) => unionBounds(all, contourBounds(shape.points)), null);
|
|
717
|
+
const part = { kind: 'path', box, points: shapes[0].points, closed: true,
|
|
718
|
+
style: { fill: color.hex, stroke: color.hex, strokeWidth: 0 }, alpha: color.alpha };
|
|
719
|
+
if (shapes.length > 1) part.subpaths = shapes.slice(1).map(shape => shape.points);
|
|
720
|
+
parts.push(part);
|
|
721
|
+
}
|
|
722
|
+
return parts.length ? parts : null;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function textPart(character, where) {
|
|
726
|
+
const fontId = character.fontId ?? character.records?.[0]?.fontId ??
|
|
727
|
+
(character.fontClass && classBindings.find(binding => binding.name.replace('::', '.') === character.fontClass.replace('::', '.'))?.id);
|
|
728
|
+
const font = symbolTable.get(fontId);
|
|
729
|
+
const nativeFont = font?.type === 'Font' && character.type === 'EditText' &&
|
|
730
|
+
(nativeClasses || character.useOutlines && (font.glyphs?.length || font.fontData));
|
|
731
|
+
const fontFamily = shortName(font?.name, 'Arial').replace(/[^\w\s-]/g, '') || 'Arial';
|
|
732
|
+
if (nativeFont) {
|
|
733
|
+
fontIds.add(fontId);
|
|
734
|
+
if (character.useOutlines && !fontFaces.has(fontId)) {
|
|
735
|
+
const bytes = encodeBrowserFont(font);
|
|
736
|
+
fontFaces.set(fontId, bytes && { id: fontId, family: fontFamily, bold: !!(font.flags & 1), italic: !!(font.flags & 2),
|
|
737
|
+
data: bytes.toString('base64') });
|
|
738
|
+
}
|
|
739
|
+
if (character.useOutlines && !fontFaces.get(fontId)) report.approximated('Embedded font without browser outlines (system font on editing canvas)', where);
|
|
740
|
+
} else if (font?.glyphs?.length && (character.useOutlines || character.type === 'Text')) {
|
|
741
|
+
report.approximated('Embedded fonts (a system font is used)', where);
|
|
742
|
+
}
|
|
743
|
+
const box = character.bounds
|
|
744
|
+
? { x: character.bounds.xMin / 20, y: character.bounds.yMin / 20, w: (character.bounds.xMax - character.bounds.xMin) / 20, h: (character.bounds.yMax - character.bounds.yMin) / 20 }
|
|
745
|
+
: { x: 0, y: 0, w: 100, h: 20 };
|
|
746
|
+
let text, size, color, align = 'left';
|
|
747
|
+
if (character.type === 'EditText') {
|
|
748
|
+
text = String(character.initialText ?? '').replace(/\r\n?/g, '\n');
|
|
749
|
+
if (character.html) text = text.replace(/<[^>]*>/g, '');
|
|
750
|
+
size = (character.fontHeight || 240) / 20;
|
|
751
|
+
color = parseColor(character.color ?? '#000000');
|
|
752
|
+
align = ['left', 'right', 'center', 'left'][character.align | 0];
|
|
753
|
+
} else {
|
|
754
|
+
const records = character.records ?? [];
|
|
755
|
+
text = records.map(record => {
|
|
756
|
+
const recordFont = symbolTable.get(record.fontId);
|
|
757
|
+
return (record.glyphs ?? []).map(glyph => {
|
|
758
|
+
const code = recordFont?.codes?.[glyph.glyphIndex];
|
|
759
|
+
try { return String.fromCodePoint(code ?? 0x20); } catch { return ' '; }
|
|
760
|
+
}).join('');
|
|
761
|
+
}).join(' ');
|
|
762
|
+
size = (records[0]?.fontHeight || 240) / 20;
|
|
763
|
+
color = parseColor(records[0]?.color ?? '#000000');
|
|
764
|
+
if (character.matrix && (character.matrix.a !== 1 || character.matrix.b || character.matrix.c || character.matrix.d !== 1)) {
|
|
765
|
+
report.approximated('Transformed static text', where);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
if (size < 6 || size > 240) report.approximated('Text sizes outside 6–240 px', where);
|
|
769
|
+
return {
|
|
770
|
+
kind: 'text', box, alpha: color.alpha,
|
|
771
|
+
text: {
|
|
772
|
+
text: text || ' ', fontFamily,
|
|
773
|
+
fontSize: clamp(round(size), 6, 240), textColor: color.hex, textAlign: align,
|
|
774
|
+
bold: !!(font?.flags & 1), inputText: character.type === 'EditText' && !character.readOnly,
|
|
775
|
+
},
|
|
776
|
+
// Text field settings scripts depend on: variable bindings (`gateReadout`), HTML, editing.
|
|
777
|
+
field: character.type === 'EditText' ? {
|
|
778
|
+
...(nativeFont && { fontId, fontFamily, fontLibrary: libraryId, useOutlines: !!character.useOutlines }),
|
|
779
|
+
...(character.variableName ? { variable: character.variableName } : {}),
|
|
780
|
+
...(character.html ? { html: true, htmlText: String(character.initialText ?? '') } : {}),
|
|
781
|
+
multiline: !!character.multiline, wordWrap: !!character.wordWrap, editable: !character.readOnly,
|
|
782
|
+
selectable: !character.noSelect, password: !!character.password, border: !!character.border,
|
|
783
|
+
...(character.maxLength ? { maxLength: character.maxLength } : {}),
|
|
784
|
+
} : undefined,
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// Characters become either inline parts or a symbol definition, cached by ID.
|
|
789
|
+
const converting = new Set();
|
|
790
|
+
async function characterPlan(id, where, ratio = 0) {
|
|
791
|
+
const sampled = ratio && symbolTable.get(id)?.type === 'MorphShape';
|
|
792
|
+
const cache = sampled ? morphVariants : partsCache;
|
|
793
|
+
const key = sampled ? `${id}@${ratio}` : id;
|
|
794
|
+
if (cache.has(key)) return cache.get(key);
|
|
795
|
+
if (converting.has(id)) {
|
|
796
|
+
report.dropped('Symbols that contain themselves', where);
|
|
797
|
+
return null;
|
|
798
|
+
}
|
|
799
|
+
converting.add(id);
|
|
800
|
+
try {
|
|
801
|
+
const plan = await convertCharacter(id, where, ratio);
|
|
802
|
+
if (plan?.symbol && grids.has(id)) plan.symbol.definition.scalingGrid = grids.get(id);
|
|
803
|
+
cache.set(key, plan);
|
|
804
|
+
return plan;
|
|
805
|
+
} finally {
|
|
806
|
+
converting.delete(id);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
async function convertCharacter(id, where, ratio) {
|
|
811
|
+
const character = symbolTable.get(id);
|
|
812
|
+
let plan = null;
|
|
813
|
+
const label = `character ${id}`;
|
|
814
|
+
if (!character) {
|
|
815
|
+
report.dropped('References to missing characters', where);
|
|
816
|
+
} else if (character.type === 'Shape' || character.type === 'MorphShape') {
|
|
817
|
+
let draws = [];
|
|
818
|
+
try {
|
|
819
|
+
if (character.type === 'Shape') draws = decodeShape(character.rawData, character.version || 1).draws;
|
|
820
|
+
else {
|
|
821
|
+
if (!morphs.has(id)) {
|
|
822
|
+
const refs = [];
|
|
823
|
+
morphs.set(id, { morph: decodeMorphShape(character.rawData, character.version || 1, refs), refs });
|
|
824
|
+
}
|
|
825
|
+
draws = morphDrawsFor(morphs.get(id), ratio);
|
|
826
|
+
}
|
|
827
|
+
} catch (error) {
|
|
828
|
+
report.dropped('Shapes that could not be decoded', `${label}: ${error.message}`);
|
|
829
|
+
}
|
|
830
|
+
const parts = await shapeParts(id, draws, label);
|
|
831
|
+
if (character.type === 'MorphShape' && parts.length) {
|
|
832
|
+
const symbol = await partsSymbol(`Morph ${id} · ${ratio}/65535`, parts);
|
|
833
|
+
let source = morphSources.get(id);
|
|
834
|
+
if (!source) {
|
|
835
|
+
const bitmaps = [];
|
|
836
|
+
for (const bitmapId of new Set(morphs.get(id).refs.map(ref => ref.id))) {
|
|
837
|
+
const bitmap = await bitmapAsset(bitmapId);
|
|
838
|
+
if (bitmap) bitmaps.push({ id: bitmapId, asset: bitmap.asset.id });
|
|
839
|
+
}
|
|
840
|
+
source = { id: makeId('morph'), bitmaps };
|
|
841
|
+
morphSources.set(id, source);
|
|
842
|
+
scripts.push({ id: source.id, language: 'swf-morph', name: `Morph ${id}`, swfVersion: version,
|
|
843
|
+
bytecode: Buffer.from(character.rawData).toString('base64') });
|
|
844
|
+
}
|
|
845
|
+
symbol.definition.nativeMorph = { source: source.id, version: character.version || 1, ratio, bitmaps: source.bitmaps,
|
|
846
|
+
fingerprint: importedMorphFingerprint(symbol.definition) };
|
|
847
|
+
plan = { symbol };
|
|
848
|
+
} else if (parts.length === 1) plan = { parts };
|
|
849
|
+
else if (parts.length > 1) {
|
|
850
|
+
const symbol = await partsSymbol(`Shape ${id}`, parts);
|
|
851
|
+
symbol.definition.compoundShape = true;
|
|
852
|
+
plan = { symbol };
|
|
853
|
+
}
|
|
854
|
+
} else if (character.type === 'Bitmap') {
|
|
855
|
+
const source = await bitmapAsset(id);
|
|
856
|
+
if (source) plan = { parts: [{ kind: 'bitmap', box: { x: 0, y: 0, w: source.width, h: source.height }, assetId: source.asset.id, alpha: 1 }] };
|
|
857
|
+
} else if (character.type === 'Text' && glyphTextParts(character)) {
|
|
858
|
+
// Embedded-font static text keeps its exact look as vector outlines.
|
|
859
|
+
const parts = glyphTextParts(character);
|
|
860
|
+
plan = parts.length === 1 ? { parts } : { symbol: await partsSymbol(`Text ${id}`, parts) };
|
|
861
|
+
} else if (character.type === 'Text' || character.type === 'EditText') {
|
|
862
|
+
plan = { parts: [textPart(character, label)] };
|
|
863
|
+
} else if (character.type === 'Sprite') {
|
|
864
|
+
const row = generated.get(id);
|
|
865
|
+
if (row?.[0] === 's') {
|
|
866
|
+
const base = await characterPlan(row[2], where);
|
|
867
|
+
if (base?.symbol) return { symbol: { ...base.symbol, mode: row[3] ? 'once' : 'loop' } };
|
|
868
|
+
}
|
|
869
|
+
const symbol = await spriteSymbol(id, character);
|
|
870
|
+
if (symbol) plan = { symbol };
|
|
871
|
+
} else if (character.type === 'Button') {
|
|
872
|
+
plan = await buttonPlan(id, character, label);
|
|
873
|
+
} else if (character.type === 'VideoStream') {
|
|
874
|
+
report.dropped('Video', label);
|
|
875
|
+
} else {
|
|
876
|
+
report.dropped(`${character.type} characters`, label);
|
|
877
|
+
}
|
|
878
|
+
if (classCharacters.has(id) && plan?.parts?.length && character.type !== 'Bitmap') {
|
|
879
|
+
plan = { symbol: await partsSymbol(`Character ${id}`, plan.parts) };
|
|
880
|
+
}
|
|
881
|
+
return plan;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
async function characterBounds(id) {
|
|
885
|
+
if (boundsCache.has(id)) return boundsCache.get(id);
|
|
886
|
+
boundsCache.set(id, null); // Cycle guard.
|
|
887
|
+
const plan = await characterPlan(id);
|
|
888
|
+
let box = null;
|
|
889
|
+
if (plan?.parts) box = plan.parts.reduce((all, part) => unionBounds(all, part.box), null);
|
|
890
|
+
else if (plan?.symbol) box = plan.symbol.box;
|
|
891
|
+
boundsCache.set(id, box);
|
|
892
|
+
return box;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
function newTimeline(nameText, durationFrames) {
|
|
896
|
+
const timeline = { id: makeId('t'), name: shortName(nameText, 'Timeline'), durationFrames, startFrame: 1, loop: false, layers: [], elements: [] };
|
|
897
|
+
return timeline;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
// Studio artboards have size limits. Instances map the whole artboard, so the box an
|
|
901
|
+
// instance uses must be the artboard itself, anchored at the content's top-left corner.
|
|
902
|
+
function artboard(symbol, content) {
|
|
903
|
+
symbol.width = clamp(Math.ceil(content.w) || 1, ...stageRanges.width);
|
|
904
|
+
symbol.height = clamp(Math.ceil(content.h) || 1, ...stageRanges.height);
|
|
905
|
+
if (Math.ceil(content.w) > stageRanges.width[1] || Math.ceil(content.h) > stageRanges.height[1]) {
|
|
906
|
+
report.approximated('Symbols larger than the largest artboard (content extends past it)', symbol.name);
|
|
907
|
+
}
|
|
908
|
+
return { x: content.x, y: content.y, w: symbol.width, h: symbol.height };
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
async function partsSymbol(nameText, parts) {
|
|
912
|
+
const box = parts.reduce((all, part) => unionBounds(all, part.box), null);
|
|
913
|
+
const symbol = newTimeline(nameText, 1);
|
|
914
|
+
symbol.id = makeId('sym');
|
|
915
|
+
const layer = { id: makeId('l'), name: 'Artwork', visible: true, locked: false, order: 0 };
|
|
916
|
+
symbol.layers.push(layer);
|
|
917
|
+
const offset = { a: 1, b: 0, c: 0, d: 1, tx: -box.x, ty: -box.y };
|
|
918
|
+
for (const part of parts) {
|
|
919
|
+
const element = partElement(part, `${nameText} part`, layer.id);
|
|
920
|
+
const pose = partPose(part, offset, 1);
|
|
921
|
+
element.keyframes = [{ frame: 1, ...pose.pose, tween: 'hold' }];
|
|
922
|
+
Object.assign(element, pose.pose);
|
|
923
|
+
if (pose.points) element.points = pose.points;
|
|
924
|
+
if (pose.subpaths) element.subpaths = pose.subpaths;
|
|
925
|
+
symbol.elements.push(element);
|
|
926
|
+
}
|
|
927
|
+
const frame = artboard(symbol, box);
|
|
928
|
+
symbol.origin = { x: round(box.x, 3), y: round(box.y, 3) };
|
|
929
|
+
symbols.push(symbol);
|
|
930
|
+
return { id: symbol.id, box: frame, definition: symbol, mode: 'single' };
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
function partElement(part, nameText, layerId) {
|
|
934
|
+
countObject();
|
|
935
|
+
const element = { id: makeId('e'), name: shortName(nameText, 'Object'), layerId };
|
|
936
|
+
if (part.kind === 'path') {
|
|
937
|
+
Object.assign(element, { type: 'path', closed: part.closed, ...part.style });
|
|
938
|
+
if (part.style.gradient) element.gradient = part.style.gradient;
|
|
939
|
+
} else if (part.kind === 'bitmap') {
|
|
940
|
+
Object.assign(element, { type: 'bitmap', assetId: part.assetId, fit: 'stretch' });
|
|
941
|
+
if (part.crop) element.crop = part.crop;
|
|
942
|
+
if (part.smoothed !== undefined) element.smoothed = part.smoothed;
|
|
943
|
+
} else if (part.kind === 'text') {
|
|
944
|
+
const { inputText, ...text } = part.text;
|
|
945
|
+
Object.assign(element, { type: 'text', ...text });
|
|
946
|
+
if (inputText) element.inputText = true;
|
|
947
|
+
if (part.field) element.field = part.field;
|
|
948
|
+
}
|
|
949
|
+
return element;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* Pose for a part placed by matrix `m`. Paths absorb mirroring into their points;
|
|
954
|
+
* other parts report it. `alpha` multiplies the part's own alpha.
|
|
955
|
+
*/
|
|
956
|
+
function partPose(part, m, alpha, where, notes = null) {
|
|
957
|
+
// Notes collect per-object approximations so each object is reported once, not per frame.
|
|
958
|
+
const note = feature => notes ? notes.add(feature) : report.approximated(feature, where);
|
|
959
|
+
const box = part.box;
|
|
960
|
+
const center = { x: box.x + box.w / 2, y: box.y + box.h / 2 };
|
|
961
|
+
let linear = { ...m, tx: 0, ty: 0 };
|
|
962
|
+
let points;
|
|
963
|
+
let flip = 1;
|
|
964
|
+
let mirror = false;
|
|
965
|
+
if (decompose(linear).mirrored) {
|
|
966
|
+
if (part.kind === 'path' && !part.style.bitmapStroke && !part.style.bitmapFill && !part.style.gradient && !part.style.strokeGradient) {
|
|
967
|
+
flip = -1;
|
|
968
|
+
linear = multiply(linear, { a: 1, b: 0, c: 0, d: -1, tx: 0, ty: 0 });
|
|
969
|
+
} else {
|
|
970
|
+
// Kept as `mirror`: the pose flips the object in its own space (see model.js).
|
|
971
|
+
mirror = true;
|
|
972
|
+
linear = multiply(linear, { a: 1, b: 0, c: 0, d: -1, tx: 0, ty: 0 });
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
const local = contour => contour.map(point => ({
|
|
976
|
+
x: round(point.x - center.x), y: round((point.y - center.y) * flip),
|
|
977
|
+
handleIn: { x: round(point.handleIn.x), y: round(point.handleIn.y * flip) },
|
|
978
|
+
handleOut: { x: round(point.handleOut.x), y: round(point.handleOut.y * flip) },
|
|
979
|
+
}));
|
|
980
|
+
let subpaths;
|
|
981
|
+
if (part.kind === 'path') {
|
|
982
|
+
points = local(part.points);
|
|
983
|
+
if (part.subpaths?.length) subpaths = part.subpaths.map(local);
|
|
984
|
+
}
|
|
985
|
+
const world = apply(m, center.x, center.y);
|
|
986
|
+
const parts = decompose(linear);
|
|
987
|
+
if (Math.abs(parts.skew) > 85) note('Extreme skew (limited to 85°)');
|
|
988
|
+
// Below 1% (Flash scales objects from 0 to make them pop in) the object is too small to see,
|
|
989
|
+
// so it imports as hidden at Studio's smallest scale instead of a visible speck. Not for
|
|
990
|
+
// clips and text in scripted movies: a script may grow them (`_xscale += 10`) without
|
|
991
|
+
// touching their opacity, so they stay at 1%.
|
|
992
|
+
const scriptable = part.kind === 'symbol' || part.kind === 'text' || part.kind === 'button';
|
|
993
|
+
const vanishing = (parts.scaleX < 0.01 || parts.scaleY < 0.01) && !(scriptable && hasActionScript);
|
|
994
|
+
if ((parts.scaleX < 0.01 || parts.scaleY < 0.01) && !vanishing) note('Movie clips scaled below 1% in scripted movies (shown at 1%)');
|
|
995
|
+
if (parts.scaleX > 100 || parts.scaleY > 100) note('Scales above 10000%');
|
|
996
|
+
const x = clamp(round(world.x), -ranges.x, ranges.x), y = clamp(round(world.y), -ranges.y, ranges.y);
|
|
997
|
+
if (x !== round(world.x) || y !== round(world.y)) note('Objects far outside the stage (moved closer)');
|
|
998
|
+
return {
|
|
999
|
+
pose: {
|
|
1000
|
+
x, y,
|
|
1001
|
+
width: poseSize(box.w, 'width'), height: poseSize(box.h, 'height'),
|
|
1002
|
+
scaleX: clamp(round(parts.scaleX, 4), 0.01, 100), scaleY: clamp(round(parts.scaleY, 4), 0.01, 100),
|
|
1003
|
+
rotation: round(parts.rotation), skew: clamp(round(parts.skew), -85, 85),
|
|
1004
|
+
opacity: vanishing ? 0 : clamp(round(alpha * (part.alpha ?? 1), 3), 0, 1),
|
|
1005
|
+
...(mirror ? { mirror: true } : {}),
|
|
1006
|
+
},
|
|
1007
|
+
points,
|
|
1008
|
+
subpaths,
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
async function buttonPlan(id, character, label) {
|
|
1013
|
+
let button;
|
|
1014
|
+
try {
|
|
1015
|
+
button = decodeButton(character.rawData, character.version || 2, buttonColorTransforms.get(id));
|
|
1016
|
+
for (const action of button.actions ?? []) {
|
|
1017
|
+
action.bytecode = standaloneActions(action.bytecode, buttonPrefixes.get(id), action.bytecodeOffset, character.rawData.length);
|
|
1018
|
+
}
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
report.dropped('Buttons that could not be decoded', `${label}: ${error.message}`);
|
|
1021
|
+
return null;
|
|
1022
|
+
}
|
|
1023
|
+
const row = generated.get(id);
|
|
1024
|
+
const entry = button.actions?.at(-1);
|
|
1025
|
+
const triggers = entry && buttonTriggers(entry.conditions);
|
|
1026
|
+
if (row && entry?.bytecode?.length && triggers.on.length === 1 && triggers.on[0] === 'release') {
|
|
1027
|
+
let basePlan;
|
|
1028
|
+
if (row[0] === 'w' && mode !== 'library' && button.actions.length === 1 && !button.trackAsMenu) {
|
|
1029
|
+
const identity = Object.values(button.stateRecords).every(records => {
|
|
1030
|
+
if (records.length !== 1) return false;
|
|
1031
|
+
const { characterId, depth, matrix, colorTransform, filters, blendMode } = records[0];
|
|
1032
|
+
return characterId === row[2] && depth === 1 && !filters?.length && !blendMode &&
|
|
1033
|
+
Object.entries(IDENTITY).every(([key, value]) => matrix[key] === value) &&
|
|
1034
|
+
Object.entries(colorTransform ?? {}).every(([key, value]) => value === (key.endsWith('Mult') ? 256 : 0));
|
|
1035
|
+
});
|
|
1036
|
+
if (identity) {
|
|
1037
|
+
const artwork = await characterPlan(row[2], label);
|
|
1038
|
+
if (artwork?.parts?.length === 1 && !artwork.parts[0].field?.editable) basePlan = artwork;
|
|
1039
|
+
}
|
|
1040
|
+
} else if (row[0] === 'b') {
|
|
1041
|
+
const original = symbolTable.get(row[2]);
|
|
1042
|
+
let base;
|
|
1043
|
+
try { base = decodeButton(original.rawData, original.version || 2, buttonColorTransforms.get(row[2])); }
|
|
1044
|
+
catch { /* The ordinary import below reports damaged artwork. */ }
|
|
1045
|
+
if (base && base.trackAsMenu === button.trackAsMenu && base.actions.length + 1 === button.actions.length &&
|
|
1046
|
+
JSON.stringify(base.states) === JSON.stringify(button.states) &&
|
|
1047
|
+
base.actions.every((action, index) => JSON.stringify(action.conditions) === JSON.stringify(button.actions[index].conditions) &&
|
|
1048
|
+
Buffer.from(action.bytecode).equals(button.actions[index].bytecode))) {
|
|
1049
|
+
basePlan = await characterPlan(row[2], label);
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
if (basePlan) {
|
|
1053
|
+
const simple = simpleActions(entry.bytecode);
|
|
1054
|
+
return simple?.length === 1 ? { ...basePlan, action: simple[0] } :
|
|
1055
|
+
{ ...basePlan, action: { op: 'script', script: keepScript(entry.bytecode, `Button ${id}: on (release)`) } };
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
// Like Flash's own button timelines: frames 1–4 hold the Up, Over, Down, and Hit states.
|
|
1059
|
+
const frames = ['up', 'over', 'down', 'hit'].map((state, frameIndex) => ({
|
|
1060
|
+
frameIndex, removes: frameIndex ? [...new Set(['up', 'over', 'down', 'hit'].slice(0, frameIndex)
|
|
1061
|
+
.flatMap(previous => (button.stateRecords[previous] ?? []).map(record => record.depth)))] : [],
|
|
1062
|
+
places: (button.stateRecords[state] ?? []).map(record => ({
|
|
1063
|
+
depth: record.depth, characterId: record.characterId, move: false, matrix: record.matrix ?? IDENTITY,
|
|
1064
|
+
colorTransform: record.colorTransform, filters: record.filters, blendMode: record.blendMode,
|
|
1065
|
+
})),
|
|
1066
|
+
}));
|
|
1067
|
+
// Buttons with no art are keyboard listeners (on (keyPress …)); they stay.
|
|
1068
|
+
const symbol = await timelineSymbol(`Button ${id}`, frames, [], label, { allowEmpty: true });
|
|
1069
|
+
if (!symbol) return null;
|
|
1070
|
+
symbol.mode = 'single';
|
|
1071
|
+
symbol.definition.button = true;
|
|
1072
|
+
if (button.trackAsMenu) symbol.definition.trackAsMenu = true;
|
|
1073
|
+
for (const [transition, cue] of Object.entries(buttonTransitions.get(id) ?? {})) {
|
|
1074
|
+
const source = await soundAsset(cue.soundId);
|
|
1075
|
+
if (source) (symbol.definition.buttonSounds ??= {})[transition] = { assetId: source.asset.id, soundInfo: cue.soundInfo };
|
|
1076
|
+
}
|
|
1077
|
+
// A single release with one constant navigation stays a typed, editable button action.
|
|
1078
|
+
// Anything else keeps every handler as a script on the button symbol.
|
|
1079
|
+
const entries = (button.actions ?? []).filter(entry => entry.bytecode?.length);
|
|
1080
|
+
const only = entries.length === 1 ? entries[0] : null;
|
|
1081
|
+
const simple = only && simpleActions(only.bytecode);
|
|
1082
|
+
const conditions = only ? buttonTriggers(only.conditions) : null;
|
|
1083
|
+
if (!baseButtons.has(id) && simple?.length === 1 && conditions.on.length === 1 && conditions.on[0] === 'release') return { symbol, action: simple[0] };
|
|
1084
|
+
const events = [];
|
|
1085
|
+
for (const entry of entries) {
|
|
1086
|
+
const { on, key } = buttonTriggers(entry.conditions);
|
|
1087
|
+
if (!on.length) continue;
|
|
1088
|
+
events.push({ on, ...(key ? { key } : {}), script: keepScript(entry.bytecode, `${symbol.definition.name}: on (${on.join(', ')})`) });
|
|
1089
|
+
}
|
|
1090
|
+
if (events.length) symbol.definition.scriptEvents = events;
|
|
1091
|
+
return { symbol, action: null };
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
async function spriteSymbol(id, character) {
|
|
1095
|
+
const authored = baseSprites.get(id);
|
|
1096
|
+
const rawTags = character.tags ?? [];
|
|
1097
|
+
const stop = authored?.stop ? finalStopIndex(rawTags) : -1;
|
|
1098
|
+
const decoded = (stop < 0 ? rawTags : rawTags.filter((_, i) => i !== stop)).map(raw => {
|
|
1099
|
+
try {
|
|
1100
|
+
return decodeTag(raw, { header: { version } }, diagnostics);
|
|
1101
|
+
} catch {
|
|
1102
|
+
return { type: 'Unknown' };
|
|
1103
|
+
}
|
|
1104
|
+
});
|
|
1105
|
+
resolveLinkedActions(decoded);
|
|
1106
|
+
const frames = buildFramesFromTags(decoded);
|
|
1107
|
+
frames.length = Math.max(frames.length, character.frameCount ?? 1);
|
|
1108
|
+
const name = character.name ? character.name : `Sprite ${id}`;
|
|
1109
|
+
// Empty clips stay: scripts draw into them, attach symbols to them, or use them as controllers.
|
|
1110
|
+
const symbol = await timelineSymbol(name, frames, decoded, `sprite ${id}`, { allowEmpty: true });
|
|
1111
|
+
if (symbol) {
|
|
1112
|
+
symbol.definition.loop = authored?.loops ?? true;
|
|
1113
|
+
if (decoded.some(tag => tag?.type === 'DoABC' || tag?.type === 'SymbolClass')) nestedAbc.push({ symbol: symbol.definition, decoded });
|
|
1114
|
+
// Sounds the symbol's own timeline starts, and its sound stream when it has sound data
|
|
1115
|
+
// (Flash writes an empty stream header into most symbols).
|
|
1116
|
+
await frameSounds(symbol.definition, frames, 0, `sprite ${id}`);
|
|
1117
|
+
await streamSounds(decoded, [{ timeline: symbol.definition, offset: 0 }], `sprite ${id}`);
|
|
1118
|
+
}
|
|
1119
|
+
return symbol;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
/** Convert frames into a symbol definition whose artboard covers all its content. */
|
|
1123
|
+
async function timelineSymbol(nameText, frames, decodedTags, where, { allowEmpty = false } = {}) {
|
|
1124
|
+
const built = await buildTimeline(frames, decodedTags, { where, maxFrames: MAX_TIMELINE_FRAMES });
|
|
1125
|
+
if (!built.box && !allowEmpty) return null;
|
|
1126
|
+
const box = built.box ?? { x: 0, y: 0, w: 1, h: 1 };
|
|
1127
|
+
const symbol = newTimeline(nameText, built.durationFrames);
|
|
1128
|
+
symbol.id = makeId('sym');
|
|
1129
|
+
const offset = { a: 1, b: 0, c: 0, d: 1, tx: -box.x, ty: -box.y };
|
|
1130
|
+
const frame = artboard(symbol, box);
|
|
1131
|
+
// The artboard's top-left in the symbol's own coordinates. Scripts move and scale clips
|
|
1132
|
+
// around this registration point, so playback restores it.
|
|
1133
|
+
symbol.origin = { x: round(box.x, 3), y: round(box.y, 3) };
|
|
1134
|
+
symbols.push(symbol);
|
|
1135
|
+
const result = { id: symbol.id, box: frame, definition: symbol };
|
|
1136
|
+
await built.emit(symbol, offset);
|
|
1137
|
+
return result;
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
/**
|
|
1141
|
+
* Simulate a timeline's display list. Returns its duration, content bounds, and an `emit`
|
|
1142
|
+
* function that writes layers, elements, events, and audio clips into a Studio timeline.
|
|
1143
|
+
*/
|
|
1144
|
+
async function buildTimeline(frames, decodedTags, { where, maxFrames, range }) {
|
|
1145
|
+
const first = range?.start ?? 0;
|
|
1146
|
+
const last = Math.min(range?.end ?? frames.length, first + maxFrames);
|
|
1147
|
+
if ((range?.end ?? frames.length) - first > maxFrames) report.approximated(`Timelines longer than ${maxFrames} frames (truncated)`, where);
|
|
1148
|
+
const durationFrames = Math.max(1, last - first);
|
|
1149
|
+
const display = new Map();
|
|
1150
|
+
const instances = [];
|
|
1151
|
+
let box = null;
|
|
1152
|
+
|
|
1153
|
+
// Clip actions (onClipEvent) by "frame:depth"; buildFramesFromTags does not carry them.
|
|
1154
|
+
const clipActionsAt = new Map();
|
|
1155
|
+
{
|
|
1156
|
+
let frameIndex = 0;
|
|
1157
|
+
for (const tag of decodedTags ?? []) {
|
|
1158
|
+
if (tag?.type === 'ShowFrame') frameIndex++;
|
|
1159
|
+
else if (tag?.clipActions?.length) clipActionsAt.set(`${frameIndex}:${tag.depth}`, tag.clipActions);
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
// Apply frames before the range so the display list is correct at its start.
|
|
1164
|
+
const step = (frame, frameIndex) => {
|
|
1165
|
+
for (const depth of frame.removes ?? []) display.delete(depth);
|
|
1166
|
+
for (const place of frame.places ?? []) {
|
|
1167
|
+
if (place.remove) { display.delete(place.depth); continue; }
|
|
1168
|
+
if (place.tabIndex !== undefined && place.characterId === undefined && !place.matrix) continue;
|
|
1169
|
+
const existing = display.get(place.depth);
|
|
1170
|
+
const replaces = place.characterId !== undefined && (!place.move || !existing || existing.characterId !== place.characterId);
|
|
1171
|
+
// A move that names a new character swaps it in place: the new character keeps the
|
|
1172
|
+
// transform, color, name and clip depth already at that depth (button states do this).
|
|
1173
|
+
const swaps = replaces && place.move && existing;
|
|
1174
|
+
const state = replaces
|
|
1175
|
+
? swaps
|
|
1176
|
+
? { ...existing, characterId: place.characterId, ratio: place.ratio, serial: Symbol('instance') }
|
|
1177
|
+
: { characterId: place.characterId, matrix: IDENTITY, colorTransform: null, filters: null, name: place.name, clipDepth: place.clipDepth, visible: true, ratio: place.ratio, serial: Symbol('instance') }
|
|
1178
|
+
: existing ? { ...existing } : null;
|
|
1179
|
+
if (!state) continue;
|
|
1180
|
+
// Placement translations are in twips; shape geometry is already in pixels.
|
|
1181
|
+
if (place.matrix) state.matrix = { ...place.matrix, tx: place.matrix.tx / 20, ty: place.matrix.ty / 20 };
|
|
1182
|
+
if (place.colorTransform) state.colorTransform = place.colorTransform;
|
|
1183
|
+
if (place.filters) state.filters = place.filters;
|
|
1184
|
+
if (place.name != null) state.name = place.name;
|
|
1185
|
+
if (place.clipDepth != null) state.clipDepth = place.clipDepth;
|
|
1186
|
+
if (place.visible != null) state.visible = !!place.visible;
|
|
1187
|
+
if (place.ratio != null) {
|
|
1188
|
+
// Studio stores each authored morph exposure as editable paths. Reuse its
|
|
1189
|
+
// decoded artwork at repeated ratios, including reversals and holds.
|
|
1190
|
+
if (!replaces && place.ratio !== (state.ratio ?? 0) && symbolTable.get(state.characterId)?.type === 'MorphShape') {
|
|
1191
|
+
state.serial = Symbol('morph exposure');
|
|
1192
|
+
}
|
|
1193
|
+
state.ratio = place.ratio;
|
|
1194
|
+
}
|
|
1195
|
+
if (place.blendMode !== undefined) state.blendMode = place.blendMode;
|
|
1196
|
+
if (replaces) state.clipActions = clipActionsAt.get(`${frameIndex}:${place.depth}`);
|
|
1197
|
+
display.set(place.depth, state);
|
|
1198
|
+
}
|
|
1199
|
+
};
|
|
1200
|
+
for (let index = 0; index < first; index++) if (frames[index]) step(frames[index], index);
|
|
1201
|
+
const open = new Map();
|
|
1202
|
+
for (let index = first; index < last; index++) {
|
|
1203
|
+
step(frames[index] ?? { places: [], removes: [] }, index);
|
|
1204
|
+
const frame = index - first + 1;
|
|
1205
|
+
for (const [depth, state] of display) {
|
|
1206
|
+
let instance = open.get(depth);
|
|
1207
|
+
if (!instance || instance.serial !== state.serial) {
|
|
1208
|
+
if (instance) instance.end = frame;
|
|
1209
|
+
instance = { depth, serial: state.serial, characterId: state.characterId, name: state.name, start: frame, end: null, states: [], clipDepth: state.clipDepth, clipActions: state.clipActions };
|
|
1210
|
+
instances.push(instance);
|
|
1211
|
+
open.set(depth, instance);
|
|
1212
|
+
}
|
|
1213
|
+
// Placements create a new state object only when something changes.
|
|
1214
|
+
if (instance.last !== state) {
|
|
1215
|
+
instance.states.push({ frame, ...state });
|
|
1216
|
+
instance.last = state;
|
|
1217
|
+
}
|
|
1218
|
+
if (state.clipDepth) instance.clipDepth = state.clipDepth;
|
|
1219
|
+
}
|
|
1220
|
+
for (const [depth, instance] of open) {
|
|
1221
|
+
if (!display.has(depth)) { instance.end = frame; open.delete(depth); }
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
for (const instance of instances) {
|
|
1226
|
+
let plan = await characterPlan(instance.characterId, where, instance.states[0].ratio);
|
|
1227
|
+
if (plan?.parts && instance.clipActions?.length) {
|
|
1228
|
+
if (!scriptedArtwork.has(plan)) {
|
|
1229
|
+
const symbol = await partsSymbol(`Character ${instance.characterId}`, plan.parts);
|
|
1230
|
+
scriptedArtwork.set(plan, { ...plan, parts: undefined, symbol });
|
|
1231
|
+
}
|
|
1232
|
+
plan = scriptedArtwork.get(plan);
|
|
1233
|
+
}
|
|
1234
|
+
instance.plan = plan;
|
|
1235
|
+
if (!plan) continue;
|
|
1236
|
+
const local = plan.parts ? plan.parts.reduce((all, part) => unionBounds(all, part.box), null) : plan.symbol.box;
|
|
1237
|
+
for (const state of instance.states) box = unionBounds(box, transformBounds(state.matrix, local));
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
// Flash often cycles the same artwork through a depth thousands of times. Each return
|
|
1241
|
+
// after a blank exposure can live on its previous Studio track. Mask links and script
|
|
1242
|
+
// handlers belong to individual placements and keep their own tracks.
|
|
1243
|
+
const masks = instances.filter(instance => instance.clipDepth);
|
|
1244
|
+
const shapeTracks = new Map();
|
|
1245
|
+
const tracks = instances.filter(instance => {
|
|
1246
|
+
if (!instance.plan?.symbol || symbolTable.get(instance.characterId)?.type !== 'Shape' || instance.clipActions?.length ||
|
|
1247
|
+
masks.some(mask => instance.depth >= mask.depth && instance.depth <= mask.clipDepth)) return true;
|
|
1248
|
+
const state = instance.states[0];
|
|
1249
|
+
const matrix = state.matrix;
|
|
1250
|
+
const key = JSON.stringify([instance.depth, instance.characterId, instance.name, state.filters, state.colorTransform,
|
|
1251
|
+
state.blendMode, matrix.a * matrix.d < matrix.b * matrix.c]);
|
|
1252
|
+
const previous = shapeTracks.get(key);
|
|
1253
|
+
if (!previous || previous.end == null || previous.end >= instance.start) {
|
|
1254
|
+
shapeTracks.set(key, instance);
|
|
1255
|
+
return true;
|
|
1256
|
+
}
|
|
1257
|
+
previous.states.push({ frame: previous.end, blank: true });
|
|
1258
|
+
for (const state of instance.states) previous.states.push(state);
|
|
1259
|
+
previous.end = instance.end;
|
|
1260
|
+
return false;
|
|
1261
|
+
});
|
|
1262
|
+
|
|
1263
|
+
// Frame actions and sounds from the tag stream.
|
|
1264
|
+
const actionsByFrame = new Map();
|
|
1265
|
+
let frameIndex = 0;
|
|
1266
|
+
for (const tag of decodedTags ?? []) {
|
|
1267
|
+
if (!tag) continue;
|
|
1268
|
+
if (tag.type === 'ShowFrame') { frameIndex++; continue; }
|
|
1269
|
+
if (tag.type === 'DoAction' && frameIndex >= first && frameIndex < last) {
|
|
1270
|
+
const list = actionsByFrame.get(frameIndex) ?? [];
|
|
1271
|
+
list.push(tag.bytecode ?? new Uint8Array());
|
|
1272
|
+
actionsByFrame.set(frameIndex, list);
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
const labels = new Map();
|
|
1276
|
+
frames.forEach((frame, index) => { for (const name of frame.labels ?? (frame.label ? [frame.label] : [])) labels.set(name, index); });
|
|
1277
|
+
|
|
1278
|
+
async function emit(timeline, offset, { resolveFrame } = {}) {
|
|
1279
|
+
const layers = new Map();
|
|
1280
|
+
const elementsByInstance = new Map();
|
|
1281
|
+
const sortedDepths = [...new Set(instances.filter(item => item.plan).map(item => item.depth))].sort((a, b) => a - b);
|
|
1282
|
+
sortedDepths.forEach((depth, order) => {
|
|
1283
|
+
const named = instances.find(item => item.depth === depth && item.name)?.name;
|
|
1284
|
+
const layer = { id: makeId('l'), name: shortName(named, `Depth ${depth}`), visible: true, locked: false, order };
|
|
1285
|
+
layers.set(depth, layer);
|
|
1286
|
+
timeline.layers.push(layer);
|
|
1287
|
+
});
|
|
1288
|
+
if (!timeline.layers.length) timeline.layers.push({ id: makeId('l'), name: 'Layer 1', visible: true, locked: false, order: 0 });
|
|
1289
|
+
|
|
1290
|
+
for (const instance of tracks) {
|
|
1291
|
+
const plan = instance.plan;
|
|
1292
|
+
if (!plan) continue;
|
|
1293
|
+
const layer = layers.get(instance.depth);
|
|
1294
|
+
const at = `${where}, frame ${instance.start}, depth ${instance.depth}`;
|
|
1295
|
+
let element, part;
|
|
1296
|
+
if (plan.parts) {
|
|
1297
|
+
part = plan.parts[0];
|
|
1298
|
+
element = partElement(part, instance.name ?? `${part.kind === 'text' ? 'Text' : part.kind === 'bitmap' ? 'Image' : 'Shape'} ${instance.characterId}`, layer.id);
|
|
1299
|
+
} else {
|
|
1300
|
+
countObject();
|
|
1301
|
+
element = { id: makeId('e'), name: shortName(instance.name, `${plan.symbol.definition.name}`), layerId: layer.id, type: 'symbol', symbolId: plan.symbol.id };
|
|
1302
|
+
if (plan.symbol.mode) element.symbolMode = plan.symbol.mode;
|
|
1303
|
+
part = { kind: 'symbol', box: plan.symbol.box, alpha: 1 };
|
|
1304
|
+
}
|
|
1305
|
+
if (plan.action) {
|
|
1306
|
+
const action = plan.action.op === 'script' ? { trigger: 'click', type: 'script', script: plan.action.script }
|
|
1307
|
+
: buttonAction(plan.action, resolveFrame, at);
|
|
1308
|
+
if (action) element.buttonAction = action;
|
|
1309
|
+
}
|
|
1310
|
+
const clipEvents = [];
|
|
1311
|
+
const component = element.type === 'symbol' ? componentOf(instance.characterId) : null;
|
|
1312
|
+
for (const clip of instance.clipActions ?? []) {
|
|
1313
|
+
const on = clipTriggers(clip.eventFlags);
|
|
1314
|
+
if (!on.length || !clip.bytecode?.length) continue;
|
|
1315
|
+
// A component's parameter handler becomes data the inspector edits (controls.md §1.3).
|
|
1316
|
+
if (component && !element.component && on.length === 1 && (on[0] === 'initialize' || on[0] === 'construct') && !clipEvents.length) {
|
|
1317
|
+
const parameters = decodeComponentParameters(clip.bytecode);
|
|
1318
|
+
if (parameters) {
|
|
1319
|
+
element.component = { kind: component.kind, event: on[0], parameters };
|
|
1320
|
+
continue;
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
clipEvents.push({ on, ...(clip.keyCode ? { key: clip.keyCode } : {}), script: keepScript(clip.bytecode, `${element.name}: onClipEvent (${on.join(', ')})`) });
|
|
1324
|
+
}
|
|
1325
|
+
if (clipEvents.length) {
|
|
1326
|
+
if (element.type === 'symbol') element.scriptEvents = clipEvents;
|
|
1327
|
+
else report.dropped('Clip actions on objects that are not movie clips', at);
|
|
1328
|
+
}
|
|
1329
|
+
const keyframes = [];
|
|
1330
|
+
const notes = new Set();
|
|
1331
|
+
let previous = null;
|
|
1332
|
+
for (const state of instance.states) {
|
|
1333
|
+
if (state.blank) {
|
|
1334
|
+
keyframes.push({ ...keyframes.at(-1), frame: state.frame, blank: true });
|
|
1335
|
+
previous = null;
|
|
1336
|
+
continue;
|
|
1337
|
+
}
|
|
1338
|
+
const ct = state.colorTransform;
|
|
1339
|
+
let alpha = state.visible === false ? 0 : 1;
|
|
1340
|
+
if (ct) {
|
|
1341
|
+
alpha *= clamp(((ct.aMult ?? 256) + (ct.aAdd ?? 0)) / 256, 0, 1);
|
|
1342
|
+
if (ct.aAdd && (ct.aMult ?? 256) !== 256) notes.add('Alpha offsets combined with alpha multipliers (opacity approximated)');
|
|
1343
|
+
}
|
|
1344
|
+
const { pose, points, subpaths } = partPose(part, multiply(offset, state.matrix), alpha, at, notes);
|
|
1345
|
+
// Tints and brightness: Flash color transforms map to Studio's colorTransform.
|
|
1346
|
+
const tint = ct && readColorTransform({
|
|
1347
|
+
redMultiplier: clamp((ct.rMult ?? 256) / 256, -128, 128), greenMultiplier: clamp((ct.gMult ?? 256) / 256, -128, 128),
|
|
1348
|
+
blueMultiplier: clamp((ct.bMult ?? 256) / 256, -128, 128), redOffset: clamp(ct.rAdd ?? 0, -512, 512),
|
|
1349
|
+
greenOffset: clamp(ct.gAdd ?? 0, -512, 512), blueOffset: clamp(ct.bAdd ?? 0, -512, 512),
|
|
1350
|
+
}, at);
|
|
1351
|
+
if (tint) pose.colorTransform = tint;
|
|
1352
|
+
if (state.filters?.length) pose.filters = state.filters;
|
|
1353
|
+
if (state.blendMode > 1) pose.blendMode = state.blendMode;
|
|
1354
|
+
const signature = JSON.stringify(pose);
|
|
1355
|
+
if (!keyframes.length) {
|
|
1356
|
+
Object.assign(element, pose);
|
|
1357
|
+
if (points) element.points = points;
|
|
1358
|
+
if (subpaths) element.subpaths = subpaths;
|
|
1359
|
+
}
|
|
1360
|
+
if (signature !== previous) keyframes.push({ frame: state.frame, ...pose, tween: 'hold' });
|
|
1361
|
+
previous = signature;
|
|
1362
|
+
}
|
|
1363
|
+
for (const feature of notes) report.approximated(feature, at);
|
|
1364
|
+
const firstPose = { ...keyframes[0] };
|
|
1365
|
+
delete firstPose.tween;
|
|
1366
|
+
if (instance.start > 1) keyframes.unshift({ ...firstPose, frame: 1, tween: 'hold', blank: true });
|
|
1367
|
+
if (instance.end && instance.end <= durationFrames) keyframes.push({ ...firstPose, frame: instance.end, tween: 'hold', blank: true });
|
|
1368
|
+
// Merge per-frame placements back into the tweens that produced them.
|
|
1369
|
+
element.keyframes = recoverTweens({ ...element, keyframes });
|
|
1370
|
+
|
|
1371
|
+
element.depth = instance.depth; // Scripts address depths (getDepth, swapDepths, attachMovie).
|
|
1372
|
+
timeline.elements.push(element);
|
|
1373
|
+
elementsByInstance.set(instance, element);
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
// Masks: a closed vector at a clipping depth masks the depths it covers. Flash swaps a mask
|
|
1377
|
+
// by placing another object at its depth with the same clip depth; those form one mask slot
|
|
1378
|
+
// (swooflib-integration.md). Targets link to the slot's first closed shape, and the editor
|
|
1379
|
+
// clips them with whichever slot object is on stage, symbols included.
|
|
1380
|
+
const slots = new Map();
|
|
1381
|
+
for (const mask of instances.filter(item => item.clipDepth)) {
|
|
1382
|
+
const key = `${mask.depth}:${mask.clipDepth}`;
|
|
1383
|
+
slots.set(key, [...(slots.get(key) ?? []), mask]);
|
|
1384
|
+
}
|
|
1385
|
+
for (const members of slots.values()) {
|
|
1386
|
+
const linkable = members.map(mask => elementsByInstance.get(mask)).find(canMask);
|
|
1387
|
+
for (const mask of members) {
|
|
1388
|
+
const source = elementsByInstance.get(mask);
|
|
1389
|
+
// The SWF's clip depth: Preview masks every depth up to it, as Flash does.
|
|
1390
|
+
if (source) source.clipDepth = Math.max(source.clipDepth ?? 0, mask.clipDepth);
|
|
1391
|
+
if (!canMask(source)) {
|
|
1392
|
+
report.approximated('Masks that are not a closed shape (masking shown in Preview only)', `${where}, frame ${mask.start}, depth ${mask.depth}`);
|
|
1393
|
+
if (source) source.keyframes.forEach(key => { key.opacity = 0; });
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
if (!linkable) continue;
|
|
1397
|
+
for (const target of instances) {
|
|
1398
|
+
const element = elementsByInstance.get(target);
|
|
1399
|
+
if (!element || members.includes(target) || element.maskId) continue;
|
|
1400
|
+
const overlaps = members.some(mask => target.depth > mask.depth && target.depth <= mask.clipDepth
|
|
1401
|
+
&& target.start < (mask.end ?? Infinity) && (target.end ?? Infinity) > mask.start);
|
|
1402
|
+
if (overlaps) element.maskId = linkable.id;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
// Frame actions become typed frame events where every block is simple navigation.
|
|
1407
|
+
// Otherwise every block on that frame is kept as a script, in order, so nothing runs twice.
|
|
1408
|
+
const events = [];
|
|
1409
|
+
for (const [index, list] of actionsByFrame) {
|
|
1410
|
+
const frame = index - first + 1;
|
|
1411
|
+
const at = `${where}, frame ${frame}`;
|
|
1412
|
+
const actions = [];
|
|
1413
|
+
if (list.some(bytes => frameCarriers.has(bytes) || !simpleActions(bytes))) {
|
|
1414
|
+
list.forEach((bytes, block) => actions.push({ type: 'script', script: keepScript(bytes, `${where}, frame ${frame}${list.length > 1 ? ` (${block + 1})` : ''}`) }));
|
|
1415
|
+
events.push({ trigger: 'frameEnter', frame, actions });
|
|
1416
|
+
continue;
|
|
1417
|
+
}
|
|
1418
|
+
for (const bytes of list) {
|
|
1419
|
+
const simple = simpleActions(bytes);
|
|
1420
|
+
for (const action of simple) {
|
|
1421
|
+
const converted = timelineAction(action, resolveFrame, at);
|
|
1422
|
+
if (converted) actions.push(converted);
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
const jump = actions.findIndex(action => action.type === 'gotoFrame' || action.type === 'gotoScene');
|
|
1426
|
+
if (jump >= 0) actions.splice(jump + 1);
|
|
1427
|
+
if (actions.length) events.push({ trigger: 'frameEnter', frame, actions });
|
|
1428
|
+
}
|
|
1429
|
+
if (events.length) timeline.events = events.sort((a, b) => a.frame - b.frame);
|
|
1430
|
+
// Frame labels: scripts jump to them by name.
|
|
1431
|
+
const frameLabels = [...labels].filter(([, index]) => index >= first && index < last)
|
|
1432
|
+
.map(([name, index]) => ({ frame: index - first + 1, name })).sort((a, b) => a.frame - b.frame);
|
|
1433
|
+
if (frameLabels.length) timeline.labels = frameLabels;
|
|
1434
|
+
return elementsByInstance;
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
function localFrame(index) {
|
|
1438
|
+
return index >= first && index < last ? index - first + 1 : null;
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
function buttonAction(action, resolveFrame, at) {
|
|
1442
|
+
const converted = timelineAction(action, resolveFrame, at);
|
|
1443
|
+
if (!converted) return null;
|
|
1444
|
+
const result = { trigger: 'click', type: converted.type };
|
|
1445
|
+
if (converted.target !== undefined) result.target = converted.target;
|
|
1446
|
+
if (converted.play) result.play = true;
|
|
1447
|
+
return result;
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
function timelineAction(action, resolveFrame, at) {
|
|
1451
|
+
if (action.op === 'stop' || action.op === 'play') return { type: action.op };
|
|
1452
|
+
const index = action.op === 'gotoFrame' ? action.frame - 1 : labels.get(action.label);
|
|
1453
|
+
if (index === undefined) {
|
|
1454
|
+
report.dropped('Jumps to unknown frame labels', at);
|
|
1455
|
+
return null;
|
|
1456
|
+
}
|
|
1457
|
+
const resolved = resolveFrame ? resolveFrame(index) : { frame: localFrame(index) };
|
|
1458
|
+
if (resolved?.scene) return { type: 'gotoScene', target: resolved.scene, ...(action.play ? { play: true } : {}) };
|
|
1459
|
+
if (!resolved?.frame) {
|
|
1460
|
+
report.dropped('Jumps outside the converted frames', at);
|
|
1461
|
+
return null;
|
|
1462
|
+
}
|
|
1463
|
+
return { type: 'gotoFrame', target: resolved.frame, ...(action.play ? { play: true } : {}) };
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
return { durationFrames, box, emit, instances, labels };
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
// #initclip code (DoInitAction) runs once before its sprite is first used; it belongs to the symbol.
|
|
1470
|
+
// Components (controls.md): recognized from their linkage names.
|
|
1471
|
+
const componentsById = new Map();
|
|
1472
|
+
for (const tag of tags) {
|
|
1473
|
+
if (tag?.type !== 'ExportAssets') continue;
|
|
1474
|
+
for (const { id, name } of tag.assets ?? []) {
|
|
1475
|
+
const kind = componentKind(name);
|
|
1476
|
+
if (kind && !componentsById.has(id)) componentsById.set(id, kind);
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
function componentOf(characterId) {
|
|
1480
|
+
return componentsById.get(characterId) ?? null;
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
// Linkage names (ExportAssets): scripts create these symbols by name with attachMovie, so
|
|
1484
|
+
// exported clips are kept even when nothing places them on the stage.
|
|
1485
|
+
async function keepLinkage() {
|
|
1486
|
+
for (const tag of tags) {
|
|
1487
|
+
if (tag?.type !== 'ExportAssets') continue;
|
|
1488
|
+
for (const { id, name } of tag.assets ?? []) {
|
|
1489
|
+
const type = symbolTable.get(id)?.type;
|
|
1490
|
+
if (name && type === 'Sound') {
|
|
1491
|
+
// Scripts play exported sounds by name: new Sound().attachSound(name).
|
|
1492
|
+
const source = await soundAsset(id);
|
|
1493
|
+
if (source && !source.asset.linkage) source.asset.linkage = String(name).slice(0, 256);
|
|
1494
|
+
continue;
|
|
1495
|
+
}
|
|
1496
|
+
if (!name || (type !== 'Sprite' && type !== 'Button')) continue;
|
|
1497
|
+
const definition = (await characterPlan(id, `character ${id}`))?.symbol?.definition;
|
|
1498
|
+
if (definition && !definition.linkage) definition.linkage = String(name).slice(0, 256);
|
|
1499
|
+
if (definition && !definition.component && componentsById.has(id)) definition.component = { ...componentsById.get(id) };
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
async function keepInitScripts(resolveFrame) {
|
|
1505
|
+
const ordered = [];
|
|
1506
|
+
let frameIndex = 0;
|
|
1507
|
+
for (const tag of tags) {
|
|
1508
|
+
if (tag?.type === 'ShowFrame') frameIndex++;
|
|
1509
|
+
if (tag?.type !== 'DoInitAction' || !tag.bytecode?.length) continue;
|
|
1510
|
+
const plan = await characterPlan(tag.spriteId, `sprite ${tag.spriteId}`);
|
|
1511
|
+
const definition = plan?.symbol?.definition;
|
|
1512
|
+
if (definition) {
|
|
1513
|
+
definition.initScript = keepScript(tag.bytecode, `${definition.name}: #initclip`);
|
|
1514
|
+
const position = resolveFrame?.(frameIndex);
|
|
1515
|
+
if (position && frameIndex > 0) definition.initAt = { scene: position.chunk.id, frame: position.frame };
|
|
1516
|
+
if (!ordered.includes(definition)) ordered.push(definition);
|
|
1517
|
+
} else report.dropped('Initialization code for missing symbols', `sprite ${tag.spriteId}`);
|
|
1518
|
+
}
|
|
1519
|
+
// Initialization code runs in library order: put these symbols in the order the SWF runs
|
|
1520
|
+
// them (base classes first), in the slots they already occupy.
|
|
1521
|
+
const slots = symbols.map((symbol, index) => ordered.includes(symbol) ? index : -1).filter(index => index >= 0);
|
|
1522
|
+
slots.forEach((slot, i) => { symbols[slot] = ordered[i]; });
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
async function keepAvm2(sourceTags, locate, documentSymbol) {
|
|
1526
|
+
let frame = 0;
|
|
1527
|
+
for (const tag of sourceTags) {
|
|
1528
|
+
if (tag?.type === 'ShowFrame') { frame++; continue; }
|
|
1529
|
+
if (tag?.type !== 'DoABC' && tag?.type !== 'SymbolClass') continue;
|
|
1530
|
+
const position = locate(frame);
|
|
1531
|
+
if (!position) { report.dropped('ActionScript 3 records beyond the timeline'); continue; }
|
|
1532
|
+
const { timeline, at } = position;
|
|
1533
|
+
const records = timeline.avm2 ??= [];
|
|
1534
|
+
if (tag.type === 'DoABC') {
|
|
1535
|
+
const id = makeId('abc');
|
|
1536
|
+
scripts.push({ id, language: 'avm2', swfVersion: version, name: shortName(tag.name, 'ActionScript 3 block'),
|
|
1537
|
+
abcName: tag.name, flags: tag.flags, ...(tag.legacy && { legacy: true }), bytecode: Buffer.from(tag.abcData).toString('base64') });
|
|
1538
|
+
records.push({ frame: at, script: id });
|
|
1539
|
+
} else {
|
|
1540
|
+
const classes = [];
|
|
1541
|
+
for (const { name, id } of buildSymbolClasses([tag])) {
|
|
1542
|
+
const character = symbolTable.get(id);
|
|
1543
|
+
if (!id) classes.push(documentSymbol ? { name, symbol: documentSymbol } : { name, document: true });
|
|
1544
|
+
else if (nativeClasses && character && !partsCache.get(id)?.symbol) {
|
|
1545
|
+
classes.push({ name, native: id });
|
|
1546
|
+
}
|
|
1547
|
+
else if (character?.type === 'DefineBinaryData') {
|
|
1548
|
+
classes.push({ name, binary: Buffer.from(character.rawData).toString('base64') });
|
|
1549
|
+
} else if (character?.type === 'Bitmap' || character?.type === 'Sound') {
|
|
1550
|
+
const source = character.type === 'Bitmap' ? await bitmapAsset(id) : await soundAsset(id);
|
|
1551
|
+
if (source) classes.push({ name, asset: source.asset.id });
|
|
1552
|
+
else report.dropped('ActionScript 3 classes for unavailable media', name);
|
|
1553
|
+
} else {
|
|
1554
|
+
const symbol = (await characterPlan(id, name))?.symbol;
|
|
1555
|
+
if (symbol) classes.push({ name, symbol: symbol.id });
|
|
1556
|
+
else report.dropped('ActionScript 3 classes for unsupported characters', name);
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
if (classes.length) records.push({ frame: at, classes });
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
async function keepNestedAvm2() {
|
|
1564
|
+
for (const { symbol, decoded } of nestedAbc) {
|
|
1565
|
+
await keepAvm2(decoded, frame => frame < symbol.durationFrames && { timeline: symbol, at: frame + 1 });
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
if (mode === 'library') {
|
|
1570
|
+
await keepLinkage();
|
|
1571
|
+
await keepInitScripts();
|
|
1572
|
+
for (const id of symbolTable.ids()) {
|
|
1573
|
+
const type = symbolTable.get(id)?.type;
|
|
1574
|
+
if (type === 'Sprite' || type === 'Button') await characterPlan(id, `character ${id}`);
|
|
1575
|
+
}
|
|
1576
|
+
if (tags.some(tag => tag?.type === 'DoABC' || tag?.type === 'SymbolClass')) {
|
|
1577
|
+
const root = await timelineSymbol(shortName(name, 'Imported movie'), buildFramesFromTags(tags), tags, name, { allowEmpty: true });
|
|
1578
|
+
await keepAvm2(tags, () => ({ timeline: root.definition, at: 1 }), root.id);
|
|
1579
|
+
}
|
|
1580
|
+
await keepNestedAvm2();
|
|
1581
|
+
keepFontLibrary();
|
|
1582
|
+
const summary = `Imported ${symbols.length} symbol${symbols.length === 1 ? '' : 's'} and ${assets.length} media file${assets.length === 1 ? '' : 's'}.`;
|
|
1583
|
+
return { symbols, assets, scripts, report: finishReport(summary), summary, objectCount: objects };
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
// --- Root timeline into scenes --------------------------------------------
|
|
1587
|
+
|
|
1588
|
+
const rootFrames = buildFramesFromTags(tags);
|
|
1589
|
+
rootFrames.length = Math.max(rootFrames.length, header.frameCount ?? 1);
|
|
1590
|
+
const sceneTag = tags.find(tag => tag?.type === 'SceneAndFrameLabels');
|
|
1591
|
+
const studioSceneList = studioScenes.length > 1 && studioScenes.at(-1)[1] < rootFrames.length
|
|
1592
|
+
? studioScenes.map(([, offset, name, transition]) => ({ offset, name, transition })) : null;
|
|
1593
|
+
const declaredScenes = sceneTag?.scenes?.length ? sceneTag.scenes : studioSceneList ?? [{ offset: 0, name: 'Scene 1' }];
|
|
1594
|
+
const chunks = [];
|
|
1595
|
+
declaredScenes.forEach((scene, index) => {
|
|
1596
|
+
const start = scene.offset | 0;
|
|
1597
|
+
const end = Math.max(start + 1, declaredScenes[index + 1]?.offset ?? rootFrames.length);
|
|
1598
|
+
const parts = Math.ceil((end - start) / MAX_TIMELINE_FRAMES);
|
|
1599
|
+
if (parts > 1) report.approximated(`Scenes longer than ${MAX_TIMELINE_FRAMES} frames (split into parts)`, scene.name);
|
|
1600
|
+
for (let part = 0; part < parts; part++) {
|
|
1601
|
+
const chunkStart = start + part * MAX_TIMELINE_FRAMES;
|
|
1602
|
+
chunks.push({ start: chunkStart, end: Math.min(end, chunkStart + MAX_TIMELINE_FRAMES), transition: part === 0 ? scene.transition : null,
|
|
1603
|
+
name: shortName(parts > 1 ? `${scene.name || `Scene ${index + 1}`} (${part + 1})` : scene.name, `Scene ${index + 1}`), id: makeId('s') });
|
|
1604
|
+
}
|
|
1605
|
+
});
|
|
1606
|
+
const resolveRoot = index => {
|
|
1607
|
+
const chunk = chunks.find(item => index >= item.start && index < item.end);
|
|
1608
|
+
if (!chunk) return null;
|
|
1609
|
+
return { chunk, frame: index - chunk.start + 1 };
|
|
1610
|
+
};
|
|
1611
|
+
|
|
1612
|
+
const scenes = [];
|
|
1613
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
1614
|
+
const built = await buildTimeline(rootFrames, tags, { where: chunk.name, maxFrames: MAX_TIMELINE_FRAMES, range: chunk });
|
|
1615
|
+
const scene = { ...newTimeline(chunk.name, built.durationFrames), id: chunk.id };
|
|
1616
|
+
if (chunk.transition) {
|
|
1617
|
+
try { scene.transition = readTransition(chunk.transition); } catch { /* A transition this Studio does not know is left out. */ }
|
|
1618
|
+
}
|
|
1619
|
+
await built.emit(scene, IDENTITY, {
|
|
1620
|
+
resolveFrame(frameIndex) {
|
|
1621
|
+
const target = resolveRoot(frameIndex);
|
|
1622
|
+
if (!target) return null;
|
|
1623
|
+
if (target.chunk === chunk) return { frame: target.frame };
|
|
1624
|
+
if (target.frame === 1) return { scene: target.chunk.id };
|
|
1625
|
+
report.approximated('Jumps into the middle of another scene (go to its start)', chunk.name);
|
|
1626
|
+
return { scene: target.chunk.id };
|
|
1627
|
+
},
|
|
1628
|
+
});
|
|
1629
|
+
// The root timeline loops through every scene unless a frame action stops it.
|
|
1630
|
+
const lastFrame = scene.durationFrames;
|
|
1631
|
+
const ending = scene.events?.find(event => event.frame === lastFrame);
|
|
1632
|
+
const next = chunks[index + 1] ?? chunks[0];
|
|
1633
|
+
// A script on the last frame decides for itself; Flash then continues as the SWF does.
|
|
1634
|
+
const scripted = ending?.actions.some(action => action.type === 'script');
|
|
1635
|
+
if (scripted && chunks.length === 1) scene.loop = true;
|
|
1636
|
+
else if (!scripted && !ending?.actions.some(action => action.type === 'stop' || action.type.startsWith('goto'))) {
|
|
1637
|
+
if (chunks.length === 1) scene.loop = true;
|
|
1638
|
+
else {
|
|
1639
|
+
const event = ending ?? { trigger: 'frameEnter', frame: lastFrame, actions: [] };
|
|
1640
|
+
event.actions.push({ type: 'gotoScene', target: next.id, play: true });
|
|
1641
|
+
if (!ending) (scene.events ??= []).push(event);
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
await frameSounds(scene, rootFrames, chunk.start, scene.name);
|
|
1645
|
+
scenes.push(scene);
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
if (rootFrames.some(frame => frame.streamBlocks?.length)) {
|
|
1649
|
+
await streamSounds(tags, scenes.map((timeline, i) => ({ timeline, offset: chunks[i].start })), 'Root timeline');
|
|
1650
|
+
}
|
|
1651
|
+
await keepLinkage();
|
|
1652
|
+
await keepInitScripts(resolveRoot);
|
|
1653
|
+
await keepAvm2(tags, index => {
|
|
1654
|
+
const position = resolveRoot(index);
|
|
1655
|
+
return position && { timeline: scenes.find(scene => scene.id === position.chunk.id), at: position.frame };
|
|
1656
|
+
});
|
|
1657
|
+
await keepNestedAvm2();
|
|
1658
|
+
keepFontLibrary();
|
|
1659
|
+
if (nativeClasses) {
|
|
1660
|
+
(scenes[0].avm2 ??= []).unshift({ frame: 1, library: libraryId, sourceLength: header.fileLength,
|
|
1661
|
+
sourceHash: createHash('sha256').update(bytes).digest('hex'),
|
|
1662
|
+
symbols: [...partsCache].filter(([id, plan]) => Number.isInteger(id) && plan?.symbol)
|
|
1663
|
+
.map(([id, plan]) => ({ id, symbol: plan.symbol.id })) });
|
|
1664
|
+
}
|
|
1665
|
+
const project = { format: PROJECT_FORMAT, version: PROJECT_VERSION, stage, scenes };
|
|
1666
|
+
if (symbols.length) project.symbols = symbols;
|
|
1667
|
+
if (assets.length) project.assets = assets;
|
|
1668
|
+
if (scripts.length) project.scripts = scripts;
|
|
1669
|
+
|
|
1670
|
+
const elementCount = [...scenes, ...symbols].reduce((sum, timeline) => sum + timeline.elements.length, 0);
|
|
1671
|
+
const summary = `Converted ${scenes.length} scene${scenes.length === 1 ? '' : 's'}, ${symbols.length} symbol${symbols.length === 1 ? '' : 's'}, ` +
|
|
1672
|
+
`${elementCount} object${elementCount === 1 ? '' : 's'}, ${assets.length} media file${assets.length === 1 ? '' : 's'}, ` +
|
|
1673
|
+
`and ${scripts.length} script${scripts.length === 1 ? '' : 's'}.`;
|
|
1674
|
+
return { project, report: finishReport(summary), summary, objectCount: objects };
|
|
1675
|
+
}
|