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,1208 @@
|
|
|
1
|
+
// SVG import (studiospec/svg-import.md). An SVG image becomes a one-frame Studio project, which then
|
|
2
|
+
// goes through parseProjectJson like any other project.
|
|
3
|
+
//
|
|
4
|
+
// An SVG Studio exported with its project embedded, unchanged since, opens exactly. Any other SVG
|
|
5
|
+
// is read as drawn (one frame; SMIL animation is reported, not read): shapes become rectangles, ellipses and paths, text becomes text,
|
|
6
|
+
// embedded images become bitmaps, clip paths become masks, top-level groups become Studio groups.
|
|
7
|
+
// What Studio cannot hold (filters, patterns, CSS classes, animation) is reported. The file is
|
|
8
|
+
// untrusted: no entity is expanded, nothing is fetched, sizes and depth are capped.
|
|
9
|
+
import { studioPose, threePoints } from './lottie-import.js';
|
|
10
|
+
import { placementFilters } from './placement-effects.js';
|
|
11
|
+
import { gunzipBase64, studioHash } from './lottie-export.js';
|
|
12
|
+
|
|
13
|
+
const MAX_TEXT = 64 * 1024 * 1024;
|
|
14
|
+
const MAX_NODES = 200000;
|
|
15
|
+
const MAX_DEPTH = 256;
|
|
16
|
+
const round = value => Math.round(value * 1e4) / 1e4;
|
|
17
|
+
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
|
|
18
|
+
const finite = (value, fallback = 0) => Number.isFinite(+value) ? +value : fallback;
|
|
19
|
+
|
|
20
|
+
// ---- XML ---------------------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
const ENTITIES = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'", nbsp: ' ' };
|
|
23
|
+
const decode = text => text.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (all, name) => {
|
|
24
|
+
if (name[0] === '#') {
|
|
25
|
+
const code = name[1].toLowerCase() === 'x' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
|
|
26
|
+
return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : '';
|
|
27
|
+
}
|
|
28
|
+
return ENTITIES[name] ?? '';
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
/** A small XML reader: elements, attributes, text and CDATA. DOCTYPEs and their entities are skipped. */
|
|
32
|
+
export function parseXml(text) {
|
|
33
|
+
if (text.length > MAX_TEXT) throw new Error('This SVG is too large to import');
|
|
34
|
+
const root = { name: '#document', attrs: {}, children: [] };
|
|
35
|
+
const stack = [root];
|
|
36
|
+
let index = 0, count = 0;
|
|
37
|
+
const pattern = /<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE(?:[^[>]|\[[\s\S]*?\])*>|<\/([^\s>]+)\s*>|<([^\s/>!?]+)((?:\s+[^\s=/>]+(?:\s*=\s*(?:"[^"]*"|'[^']*'))?)*)\s*(\/?)>/gi;
|
|
38
|
+
for (let match; (match = pattern.exec(text));) {
|
|
39
|
+
const parent = stack.at(-1);
|
|
40
|
+
if (match.index > index) {
|
|
41
|
+
const between = text.slice(index, match.index);
|
|
42
|
+
if (between.trim() || parent.name === 'text' || parent.name === 'tspan') parent.children.push({ text: decode(between) });
|
|
43
|
+
}
|
|
44
|
+
index = pattern.lastIndex;
|
|
45
|
+
if (match[1] !== undefined) parent.children.push({ text: match[1] });
|
|
46
|
+
else if (match[2]) {
|
|
47
|
+
const name = match[2].replace(/^svg:/, '');
|
|
48
|
+
const at = stack.map(node => node.name).lastIndexOf(name);
|
|
49
|
+
if (at > 0) stack.length = at;
|
|
50
|
+
} else if (match[3]) {
|
|
51
|
+
if (++count > MAX_NODES) throw new Error('This SVG has too many elements to import');
|
|
52
|
+
const attrs = {};
|
|
53
|
+
for (const [, key, , double, single] of match[4].matchAll(/([^\s=/>]+)(\s*=\s*(?:"([^"]*)"|'([^']*)'))?/g)) {
|
|
54
|
+
attrs[key.replace(/^xlink:/, 'xlink:')] = decode(double ?? single ?? '');
|
|
55
|
+
}
|
|
56
|
+
const node = { name: match[3].replace(/^svg:/, ''), attrs, children: [] };
|
|
57
|
+
parent.children.push(node);
|
|
58
|
+
if (!match[5]) {
|
|
59
|
+
if (stack.length >= MAX_DEPTH) throw new Error('This SVG is nested too deeply to import');
|
|
60
|
+
stack.push(node);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return root;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const textOf = node => node.text ?? node.children?.map(textOf).join('') ?? '';
|
|
68
|
+
|
|
69
|
+
// ---- Values ------------------------------------------------------------------------------------
|
|
70
|
+
|
|
71
|
+
const NAMED = { black: '#000000', white: '#ffffff', red: '#ff0000', green: '#008000', lime: '#00ff00', blue: '#0000ff', yellow: '#ffff00',
|
|
72
|
+
cyan: '#00ffff', aqua: '#00ffff', magenta: '#ff00ff', fuchsia: '#ff00ff', gray: '#808080', grey: '#808080', silver: '#c0c0c0',
|
|
73
|
+
maroon: '#800000', olive: '#808000', purple: '#800080', teal: '#008080', navy: '#000080', orange: '#ffa500', pink: '#ffc0cb',
|
|
74
|
+
brown: '#a52a2a', gold: '#ffd700', indigo: '#4b0082', violet: '#ee82ee', coral: '#ff7f50', salmon: '#fa8072', tomato: '#ff6347',
|
|
75
|
+
crimson: '#dc143c', khaki: '#f0e68c', beige: '#f5f5dc', ivory: '#fffff0', lavender: '#e6e6fa', turquoise: '#40e0d0', tan: '#d2b48c',
|
|
76
|
+
chocolate: '#d2691e', darkgray: '#a9a9a9', darkgrey: '#a9a9a9', lightgray: '#d3d3d3', lightgrey: '#d3d3d3', dimgray: '#696969',
|
|
77
|
+
darkblue: '#00008b', darkgreen: '#006400', darkred: '#8b0000', lightblue: '#add8e6', lightgreen: '#90ee90', skyblue: '#87ceeb',
|
|
78
|
+
steelblue: '#4682b4', royalblue: '#4169e1', firebrick: '#b22222', forestgreen: '#228b22', seagreen: '#2e8b57', slategray: '#708090',
|
|
79
|
+
whitesmoke: '#f5f5f5', gainsboro: '#dcdcdc', orchid: '#da70d6', plum: '#dda0dd', sienna: '#a0522d', peru: '#cd853f', wheat: '#f5deb3' };
|
|
80
|
+
|
|
81
|
+
const hex2 = value => Math.round(clamp(value, 0, 255)).toString(16).padStart(2, '0');
|
|
82
|
+
|
|
83
|
+
/** A CSS colour as { color: '#rrggbb', alpha }, null for none, or undefined when unknown. */
|
|
84
|
+
export function parseColor(text, resolve) {
|
|
85
|
+
const value = String(text ?? '').trim().toLowerCase();
|
|
86
|
+
if (!value || value === 'none' || value === 'transparent') return null;
|
|
87
|
+
let match;
|
|
88
|
+
if ((match = value.match(/^#([0-9a-f]{3,4})$/))) {
|
|
89
|
+
const [r, g, b, a = 'f'] = match[1];
|
|
90
|
+
return { color: `#${r}${r}${g}${g}${b}${b}`, alpha: parseInt(a + a, 16) / 255 };
|
|
91
|
+
}
|
|
92
|
+
if ((match = value.match(/^#([0-9a-f]{6})([0-9a-f]{2})?$/))) return { color: `#${match[1]}`, alpha: match[2] ? parseInt(match[2], 16) / 255 : 1 };
|
|
93
|
+
if ((match = value.match(/^rgba?\(\s*([^)]*)\)$/))) {
|
|
94
|
+
const parts = match[1].split(/[\s,/]+/).filter(Boolean);
|
|
95
|
+
const channel = part => part.endsWith('%') ? parseFloat(part) * 2.55 : parseFloat(part);
|
|
96
|
+
const alpha = parts[3] === undefined ? 1 : parts[3].endsWith('%') ? parseFloat(parts[3]) / 100 : parseFloat(parts[3]);
|
|
97
|
+
return { color: `#${parts.slice(0, 3).map(part => hex2(finite(channel(part)))).join('')}`, alpha: clamp(finite(alpha, 1), 0, 1) };
|
|
98
|
+
}
|
|
99
|
+
if (NAMED[value]) return { color: NAMED[value], alpha: 1 };
|
|
100
|
+
const resolved = resolve?.(value);
|
|
101
|
+
return resolved ? parseColor(resolved) : undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const length = (value, reference = 0, fallback = 0) => {
|
|
105
|
+
if (value == null || value === '') return fallback;
|
|
106
|
+
const text = String(value).trim();
|
|
107
|
+
const number = parseFloat(text);
|
|
108
|
+
if (!Number.isFinite(number)) return fallback;
|
|
109
|
+
if (text.endsWith('%')) return number / 100 * reference;
|
|
110
|
+
const unit = text.match(/[a-z]+$/i)?.[0];
|
|
111
|
+
return number * ({ px: 1, pt: 4 / 3, pc: 16, mm: 96 / 25.4, cm: 96 / 2.54, in: 96, em: 16, ex: 8 }[unit] ?? 1);
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
// ---- Geometry ----------------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
const IDENTITY = [1, 0, 0, 1, 0, 0];
|
|
117
|
+
const mul = (m, n) => [m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1], m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3],
|
|
118
|
+
m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5]];
|
|
119
|
+
const apply = (m, [x, y]) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
|
|
120
|
+
const translate = (x, y) => [1, 0, 0, 1, x, y];
|
|
121
|
+
|
|
122
|
+
/** An SVG transform list as a matrix. */
|
|
123
|
+
export function parseTransform(text) {
|
|
124
|
+
let matrix = IDENTITY;
|
|
125
|
+
for (const [, name, args] of String(text ?? '').matchAll(/(\w+)\s*\(([^)]*)\)/g)) {
|
|
126
|
+
const n = (args.match(/[-+]?(?:\d*\.\d+|\d+\.?)(?:e[-+]?\d+)?/gi) ?? []).map(Number);
|
|
127
|
+
const rad = Math.PI / 180;
|
|
128
|
+
let step = IDENTITY;
|
|
129
|
+
if (name === 'matrix' && n.length >= 6) step = n.slice(0, 6);
|
|
130
|
+
else if (name === 'translate') step = translate(n[0] ?? 0, n[1] ?? 0);
|
|
131
|
+
else if (name === 'scale') step = [n[0] ?? 1, 0, 0, n[1] ?? n[0] ?? 1, 0, 0];
|
|
132
|
+
else if (name === 'rotate') {
|
|
133
|
+
const a = (n[0] ?? 0) * rad, rotate = [Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0];
|
|
134
|
+
step = n.length >= 3 ? mul(translate(n[1], n[2]), mul(rotate, translate(-n[1], -n[2]))) : rotate;
|
|
135
|
+
} else if (name === 'skewX') step = [1, 0, Math.tan((n[0] ?? 0) * rad), 1, 0, 0];
|
|
136
|
+
else if (name === 'skewY') step = [1, Math.tan((n[0] ?? 0) * rad), 0, 1, 0, 0];
|
|
137
|
+
if (step.every(Number.isFinite)) matrix = mul(matrix, step);
|
|
138
|
+
}
|
|
139
|
+
return matrix;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Arc to cubics (SVG implementation notes, F.6).
|
|
143
|
+
function arcCubics(x1, y1, rx, ry, angle, large, sweep, x2, y2) {
|
|
144
|
+
if (!rx || !ry) return [[x1, y1, x2, y2, x2, y2]];
|
|
145
|
+
const phi = angle * Math.PI / 180, cos = Math.cos(phi), sin = Math.sin(phi);
|
|
146
|
+
const dx = (x1 - x2) / 2, dy = (y1 - y2) / 2;
|
|
147
|
+
const xp = cos * dx + sin * dy, yp = -sin * dx + cos * dy;
|
|
148
|
+
rx = Math.abs(rx); ry = Math.abs(ry);
|
|
149
|
+
const lambda = xp * xp / (rx * rx) + yp * yp / (ry * ry);
|
|
150
|
+
if (lambda > 1) { rx *= Math.sqrt(lambda); ry *= Math.sqrt(lambda); }
|
|
151
|
+
const sign = large === sweep ? -1 : 1;
|
|
152
|
+
const factor = sign * Math.sqrt(Math.max(0, (rx * rx * ry * ry - rx * rx * yp * yp - ry * ry * xp * xp) / (rx * rx * yp * yp + ry * ry * xp * xp)));
|
|
153
|
+
const cxp = factor * rx * yp / ry, cyp = -factor * ry * xp / rx;
|
|
154
|
+
const cx = cos * cxp - sin * cyp + (x1 + x2) / 2, cy = sin * cxp + cos * cyp + (y1 + y2) / 2;
|
|
155
|
+
const angleOf = (ux, uy, vx, vy) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
|
|
156
|
+
const start = angleOf(1, 0, (xp - cxp) / rx, (yp - cyp) / ry);
|
|
157
|
+
let delta = angleOf((xp - cxp) / rx, (yp - cyp) / ry, (-xp - cxp) / rx, (-yp - cyp) / ry);
|
|
158
|
+
if (!sweep && delta > 0) delta -= 2 * Math.PI;
|
|
159
|
+
if (sweep && delta < 0) delta += 2 * Math.PI;
|
|
160
|
+
const segments = Math.max(1, Math.ceil(Math.abs(delta) / (Math.PI / 2)));
|
|
161
|
+
const step = delta / segments, k = 4 / 3 * Math.tan(step / 4);
|
|
162
|
+
const point = t => [cx + rx * Math.cos(t) * cos - ry * Math.sin(t) * sin, cy + rx * Math.cos(t) * sin + ry * Math.sin(t) * cos];
|
|
163
|
+
const tangent = t => [-rx * Math.sin(t) * cos - ry * Math.cos(t) * sin, -rx * Math.sin(t) * sin + ry * Math.cos(t) * cos];
|
|
164
|
+
const out = [];
|
|
165
|
+
for (let i = 0; i < segments; i++) {
|
|
166
|
+
const a = start + i * step, b = a + step;
|
|
167
|
+
const [ax, ay] = point(a), [bx, by] = point(b), [tax, tay] = tangent(a), [tbx, tby] = tangent(b);
|
|
168
|
+
out.push([ax + k * tax, ay + k * tay, bx - k * tbx, by - k * tby, bx, by]);
|
|
169
|
+
}
|
|
170
|
+
return out;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** SVG path data as contours of cubic points: [{ points: [{ x, y, in, out }], closed }]. */
|
|
174
|
+
export function parsePathData(d) {
|
|
175
|
+
const tokens = String(d ?? '').match(/[a-z]|[-+]?(?:\d*\.\d+|\d+\.?)(?:e[-+]?\d+)?/gi) ?? [];
|
|
176
|
+
const contours = [];
|
|
177
|
+
let i = 0, command = '', x = 0, y = 0, startX = 0, startY = 0, lastControl = null;
|
|
178
|
+
let current = null;
|
|
179
|
+
const number = () => +tokens[i++];
|
|
180
|
+
const flag = () => {
|
|
181
|
+
// Arc flags may be written without separators ("a5 5 0 1010 10").
|
|
182
|
+
const token = tokens[i];
|
|
183
|
+
if (token?.length > 1 && /^[01]/.test(token)) { tokens[i] = token.slice(1); return +token[0]; }
|
|
184
|
+
i++;
|
|
185
|
+
return +token;
|
|
186
|
+
};
|
|
187
|
+
const begin = () => { current = { points: [{ x, y, in: [0, 0], out: [0, 0] }], closed: false }; contours.push(current); };
|
|
188
|
+
const cubic = (c1x, c1y, c2x, c2y, ex, ey) => {
|
|
189
|
+
if (!current) begin();
|
|
190
|
+
const last = current.points.at(-1);
|
|
191
|
+
last.out = [c1x - last.x, c1y - last.y];
|
|
192
|
+
current.points.push({ x: ex, y: ey, in: [c2x - ex, c2y - ey], out: [0, 0] });
|
|
193
|
+
x = ex; y = ey;
|
|
194
|
+
};
|
|
195
|
+
const line = (ex, ey) => cubic(x, y, ex, ey, ex, ey);
|
|
196
|
+
while (i < tokens.length) {
|
|
197
|
+
if (/^[a-z]$/i.test(tokens[i])) command = tokens[i++];
|
|
198
|
+
else if (!command) { i++; continue; }
|
|
199
|
+
const relative = command === command.toLowerCase() && command.toLowerCase() !== 'z';
|
|
200
|
+
const ox = relative ? x : 0, oy = relative ? y : 0;
|
|
201
|
+
const upper = command.toUpperCase();
|
|
202
|
+
const before = i;
|
|
203
|
+
if (upper === 'M') {
|
|
204
|
+
x = ox + number(); y = oy + number(); startX = x; startY = y;
|
|
205
|
+
begin();
|
|
206
|
+
command = relative ? 'l' : 'L';
|
|
207
|
+
lastControl = null;
|
|
208
|
+
} else if (upper === 'L') { line(ox + number(), oy + number()); lastControl = null; }
|
|
209
|
+
else if (upper === 'H') { line(ox + number(), y); lastControl = null; }
|
|
210
|
+
else if (upper === 'V') { line(x, oy + number()); lastControl = null; }
|
|
211
|
+
else if (upper === 'C') {
|
|
212
|
+
const c = [ox + number(), oy + number(), ox + number(), oy + number(), ox + number(), oy + number()];
|
|
213
|
+
cubic(...c); lastControl = ['C', c[2], c[3]];
|
|
214
|
+
} else if (upper === 'S') {
|
|
215
|
+
const [c1x, c1y] = lastControl?.[0] === 'C' ? [2 * x - lastControl[1], 2 * y - lastControl[2]] : [x, y];
|
|
216
|
+
const c = [ox + number(), oy + number(), ox + number(), oy + number()];
|
|
217
|
+
cubic(c1x, c1y, ...c); lastControl = ['C', c[0], c[1]];
|
|
218
|
+
} else if (upper === 'Q' || upper === 'T') {
|
|
219
|
+
const [qx, qy] = upper === 'Q' ? [ox + number(), oy + number()] : lastControl?.[0] === 'Q' ? [2 * x - lastControl[1], 2 * y - lastControl[2]] : [x, y];
|
|
220
|
+
const ex = ox + number(), ey = oy + number();
|
|
221
|
+
cubic(x + 2 / 3 * (qx - x), y + 2 / 3 * (qy - y), ex + 2 / 3 * (qx - ex), ey + 2 / 3 * (qy - ey), ex, ey);
|
|
222
|
+
lastControl = ['Q', qx, qy];
|
|
223
|
+
} else if (upper === 'A') {
|
|
224
|
+
const rx = number(), ry = number(), angle = number(), large = flag(), sweep = flag(), ex = ox + number(), ey = oy + number();
|
|
225
|
+
for (const c of arcCubics(x, y, rx, ry, angle, large, sweep, ex, ey)) cubic(...c);
|
|
226
|
+
lastControl = null;
|
|
227
|
+
} else if (upper === 'Z') {
|
|
228
|
+
if (current) {
|
|
229
|
+
current.closed = true;
|
|
230
|
+
const first = current.points[0], last = current.points.at(-1);
|
|
231
|
+
if (current.points.length > 1 && Math.abs(first.x - last.x) < 1e-6 && Math.abs(first.y - last.y) < 1e-6) {
|
|
232
|
+
first.in = last.in;
|
|
233
|
+
current.points.pop();
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
x = startX; y = startY;
|
|
237
|
+
current = null;
|
|
238
|
+
lastControl = null;
|
|
239
|
+
command = '';
|
|
240
|
+
} else i++;
|
|
241
|
+
if (i === before && upper !== 'Z') i++;
|
|
242
|
+
if ([x, y].some(value => !Number.isFinite(value))) break;
|
|
243
|
+
}
|
|
244
|
+
return contours.filter(contour => contour.points.length > 1);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const KAPPA = 0.5522847498;
|
|
248
|
+
const ellipseContour = (cx, cy, rx, ry) => ({ closed: true, points: [
|
|
249
|
+
{ x: cx + rx, y: cy, in: [0, -ry * KAPPA], out: [0, ry * KAPPA] },
|
|
250
|
+
{ x: cx, y: cy + ry, in: [rx * KAPPA, 0], out: [-rx * KAPPA, 0] },
|
|
251
|
+
{ x: cx - rx, y: cy, in: [0, ry * KAPPA], out: [0, -ry * KAPPA] },
|
|
252
|
+
{ x: cx, y: cy - ry, in: [-rx * KAPPA, 0], out: [rx * KAPPA, 0] }] });
|
|
253
|
+
|
|
254
|
+
function roundedRectContour(x, y, w, h, rx, ry) {
|
|
255
|
+
if (!rx && !ry) return { closed: true, points: [[x, y], [x + w, y], [x + w, y + h], [x, y + h]].map(([px, py]) => ({ x: px, y: py, in: [0, 0], out: [0, 0] })) };
|
|
256
|
+
const kx = rx * KAPPA, ky = ry * KAPPA;
|
|
257
|
+
return { closed: true, points: [
|
|
258
|
+
{ x: x + rx, y, in: [-kx, 0], out: [0, 0] }, { x: x + w - rx, y, in: [0, 0], out: [kx, 0] },
|
|
259
|
+
{ x: x + w, y: y + ry, in: [0, -ky], out: [0, 0] }, { x: x + w, y: y + h - ry, in: [0, 0], out: [0, ky] },
|
|
260
|
+
{ x: x + w - rx, y: y + h, in: [kx, 0], out: [0, 0] }, { x: x + rx, y: y + h, in: [0, 0], out: [-kx, 0] },
|
|
261
|
+
{ x, y: y + h - ry, in: [0, ky], out: [0, 0] }, { x, y: y + ry, in: [0, 0], out: [0, -ky] }] };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const transformContour = (contour, m) => ({ closed: contour.closed, points: contour.points.map(p => {
|
|
265
|
+
const [x, y] = apply(m, [p.x, p.y]);
|
|
266
|
+
return { x, y, in: [m[0] * p.in[0] + m[2] * p.in[1], m[1] * p.in[0] + m[3] * p.in[1]], out: [m[0] * p.out[0] + m[2] * p.out[1], m[1] * p.out[0] + m[3] * p.out[1]] };
|
|
267
|
+
}) });
|
|
268
|
+
|
|
269
|
+
function bounds(contours) {
|
|
270
|
+
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
|
|
271
|
+
for (const contour of contours) for (const p of contour.points) {
|
|
272
|
+
for (const [x, y] of [[p.x, p.y], [p.x + p.in[0], p.y + p.in[1]], [p.x + p.out[0], p.y + p.out[1]]]) {
|
|
273
|
+
x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
return x0 === Infinity ? [0, 0, 0, 0] : [x0, y0, x1, y1];
|
|
277
|
+
}
|
|
278
|
+
const coordinate = value => round(clamp(finite(value), -100000, 100000));
|
|
279
|
+
const studioPoints = (contour, cx, cy) => threePoints(contour.points.map(p => ({ x: p.x - cx, y: p.y - cy, handleIn: { x: p.in[0], y: p.in[1] }, handleOut: { x: p.out[0], y: p.out[1] } })))
|
|
280
|
+
.map(p => ({ x: coordinate(p.x), y: coordinate(p.y), handleIn: { x: coordinate(p.handleIn.x), y: coordinate(p.handleIn.y) }, handleOut: { x: coordinate(p.handleOut.x), y: coordinate(p.handleOut.y) } }));
|
|
281
|
+
|
|
282
|
+
// ---- Import ------------------------------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
/** Studio's embedded project (svg-animation.js withStudioData) and the SVG without it, or null. */
|
|
285
|
+
export function svgStudioData(text) {
|
|
286
|
+
const match = text.match(/<metadata id="swoof-studio" data-format="swoof-studio-svg" data-version="1" data-hash="([0-9a-z]+)">([A-Za-z0-9+/=]*)<\/metadata>/);
|
|
287
|
+
return match ? { hash: match[1], project: match[2], content: text.slice(0, match.index) + text.slice(match.index + match[0].length) } : null;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Whether `text` looks like an SVG document. */
|
|
291
|
+
export function isSvgText(text) {
|
|
292
|
+
return typeof text === 'string' && /^\s*(?:<\?xml[^>]*>\s*)?(?:<!--[\s\S]*?-->\s*|<!DOCTYPE(?:[^[>]|\[[\s\S]*?\])*>\s*)*<(?:svg:)?svg[\s>]/i.test(text.slice(0, 65536));
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Reads SVG text. Returns { json, notes, exact }. options: measure(font, text) → canvas metrics,
|
|
297
|
+
* layoutText(fields) → Studio's first line placement, resolveColor(css) → '#rrggbb' or ''.
|
|
298
|
+
*/
|
|
299
|
+
export async function importSvg(text, { measure = null, layoutText = null, resolveColor = null, rasterize = null } = {}) {
|
|
300
|
+
if (!isSvgText(text)) throw new Error('This is not an SVG image');
|
|
301
|
+
const notes = new Set();
|
|
302
|
+
const report = note => notes.add(note);
|
|
303
|
+
const studio = svgStudioData(text);
|
|
304
|
+
if (studio) {
|
|
305
|
+
if (studioHash(studio.content) === studio.hash) return { json: await gunzipBase64(studio.project), notes: [], exact: true };
|
|
306
|
+
report('This SVG was changed after Studio exported it: it is read as drawn, without its animation');
|
|
307
|
+
}
|
|
308
|
+
const document = parseXml(text);
|
|
309
|
+
const svg = document.children.find(node => node.name === 'svg');
|
|
310
|
+
if (!svg) throw new Error('This is not an SVG image');
|
|
311
|
+
return { json: JSON.stringify(await convert(svg, report, { measure, layoutText, resolveColor, rasterize })), notes: [...notes], exact: false };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Draw SVG text as an image, in a browser: what `importSvg` uses for pattern tiles and for parts
|
|
316
|
+
* Studio cannot hold (soft masks, other filters). An SVG drawn as an image runs no script and
|
|
317
|
+
* fetches nothing. With `crop`, the result is cut to what was drawn; `null` if nothing was.
|
|
318
|
+
* Returns `{ data (PNG data URI), x, y, width, height }` in pixels of the drawing.
|
|
319
|
+
*/
|
|
320
|
+
export async function rasterizeInBrowser(text, width, height, { crop = false } = {}) {
|
|
321
|
+
const url = URL.createObjectURL(new Blob([text], { type: 'image/svg+xml' }));
|
|
322
|
+
try {
|
|
323
|
+
const image = new Image();
|
|
324
|
+
image.src = url;
|
|
325
|
+
await image.decode();
|
|
326
|
+
const canvas = document.createElement('canvas');
|
|
327
|
+
canvas.width = width; canvas.height = height;
|
|
328
|
+
const context = canvas.getContext('2d', { willReadFrequently: crop });
|
|
329
|
+
context.drawImage(image, 0, 0, width, height);
|
|
330
|
+
let box = { x: 0, y: 0, width, height };
|
|
331
|
+
if (crop) {
|
|
332
|
+
const data = context.getImageData(0, 0, width, height).data;
|
|
333
|
+
let minX = width, minY = height, maxX = -1, maxY = -1;
|
|
334
|
+
for (let y = 0; y < height; y++) {
|
|
335
|
+
for (let x = 0; x < width; x++) {
|
|
336
|
+
if (!data[(y * width + x) * 4 + 3]) continue;
|
|
337
|
+
if (x < minX) minX = x; if (x > maxX) maxX = x;
|
|
338
|
+
if (y < minY) minY = y; if (y > maxY) maxY = y;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
if (maxX < 0) return null;
|
|
342
|
+
box = { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 };
|
|
343
|
+
}
|
|
344
|
+
const out = document.createElement('canvas');
|
|
345
|
+
out.width = box.width; out.height = box.height;
|
|
346
|
+
out.getContext('2d').drawImage(canvas, box.x, box.y, box.width, box.height, 0, 0, box.width, box.height);
|
|
347
|
+
return { data: out.toDataURL('image/png'), ...box };
|
|
348
|
+
} catch {
|
|
349
|
+
return null;
|
|
350
|
+
} finally {
|
|
351
|
+
URL.revokeObjectURL(url);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const INHERITED = ['fill', 'stroke', 'stroke-width', 'fill-opacity', 'stroke-opacity', 'fill-rule', 'font-family', 'font-size', 'font-weight',
|
|
356
|
+
'font-style', 'text-anchor', 'visibility', 'color', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'letter-spacing', 'word-spacing', 'marker-start', 'marker-mid', 'marker-end'];
|
|
357
|
+
const DRAWN = new Set(['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path', 'text', 'image', 'use']);
|
|
358
|
+
const DRAWN_OR_GROUP = new Set([...DRAWN, 'g', 'a', 'svg', 'switch']);
|
|
359
|
+
// What the browser is asked to draw for one file: pictures are a full stage each.
|
|
360
|
+
const MAX_PICTURES = 64, MAX_TILES = 64;
|
|
361
|
+
const ANIMATION = new Set(['animate', 'animateTransform', 'animateMotion', 'set']);
|
|
362
|
+
// CSS blend modes as Studio's (Flash's) blend mode numbers.
|
|
363
|
+
const BLEND_MODES = { multiply: 3, screen: 4, lighten: 5, darken: 6, difference: 7, overlay: 13, 'hard-light': 14, 'plus-lighter': 8 };
|
|
364
|
+
|
|
365
|
+
async function convert(svg, report, { measure, layoutText, resolveColor, rasterize }) {
|
|
366
|
+
const ids = new Map();
|
|
367
|
+
const index = node => {
|
|
368
|
+
if (node.attrs?.id) ids.set(node.attrs.id, node);
|
|
369
|
+
node.children?.forEach(index);
|
|
370
|
+
};
|
|
371
|
+
index(svg);
|
|
372
|
+
const reference = value => {
|
|
373
|
+
const id = String(value ?? '').match(/^\s*(?:url\(\s*['"]?)?#([^'")\s]+)/)?.[1];
|
|
374
|
+
return id ? ids.get(id) : undefined;
|
|
375
|
+
};
|
|
376
|
+
|
|
377
|
+
// Size: the viewBox is the stage; width and height only scale it.
|
|
378
|
+
const viewBox = String(svg.attrs.viewBox ?? '').split(/[\s,]+/).map(Number);
|
|
379
|
+
const hasBox = viewBox.length === 4 && viewBox.every(Number.isFinite) && viewBox[2] > 0 && viewBox[3] > 0;
|
|
380
|
+
const boxW = hasBox ? viewBox[2] : length(svg.attrs.width, 0, 300) || 300;
|
|
381
|
+
const boxH = hasBox ? viewBox[3] : length(svg.attrs.height, 0, 150) || 150;
|
|
382
|
+
const fit = Math.min(Math.max(1, 160 / boxW, 120 / boxH), 2400 / boxW, 1600 / boxH);
|
|
383
|
+
const width = Math.round(clamp(boxW * fit, 160, 2400)), height = Math.round(clamp(boxH * fit, 120, 1600));
|
|
384
|
+
if (fit !== 1) report(`A ${Math.round(boxW)} × ${Math.round(boxH)} image (scaled to ${width} × ${height})`);
|
|
385
|
+
const root = mul([fit, 0, 0, fit, 0, 0], hasBox ? translate(-viewBox[0], -viewBox[1]) : IDENTITY);
|
|
386
|
+
|
|
387
|
+
const elements = [], assets = [], images = new Map();
|
|
388
|
+
// Closed outlines of fills without a stroke and of strokes without a fill: a stroke drawn over the
|
|
389
|
+
// fill of the same outline (as Studio and other tools write them) becomes one object again.
|
|
390
|
+
const outlines = new Map();
|
|
391
|
+
const mergeOutlines = made => {
|
|
392
|
+
for (let k = made.length - 1; k > 0; k--) {
|
|
393
|
+
const stroke = made[k], fill = made[k - 1];
|
|
394
|
+
if (!outlines.get(stroke)?.startsWith('stroke ') || outlines.get(fill) !== `fill ${outlines.get(stroke).slice(7)}`) continue;
|
|
395
|
+
if (Math.abs(fill.opacity - stroke.opacity) > 0.01 || fill.maskId !== stroke.maskId || fill.effect || stroke.effect) continue;
|
|
396
|
+
fill.stroke = stroke.stroke;
|
|
397
|
+
fill.strokeWidth = stroke.strokeWidth;
|
|
398
|
+
if (stroke.strokeGradient) fill.strokeGradient = stroke.strokeGradient;
|
|
399
|
+
for (const key of ['lineCap', 'lineJoin', 'miterLimit', 'strokeDash', 'strokeDashOffset']) if (stroke[key] !== undefined) fill[key] = stroke[key];
|
|
400
|
+
made.splice(k, 1);
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
let nextId = 1;
|
|
404
|
+
const newId = prefix => `${prefix}-${nextId++}`;
|
|
405
|
+
|
|
406
|
+
// Style sheets: rules whose selectors are simple (tag, .class, #id, or a compound of them),
|
|
407
|
+
// ordered by specificity and then by place, as browsers do. Others are reported.
|
|
408
|
+
const sheet = [];
|
|
409
|
+
const collect = node => {
|
|
410
|
+
if (node.name === 'style') {
|
|
411
|
+
const css = (node.children ?? []).map(textOf).join('').replace(/\/\*[\s\S]*?\*\//g, '').slice(0, 1 << 20);
|
|
412
|
+
for (const [, selectors, body] of css.replace(/@[^{;]*;/g, '').matchAll(/([^{}@]+)\{([^{}]*)\}/g)) {
|
|
413
|
+
for (const selector of selectors.split(',').map(text => text.trim()).filter(Boolean)) {
|
|
414
|
+
const parts = selector.match(/^([a-zA-Z][\w-]*|\*)?((?:[.#][\w-]+)*)$/);
|
|
415
|
+
if (!parts) { report('Style sheet rules with combinators or pseudo-classes (left out)'); continue; }
|
|
416
|
+
const ids = [...parts[2].matchAll(/#([\w-]+)/g)].map(match => match[1]), classes = [...parts[2].matchAll(/\.([\w-]+)/g)].map(match => match[1]);
|
|
417
|
+
const tag = parts[1] && parts[1] !== '*' ? parts[1] : null;
|
|
418
|
+
sheet.push({ tag, ids, classes, body, order: sheet.length, specificity: ids.length * 10000 + classes.length * 100 + (tag ? 1 : 0) });
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
if (/@media|@supports/.test(css)) report('Style sheet @media and @supports rules (left out)');
|
|
422
|
+
}
|
|
423
|
+
node.children?.forEach(child => child.name && collect(child));
|
|
424
|
+
};
|
|
425
|
+
collect(svg);
|
|
426
|
+
sheet.sort((a, b) => a.specificity - b.specificity || a.order - b.order);
|
|
427
|
+
const rulesFor = node => {
|
|
428
|
+
if (!sheet.length || !node.name) return [];
|
|
429
|
+
const classes = String(node.attrs.class ?? '').split(/\s+/).filter(Boolean);
|
|
430
|
+
return sheet.filter(rule => (!rule.tag || rule.tag === node.name) && rule.ids.every(id => id === node.attrs.id) && rule.classes.every(name => classes.includes(name)));
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
// Style: presentation attributes, then style sheet rules, then the style attribute; inherited
|
|
434
|
+
// properties flow down, the node's own (opacity, display, clip-path, mask, filter) do not.
|
|
435
|
+
const OWN = ['opacity', 'display', 'clip-path', 'mask', 'filter', 'mix-blend-mode'];
|
|
436
|
+
const styleOf = (node, inherited) => {
|
|
437
|
+
const style = { ...inherited }, own = {};
|
|
438
|
+
for (const key of INHERITED) if (node.attrs[key] !== undefined) style[key] = node.attrs[key];
|
|
439
|
+
for (const key of OWN) if (node.attrs[key] !== undefined) own[key] = node.attrs[key];
|
|
440
|
+
const declare = text => {
|
|
441
|
+
for (const declaration of String(text ?? '').split(';')) {
|
|
442
|
+
const [key, ...rest] = declaration.split(':');
|
|
443
|
+
if (!key?.trim() || !rest.length) continue;
|
|
444
|
+
const name = key.trim().toLowerCase(), value = rest.join(':').replace(/!important/, '').trim();
|
|
445
|
+
if (OWN.includes(name)) own[name] = value;
|
|
446
|
+
else style[name] = value;
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
for (const rule of rulesFor(node)) declare(rule.body);
|
|
450
|
+
declare(node.attrs.style);
|
|
451
|
+
// The font shorthand: [style] [variant] [weight] size[/line-height] family.
|
|
452
|
+
const font = String(style.font ?? '').match(/^\s*((?:(?:italic|oblique|normal|small-caps|bold|bolder|lighter|[1-9]00)\s+)*)([\d.]+[a-z%]*)(?:\/\S+)?\s+(.+)$/i);
|
|
453
|
+
if (font) {
|
|
454
|
+
delete style.font;
|
|
455
|
+
style['font-size'] = font[2];
|
|
456
|
+
style['font-family'] = font[3];
|
|
457
|
+
style['font-weight'] = /bold|bolder|[6-9]00/i.test(font[1]) ? 'bold' : 'normal';
|
|
458
|
+
style['font-style'] = /italic|oblique/i.test(font[1]) ? 'italic' : 'normal';
|
|
459
|
+
}
|
|
460
|
+
for (const key of OWN) style[`own-${key}`] = own[key];
|
|
461
|
+
return style;
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
const paintOf = (value, style, opacityKey, patterns = false) => {
|
|
465
|
+
if (value === undefined) return null;
|
|
466
|
+
if (/^\s*url\(/.test(value)) {
|
|
467
|
+
const target = reference(value);
|
|
468
|
+
if (target?.name === 'linearGradient' || target?.name === 'radialGradient') return { gradient: target, alpha: clamp(finite(style[opacityKey], 1), 0, 1) };
|
|
469
|
+
const fallback = value.replace(/^\s*url\([^)]*\)\s*/, '');
|
|
470
|
+
const plain = fallback ? paintOf(fallback, style, opacityKey) : { color: '#808080', alpha: 1 };
|
|
471
|
+
if (target?.name === 'pattern') {
|
|
472
|
+
if (patterns && rasterize) return { pattern: target, color: plain?.color ?? '#808080', alpha: clamp(finite(style[opacityKey], 1), 0, 1) };
|
|
473
|
+
report(patterns ? 'Pattern fills (drawn in a plain colour)' : 'Pattern strokes and text (drawn in a plain colour)');
|
|
474
|
+
}
|
|
475
|
+
return plain;
|
|
476
|
+
}
|
|
477
|
+
const color = parseColor(value === 'currentColor' ? style.color ?? 'black' : value, resolveColor);
|
|
478
|
+
if (color === null) return null;
|
|
479
|
+
if (color === undefined) { report(`Colours Studio does not know (${String(value).slice(0, 30)}, drawn black)`); return { color: '#000000', alpha: 1 }; }
|
|
480
|
+
return { color: color.color, alpha: color.alpha * clamp(finite(style[opacityKey], 1), 0, 1) };
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
// A gradient with its inherited attributes and stops (href chains, capped).
|
|
484
|
+
const gradientData = node => {
|
|
485
|
+
const chain = [];
|
|
486
|
+
for (let at = node; at && chain.length < 16 && !chain.includes(at); at = reference(at.attrs.href ?? at.attrs['xlink:href'])) chain.push(at);
|
|
487
|
+
const attr = key => chain.find(item => item.attrs[key] !== undefined)?.attrs[key];
|
|
488
|
+
const stopNodes = chain.find(item => item.children.some(child => child.name === 'stop'))?.children.filter(child => child.name === 'stop') ?? [];
|
|
489
|
+
let last = 0;
|
|
490
|
+
const stops = stopNodes.map(stop => {
|
|
491
|
+
const style = styleOf(stop, {});
|
|
492
|
+
const raw = String(stop.attrs.offset ?? '0');
|
|
493
|
+
const ratio = clamp(Math.max(last, raw.endsWith('%') ? parseFloat(raw) / 100 : finite(raw)), 0, 1);
|
|
494
|
+
last = ratio;
|
|
495
|
+
const colorText = style['stop-color'] ?? stop.attrs['stop-color'] ?? 'black';
|
|
496
|
+
const color = parseColor(colorText, resolveColor) ?? { color: '#000000', alpha: 0 };
|
|
497
|
+
return { ratio: round(ratio), color: color.color, alpha: round(clamp(color.alpha * finite(style['stop-opacity'] ?? stop.attrs['stop-opacity'], 1), 0, 1)) };
|
|
498
|
+
});
|
|
499
|
+
return { node, attr, stops, units: attr('gradientUnits') ?? 'objectBoundingBox', transform: parseTransform(attr('gradientTransform')) };
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
// Studio's gradient (box-relative Flash gradient matrix) from an SVG gradient on a shape whose
|
|
503
|
+
// points were mapped by `matrix`; `box` is the shape's own bounding box before mapping, `center`
|
|
504
|
+
// and `size` the Studio object's box after.
|
|
505
|
+
const studioGradient = (paint, box, matrix, center, size) => {
|
|
506
|
+
const data = gradientData(paint.gradient);
|
|
507
|
+
if (!data.stops.length) return null;
|
|
508
|
+
const unit = data.units === 'objectBoundingBox' ? [box[2] - box[0] || 1, 0, 0, box[3] - box[1] || 1, box[0], box[1]] : IDENTITY;
|
|
509
|
+
const space = mul(matrix, mul(unit, data.transform));
|
|
510
|
+
const n = (key, fallback) => {
|
|
511
|
+
const value = data.attr(key);
|
|
512
|
+
if (value === undefined) return fallback;
|
|
513
|
+
return String(value).endsWith('%') ? parseFloat(value) / 100 : finite(value, fallback);
|
|
514
|
+
};
|
|
515
|
+
let g;
|
|
516
|
+
const gradient = { type: data.node.name === 'radialGradient' ? 'radial' : 'linear', endColor: data.stops.at(-1).color,
|
|
517
|
+
stops: data.stops.map(stop => ({ ...stop, alpha: round(stop.alpha * paint.alpha) })) };
|
|
518
|
+
if (['reflect', 'repeat'].includes(data.attr('spreadMethod'))) gradient.spreadMethod = data.attr('spreadMethod');
|
|
519
|
+
if (gradient.type === 'linear') {
|
|
520
|
+
const s = [n('x1', 0), n('y1', 0)], e = [n('x2', 1), n('y2', 0)];
|
|
521
|
+
const dx = e[0] - s[0], dy = e[1] - s[1], len = Math.hypot(dx, dy) || 1e-6, angle = Math.atan2(dy, dx);
|
|
522
|
+
const k = len / 1638.4;
|
|
523
|
+
g = [Math.cos(angle) * k, Math.sin(angle) * k, -Math.sin(angle) * k, Math.cos(angle) * k, (s[0] + e[0]) / 2, (s[1] + e[1]) / 2];
|
|
524
|
+
gradient.angle = round(angle * 180 / Math.PI);
|
|
525
|
+
} else {
|
|
526
|
+
const c = [n('cx', 0.5), n('cy', 0.5)], r = n('r', 0.5) || 1e-6, f = [n('fx', c[0]), n('fy', c[1])];
|
|
527
|
+
const turn = Math.atan2(f[1] - c[1], f[0] - c[0]), k = r / 819.2;
|
|
528
|
+
g = [Math.cos(turn) * k, Math.sin(turn) * k, -Math.sin(turn) * k, Math.cos(turn) * k, c[0], c[1]];
|
|
529
|
+
gradient.focus = round(clamp(Math.hypot(f[0] - c[0], f[1] - c[1]) / r, 0, 0.99));
|
|
530
|
+
}
|
|
531
|
+
g = mul(translate(-center[0], -center[1]), mul(space, g));
|
|
532
|
+
const [w, h] = size;
|
|
533
|
+
gradient.matrix = { a: round(g[0] * 819.2 / w), b: round(g[1] * 819.2 / h), c: round(g[2] * 819.2 / w), d: round(g[3] * 819.2 / h), tx: round(g[4] / w), ty: round(g[5] / h) };
|
|
534
|
+
return gradient;
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
const opacityPose = opacity => round(clamp(opacity, 0, 1));
|
|
538
|
+
const poseFor = matrix => {
|
|
539
|
+
const pose = studioPose(matrix);
|
|
540
|
+
return { x: round(clamp(pose.x, -100000, 100000)), y: round(clamp(pose.y, -100000, 100000)), rotation: round(pose.rotation),
|
|
541
|
+
skew: round(clamp(pose.skew, -85, 85)), scaleX: round(clamp(pose.scaleX, 0.01, 100)), scaleY: round(clamp(pose.scaleY, 0.01, 100)), mirror: pose.mirror };
|
|
542
|
+
};
|
|
543
|
+
const fits = m => {
|
|
544
|
+
const sx = Math.hypot(m[0], m[1]), sy = Math.hypot(m[2], m[3]);
|
|
545
|
+
return sx >= 0.01 && sx <= 100 && sy >= 0.01 && sy <= 100 && Math.abs(studioPose(m).skew) <= 85;
|
|
546
|
+
};
|
|
547
|
+
const place = (element, pose) => {
|
|
548
|
+
const { mirror, ...fields } = pose;
|
|
549
|
+
Object.assign(element, fields);
|
|
550
|
+
element.keyframes = [{ frame: 1, ...fields, ...(mirror ? { mirror: true } : {}), tween: 'linear' }];
|
|
551
|
+
return element;
|
|
552
|
+
};
|
|
553
|
+
|
|
554
|
+
// SVG's stroke details as the element's: SVG defaults to flat ends and sharp corners (miter
|
|
555
|
+
// limit 4), Studio to round ones; dash lengths scale with the stroke.
|
|
556
|
+
const strokeStyle = (element, style, scale) => {
|
|
557
|
+
const cap = String(style['stroke-linecap'] ?? 'butt').trim(), join = String(style['stroke-linejoin'] ?? 'miter').trim();
|
|
558
|
+
if (cap !== 'round') element.lineCap = cap === 'square' ? 'square' : 'butt';
|
|
559
|
+
if (join !== 'round') element.lineJoin = join === 'bevel' ? 'bevel' : 'miter';
|
|
560
|
+
if (element.lineJoin === 'miter') element.miterLimit = round(clamp(finite(style['stroke-miterlimit'], 4), 1, 255));
|
|
561
|
+
const dash = String(style['stroke-dasharray'] ?? 'none').trim();
|
|
562
|
+
if (dash !== 'none') {
|
|
563
|
+
const lengths = dash.split(/[\s,]+/).map(value => length(value, 0, NaN) * scale);
|
|
564
|
+
if (lengths.length && lengths.length <= 64 && lengths.every(value => Number.isFinite(value) && value >= 0) && lengths.some(value => value > 0)) {
|
|
565
|
+
element.strokeDash = lengths.map(value => round(clamp(value, 0, 10000)));
|
|
566
|
+
const offset = length(style['stroke-dashoffset'], 0, 0) * scale;
|
|
567
|
+
if (offset) element.strokeDashOffset = round(clamp(offset, -100000, 100000));
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
const strokeGradient = (element, paint, box, matrix, center, size) => {
|
|
573
|
+
const gradient = studioGradient(paint, box, matrix, center, size);
|
|
574
|
+
if (gradient) { element.strokeGradient = gradient; element.stroke = gradient.stops[0].color; }
|
|
575
|
+
};
|
|
576
|
+
|
|
577
|
+
// Whether one outline crosses itself (its curves flattened; very long outlines are not checked).
|
|
578
|
+
const selfCrossing = contour => {
|
|
579
|
+
const line = [];
|
|
580
|
+
const points = contour.closed ? [...contour.points, contour.points[0]] : contour.points;
|
|
581
|
+
for (let k = 1; k < points.length; k++) {
|
|
582
|
+
const a = points[k - 1], b = points[k];
|
|
583
|
+
const c1 = [a.x + a.out[0], a.y + a.out[1]], c2 = [b.x + b.in[0], b.y + b.in[1]];
|
|
584
|
+
const steps = a.out[0] || a.out[1] || b.in[0] || b.in[1] ? 8 : 1;
|
|
585
|
+
for (let i = k === 1 ? 0 : 1; i <= steps; i++) {
|
|
586
|
+
const t = i / steps, u = 1 - t;
|
|
587
|
+
line.push([u * u * u * a.x + 3 * u * u * t * c1[0] + 3 * u * t * t * c2[0] + t * t * t * b.x, u * u * u * a.y + 3 * u * u * t * c1[1] + 3 * u * t * t * c2[1] + t * t * t * b.y]);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
if (line.length > 1500) return false;
|
|
591
|
+
const cross = (p, q, r) => (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);
|
|
592
|
+
for (let i = 1; i < line.length; i++) {
|
|
593
|
+
for (let j = i + 2; j < line.length; j++) {
|
|
594
|
+
if (i === 1 && j === line.length - 1) continue;
|
|
595
|
+
const [p1, p2, p3, p4] = [line[i - 1], line[i], line[j - 1], line[j]];
|
|
596
|
+
const d1 = cross(p3, p4, p1), d2 = cross(p3, p4, p2), d3 = cross(p1, p2, p3), d4 = cross(p1, p2, p4);
|
|
597
|
+
if (((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0))) return true;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
return false;
|
|
601
|
+
};
|
|
602
|
+
|
|
603
|
+
// Shapes from contours in the element's own space, mapped by `matrix` into the stage.
|
|
604
|
+
// Drawing done by the browser after the walk (pattern tiles, pictures), awaited at the end.
|
|
605
|
+
const jobs = [];
|
|
606
|
+
const escapeXml = value => String(value).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
607
|
+
const serialize = node => node.text !== undefined ? escapeXml(node.text)
|
|
608
|
+
: `<${node.name}${Object.entries(node.attrs ?? {}).map(([key, value]) => ` ${key}="${escapeXml(value)}"`).join('')}>${(node.children ?? []).map(serialize).join('')}</${node.name}>`;
|
|
609
|
+
const namespaces = Object.entries(svg.attrs).filter(([key]) => key.startsWith('xmlns:') && key !== 'xmlns:xlink').map(([key, value]) => ` ${key}="${escapeXml(value)}"`).join('');
|
|
610
|
+
// What the drawn nodes need, kept out of sight: the style sheets, and every definition they
|
|
611
|
+
// refer to (gradients, filters, masks, patterns, symbols), followed through their own references.
|
|
612
|
+
const sheets = [];
|
|
613
|
+
const findSheets = node => { if (node.name === 'style') sheets.push(node); else node.children?.forEach(findSheets); };
|
|
614
|
+
findSheets(svg);
|
|
615
|
+
const standalone = (width, height, viewBox, nodes, body) => {
|
|
616
|
+
const needed = new Set(), queue = [...nodes];
|
|
617
|
+
while (queue.length && needed.size < 5000) {
|
|
618
|
+
const node = queue.pop();
|
|
619
|
+
for (const value of Object.values(node.attrs ?? {})) {
|
|
620
|
+
for (const match of String(value).matchAll(/(?:url\(\s*['"]?#|^\s*#)([^'")\s]+)/g)) {
|
|
621
|
+
const target = ids.get(match[1]);
|
|
622
|
+
if (target && !needed.has(target)) { needed.add(target); queue.push(target); }
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
node.children?.forEach(child => child.name && queue.push(child));
|
|
626
|
+
}
|
|
627
|
+
const library = `<defs>${[...sheets, ...needed].map(serialize).join('')}</defs>`;
|
|
628
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"${namespaces} width="${width}" height="${height}" viewBox="${viewBox}" preserveAspectRatio="none">${library}${body}</svg>`;
|
|
629
|
+
};
|
|
630
|
+
const addImage = (data, name) => {
|
|
631
|
+
if (!images.has(data)) {
|
|
632
|
+
const id = newId('image');
|
|
633
|
+
assets.push({ id, name, type: 'image/png', kind: 'image', data });
|
|
634
|
+
images.set(data, id);
|
|
635
|
+
}
|
|
636
|
+
return images.get(data);
|
|
637
|
+
};
|
|
638
|
+
const matrixText = m => `matrix(${m.map(value => +value.toFixed(6)).join(' ')})`;
|
|
639
|
+
|
|
640
|
+
// A pattern fill as Studio's bitmap fill: the tile drawn once by the browser, repeated, with
|
|
641
|
+
// the pattern's units, viewBox and transform. `box` is the shape's own bounds; `matrix` maps
|
|
642
|
+
// its space onto the stage; the path's points are relative to `center`.
|
|
643
|
+
const patterns = new Map();
|
|
644
|
+
const patternFill = (element, pattern, box, matrix, center) => {
|
|
645
|
+
const chain = [];
|
|
646
|
+
for (let item = pattern; item?.name === 'pattern' && chain.length < 16 && !chain.includes(item); item = reference(item.attrs.href ?? item.attrs['xlink:href'])) chain.push(item);
|
|
647
|
+
const attr = name => chain.find(item => item.attrs[name] !== undefined)?.attrs[name];
|
|
648
|
+
const content = chain.find(item => item.children?.some(child => child.name))?.children.filter(child => child.name) ?? [];
|
|
649
|
+
const [bx, by, bw, bh] = [box[0], box[1], box[2] - box[0], box[3] - box[1]];
|
|
650
|
+
const boxUnits = attr('patternUnits') !== 'userSpaceOnUse';
|
|
651
|
+
const unit = (value, origin, size) => boxUnits ? origin + (String(value ?? '0').trim().endsWith('%') ? parseFloat(value) / 100 : finite(value)) * size : length(value, size);
|
|
652
|
+
const x = unit(attr('x'), bx, bw), y = unit(attr('y'), by, bh), w = unit(attr('width'), 0, bw), h = unit(attr('height'), 0, bh);
|
|
653
|
+
const fail = note => { report(note); delete element.bitmapFill; };
|
|
654
|
+
if (!(w > 0 && h > 0) || !content.length) return fail('Empty patterns (drawn in a plain colour)');
|
|
655
|
+
const viewBox = String(attr('viewBox') ?? '').split(/[\s,]+/).map(Number);
|
|
656
|
+
const inner = viewBox.length === 4 && viewBox.every(Number.isFinite) && viewBox[2] > 0 && viewBox[3] > 0
|
|
657
|
+
? mul([w / viewBox[2], 0, 0, h / viewBox[3], 0, 0], translate(-viewBox[0], -viewBox[1]))
|
|
658
|
+
: attr('patternContentUnits') === 'objectBoundingBox' ? [bw, 0, 0, bh, 0, 0] : IDENTITY;
|
|
659
|
+
const tileToStage = mul(matrix, mul(parseTransform(attr('patternTransform')), translate(x, y)));
|
|
660
|
+
// Twice the stage resolution, at most 2048 pixels a side.
|
|
661
|
+
const scale = Math.max(Math.hypot(tileToStage[0], tileToStage[1]), Math.hypot(tileToStage[2], tileToStage[3])) * 2;
|
|
662
|
+
const pixels = [w, h].map(side => Math.max(1, Math.min(2048, Math.round(side * scale))));
|
|
663
|
+
const key = JSON.stringify([pattern.attrs.id, w, h, inner, pixels]);
|
|
664
|
+
if (!patterns.has(key) && patterns.size >= MAX_TILES) return fail(`More than ${MAX_TILES} pattern tiles (the rest drawn in a plain colour)`);
|
|
665
|
+
if (!patterns.has(key)) {
|
|
666
|
+
const text = standalone(pixels[0], pixels[1], `0 0 ${w} ${h}`, content, `<g transform="${matrixText(inner)}">${content.map(serialize).join('')}</g>`);
|
|
667
|
+
patterns.set(key, rasterize(text, pixels[0], pixels[1]).catch(() => null));
|
|
668
|
+
}
|
|
669
|
+
const m = mul(translate(-center[0], -center[1]), mul(tileToStage, [w / pixels[0], 0, 0, h / pixels[1], 0, 0]));
|
|
670
|
+
element.bitmapFill = { matrix: { a: m[0], b: m[1], c: m[2], d: m[3], tx: m[4], ty: m[5] }, repeat: true, smoothed: true };
|
|
671
|
+
jobs.push(patterns.get(key).then(result => {
|
|
672
|
+
if (!result) return fail('Patterns the browser could not draw (drawn in a plain colour)');
|
|
673
|
+
element.assetId = addImage(result.data, `pattern ${String(pattern.attrs.id ?? '').slice(0, 60)}`.trim());
|
|
674
|
+
}));
|
|
675
|
+
};
|
|
676
|
+
|
|
677
|
+
// What Studio cannot hold (soft masks, other filters) as a picture of how the browser draws it.
|
|
678
|
+
let pictures = 0;
|
|
679
|
+
const picture = (node, inherited, matrix, opacity) => {
|
|
680
|
+
const element = { id: newId('bitmap'), name: String(node.attrs.id ?? node.name).slice(0, 120), type: 'bitmap', assetId: '', width: 1, height: 1, fit: 'stretch' };
|
|
681
|
+
place(element, { ...poseFor(IDENTITY), opacity: opacityPose(opacity) });
|
|
682
|
+
const scale = Math.min(2, 4096 / Math.max(width, height));
|
|
683
|
+
const pixels = [Math.max(1, Math.round(width * scale)), Math.max(1, Math.round(height * scale))];
|
|
684
|
+
const styleAttributes = INHERITED.filter(key => inherited[key] !== undefined).map(key => ` ${key}="${escapeXml(inherited[key])}"`).join('');
|
|
685
|
+
const text = standalone(pixels[0], pixels[1], `0 0 ${width} ${height}`, [node, { attrs: inherited }], `<g transform="${matrixText(matrix)}"${styleAttributes}>${serialize(node)}</g>`);
|
|
686
|
+
jobs.push(rasterize(text, pixels[0], pixels[1], { crop: true }).catch(() => null).then(result => {
|
|
687
|
+
if (!result) { element.failed = true; return; }
|
|
688
|
+
element.assetId = addImage(result.data, `picture ${element.name}`.trim());
|
|
689
|
+
const size = { width: round(clamp(result.width / scale, 1, 10000)), height: round(clamp(result.height / scale, 1, 10000)),
|
|
690
|
+
x: round((result.x + result.width / 2) / scale), y: round((result.y + result.height / 2) / scale) };
|
|
691
|
+
Object.assign(element, size);
|
|
692
|
+
Object.assign(element.keyframes[0], { x: size.x, y: size.y });
|
|
693
|
+
}));
|
|
694
|
+
return element;
|
|
695
|
+
};
|
|
696
|
+
// A mask whose content is anything but opaque white has soft edges or partial coverage.
|
|
697
|
+
const softMask = mask => {
|
|
698
|
+
const seen = item => {
|
|
699
|
+
if (!item.name) return false;
|
|
700
|
+
const style = styleOf(item, {});
|
|
701
|
+
const paint = ['fill', 'stroke'].map(key => item.attrs[key] ?? style[key]).filter(value => value !== undefined && value !== 'none');
|
|
702
|
+
if (paint.some(value => !/^\s*(white|#fff|#ffffff|rgb\(\s*255\s*,\s*255\s*,\s*255\s*\))\s*$/i.test(value))) return true;
|
|
703
|
+
if (['opacity', 'fill-opacity', 'stroke-opacity'].some(key => finite(item.attrs[key] ?? style[key] ?? style[`own-${key}`], 1) < 1)) return true;
|
|
704
|
+
if ((item.attrs.filter ?? style['own-filter'] ?? 'none') !== 'none') return true;
|
|
705
|
+
return (item.children ?? []).some(seen);
|
|
706
|
+
};
|
|
707
|
+
return mask.children.some(seen);
|
|
708
|
+
};
|
|
709
|
+
|
|
710
|
+
const shape = (node, style, matrix, opacity, contours, primitive) => {
|
|
711
|
+
// A straight two-point outline (a line drawn as a path) encloses nothing to fill.
|
|
712
|
+
const flat = contours.every(contour => contour.points.length < 3 && contour.points.every(p => !p.in[0] && !p.in[1] && !p.out[0] && !p.out[1]));
|
|
713
|
+
const fillPaint = flat ? null : paintOf(style.fill ?? 'black', style, 'fill-opacity', true);
|
|
714
|
+
const strokePaint = paintOf(style.stroke, style, 'stroke-opacity');
|
|
715
|
+
const strokeWidth = strokePaint ? length(style['stroke-width'], 0, 1) : 0;
|
|
716
|
+
if (!fillPaint && !strokePaint) return [];
|
|
717
|
+
const own = bounds(contours);
|
|
718
|
+
const name = String(node.attrs.id ?? node.attrs['inkscape:label'] ?? node.name).slice(0, 120);
|
|
719
|
+
const lineScale = Math.sqrt(Math.abs(matrix[0] * matrix[3] - matrix[1] * matrix[2]));
|
|
720
|
+
const made = [];
|
|
721
|
+
// Rectangles and ellipses stay so when the pose can hold their transform.
|
|
722
|
+
if (primitive && fillPaint && !fillPaint.pattern && fits(matrix)) {
|
|
723
|
+
const [px, py, pw, ph] = primitive.box;
|
|
724
|
+
const element = { id: newId(primitive.type), name, type: primitive.type, width: round(clamp(pw, 1, 10000)), height: round(clamp(ph, 1, 10000)),
|
|
725
|
+
fill: fillPaint.color ?? '#000000', stroke: strokePaint?.color ?? '#000000', strokeWidth: strokePaint ? round(clamp(strokeWidth, 0, 3276.75)) : 0,
|
|
726
|
+
...(primitive.radius ? { cornerRadius: round(clamp(primitive.radius, 0, 5000)) } : {}) };
|
|
727
|
+
const center = [px + pw / 2, py + ph / 2];
|
|
728
|
+
place(element, { ...poseFor(mul(matrix, translate(...center))), opacity: opacityPose(opacity * (fillPaint.gradient ? 1 : fillPaint.alpha)) });
|
|
729
|
+
if (fillPaint.gradient) {
|
|
730
|
+
const gradient = studioGradient(fillPaint, own, translate(-center[0], -center[1]), [0, 0], [element.width, element.height]);
|
|
731
|
+
if (gradient) { element.gradient = gradient; element.fill = gradient.stops[0].color; element.keyframes[0].fill = element.fill; }
|
|
732
|
+
}
|
|
733
|
+
if (strokePaint?.gradient) strokeGradient(element, strokePaint, own, translate(-center[0], -center[1]), [0, 0], [element.width, element.height]);
|
|
734
|
+
if (strokePaint) strokeStyle(element, style, 1);
|
|
735
|
+
return [element];
|
|
736
|
+
}
|
|
737
|
+
// Paths: the transform is baked into the points, so any matrix fits.
|
|
738
|
+
const mapped = contours.map(contour => transformContour(contour, matrix));
|
|
739
|
+
const outline = mapped.map(contour => contour.points.map(p => [p.x, p.y, ...p.in, ...p.out].map(v => v.toFixed(2)).join(',')).join(' ')).join('|');
|
|
740
|
+
const box = bounds(mapped);
|
|
741
|
+
const cx = (box[0] + box[2]) / 2, cy = (box[1] + box[3]) / 2;
|
|
742
|
+
const size = [clamp(round(box[2] - box[0]), 1, 10000), clamp(round(box[3] - box[1]), 1, 10000)];
|
|
743
|
+
const base = { x: round(clamp(cx, -100000, 100000)), y: round(clamp(cy, -100000, 100000)), rotation: 0, skew: 0, scaleX: 1, scaleY: 1 };
|
|
744
|
+
if (fillPaint) {
|
|
745
|
+
// Closed and open contours alike are filled closed, as SVG fills them. Studio fills even-odd.
|
|
746
|
+
const [main, ...rest] = mapped;
|
|
747
|
+
const element = { id: newId('path'), name, type: 'path', closed: true, points: studioPoints(main, cx, cy), width: size[0], height: size[1],
|
|
748
|
+
fill: fillPaint.color ?? '#000000', strokeWidth: 0, ...(rest.length ? { subpaths: rest.map(contour => studioPoints(contour, cx, cy)) } : {}) };
|
|
749
|
+
if (strokePaint && mapped.every(contour => contour.closed) && (strokePaint.gradient || Math.abs(strokePaint.alpha - fillPaint.alpha) < 0.01 || fillPaint.gradient)) {
|
|
750
|
+
element.stroke = strokePaint.color ?? '#000000';
|
|
751
|
+
element.strokeWidth = round(clamp(strokeWidth * lineScale, 0, 3276.75));
|
|
752
|
+
if (strokePaint.gradient) strokeGradient(element, strokePaint, own, matrix, [cx, cy], size);
|
|
753
|
+
strokeStyle(element, style, lineScale);
|
|
754
|
+
}
|
|
755
|
+
// SVG fills nonzero by default; Studio fills compound paths even-odd unless told.
|
|
756
|
+
const evenOdd = String(style['fill-rule'] ?? '').trim() === 'evenodd';
|
|
757
|
+
if (!evenOdd && mapped.length > 1) element.fillRule = 'nonzero';
|
|
758
|
+
if (evenOdd && mapped.length === 1 && selfCrossing(main)) element.fillRule = 'evenodd';
|
|
759
|
+
place(element, { ...base, opacity: opacityPose(opacity * (fillPaint.gradient ? 1 : fillPaint.alpha)) });
|
|
760
|
+
if (!element.strokeWidth && mapped.every(contour => contour.closed)) outlines.set(element, `fill ${outline}`);
|
|
761
|
+
if (fillPaint.gradient) {
|
|
762
|
+
const gradient = studioGradient(fillPaint, own, matrix, [cx, cy], size);
|
|
763
|
+
if (gradient) { element.gradient = gradient; element.fill = gradient.stops[0].color; element.keyframes[0].fill = element.fill; }
|
|
764
|
+
}
|
|
765
|
+
if (fillPaint.pattern) patternFill(element, fillPaint.pattern, own, matrix, [cx, cy]);
|
|
766
|
+
made.push(element);
|
|
767
|
+
if (!strokePaint || element.strokeWidth) return made;
|
|
768
|
+
}
|
|
769
|
+
// Strokes on their own, or of open outlines: one open path each.
|
|
770
|
+
const color = strokePaint.color ?? gradientData(strokePaint.gradient).stops[0]?.color ?? '#000000';
|
|
771
|
+
mapped.forEach((contour, k) => {
|
|
772
|
+
const points = contour.closed ? [...contour.points, { ...contour.points[0], out: [0, 0] }] : contour.points;
|
|
773
|
+
const own = bounds([contour]);
|
|
774
|
+
const ox = (own[0] + own[2]) / 2, oy = (own[1] + own[3]) / 2;
|
|
775
|
+
const element = { id: newId('path'), name: mapped.length > 1 ? `${name} ${k + 1}` : name, type: 'path', closed: false,
|
|
776
|
+
points: studioPoints({ points }, ox, oy), width: clamp(round(own[2] - own[0]), 1, 10000), height: clamp(round(own[3] - own[1]), 1, 10000),
|
|
777
|
+
fill: '#000000', stroke: color, strokeWidth: round(clamp(strokeWidth * lineScale, 0, 3276.75)) };
|
|
778
|
+
place(element, { ...base, x: round(clamp(ox, -100000, 100000)), y: round(clamp(oy, -100000, 100000)), opacity: opacityPose(opacity * (strokePaint.gradient ? 1 : strokePaint.alpha)) });
|
|
779
|
+
if (strokePaint.gradient) strokeGradient(element, strokePaint, contours.length === 1 ? bounds([contours[k]]) : bounds(contours), matrix, [ox, oy], [element.width, element.height]);
|
|
780
|
+
strokeStyle(element, style, lineScale);
|
|
781
|
+
if (!fillPaint && mapped.length === 1 && contour.closed) outlines.set(element, `stroke ${outline}`);
|
|
782
|
+
made.push(element);
|
|
783
|
+
});
|
|
784
|
+
return made;
|
|
785
|
+
};
|
|
786
|
+
|
|
787
|
+
// What text on a path places as one piece: a grapheme (a letter with its marks), or a whole
|
|
788
|
+
// word in scripts whose letters join and reshape (Arabic, Indic, Southeast Asian), which come
|
|
789
|
+
// apart when drawn letter by letter.
|
|
790
|
+
const JOINING = /[\u0590-\u08ff\u0900-\u0dff\u0f00-\u0fff\u1000-\u109f\u1780-\u17ff\ua8e0-\ua8ff\ufb1d-\ufdff\ufe70-\ufeff]/u;
|
|
791
|
+
const graphemes = typeof Intl !== 'undefined' && Intl.Segmenter ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null;
|
|
792
|
+
const clusters = text => {
|
|
793
|
+
const pieces = graphemes ? [...graphemes.segment(text)].map(item => item.segment) : [...text];
|
|
794
|
+
const out = [];
|
|
795
|
+
for (const piece of pieces) {
|
|
796
|
+
if (out.length && piece !== ' ' && JOINING.test(piece) && JOINING.test(out.at(-1))) out[out.length - 1] += piece;
|
|
797
|
+
else out.push(piece);
|
|
798
|
+
}
|
|
799
|
+
return out;
|
|
800
|
+
};
|
|
801
|
+
|
|
802
|
+
// Font, size and measuring for a text style (sizes outside Studio's range are scaled).
|
|
803
|
+
const fontOf = style => {
|
|
804
|
+
const size = length(style['font-size'], 16, 16) || 16;
|
|
805
|
+
const fontSize = clamp(size, 6, 240), scale = size / fontSize;
|
|
806
|
+
const family = String(style['font-family'] ?? 'Arial').split(',')[0].replace(/['"]/g, '').trim() || 'Arial';
|
|
807
|
+
const bold = /bold|bolder|[6-9]00/.test(String(style['font-weight'] ?? ''));
|
|
808
|
+
const italic = /italic|oblique/.test(String(style['font-style'] ?? ''));
|
|
809
|
+
const css = `${italic ? 'italic ' : ''}${bold ? 'bold ' : ''}${fontSize}px ${family}`;
|
|
810
|
+
const metrics = text => measure?.(css, text) ?? { width: text.length * fontSize * 0.55, fontBoundingBoxAscent: fontSize * 0.9 };
|
|
811
|
+
return { fontSize, scale, family, bold, italic, metrics };
|
|
812
|
+
};
|
|
813
|
+
|
|
814
|
+
// A text object whose anchor point (left, centre or right end of the first baseline) is placed
|
|
815
|
+
// by `at`, a matrix from the text's own space.
|
|
816
|
+
const textObject = (lines, font, align, at, fillPaint, opacity, name) => {
|
|
817
|
+
const { fontSize, scale, family, bold, italic, metrics } = font;
|
|
818
|
+
const widest = Math.max(1, ...lines.map(line => metrics(line).width));
|
|
819
|
+
const boxWidth = Math.ceil(widest + 12), boxHeight = Math.ceil(fontSize * 1.25 * lines.length + 8);
|
|
820
|
+
let ox = align === 'left' ? -boxWidth / 2 + 2 : align === 'right' ? boxWidth / 2 - 2 : 0;
|
|
821
|
+
let oy = -boxHeight / 2 + 2 + (metrics('Hg').fontBoundingBoxAscent ?? fontSize * 0.9);
|
|
822
|
+
const fields = { text: lines.join('\n'), fontFamily: family, fontSize: round(fontSize), bold, textAlign: align, width: boxWidth, height: boxHeight };
|
|
823
|
+
const placed = layoutText?.({ ...fields, textColor: '#000000', ...(italic ? { italic } : {}) });
|
|
824
|
+
if (placed) { ox = placed.x; oy = placed.baseline; }
|
|
825
|
+
const element = { id: newId('text'), name: String(name).slice(0, 120), type: 'text', ...fields, textColor: fillPaint.color ?? '#000000', strokeWidth: 0,
|
|
826
|
+
...(italic ? { italic: true } : {}) };
|
|
827
|
+
place(element, { ...poseFor(mul(at, mul([scale, 0, 0, scale, 0, 0], translate(-ox, -oy)))), opacity: opacityPose(opacity * (fillPaint.alpha ?? 1)) });
|
|
828
|
+
return element;
|
|
829
|
+
};
|
|
830
|
+
|
|
831
|
+
// Text on a path: each letter its own text object, centred on the path at its distance along
|
|
832
|
+
// it and turned with it, as SVG lays glyphs out (letters past the path's end are not drawn).
|
|
833
|
+
const textOnPath = (textPath, style, matrix, opacity) => {
|
|
834
|
+
const own = styleOf(textPath, style);
|
|
835
|
+
const fillPaint = paintOf(own.fill ?? 'black', own, 'fill-opacity');
|
|
836
|
+
const target = reference(textPath.attrs.href ?? textPath.attrs['xlink:href']);
|
|
837
|
+
const d = target?.name === 'path' ? target.attrs.d : textPath.attrs.path;
|
|
838
|
+
if (!fillPaint || !d) { if (!d) report('Text on a missing path (left out)'); return []; }
|
|
839
|
+
// The letters, with what each tspan adds: dx and dy shifts (cumulative), rotations (the last
|
|
840
|
+
// one repeats), letter and word spacing. Runs of white space are one space.
|
|
841
|
+
const chars = [];
|
|
842
|
+
const gather = (item, itemStyle, inherited) => {
|
|
843
|
+
const lists = { ...inherited };
|
|
844
|
+
for (const key of ['dx', 'dy', 'rotate']) {
|
|
845
|
+
if (item.attrs?.[key] !== undefined) lists[key] = { values: String(item.attrs[key]).trim().split(/[\s,]+/).map(value => length(value)), start: chars.length };
|
|
846
|
+
}
|
|
847
|
+
const spacing = length(itemStyle['letter-spacing']), word = length(itemStyle['word-spacing']);
|
|
848
|
+
for (const child of item.children ?? []) {
|
|
849
|
+
if (child.text !== undefined) {
|
|
850
|
+
for (const ch of clusters(child.text.replace(/\s+/g, ' '))) {
|
|
851
|
+
if (ch === ' ' && (!chars.length || chars.at(-1).ch === ' ')) continue;
|
|
852
|
+
if (chars.length >= 4000) return;
|
|
853
|
+
const at = key => {
|
|
854
|
+
const list = lists[key], index = chars.length - (list?.start ?? 0);
|
|
855
|
+
return !list ? 0 : key === 'rotate' ? list.values[Math.min(index, list.values.length - 1)] : list.values[index] ?? 0;
|
|
856
|
+
};
|
|
857
|
+
chars.push({ ch, dx: at('dx'), dy: at('dy'), rotate: at('rotate'), spacing: spacing + (ch === ' ' ? word : 0) });
|
|
858
|
+
}
|
|
859
|
+
} else if (child.name === 'tspan') gather(child, styleOf(child, itemStyle), lists);
|
|
860
|
+
}
|
|
861
|
+
};
|
|
862
|
+
gather(textPath, own, {});
|
|
863
|
+
while (chars.at(-1)?.ch === ' ') chars.pop();
|
|
864
|
+
const string = chars.map(item => item.ch).join('');
|
|
865
|
+
if (!string) return [];
|
|
866
|
+
// Prefix widths by cluster (a cluster may be several code units).
|
|
867
|
+
const ends = [];
|
|
868
|
+
chars.reduce((sum, item) => { ends.push(sum + item.ch.length); return sum + item.ch.length; }, 0);
|
|
869
|
+
// The path as straight pieces, in the text's space (its own transform applies).
|
|
870
|
+
const pathMatrix = target?.attrs.transform ? parseTransform(target.attrs.transform) : IDENTITY;
|
|
871
|
+
const pieces = [];
|
|
872
|
+
let total = 0;
|
|
873
|
+
for (const contour of parsePathData(d)) {
|
|
874
|
+
const points = contour.points, count = points.length;
|
|
875
|
+
const segments = contour.closed ? count : count - 1;
|
|
876
|
+
for (let k = 0; k < segments; k++) {
|
|
877
|
+
const p = points[k], q = points[(k + 1) % count];
|
|
878
|
+
const c = [[p.x, p.y], [p.x + p.out[0], p.y + p.out[1]], [q.x + q.in[0], q.y + q.in[1]], [q.x, q.y]];
|
|
879
|
+
const curved = p.out[0] || p.out[1] || q.in[0] || q.in[1];
|
|
880
|
+
let previous = apply(pathMatrix, c[0]);
|
|
881
|
+
for (let i = 1, n = curved ? 24 : 1; i <= n; i++) {
|
|
882
|
+
const t = i / n, u = 1 - t;
|
|
883
|
+
const next = apply(pathMatrix, [0, 1].map(j => u * u * u * c[0][j] + 3 * u * u * t * c[1][j] + 3 * u * t * t * c[2][j] + t * t * t * c[3][j]));
|
|
884
|
+
const span = Math.hypot(next[0] - previous[0], next[1] - previous[1]);
|
|
885
|
+
if (span > 0) { pieces.push({ from: previous, to: next, start: total, span }); total += span; }
|
|
886
|
+
previous = next;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
if (!(total > 0)) return [];
|
|
891
|
+
const font = fontOf(own);
|
|
892
|
+
const widthOf = text => font.metrics(text).width * font.scale;
|
|
893
|
+
const anchor = own['text-anchor'] ?? 'start';
|
|
894
|
+
const full = widthOf(string) + chars.reduce((sum, item) => sum + item.dx + item.spacing, 0);
|
|
895
|
+
const distance = length(textPath.attrs.startOffset, total, 0) - (anchor === 'middle' ? full / 2 : anchor === 'end' ? full : 0);
|
|
896
|
+
const made = [];
|
|
897
|
+
let before = 0, shift = 0, lift = 0, piece = 0;
|
|
898
|
+
for (let i = 0; i < chars.length; i++) {
|
|
899
|
+
const after = widthOf(string.slice(0, ends[i])), advance = after - before;
|
|
900
|
+
shift += chars[i].dx;
|
|
901
|
+
lift += chars[i].dy;
|
|
902
|
+
const centre = distance + before + shift + advance / 2;
|
|
903
|
+
before = after;
|
|
904
|
+
shift += chars[i].spacing;
|
|
905
|
+
if (chars[i].ch === ' ' || centre < 0 || centre > total) continue;
|
|
906
|
+
while (piece < pieces.length - 1 && pieces[piece].start + pieces[piece].span < centre) piece++;
|
|
907
|
+
while (piece > 0 && pieces[piece].start > centre) piece--;
|
|
908
|
+
const { from, to, start, span } = pieces[piece], t = (centre - start) / span;
|
|
909
|
+
const angle = Math.atan2(to[1] - from[1], to[0] - from[0]), turn = angle + chars[i].rotate * Math.PI / 180;
|
|
910
|
+
const x = from[0] + (to[0] - from[0]) * t - Math.sin(angle) * lift, y = from[1] + (to[1] - from[1]) * t + Math.cos(angle) * lift;
|
|
911
|
+
const at = mul(matrix, [Math.cos(turn), Math.sin(turn), -Math.sin(turn), Math.cos(turn), x, y]);
|
|
912
|
+
made.push(textObject([chars[i].ch], font, 'center', at, fillPaint, opacity, `${string.slice(0, 40)} ${made.length + 1}`));
|
|
913
|
+
}
|
|
914
|
+
if (made.length > 1) {
|
|
915
|
+
const groupId = newId('group');
|
|
916
|
+
for (const item of made) item.groupId = groupId;
|
|
917
|
+
}
|
|
918
|
+
if (fillPaint.gradient) report('Gradient text (in its first colour)');
|
|
919
|
+
return made;
|
|
920
|
+
};
|
|
921
|
+
|
|
922
|
+
const textElement = (node, style, matrix, opacity) => {
|
|
923
|
+
const fillPaint = paintOf(style.fill ?? 'black', style, 'fill-opacity');
|
|
924
|
+
// Lines: the text's own run, then each tspan with its own position starts a new line.
|
|
925
|
+
const lines = [''];
|
|
926
|
+
const onPaths = [];
|
|
927
|
+
const walk = item => {
|
|
928
|
+
for (const child of item.children ?? []) {
|
|
929
|
+
if (child.text !== undefined) lines[lines.length - 1] += child.text;
|
|
930
|
+
else if (child.name === 'textPath') onPaths.push(child);
|
|
931
|
+
else if (child.name === 'tspan') {
|
|
932
|
+
if ((child.attrs.y !== undefined || child.attrs.dy !== undefined) && lines.at(-1).trim()) lines.push('');
|
|
933
|
+
walk(child);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
walk(node);
|
|
938
|
+
const made = onPaths.flatMap(textPath => textOnPath(textPath, style, matrix, opacity));
|
|
939
|
+
const clean = lines.map(line => line.replace(/\s+/g, ' ').trim()).filter(Boolean);
|
|
940
|
+
if (!clean.length || !fillPaint) return made;
|
|
941
|
+
const align = { middle: 'center', end: 'right' }[style['text-anchor']] ?? 'left';
|
|
942
|
+
const first = node.children.find(child => child.name === 'tspan' && child.attrs.x !== undefined);
|
|
943
|
+
const x = length(String(node.attrs.x ?? first?.attrs.x ?? 0).split(/[\s,]+/)[0]) + length(node.attrs.dx);
|
|
944
|
+
const y = length(String(node.attrs.y ?? first?.attrs.y ?? 0).split(/[\s,]+/)[0]) + length(node.attrs.dy);
|
|
945
|
+
if (fillPaint.gradient) report('Gradient text (in its first colour)');
|
|
946
|
+
return [textObject(clean, fontOf(style), align, mul(matrix, translate(x, y)), fillPaint, opacity, node.attrs.id ?? clean[0]), ...made];
|
|
947
|
+
};
|
|
948
|
+
|
|
949
|
+
const imageElement = (node, matrix, opacity) => {
|
|
950
|
+
const href = String(node.attrs.href ?? node.attrs['xlink:href'] ?? '');
|
|
951
|
+
const type = href.match(/^data:(image\/(?:png|jpeg|gif|webp|svg\+xml));base64,/i)?.[1];
|
|
952
|
+
if (!type) { report('Images linked from outside the file (left out)'); return []; }
|
|
953
|
+
if (!images.has(href)) {
|
|
954
|
+
const id = newId('image');
|
|
955
|
+
assets.push({ id, name: node.attrs.id ?? `image ${assets.length + 1}`, type: type.toLowerCase(), kind: 'image', data: href });
|
|
956
|
+
images.set(href, id);
|
|
957
|
+
}
|
|
958
|
+
const w = length(node.attrs.width, 0, 0), h = length(node.attrs.height, 0, 0);
|
|
959
|
+
if (!(w > 0 && h > 0)) { report('Images without a width and height (left out)'); return []; }
|
|
960
|
+
if (node.attrs.preserveAspectRatio && node.attrs.preserveAspectRatio !== 'none') report('Images fitted with preserveAspectRatio (stretched to their box)');
|
|
961
|
+
const element = { id: newId('bitmap'), name: String(node.attrs.id ?? 'image').slice(0, 120), type: 'bitmap', assetId: images.get(href),
|
|
962
|
+
width: round(clamp(w, 1, 10000)), height: round(clamp(h, 1, 10000)) };
|
|
963
|
+
place(element, { ...poseFor(mul(matrix, translate(length(node.attrs.x) + w / 2, length(node.attrs.y) + h / 2))), opacity: opacityPose(opacity) });
|
|
964
|
+
return [element];
|
|
965
|
+
};
|
|
966
|
+
|
|
967
|
+
// An SVG filter as Studio's effect, when it is a blur, or a shadow or glow (blur, offset, colour):
|
|
968
|
+
// the forms Studio and most editors write. Sizes are mapped by `matrix` into the stage.
|
|
969
|
+
const effectFor = (filter, matrix) => {
|
|
970
|
+
const steps = filter.children.filter(child => child.name?.startsWith('fe'));
|
|
971
|
+
const names = steps.map(step => step.name);
|
|
972
|
+
const known = new Set(['feGaussianBlur', 'feOffset', 'feColorMatrix', 'feComponentTransfer', 'feFlood', 'feComposite', 'feMerge', 'feBlend']);
|
|
973
|
+
if (!steps.length || names.some(name => !known.has(name))) return null;
|
|
974
|
+
// Inner shadows and glows paint inside the outline, from its inverted alpha: Inkscape floods
|
|
975
|
+
// `out` of the source, Figma subtracts arithmetically, Studio inverts with a colour matrix.
|
|
976
|
+
const values = step => String(step.attrs.values ?? '').trim().split(/[\s,]+/).map(Number);
|
|
977
|
+
const inverting = step => (step.name === 'feComposite' && step.attrs.operator === 'out' && /^Source/.test(step.attrs.in2 ?? '') && !/^Source/.test(step.attrs.in ?? 'x'))
|
|
978
|
+
|| (step.name === 'feComposite' && step.attrs.operator === 'arithmetic' && !finite(step.attrs.k1) && finite(step.attrs.k2) * finite(step.attrs.k3) < 0)
|
|
979
|
+
|| (step.name === 'feColorMatrix' && values(step).length === 20 && values(step)[18] < 0 && values(step)[19] > 0);
|
|
980
|
+
const inner = steps.some(inverting);
|
|
981
|
+
// Other blends and arithmetic composites are not shadows.
|
|
982
|
+
if (steps.some(step => (step.name === 'feBlend' && (step.attrs.mode ?? 'normal') !== 'normal') || (step.name === 'feComposite' && step.attrs.operator === 'arithmetic' && !inverting(step)))) return null;
|
|
983
|
+
const deviation = String(steps.find(step => step.name === 'feGaussianBlur')?.attrs.stdDeviation ?? '0').trim().split(/[\s,]+/).map(Number);
|
|
984
|
+
const blur = (value, scale) => round(clamp(Math.sqrt(12 * (finite(value) * scale) ** 2 + 1), 0, 255));
|
|
985
|
+
const [blurX, blurY] = [blur(deviation[0], Math.hypot(matrix[0], matrix[1])), blur(deviation[1] ?? deviation[0], Math.hypot(matrix[2], matrix[3]))];
|
|
986
|
+
if (names.every(name => name === 'feGaussianBlur')) return names.length === 1 ? { type: 'blur', blurX, blurY } : null;
|
|
987
|
+
// A shadow paints a colour from the blurred alpha under the source.
|
|
988
|
+
if (!inner && steps.some(step => step.name === 'feComposite' && step.attrs.operator === 'in' && step.attrs.in2 === 'SourceGraphic' && !step.attrs.in?.startsWith('Source'))) return null;
|
|
989
|
+
let color = '#000000', alpha = 1;
|
|
990
|
+
// The colour is the last colour matrix (Figma first writes a hard alpha one).
|
|
991
|
+
const tint = steps.filter(step => step.name === 'feColorMatrix' && (step.attrs.type ?? 'matrix') === 'matrix' && !inverting(step)).at(-1);
|
|
992
|
+
const numbers = String(tint?.attrs.values ?? '').trim().split(/[\s,]+/).map(Number);
|
|
993
|
+
if (numbers.length === 20 && [0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17].every(k => Math.abs(numbers[k]) < 1e-6)) {
|
|
994
|
+
color = `#${[4, 9, 14].map(k => hex2(numbers[k] * 255)).join('')}`;
|
|
995
|
+
// Studio writes its glow strength here and the alpha as a transfer slope.
|
|
996
|
+
alpha = steps.some(step => step.name === 'feComponentTransfer') ? 1 : numbers[18];
|
|
997
|
+
} else {
|
|
998
|
+
const flood = steps.find(step => step.name === 'feFlood' && finite(step.attrs['flood-opacity'], 1) > 0);
|
|
999
|
+
const parsed = flood && parseColor(styleOf(flood, {})['flood-color'] ?? flood.attrs['flood-color'] ?? 'black', resolveColor);
|
|
1000
|
+
if (parsed) { color = parsed.color; alpha = parsed.alpha * finite(styleOf(flood, {})['flood-opacity'] ?? flood.attrs['flood-opacity'], 1); }
|
|
1001
|
+
}
|
|
1002
|
+
const slope = steps.find(step => step.name === 'feComponentTransfer')?.children.find(child => child.name === 'feFuncA')?.attrs.slope;
|
|
1003
|
+
if (slope !== undefined) alpha *= finite(slope, 1);
|
|
1004
|
+
const offset = steps.find(step => step.name === 'feOffset');
|
|
1005
|
+
const local = [finite(offset?.attrs.dx), finite(offset?.attrs.dy)];
|
|
1006
|
+
const [dx, dy] = [matrix[0] * local[0] + matrix[2] * local[1], matrix[1] * local[0] + matrix[3] * local[1]];
|
|
1007
|
+
const fields = { color, alpha: round(clamp(alpha, 0, 1)), blurX, blurY, ...(inner ? { inner: true } : {}) };
|
|
1008
|
+
const distance = Math.hypot(dx, dy);
|
|
1009
|
+
if (distance < 0.01) return { type: 'glow', ...fields };
|
|
1010
|
+
return { type: 'shadow', ...fields, distance: round(clamp(distance, 0, 1000)), angle: round(((Math.atan2(dy, dx) * 180 / Math.PI) + 360) % 360) };
|
|
1011
|
+
};
|
|
1012
|
+
|
|
1013
|
+
// Line markers (arrowheads, dots) drawn at the vertices of a line, polyline, polygon or path,
|
|
1014
|
+
// turned with the line where `orient` says so and sized by its stroke width.
|
|
1015
|
+
const markersFor = (node, style, matrix, opacity, contours, depth, useDepth) => {
|
|
1016
|
+
const made = [];
|
|
1017
|
+
const kinds = ['start', 'mid', 'end'].map(kind => [kind, reference(style[`marker-${kind}`] ?? style.marker)]).filter(([, marker]) => marker?.name === 'marker');
|
|
1018
|
+
if (!kinds.length || useDepth > 16) return made;
|
|
1019
|
+
const strokeWidth = length(style['stroke-width'], 0, 1);
|
|
1020
|
+
const angle = (x, y) => Math.atan2(y, x);
|
|
1021
|
+
const vertices = [];
|
|
1022
|
+
for (const contour of contours) {
|
|
1023
|
+
const points = contour.points, count = points.length;
|
|
1024
|
+
points.forEach((point, k) => {
|
|
1025
|
+
const previous = points[k - 1] ?? (contour.closed ? points[count - 1] : null), next = points[k + 1] ?? (contour.closed ? points[0] : null);
|
|
1026
|
+
const incoming = previous && (point.in[0] || point.in[1] ? angle(-point.in[0], -point.in[1]) : angle(point.x - previous.x, point.y - previous.y));
|
|
1027
|
+
const outgoing = next && (point.out[0] || point.out[1] ? angle(point.out[0], point.out[1]) : angle(next.x - point.x, next.y - point.y));
|
|
1028
|
+
const turn = incoming == null ? outgoing : outgoing == null ? incoming : incoming + Math.atan2(Math.sin(outgoing - incoming), Math.cos(outgoing - incoming)) / 2;
|
|
1029
|
+
vertices.push({ x: point.x, y: point.y, turn: turn ?? 0, kind: k === 0 ? 'start' : k === count - 1 && !contour.closed ? 'end' : 'mid' });
|
|
1030
|
+
});
|
|
1031
|
+
if (contour.closed) vertices.push({ ...vertices[vertices.length - count], kind: 'end' });
|
|
1032
|
+
}
|
|
1033
|
+
if (vertices.length > 5000) { report('Lines with more than 5000 markers (left out)'); return made; }
|
|
1034
|
+
for (const [kind, marker] of kinds) {
|
|
1035
|
+
const m = marker.attrs;
|
|
1036
|
+
const w = length(m.markerWidth, 0, 3), h = length(m.markerHeight, 0, 3);
|
|
1037
|
+
const box = String(m.viewBox ?? '').split(/[\s,]+/).map(Number);
|
|
1038
|
+
const viewBox = box.length === 4 && box.every(Number.isFinite) && box[2] > 0 && box[3] > 0;
|
|
1039
|
+
const fit = viewBox ? Math.min(w / box[2], h / box[3]) : 1;
|
|
1040
|
+
const content = viewBox ? mul([fit, 0, 0, fit, 0, 0], translate(-box[0], -box[1])) : IDENTITY;
|
|
1041
|
+
const ref = apply(content, [length(m.refX), length(m.refY)]);
|
|
1042
|
+
const units = m.markerUnits === 'userSpaceOnUse' ? 1 : strokeWidth;
|
|
1043
|
+
for (const vertex of vertices.filter(item => item.kind === kind)) {
|
|
1044
|
+
const orient = String(m.orient ?? '0');
|
|
1045
|
+
const turn = orient === 'auto' ? vertex.turn : orient === 'auto-start-reverse' ? vertex.turn + (kind === 'start' ? Math.PI : 0) : finite(parseFloat(orient)) * Math.PI / 180;
|
|
1046
|
+
const at = mul(matrix, mul(translate(vertex.x, vertex.y), mul([Math.cos(turn), Math.sin(turn), -Math.sin(turn), Math.cos(turn), 0, 0],
|
|
1047
|
+
mul([units, 0, 0, units, 0, 0], mul(translate(-ref[0], -ref[1]), content)))));
|
|
1048
|
+
walkNodes(marker.children, styleOf(marker, {}), at, opacity, made, depth + 1, false, useDepth + 1);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
return made;
|
|
1052
|
+
};
|
|
1053
|
+
|
|
1054
|
+
// A clip path's shapes, or an SVG mask's (its shapes' outline, without its shades), as one mask
|
|
1055
|
+
// object: the first shape; others are reported.
|
|
1056
|
+
const maskFor = (clip, matrix) => {
|
|
1057
|
+
const made = [];
|
|
1058
|
+
const userSpace = (clip.attrs.clipPathUnits ?? clip.attrs.maskContentUnits) !== 'objectBoundingBox';
|
|
1059
|
+
if (!userSpace) { report('Clip paths and masks in bounding-box units (left out)'); return null; }
|
|
1060
|
+
walkNodes(clip.children, { fill: 'black' }, mul(matrix, parseTransform(clip.attrs.transform)), 1, made, 0, true);
|
|
1061
|
+
if (!made.length) return null;
|
|
1062
|
+
if (made.length > 1) report(clip.name === 'mask' ? 'SVG masks of several shapes (the first one masks)' : 'Clip paths of several shapes (the first one clips)');
|
|
1063
|
+
const mask = made[0];
|
|
1064
|
+
mask.fill = '#000000';
|
|
1065
|
+
delete mask.gradient;
|
|
1066
|
+
elements.push(mask);
|
|
1067
|
+
return mask.id;
|
|
1068
|
+
};
|
|
1069
|
+
|
|
1070
|
+
function walkNodes(nodes, inherited, matrix, opacity, out, depth, inClip = false, useDepth = 0) {
|
|
1071
|
+
for (const node of nodes) {
|
|
1072
|
+
if (!node.name || depth > MAX_DEPTH) continue;
|
|
1073
|
+
if (ANIMATION.has(node.name)) { report('SVG animation (the image is imported as drawn without it)'); continue; }
|
|
1074
|
+
if (['defs', 'symbol', 'clipPath', 'mask', 'linearGradient', 'radialGradient', 'pattern', 'marker', 'style', 'title', 'desc', 'metadata', 'script', 'filter'].includes(node.name)) {
|
|
1075
|
+
if (node.name === 'script') report('Scripts (left out)');
|
|
1076
|
+
continue;
|
|
1077
|
+
}
|
|
1078
|
+
if (node.name === 'foreignObject') { report('<foreignObject> elements (left out)'); continue; }
|
|
1079
|
+
// A switch draws its first child that needs no extension (Studio reads no other language).
|
|
1080
|
+
if (node.name === 'switch') {
|
|
1081
|
+
const chosen = node.children.find(child => child.name && child.name !== 'foreignObject' && child.attrs.requiredExtensions === undefined);
|
|
1082
|
+
if (chosen) walkNodes([{ ...node, name: 'g', children: [chosen] }], inherited, matrix, opacity, out, depth, inClip, useDepth);
|
|
1083
|
+
continue;
|
|
1084
|
+
}
|
|
1085
|
+
if (node.name.includes(':')) continue;
|
|
1086
|
+
if (node.children?.some(child => ANIMATION.has(child.name))) report('SVG animation (the image is imported as drawn without it)');
|
|
1087
|
+
const style = styleOf(node, inherited);
|
|
1088
|
+
if (style['own-display'] === 'none' || style.visibility === 'hidden') continue;
|
|
1089
|
+
let here = mul(matrix, parseTransform(node.attrs.transform));
|
|
1090
|
+
const alpha = opacity * clamp(finite(style['own-opacity'], 1), 0, 1);
|
|
1091
|
+
const filter = style['own-filter'] && style['own-filter'] !== 'none' ? reference(style['own-filter']) : null;
|
|
1092
|
+
// Inkscape 0.x wrote a blend mode as a filter of one feBlend with the background.
|
|
1093
|
+
const steps = filter?.children.filter(child => child.name?.startsWith('fe')) ?? [];
|
|
1094
|
+
const blendFilter = steps.length === 1 && steps[0].name === 'feBlend' && steps[0].attrs.in2 === 'BackgroundImage' ? steps[0].attrs.mode ?? 'normal' : null;
|
|
1095
|
+
if (blendFilter && blendFilter !== 'normal') style['own-mix-blend-mode'] ??= blendFilter;
|
|
1096
|
+
const effect = filter?.name === 'filter' && !blendFilter ? effectFor(filter, here) : null;
|
|
1097
|
+
const otherFilter = style['own-filter'] && style['own-filter'] !== 'none' && !effect && !blendFilter;
|
|
1098
|
+
const maskTarget = style['own-mask'] && style['own-mask'] !== 'none' ? reference(style['own-mask']) : null;
|
|
1099
|
+
const soft = maskTarget?.name === 'mask' && softMask(maskTarget);
|
|
1100
|
+
if (rasterize && !inClip && (otherFilter || soft) && DRAWN_OR_GROUP.has(node.name) && pictures >= MAX_PICTURES) report(`More than ${MAX_PICTURES} pictures (the rest drawn without their filter or soft mask)`);
|
|
1101
|
+
if (rasterize && !inClip && (otherFilter || soft) && DRAWN_OR_GROUP.has(node.name) && pictures++ < MAX_PICTURES) {
|
|
1102
|
+
report(soft ? 'Soft SVG masks (drawn as pictures)' : 'Filters other than blurs, shadows and glows (drawn as pictures)');
|
|
1103
|
+
const item = picture(node, inherited, matrix, opacity);
|
|
1104
|
+
const blend = style['own-mix-blend-mode'];
|
|
1105
|
+
if (blend && blend !== 'normal' && BLEND_MODES[blend]) item.keyframes[0].blendMode = BLEND_MODES[blend];
|
|
1106
|
+
out.push(item);
|
|
1107
|
+
continue;
|
|
1108
|
+
}
|
|
1109
|
+
if (otherFilter) report('Filters other than blurs, shadows and glows (left out)');
|
|
1110
|
+
const made = [];
|
|
1111
|
+
if (node.name === 'g' || node.name === 'svg' || node.name === 'a') {
|
|
1112
|
+
if (node.name === 'svg' && depth > 0) {
|
|
1113
|
+
here = mul(here, translate(length(node.attrs.x), length(node.attrs.y)));
|
|
1114
|
+
report('Nested <svg> elements (drawn without their own viewport)');
|
|
1115
|
+
}
|
|
1116
|
+
walkNodes(node.children, style, here, alpha, made, depth + 1, inClip, useDepth);
|
|
1117
|
+
mergeOutlines(made);
|
|
1118
|
+
if (!inClip && depth === 0 && made.filter(item => !item.maskId).length > 1) {
|
|
1119
|
+
const groupId = newId('group');
|
|
1120
|
+
for (const item of made) item.groupId ??= groupId;
|
|
1121
|
+
}
|
|
1122
|
+
} else if (node.name === 'use') {
|
|
1123
|
+
const target = reference(node.attrs.href ?? node.attrs['xlink:href']);
|
|
1124
|
+
if (!target || useDepth > 16) { report('<use> of something missing or nested too deep (left out)'); continue; }
|
|
1125
|
+
const shifted = mul(here, translate(length(node.attrs.x), length(node.attrs.y)));
|
|
1126
|
+
const content = target.name === 'symbol' ? target.children : [target];
|
|
1127
|
+
walkNodes(content.map(item => item.name === 'symbol' ? { ...item, name: 'g' } : item), style, shifted, alpha, made, depth + 1, inClip, useDepth + 1);
|
|
1128
|
+
} else if (node.name === 'rect') {
|
|
1129
|
+
const x = length(node.attrs.x), y = length(node.attrs.y), w = length(node.attrs.width), h = length(node.attrs.height);
|
|
1130
|
+
if (w > 0 && h > 0) {
|
|
1131
|
+
let rx = length(node.attrs.rx, w, NaN), ry = length(node.attrs.ry, h, NaN);
|
|
1132
|
+
if (Number.isNaN(rx)) rx = Number.isNaN(ry) ? 0 : ry;
|
|
1133
|
+
if (Number.isNaN(ry)) ry = rx;
|
|
1134
|
+
rx = Math.min(rx, w / 2); ry = Math.min(ry, h / 2);
|
|
1135
|
+
const primitive = Math.abs(rx - ry) < 1e-6 ? { type: rx > 0 ? 'roundedRectangle' : 'rectangle', box: [x, y, w, h], radius: rx } : null;
|
|
1136
|
+
made.push(...shape(node, style, here, alpha, [roundedRectContour(x, y, w, h, rx, ry)], primitive));
|
|
1137
|
+
}
|
|
1138
|
+
} else if (node.name === 'circle' || node.name === 'ellipse') {
|
|
1139
|
+
const cx = length(node.attrs.cx), cy = length(node.attrs.cy);
|
|
1140
|
+
const rx = node.name === 'circle' ? length(node.attrs.r) : length(node.attrs.rx), ry = node.name === 'circle' ? rx : length(node.attrs.ry);
|
|
1141
|
+
if (rx > 0 && ry > 0) made.push(...shape(node, style, here, alpha, [ellipseContour(cx, cy, rx, ry)], { type: 'ellipse', box: [cx - rx, cy - ry, 2 * rx, 2 * ry] }));
|
|
1142
|
+
} else if (node.name === 'line') {
|
|
1143
|
+
const points = [[length(node.attrs.x1), length(node.attrs.y1)], [length(node.attrs.x2), length(node.attrs.y2)]];
|
|
1144
|
+
const contours = [{ closed: false, points: points.map(([x, y]) => ({ x, y, in: [0, 0], out: [0, 0] })) }];
|
|
1145
|
+
made.push(...shape(node, { ...style, fill: 'none' }, here, alpha, contours), ...markersFor(node, style, here, alpha, contours, depth, useDepth));
|
|
1146
|
+
} else if (node.name === 'polyline' || node.name === 'polygon') {
|
|
1147
|
+
const numbers = (String(node.attrs.points ?? '').match(/[-+]?(?:\d*\.\d+|\d+\.?)(?:e[-+]?\d+)?/gi) ?? []).map(Number);
|
|
1148
|
+
const points = [];
|
|
1149
|
+
for (let k = 0; k + 1 < numbers.length; k += 2) points.push({ x: numbers[k], y: numbers[k + 1], in: [0, 0], out: [0, 0] });
|
|
1150
|
+
const contours = [{ closed: node.name === 'polygon', points }];
|
|
1151
|
+
if (points.length > 1) made.push(...shape(node, style, here, alpha, contours), ...markersFor(node, style, here, alpha, contours, depth, useDepth));
|
|
1152
|
+
} else if (node.name === 'path') {
|
|
1153
|
+
const contours = parsePathData(node.attrs.d);
|
|
1154
|
+
if (contours.length) made.push(...shape(node, style, here, alpha, contours), ...markersFor(node, style, here, alpha, contours, depth, useDepth));
|
|
1155
|
+
} else if (node.name === 'text') {
|
|
1156
|
+
made.push(...textElement(node, style, here, alpha));
|
|
1157
|
+
} else if (node.name === 'image') {
|
|
1158
|
+
made.push(...imageElement(node, here, alpha));
|
|
1159
|
+
} else if (!DRAWN.has(node.name) && !node.name.includes(':') && node.children?.length) {
|
|
1160
|
+
report(`<${node.name}> elements (left out)`);
|
|
1161
|
+
}
|
|
1162
|
+
if (effect && !inClip) {
|
|
1163
|
+
for (const item of made) {
|
|
1164
|
+
if (item.effect) report('Filters inside filtered groups (the inner one is kept)');
|
|
1165
|
+
else if (item.type === 'text' || item.type === 'bitmap') {
|
|
1166
|
+
if (item.keyframes[0].filters) report('Filters inside filtered groups (the inner one is kept)');
|
|
1167
|
+
else { const filters = placementFilters({ effect }); for (const key of item.keyframes) key.filters = filters; }
|
|
1168
|
+
} else item.effect = effect;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
const blend = style['own-mix-blend-mode'];
|
|
1172
|
+
if (blend && blend !== 'normal' && !inClip) {
|
|
1173
|
+
const mode = BLEND_MODES[blend];
|
|
1174
|
+
if (!mode) report(`The ${String(blend).slice(0, 20)} blend mode (drawn normal)`);
|
|
1175
|
+
else for (const item of made) item.keyframes[0].blendMode ??= mode;
|
|
1176
|
+
}
|
|
1177
|
+
// A clip path or an SVG mask: one mask for everything this node draws.
|
|
1178
|
+
let clip = style['own-clip-path'] && style['own-clip-path'] !== 'none' ? reference(style['own-clip-path']) : null;
|
|
1179
|
+
const svgMask = style['own-mask'] && style['own-mask'] !== 'none' ? reference(style['own-mask']) : null;
|
|
1180
|
+
if (svgMask?.name === 'mask' && made.length) {
|
|
1181
|
+
if (clip?.name === 'clipPath') report('Objects with both a clip path and a mask (the clip path is kept)');
|
|
1182
|
+
else { clip = svgMask; report('SVG masks (as the outline of their shapes, without soft edges)'); }
|
|
1183
|
+
}
|
|
1184
|
+
if ((clip?.name === 'clipPath' || clip?.name === 'mask') && !inClip && made.length) {
|
|
1185
|
+
const maskId = maskFor(clip, here);
|
|
1186
|
+
if (maskId) for (const item of made) if (!item.maskId) item.maskId = maskId; else report('Clip paths inside clip paths (the outer one is kept)');
|
|
1187
|
+
}
|
|
1188
|
+
out.push(...made);
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
const drawn = [];
|
|
1193
|
+
walkNodes(svg.children, styleOf(svg, {}), mul(root, parseTransform(svg.attrs.transform)), clamp(finite(styleOf(svg, {})['own-opacity'], 1), 0, 1), drawn, 0);
|
|
1194
|
+
mergeOutlines(drawn);
|
|
1195
|
+
await Promise.all(jobs);
|
|
1196
|
+
if (drawn.some(item => item.failed)) report('Parts the browser could not draw (left out)');
|
|
1197
|
+
for (let k = drawn.length - 1; k >= 0; k--) if (drawn[k].failed) drawn.splice(k, 1);
|
|
1198
|
+
// Masks were pushed when made; drawn objects follow in document order.
|
|
1199
|
+
elements.push(...drawn);
|
|
1200
|
+
const order = new Map(elements.map((element, k) => [element.id, k]));
|
|
1201
|
+
// A mask comes before the objects it masks.
|
|
1202
|
+
elements.sort((a, b) => order.get(a.id) - order.get(b.id));
|
|
1203
|
+
const layerId = 'svg-layer';
|
|
1204
|
+
return { format: 'swoof-studio', version: 1, stage: { width, height, frameRate: 24, background: '#ffffff' }, assets,
|
|
1205
|
+
scenes: [{ id: 'scene-1', name: String(svg.children.find(node => node.name === 'title')?.children?.map(textOf).join('') || 'SVG').trim().slice(0, 120) || 'SVG',
|
|
1206
|
+
durationFrames: 1, startFrame: 1, loop: false, layers: [{ id: layerId, name: 'Layer 1', visible: true, locked: false, order: 0 }],
|
|
1207
|
+
elements: elements.map(element => ({ ...element, layerId })) }] };
|
|
1208
|
+
}
|