Merge pull request #86 from storytold/m6/html-canvas-export

feat(export): HTML canvas export with an interactive player (M6)
This commit is contained in:
Tanish Manku authored and GitHub committed 2026-11-09 13:55:34 -07:00
commit 86f74b71a3
20 files changed
+3316 -12

No files matched your search

+16
View File
@@ -2,6 +2,22 @@
## Unreleased
* **HTML canvas export** (ADR 0028). File › Export › Export HTML Canvas… writes the movie as
one web page that plays in any modern browser: open it from your disk, put it on a server or
send it as one file. Everything moves exactly as on the stage, because every frame of every
timeline is computed by AniCraft (classic, shape and motion tweens, easing, motion guides,
shape hints); shapes, gradients, strokes (variable-width ones too), text, bitmaps, masks,
symbols that fade or blend as one, alpha and tint all come across. It is interactive: movie
clips play on their own timelines, buttons show Up, Over and Down and answer in their Hit
area, and frame actions and button events (stop, play, go to a frame or label in any scene,
next/previous frame and scene, trace, set properties, instance paths like `panel.door`)
behave as in Test Movie: the page's player is a port of AniCraft's and the tests run both
side by side. Sounds play with the first click (Event, Start, Stop; Stream over its span).
The movie fits the browser window, sharp on high-density screens. The demo exports in 1 ms
to a 59 KB page (18 KB of movie data). Filters, Subtract and Invert blending, tints on
bitmaps and plug-in frame scripts are reported, not exported. Headless:
`file.export_html {path, title?, sound?, fit?}`.
* **Camera layer with layer depth** (ADR 0027). Click the camera button in the timeline
header (or pick the **Camera tool**, C) to add a camera: a Camera layer on top of the
timeline whose frame shows on the stage as an orange outline of what the movie will show.
Generated
+694 -1
View File
@@ -134,6 +134,15 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "aligned-vec"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"
dependencies = [
"equator",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
@@ -315,6 +324,7 @@ version = "0.1.0"
dependencies = [
"anicraft-doc",
"anicraft-geom",
"boa_engine",
"png 0.17.16",
"rayon",
"serde_json",
@@ -641,6 +651,145 @@ dependencies = [
"piper",
]
[[package]]
name = "boa_ast"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6339a700715bda376f5ea65c76e8fe8fc880930d8b0638cea68e7f3da6538e0a"
dependencies = [
"bitflags 2.13.2",
"boa_interner",
"boa_macros",
"boa_string",
"indexmap",
"num-bigint",
"rustc-hash 2.1.3",
]
[[package]]
name = "boa_engine"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1521be326f8a5c8887e95d4ce7f002917a002a23f7b93b9a6a2bf50ed4157824"
dependencies = [
"aligned-vec",
"arrayvec",
"bitflags 2.13.2",
"boa_ast",
"boa_gc",
"boa_interner",
"boa_macros",
"boa_parser",
"boa_string",
"bytemuck",
"cfg-if",
"cow-utils",
"dashmap",
"dynify",
"fast-float2",
"futures-channel",
"futures-concurrency",
"futures-lite",
"hashbrown 0.16.1",
"icu_normalizer",
"indexmap",
"intrusive-collections",
"itertools 0.14.0",
"num-bigint",
"num-integer",
"num-traits",
"num_enum",
"paste",
"portable-atomic",
"rand",
"regress",
"rustc-hash 2.1.3",
"ryu-js",
"serde",
"serde_json",
"small_btree",
"static_assertions",
"tag_ptr",
"tap",
"thin-vec",
"thiserror 2.0.21",
"time",
]
[[package]]
name = "boa_gc"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17323a98cf2e631afacf1a6d659c1212c48a68bacfa85afab0a66ade80582e51"
dependencies = [
"boa_macros",
"boa_string",
"hashbrown 0.16.1",
"thin-vec",
]
[[package]]
name = "boa_interner"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20510b8b02bcde9b0a01cf34c0c308c56156503d1d91cdab4c8cfbd292b747ea"
dependencies = [
"boa_gc",
"boa_macros",
"hashbrown 0.16.1",
"indexmap",
"once_cell",
"phf",
"rustc-hash 2.1.3",
"static_assertions",
]
[[package]]
name = "boa_macros"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5822cb4f146d243060e588bc5a5f2e709683fdad3d7111f42c48e6b5c921d23d"
dependencies = [
"cfg-if",
"cow-utils",
"proc-macro2",
"quote",
"syn 2.0.119",
"synstructure 0.13.2",
]
[[package]]
name = "boa_parser"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35bd957fa9fa93e3a001a8aba5a5cd40c2bbfde486378be4c4b472fd304aaddb"
dependencies = [
"bitflags 2.13.2",
"boa_ast",
"boa_interner",
"boa_macros",
"fast-float2",
"icu_properties",
"num-bigint",
"num-traits",
"regress",
"rustc-hash 2.1.3",
]
[[package]]
name = "boa_string"
version = "0.21.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2da1d7f4a76fd9040788a122f0d807910800a7b86f5952e9244848c36511de"
dependencies = [
"fast-float2",
"itoa",
"paste",
"rustc-hash 2.1.3",
"ryu-js",
"static_assertions",
]
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -885,6 +1034,12 @@ dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "cow-utils"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "417bef24afe1460300965a25ff4a24b8b45ad011948302ec221e8a0a81eb2c79"
[[package]]
name = "cpal"
version = "0.18.2"
@@ -961,12 +1116,32 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
[[package]]
name = "dashmap"
version = "6.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c"
dependencies = [
"cfg-if",
"crossbeam-utils",
"hashbrown 0.14.5",
"lock_api",
"once_cell",
"parking_lot_core",
]
[[package]]
name = "dasp_sample"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
[[package]]
name = "deranged"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]]
name = "dispatch"
version = "0.2.0"
@@ -985,6 +1160,17 @@ dependencies = [
"objc2 0.6.5",
]
[[package]]
name = "displaydoc"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "dlib"
version = "0.5.3"
@@ -1015,6 +1201,26 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
[[package]]
name = "dynify"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81acb15628a3e22358bf73de5e7e62360b8a777dbcb5fc9ac7dfa9ae73723747"
dependencies = [
"dynify-macros",
]
[[package]]
name = "dynify-macros"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ec431cd708430d5029356535259c5d645d60edd3d39c54e5eea9782d46caa7d"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "ecolor"
version = "0.36.2"
@@ -1072,7 +1278,7 @@ dependencies = [
"bitflags 2.13.2",
"emath",
"epaint",
"itertools",
"itertools 0.15.0",
"log",
"nohash-hasher",
"profiling",
@@ -1209,6 +1415,26 @@ version = "0.36.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13"
[[package]]
name = "equator"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"
dependencies = [
"equator-macro",
]
[[package]]
name = "equator-macro"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "equivalent"
version = "1.0.3"
@@ -1260,6 +1486,12 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "fast-float2"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f"
[[package]]
name = "fastrand"
version = "2.5.0"
@@ -1293,6 +1525,12 @@ version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "fixedbitset"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175"
[[package]]
name = "flate2"
version = "1.1.10"
@@ -1365,6 +1603,28 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "futures-channel"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
dependencies = [
"futures-core",
]
[[package]]
name = "futures-concurrency"
version = "7.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6"
dependencies = [
"fixedbitset",
"futures-core",
"futures-lite",
"pin-project",
"smallvec",
]
[[package]]
name = "futures-core"
version = "0.3.34"
@@ -1615,6 +1875,12 @@ dependencies = [
"smallvec",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -1656,6 +1922,95 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "icu_collections"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47"
dependencies = [
"displaydoc",
"potential_utf",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
name = "icu_locale_core"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"
dependencies = [
"displaydoc",
"litemap",
"serde",
"tinystr",
"writeable",
"zerovec",
]
[[package]]
name = "icu_normalizer"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b24a59706036ba941c9476a55cd57b82b77f38a3c667d637ee7cabbc85eaedc"
dependencies = [
"displaydoc",
"icu_collections",
"icu_normalizer_data",
"icu_properties",
"icu_provider",
"smallvec",
"utf16_iter",
"write16",
"zerovec",
]
[[package]]
name = "icu_normalizer_data"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3"
[[package]]
name = "icu_properties"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5a97b8ac6235e69506e8dacfb2adf38461d2ce6d3e9bd9c94c4cbc3cd4400a4"
dependencies = [
"displaydoc",
"icu_collections",
"icu_locale_core",
"icu_properties_data",
"icu_provider",
"potential_utf",
"zerotrie",
"zerovec",
]
[[package]]
name = "icu_properties_data"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632"
[[package]]
name = "icu_provider"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"
dependencies = [
"displaydoc",
"icu_locale_core",
"serde",
"stable_deref_trait",
"writeable",
"yoke",
"zerofrom",
"zerotrie",
"zerovec",
]
[[package]]
name = "image"
version = "0.25.10"
@@ -1680,6 +2035,24 @@ dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "intrusive-collections"
version = "0.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86"
dependencies = [
"memoffset",
]
[[package]]
name = "itertools"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.15.0"
@@ -1872,6 +2245,12 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litemap"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
[[package]]
name = "litrs"
version = "1.0.1"
@@ -2042,6 +2421,23 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
[[package]]
name = "num-bigint"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
dependencies = [
"num-integer",
"num-traits",
"serde",
]
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "num-derive"
version = "0.4.2"
@@ -2053,6 +2449,15 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -2085,6 +2490,15 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "num_threads"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cabcc654086861f9e1bc5115258de62ef92c79b20f4615a1b0cc57c4e82027d4"
dependencies = [
"libc",
]
[[package]]
name = "objc-sys"
version = "0.3.5"
@@ -2521,6 +2935,12 @@ dependencies = [
"windows-link",
]
[[package]]
name = "paste"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "peniko"
version = "0.6.1"
@@ -2708,6 +3128,30 @@ dependencies = [
"portable-atomic",
]
[[package]]
name = "potential_utf"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
dependencies = [
"zerovec",
]
[[package]]
name = "powerfmt"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "presser"
version = "0.3.1"
@@ -2780,6 +3224,35 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "range-alloc"
version = "0.1.5"
@@ -2862,6 +3335,16 @@ dependencies = [
"bitflags 2.13.2",
]
[[package]]
name = "regress"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2057b2325e68a893284d1538021ab90279adac1139957ca2a74426c6f118fb48"
dependencies = [
"hashbrown 0.16.1",
"memchr",
]
[[package]]
name = "renderdoc-sys"
version = "1.1.0"
@@ -2948,6 +3431,12 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "ryu-js"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714"
[[package]]
name = "same-file"
version = "1.0.6"
@@ -3113,6 +3602,15 @@ dependencies = [
"version_check",
]
[[package]]
name = "small_btree"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ba60d2df92ba73864714808ca68c059734853e6ab722b40e1cf543ebb3a057a"
dependencies = [
"arrayvec",
]
[[package]]
name = "smallvec"
version = "1.16.4"
@@ -3206,6 +3704,12 @@ dependencies = [
"bitflags 2.13.2",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "static_assertions"
version = "1.1.0"
@@ -3244,6 +3748,40 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "synstructure"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "tag_ptr"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0e973b34477b7823833469eb0f5a3a60370fef7a453e02d751b59180d0a5a05"
[[package]]
name = "tap"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -3266,6 +3804,12 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "thin-vec"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6a4b9ba8738cb4a4f399d37e266becfd475e75eb73425b87a05a2f2039ba63e"
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -3320,6 +3864,49 @@ dependencies = [
"zune-jpeg",
]
[[package]]
name = "time"
version = "0.3.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
dependencies = [
"deranged",
"libc",
"num-conv",
"num_threads",
"powerfmt",
"serde_core",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
[[package]]
name = "time-macros"
version = "0.2.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
dependencies = [
"num-conv",
"time-core",
]
[[package]]
name = "tinystr"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a"
dependencies = [
"displaydoc",
"serde_core",
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
@@ -3471,6 +4058,21 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "utf16_iter"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c7de35d9d8757dbc1f5125dc8b51438c68b4430546a735c3a9b91aaaaf9a18a"
dependencies = [
"utf_types",
]
[[package]]
name = "utf_types"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"
[[package]]
name = "uuid"
version = "1.29.0"
@@ -4313,6 +4915,18 @@ version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "write16"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936"
[[package]]
name = "writeable"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "x11-dl"
version = "2.21.0"
@@ -4376,6 +4990,29 @@ version = "0.8.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "yoke"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"
dependencies = [
"stable_deref_trait",
"yoke-derive",
"zerofrom",
]
[[package]]
name = "yoke-derive"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"synstructure 0.14.0",
]
[[package]]
name = "zbus"
version = "5.19.0"
@@ -4502,6 +5139,62 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "zerofrom"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
dependencies = [
"zerofrom-derive",
]
[[package]]
name = "zerofrom-derive"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"synstructure 0.14.0",
]
[[package]]
name = "zerotrie"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
dependencies = [
"displaydoc",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
name = "zerovec"
version = "0.11.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40"
dependencies = [
"serde",
"yoke",
"zerofrom",
"zerovec-derive",
]
[[package]]
name = "zerovec-derive"
version = "0.11.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
+2 -2
View File
@@ -294,7 +294,7 @@ impl Ctx {
/// The first frame of the unbroken run of keyframes on `layer`, up to `frame`, that hold
/// element `id` as an instance of `symbol`: where a movie clip instance started playing.
pub(crate) fn instance_start(layer: &Layer, frame: u32, id: ElementId, symbol: SymbolId) -> u32 {
pub fn instance_start(layer: &Layer, frame: u32, id: ElementId, symbol: SymbolId) -> u32 {
let Some(mut i) = layer.keyframe_index_at(frame) else { return frame };
let holds = |k: &crate::Keyframe| k.elements.iter().any(|e| e.id == id && matches!(e.kind, ElementKind::Symbol { symbol: s, .. } if s == symbol));
let mut start = layer.keyframes.get(i).map_or(frame, |k| k.start);
@@ -309,7 +309,7 @@ pub(crate) fn instance_start(layer: &Layer, frame: u32, id: ElementId, symbol: S
}
/// The path a guide layer's first shape traces at `frame`, in the layer's own space.
pub(crate) fn guide_walk(guide: &Layer, frame: u32) -> Option<PathWalk> {
pub fn guide_walk(guide: &Layer, frame: u32) -> Option<PathWalk> {
let (_, els) = evaluate_layer_elements(guide, frame)?;
els.iter().find_map(|e| match &e.kind {
ElementKind::Shape(s) => {
+1 -1
View File
@@ -28,7 +28,7 @@ pub use motion::{MotionTween, Property, PropertyKey, Props, Track};
pub use sound::{FrameSound, Sound, SoundFormat, SoundId, SoundSync};
pub use width::{MAX_WIDTH_FACTOR, MAX_WIDTH_POINTS, ProfilePreset, WidthPoint, WidthProfile};
pub use camera::Camera;
pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera};
pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_player, evaluate_scene, evaluate_scene_camera, guide_walk, instance_start};
pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, PluginScript};
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
+47
View File
@@ -83,6 +83,15 @@ pub fn specs() -> Vec<CommandSpec> {
mutates: false,
run: export_lottie,
},
CommandSpec {
id: "file.export_html",
label: "Export HTML Canvas…",
menu: "File/Export",
shortcut: None,
params: "{path (.html: one self-contained page), title? (default: the file name), sound? (default true: embed the movie's sounds), fit? (default true: scale to the browser window), confirm?}",
mutates: false,
run: export_html,
},
CommandSpec { id: "edit.undo", label: "Undo", menu: "Edit", shortcut: Some("Ctrl+Z"), params: "{}", mutates: false, run: |s, _| s.undo() },
CommandSpec { id: "edit.redo", label: "Redo", menu: "Edit", shortcut: Some("Ctrl+Y"), params: "{}", mutates: false, run: |s, _| s.redo() },
CommandSpec {
@@ -625,6 +634,44 @@ fn export_lottie(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"written": path.display().to_string(), "frames": to - from + 1, "layers": out.layers, "bytes": out.json.len(), "report": summary, "notes": out.report}))
}
/// The movie as one web page that plays in a browser, buttons and frame actions included
/// (see `anicraft_render::html`, ADR 0028).
fn export_html(s: &mut Session, p: &Value) -> Result<Value> {
let path = PathBuf::from(str_req(p, "path")?);
let stem: String = path.file_stem().map_or_else(|| "AniCraft movie".into(), |n| n.to_string_lossy().chars().take(128).collect());
let title = match opt_str(p, "title")? {
Some(t) if t.chars().count() > 256 => return Err(EngineError::Param("param 'title' is at most 256 characters".into())),
Some(t) if !t.trim().is_empty() => t.to_string(),
_ => stem,
};
let opts = anicraft_render::html::HtmlOptions { title, sound: opt_bool(p, "sound")?.unwrap_or(true), fit: opt_bool(p, "fit")?.unwrap_or(true) };
let started = std::time::Instant::now();
let out = anicraft_render::html::to_html(&s.doc, &opts).map_err(EngineError::Param)?;
std::fs::write(&path, out.html.as_bytes())?;
let summary = if out.report.is_empty() {
String::new()
} else {
format!("Approximated or left out: {}.", out.report.iter().map(|(k, n)| format!("{k} on {n}")).collect::<Vec<_>>().join(", "))
};
let st = out.stats;
Ok(json!({
"written": path.display().to_string(),
"bytes": out.html.len(),
"frames": s.doc.frame_count(),
"scenes": s.doc.scenes.len(),
"timelines": st.timelines,
"stored_frames": st.contents,
"paths": st.paths,
"images": st.images,
"sounds": st.sounds,
"data_bytes": st.data_bytes,
"code_bytes": st.code_bytes,
"ms": started.elapsed().as_millis() as u64,
"report": summary,
"notes": out.report,
}))
}
fn export_gif(s: &mut Session, p: &Value) -> Result<Value> {
let path = PathBuf::from(str_req(p, "path")?);
// The whole movie: every scene in order.
+1 -1
View File
@@ -109,7 +109,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
let same = s.path.as_deref() == Some(path);
(!same && path.exists()).then(|| overwrite(path, "Saving"))
}
"file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_audio" => {
"file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_audio" => {
let path = Path::new(p.get("path").and_then(Value::as_str)?);
path.exists().then(|| overwrite(path, "Exporting"))
}
+27
View File
@@ -1765,6 +1765,33 @@ fn lottie_export_writes_the_movie_and_asks_before_replacing() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn html_export_writes_one_page_that_holds_the_interactive_movie() {
let dir = std::env::temp_dir().join(format!("anicraft-html-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("menu.html");
let mut s = Session::new(sample::interactive());
let v = run(&mut s, "file.export_html", json!({"path": path.display().to_string()}));
let html = std::fs::read_to_string(&path).unwrap();
assert_eq!(v["bytes"].as_u64(), Some(html.len() as u64));
assert!(html.starts_with("<!DOCTYPE html>") && html.contains("<title>menu</title>"), "the title defaults to the file name");
assert!(html.contains("\"op\":\"goto_and_play\"") && html.contains("new AniCraft.Player"), "actions and the player are in the page");
assert_eq!((v["scenes"].as_u64(), v["frames"].as_u64()), (Some(1), Some(u64::from(s.doc.frame_count()))));
assert!(v["timelines"].as_u64().unwrap() >= 3, "the scene, the button and the spinner: {v}");
assert_eq!(v["report"], "");
// Replacing needs consent; params are checked.
let p = json!({"path": path.display().to_string(), "title": "Menu", "fit": false, "sound": false});
assert!(s.execute("file.export_html", &p).is_err());
let mut p = p;
p["confirm"] = json!(true);
run(&mut s, "file.export_html", p);
assert!(std::fs::read_to_string(&path).unwrap().contains("<title>Menu</title>"));
assert!(s.execute("file.export_html", &json!({"path": dir.join("x.html").display().to_string(), "title": "t".repeat(300)})).is_err());
assert!(s.execute("file.export_html", &json!({"path": dir.join("x.html").display().to_string(), "fit": "yes"})).is_err());
assert!(s.execute("file.export_html", &json!({})).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn text_lays_out_renders_edits_saves_and_breaks_apart() {
if anicraft_text::Fonts::get().families().is_empty() {
+5
View File
@@ -18,3 +18,8 @@ serde_json.workspace = true
[lints]
workspace = true
[dev-dependencies]
# Runs the exported HTML player's JavaScript in tests, to compare it with the Rust player
# (pure Rust, Unlicense OR MIT; tests only, never in the app).
boa_engine = { version = "0.21", default-features = false }
+695
View File
@@ -0,0 +1,695 @@
//! HTML canvas export (ADR 0028): the movie as one self-contained web page that plays in any
//! modern browser with `<canvas>` 2D, buttons and frame actions included.
//!
//! The page holds three things: the movie's data as JSON, the player (`html/player.js`, a port
//! of the Rust player in `anicraft-doc`) and the page code (`html/canvas.js`: drawing, timing,
//! pointer, sound). Both scripts are our own source files, embedded at build time.
//!
//! The data is baked, not re-keyed: every timeline (each scene's and each symbol's that the
//! movie uses) is evaluated frame by frame, so classic, shape and motion tweens, easing, motion
//! guides and shape hints come out exactly as AniCraft computes them, and the browser never
//! interpolates. A frame is its layers (bottom first) and their items: shapes (a path, a paint,
//! a stroke, a colour effect) and symbol instances (which the player resolves at run time: movie
//! clips have their own playheads, buttons their pointer states). Identical paths, paints and
//! frames are stored once, so a still keyframe over many frames costs one entry.
//!
//! What doesn't carry across is counted in the report: filters, Subtract and Invert blending,
//! tints on bitmaps, and plug-in frame scripts (they need the plug-in host).
use crate::stroke::variable_outline;
use anicraft_doc::actions::{Action, FrameRef, Seg};
use anicraft_doc::{BlendMode, ColorEffect, Document, Element, ElementKind, FrameScript, Layer, LayerKind, Paint, Rgba, SoundFormat, SoundSync, SymbolId, SymbolKind, Timeline, base64_encode, evaluate_guided, guide_walk, instance_start};
use anicraft_geom::{Affine, FillRule, Path, PathCmd};
use serde_json::{Map, Value, json};
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::sync::Arc;
/// The player core: instance tree, frame actions, button events (no page access).
pub const PLAYER_JS: &str = include_str!("html/player.js");
/// The page: canvas drawing, timing, pointer and sound.
pub const CANVAS_JS: &str = include_str!("html/canvas.js");
/// Version of the embedded data (`"v"`), raised when the player must change to read it.
pub const FORMAT_VERSION: u32 = 1;
/// Largest page written.
pub const MAX_HTML_BYTES: usize = 512 << 20;
/// What to export.
#[derive(Clone, Debug)]
pub struct HtmlOptions {
/// The page title.
pub title: String,
/// Embed the movie's sounds (played with Web Audio).
pub sound: bool,
/// Scale the movie to fit the browser window (else it shows at its stage size).
pub fit: bool,
}
impl Default for HtmlOptions {
fn default() -> Self {
HtmlOptions { title: "AniCraft movie".into(), sound: true, fit: true }
}
}
/// Counts of what the export holds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct HtmlStats {
pub timelines: usize,
/// Frames over every timeline.
pub frames: usize,
/// Distinct frames stored.
pub contents: usize,
pub paths: usize,
pub images: usize,
pub sounds: usize,
/// Bytes of movie data and of player code in the page.
pub data_bytes: usize,
pub code_bytes: usize,
}
/// The movie's data, as the player reads it.
pub struct Movie {
pub json: Value,
/// The exported paths, by index (the shapes' own paths; the JSON holds them rounded).
pub paths: Vec<Arc<Path>>,
/// What couldn't be carried across exactly, by kind, with how many elements (or
/// keyframes) it touched.
pub report: BTreeMap<String, usize>,
pub stats: HtmlStats,
}
/// The finished page.
pub struct HtmlExport {
pub html: String,
pub report: BTreeMap<String, usize>,
pub stats: HtmlStats,
}
/// Notes for the report.
const FILTERS: &str = "filters (not exported; drawn without them)";
const BLENDS: &str = "Subtract and Invert blending (drawn normally)";
const BITMAP_TINT: &str = "tints on bitmap fills (drawn untinted)";
const PLUGIN_SCRIPTS: &str = "plug-in frame scripts (not exported; they need the plug-in host)";
/// A number rounded to `1/scale`, written as an integer when it is one.
fn num(v: f32, scale: f64) -> Value {
let r = (f64::from(v) * scale).round() / scale;
if !r.is_finite() {
json!(0)
} else if r.fract() == 0.0 && r.abs() < 9e15 {
json!(r as i64)
} else {
json!(r)
}
}
fn coord(v: f32) -> Value {
num(v, 1000.0)
}
fn color(c: Rgba) -> Vec<Value> {
let c = c.sanitized();
[c.r, c.g, c.b, c.a].into_iter().map(|v| num(v, 10_000.0)).collect()
}
/// `[a, b, c, d, e, f]`, the linear part finer than the offset; `None` for the identity.
fn matrix(m: &Affine) -> Option<Value> {
if *m == Affine::IDENTITY {
return None;
}
let [a, b, c, d, e, f] = m.m;
Some(json!([num(a, 1e5), num(b, 1e5), num(c, 1e5), num(d, 1e5), coord(e), coord(f)]))
}
/// `[alpha, tint r, g, b, tint amount]`; `None` for no effect.
fn effect(fx: &ColorEffect) -> Option<Value> {
if *fx == ColorEffect::default() {
return None;
}
let t = fx.tint.sanitized();
let a = if fx.alpha.is_finite() { fx.alpha } else { 1.0 };
let k = if fx.tint_amount.is_finite() { fx.tint_amount } else { 0.0 };
Some(json!([num(a, 1e4), num(t.r, 1e4), num(t.g, 1e4), num(t.b, 1e4), num(k, 1e4)]))
}
/// SVG path data (what `Path2D` reads), three decimals; empty when a point isn't finite.
fn path_data(p: &Path) -> String {
use std::fmt::Write;
let mut s = String::with_capacity(p.cmds.len() * 14);
let pt = |s: &mut String, x: f32, y: f32| {
let _ = write!(s, "{} {}", coord(x), coord(y));
};
for c in &p.cmds {
match *c {
PathCmd::MoveTo(a) => {
s.push('M');
pt(&mut s, a.x, a.y);
}
PathCmd::LineTo(a) => {
s.push('L');
pt(&mut s, a.x, a.y);
}
PathCmd::QuadTo(a, b) => {
s.push('Q');
pt(&mut s, a.x, a.y);
s.push(' ');
pt(&mut s, b.x, b.y);
}
PathCmd::CubicTo(a, b, e) => {
s.push('C');
pt(&mut s, a.x, a.y);
s.push(' ');
pt(&mut s, b.x, b.y);
s.push(' ');
pt(&mut s, e.x, e.y);
}
PathCmd::Close => s.push('Z'),
}
}
let finite = p.cmds.iter().all(|c| match *c {
PathCmd::MoveTo(a) | PathCmd::LineTo(a) => a.x.is_finite() && a.y.is_finite(),
PathCmd::QuadTo(a, b) => [a, b].iter().all(|q| q.x.is_finite() && q.y.is_finite()),
PathCmd::CubicTo(a, b, e) => [a, b, e].iter().all(|q| q.x.is_finite() && q.y.is_finite()),
PathCmd::Close => true,
});
if finite { s } else { String::new() }
}
/// An action as the player reads it: `op`, the target as steps (`^` the main timeline, `..` up
/// a level, else an instance name; `e` when it isn't a valid path), and `d`, its description
/// (for messages).
fn action(a: &Action) -> Value {
let mut o = Map::new();
o.insert("op".into(), json!(a.op()));
if let Some(t) = a.target() {
match t.segments() {
Ok(segs) => {
if !segs.is_empty() {
let steps: Vec<Value> = segs
.iter()
.map(|s| match s {
Seg::Root => json!("^"),
Seg::Parent => json!(".."),
Seg::Child(n) => json!(n),
})
.collect();
o.insert("t".into(), Value::Array(steps));
}
}
Err(e) => {
o.insert("e".into(), json!(e));
}
}
}
match a {
Action::Trace { message } => {
o.insert("msg".into(), json!(message));
}
Action::GotoAndPlay { frame, scene, .. } | Action::GotoAndStop { frame, scene, .. } => {
o.insert("f".into(), match frame {
FrameRef::Number(n) => json!(n),
FrameRef::Label(l) => json!(l),
});
if let Some(s) = scene {
o.insert("s".into(), json!(s));
}
}
Action::SetProperty { property, value, .. } => {
o.insert("p".into(), json!(property.key()));
o.insert("v".into(), if value.is_finite() { json!(value) } else { json!(0) });
o.insert("pl".into(), json!(property.label().to_lowercase()));
}
_ => {}
}
if !matches!(a, Action::Trace { .. }) {
o.insert("d".into(), json!(a.describe()));
}
Value::Object(o)
}
fn actions(list: &[Action]) -> Value {
Value::Array(list.iter().map(action).collect())
}
/// Whether timeline layer `index` takes part in playback (what the player walks and draws):
/// shown, not a folder or guide, not in a hidden folder.
fn plays(tl: &Timeline, index: usize) -> bool {
tl.layers.get(index).is_some_and(|l| l.visible && !matches!(l.kind, LayerKind::Folder | LayerKind::Guide)) && !tl.hidden_by_folder(index)
}
/// Interning tables and the report, while baking.
struct Bake<'a> {
doc: &'a Document,
sound: bool,
paths: Vec<Arc<Path>>,
path_d: Vec<String>,
by_ptr: HashMap<*const Path, usize>,
/// Every path met, kept alive so no pointer in `by_ptr` is reused by a later path.
keep: Vec<Arc<Path>>,
by_d: HashMap<String, usize>,
paints: Vec<Value>,
paint_ix: HashMap<String, usize>,
contents: Vec<Value>,
content_ix: HashMap<String, usize>,
symbols: HashMap<SymbolId, usize>,
images: Vec<String>,
image_ix: HashMap<u64, usize>,
sounds: Vec<Value>,
sound_ix: HashMap<u64, usize>,
notes: BTreeMap<&'static str, BTreeSet<u64>>,
}
impl<'a> Bake<'a> {
fn path(&mut self, p: &Arc<Path>) -> usize {
// The table keeps every path alive, so a pointer is never reused while it is a key.
if let Some(&i) = self.by_ptr.get(&Arc::as_ptr(p)) {
return i;
}
let d = path_data(p);
let i = match self.by_d.get(&d) {
Some(&i) => i,
None => {
self.path_d.push(d.clone());
self.paths.push(p.clone());
self.by_d.insert(d, self.paths.len() - 1);
self.paths.len() - 1
}
};
self.by_ptr.insert(Arc::as_ptr(p), i);
self.keep.push(p.clone());
i
}
fn paint(&mut self, p: &Paint, el: &Element) -> usize {
let stops = |s: &[anicraft_doc::GradientStop]| -> Vec<Value> {
s.iter()
.map(|g| {
let o = if g.offset.is_finite() { g.offset.clamp(0.0, 1.0) } else { 0.0 };
let mut v = vec![num(o, 1e4)];
v.extend(color(g.color));
Value::Array(v)
})
.collect()
};
let v = match p {
Paint::Solid(c) => json!({"s": color(*c)}),
Paint::Linear { start, end, stops: s } => json!({"l": [coord(start.x), coord(start.y), coord(end.x), coord(end.y)], "st": stops(s)}),
Paint::Radial { center, radius, stops: s } => json!({"r": [coord(center.x), coord(center.y), coord(radius.max(0.0))], "st": stops(s)}),
Paint::Bitmap { bitmap, repeat, matrix: m } => match self.doc.bitmap(*bitmap) {
Some(b) => {
if el.color.tint_amount > 0.0 {
self.notes.entry(BITMAP_TINT).or_default().insert(el.id.0);
}
let n = self.images.len();
let i = *self.image_ix.entry(b.id.0).or_insert(n);
if i == n {
self.images.push(format!("data:image/png;base64,{}", base64_encode(&b.png)));
}
let mut o = json!({"b": i, "rep": repeat});
if let Some(m) = matrix(m) {
o["m"] = m;
}
o
}
// An image that can't be found shows grey, as on the stage.
None => json!({"s": color(Rgba::hex(0x808080))}),
},
};
let key = v.to_string();
let n = self.paints.len();
let i = *self.paint_ix.entry(key).or_insert(n);
if i == n {
self.paints.push(v);
}
i
}
/// A shape item: `p` path, `f` paint, `s` stroke `[r, g, b, a, width]`, `eo` even-odd,
/// `m` transform, `c` colour effect.
fn shape(&mut self, path: &Arc<Path>, m: &Affine, fx: &ColorEffect, fill: Option<(&Paint, &Element)>, stroke: Option<(Rgba, f32)>, rule: FillRule) -> Value {
let mut o = Map::new();
o.insert("p".into(), json!(self.path(path)));
if let Some((p, el)) = fill {
o.insert("f".into(), json!(self.paint(p, el)));
}
if let Some((c, w)) = stroke {
let mut s = color(c);
s.push(num(w, 1e3));
o.insert("s".into(), Value::Array(s));
}
if rule == FillRule::EvenOdd {
o.insert("eo".into(), json!(1));
}
if let Some(m) = matrix(m) {
o.insert("m".into(), m);
}
if let Some(c) = effect(fx) {
o.insert("c".into(), c);
}
Value::Object(o)
}
/// The items of one element on `layer` at frame `f` (its keyframe starts at `start`).
fn element(&mut self, el: &Element, layer: &Layer, f: u32, start: u32, out: &mut Vec<Value>) {
if !el.transform.is_finite() {
return;
}
match &el.kind {
ElementKind::Shape(s) => {
let stroke = s.stroke.as_ref().filter(|st| st.width.is_finite() && st.width > 0.0);
match stroke.and_then(|st| st.profile.as_ref().map(|p| (st, p))) {
// A variable-width stroke is the filled outline the renderer fills.
Some((st, profile)) => {
if let Some(p) = &s.fill {
out.push(self.shape(&s.path, &el.transform, &el.color, Some((p, el)), None, s.fill_rule));
}
let outline = variable_outline(&s.path, &el.transform, st.width, profile, crate::TOLERANCE);
if !outline.is_empty() {
let fill = Paint::Solid(st.color);
out.push(self.shape(&Arc::new(outline), &Affine::IDENTITY, &el.color, Some((&fill, el)), None, FillRule::NonZero));
}
}
None => out.push(self.shape(&s.path, &el.transform, &el.color, s.fill.as_ref().map(|p| (p, el)), stroke.map(|st| (st.color, st.width)), s.fill_rule)),
}
}
// The camera is the view, not artwork (ADR 0027): it is baked into the layers.
ElementKind::Camera => {}
ElementKind::Text(t) => {
let fill = Paint::Solid(t.color);
out.push(self.shape(&t.outline, &el.transform, &el.color, Some((&fill, el)), None, FillRule::NonZero));
}
ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events } => {
let (Some(&y), Some(sym)) = (self.symbols.get(symbol), self.doc.symbol(*symbol)) else { return };
let len = sym.timeline.frame_count();
let mut o = Map::new();
o.insert("y".into(), json!(y));
o.insert("id".into(), json!(el.id.0));
if !el.name.is_empty() {
o.insert("n".into(), json!(el.name));
}
if let Some(m) = matrix(&el.transform) {
o.insert("m".into(), m);
}
if let Some(c) = effect(&el.color) {
o.insert("c".into(), c);
}
match sym.kind {
SymbolKind::Graphic => {
let g = loop_mode.local_frame(f.saturating_sub(start), *first_frame, len);
if g > 0 {
o.insert("g".into(), json!(g));
}
}
SymbolKind::MovieClip => {
// Where the clip is outside the player (inside a button's hit area).
let af = f.saturating_sub(instance_start(layer, f, el.id, *symbol)) % len.max(1);
if af > 0 {
o.insert("af".into(), json!(af));
}
}
SymbolKind::Button => {}
}
if !blend.is_normal() {
o.insert("bl".into(), json!(blend.key()));
if matches!(blend, BlendMode::Subtract | BlendMode::Invert) {
self.notes.entry(BLENDS).or_default().insert(el.id.0);
}
}
if !filters.is_empty() {
o.insert("fx".into(), json!(1));
self.notes.entry(FILTERS).or_default().insert(el.id.0);
}
if !events.is_empty() {
o.insert("ev".into(), Value::Array(events.iter().map(|h| json!([h.event.key(), actions(&h.actions)])).collect()));
}
out.push(Value::Object(o));
}
}
}
fn sound(&mut self, id: anicraft_doc::SoundId) -> Option<usize> {
if !self.sound {
return None;
}
let s = self.doc.sound(id)?;
let n = self.sounds.len();
let i = *self.sound_ix.entry(s.id.0).or_insert(n);
if i == n {
let mime = match s.format {
SoundFormat::Wav => "audio/wav",
SoundFormat::Ogg => "audio/ogg",
SoundFormat::Mp3 => "audio/mpeg",
};
self.sounds.push(json!({"name": s.name, "mime": mime, "data": base64_encode(&s.data)}));
}
Some(i)
}
/// One timeline: its length `n`, frames as runs `f: [[content, count]…]`, mask layer count
/// `nm`, labels `lb`, and per frame the scripts `a` and sounds `snd` of keyframes starting
/// there (top layer first). A scene's frames seen through its camera (ADR 0027) carry the
/// camera's tint (`cc`) and each layer its view (`v`: the camera and the layer's depth).
fn timeline(&mut self, tl: &Timeline, scene: bool) -> Value {
let n = tl.frame_count();
// One clip slot per visible mask layer, top first (as the evaluator numbers them).
let slots: HashMap<u64, usize> = tl.layers.iter().filter(|l| l.kind == LayerKind::Mask && l.visible).enumerate().map(|(i, l)| (l.id.0, i)).collect();
let playing: Vec<usize> = (0..tl.layers.len()).filter(|&i| plays(tl, i)).collect();
let stage = self.doc.stage;
let mut runs: Vec<(usize, u32)> = Vec::new();
let mut scripts = Map::new();
let mut sounds = Map::new();
for f in 0..n {
let camera = if scene { tl.camera_at(f, &stage) } else { None };
let mut layers = Vec::new();
for &index in playing.iter().rev() {
let Some(layer) = tl.layers.get(index).filter(|l| l.kind != LayerKind::Camera) else { continue };
let mut entry = Map::new();
if let Some(v) = camera.and_then(|c| matrix(&c.view(&stage, layer.depth))) {
entry.insert("v".into(), v);
}
if layer.kind == LayerKind::Mask {
entry.insert("mk".into(), json!(slots.get(&layer.id.0).copied().unwrap_or(0)));
} else if let Some(&slot) = layer.parent.and_then(|p| slots.get(&p.0)) {
entry.insert("c".into(), json!(slot));
}
let walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, f));
let mut items = Vec::new();
if let Some((start, els)) = evaluate_guided(layer, f, walk.as_ref()) {
for el in els.iter() {
self.element(el, layer, f, start, &mut items);
}
}
if items.is_empty() && layer.kind != LayerKind::Mask {
continue;
}
entry.insert("e".into(), Value::Array(items));
layers.push(Value::Object(entry));
}
let mut content = json!({"l": layers});
if let Some(cc) = camera.and_then(|c| effect(&c.color())) {
content["cc"] = cc;
}
let key = content.to_string();
let next = self.contents.len();
let ci = *self.content_ix.entry(key).or_insert(next);
if ci == next {
self.contents.push(content);
}
match runs.last_mut() {
Some((c, count)) if *c == ci => *count += 1,
_ => runs.push((ci, 1)),
}
// What entering this frame runs and plays.
let mut a = Vec::new();
let mut snd = Vec::new();
for &index in &playing {
let Some(k) = tl.layers.get(index).and_then(|l| l.keyframe_starting_at(f).and_then(|k| l.keyframes.get(k))) else { continue };
match &k.script {
Some(FrameScript::Actions(list)) => a.push(actions(list)),
Some(FrameScript::Plugin(p)) => {
self.notes.entry(PLUGIN_SCRIPTS).or_default().insert(u64::from(f) << 20 ^ tl.layers.get(index).map_or(0, |l| l.id.0));
a.push(json!({"plugin": format!("{} · {}", p.id, p.entry)}));
}
None => {}
}
if let Some(fs) = k.sound
&& let Some(i) = self.sound(fs.sound)
{
let sync = match fs.sync {
SoundSync::Event => "event",
SoundSync::Start => "start",
SoundSync::Stop => "stop",
SoundSync::Stream => "stream",
};
snd.push(json!([i, sync, fs.repeat.max(1), fs.looping, k.duration.max(1)]));
}
}
if !a.is_empty() {
scripts.insert(f.to_string(), Value::Array(a));
}
if !snd.is_empty() {
sounds.insert(f.to_string(), Value::Array(snd));
}
}
// A label names its first frame, over every layer.
let mut labels: BTreeMap<&str, u32> = BTreeMap::new();
for k in tl.layers.iter().flat_map(|l| l.keyframes.iter()).filter(|k| !k.label.is_empty()) {
let e = labels.entry(k.label.as_str()).or_insert(k.start);
*e = (*e).min(k.start);
}
let mut o = json!({"n": n, "f": runs.iter().map(|(c, k)| json!([c, k])).collect::<Vec<_>>()});
if !slots.is_empty() {
o["nm"] = json!(slots.len());
}
if !labels.is_empty() {
o["lb"] = Value::Array(labels.into_iter().map(|(l, f)| json!([l, f])).collect());
}
if !scripts.is_empty() {
o["a"] = Value::Object(scripts);
}
if !sounds.is_empty() {
o["snd"] = Value::Object(sounds);
}
o
}
}
/// The symbols the movie uses, in the order first met (scenes first, then inside symbols).
fn used_symbols(doc: &Document) -> Vec<SymbolId> {
let mut seen: BTreeSet<SymbolId> = BTreeSet::new();
let mut order = Vec::new();
let mut queue: VecDeque<&Timeline> = doc.scenes.iter().map(|s| &s.timeline).collect();
while let Some(tl) = queue.pop_front() {
for el in tl.layers.iter().flat_map(|l| l.keyframes.iter()).flat_map(|k| k.elements.iter()) {
if let ElementKind::Symbol { symbol, .. } = &el.kind
&& let Some(sym) = doc.symbol(*symbol)
&& seen.insert(*symbol)
{
order.push(*symbol);
queue.push_back(&sym.timeline);
}
}
}
order
}
/// The movie's data: the stage, tables (paths, paints, images, sounds), symbols, scenes, and
/// every used timeline's baked frames (scenes' first, then symbols' in `symbols` order).
pub fn movie(doc: &Document, opts: &HtmlOptions) -> Movie {
let used = used_symbols(doc);
let mut b = Bake {
doc,
sound: opts.sound,
paths: Vec::new(),
path_d: Vec::new(),
by_ptr: HashMap::new(),
keep: Vec::new(),
by_d: HashMap::new(),
paints: Vec::new(),
paint_ix: HashMap::new(),
contents: Vec::new(),
content_ix: HashMap::new(),
symbols: used.iter().enumerate().map(|(i, s)| (*s, i)).collect(),
images: Vec::new(),
image_ix: HashMap::new(),
sounds: Vec::new(),
sound_ix: HashMap::new(),
notes: BTreeMap::new(),
};
let scenes = doc.scenes.len();
let mut timelines = Vec::with_capacity(scenes + used.len());
let mut frames = 0usize;
for s in &doc.scenes {
frames += s.timeline.frame_count() as usize;
timelines.push(b.timeline(&s.timeline, true));
}
let mut symbols = Vec::with_capacity(used.len());
for (i, id) in used.iter().enumerate() {
let Some(sym) = doc.symbol(*id) else { continue };
frames += sym.timeline.frame_count() as usize;
timelines.push(b.timeline(&sym.timeline, false));
let kind = match sym.kind {
SymbolKind::Graphic => "graphic",
SymbolKind::MovieClip => "movieclip",
SymbolKind::Button => "button",
};
symbols.push(json!({"name": sym.name, "k": kind, "tl": scenes + i}));
}
let stage = doc.stage;
let fps = if stage.fps.is_finite() && stage.fps > 0.0 { stage.fps } else { 24.0 };
let json = json!({
"v": FORMAT_VERSION,
"generator": format!("AniCraft {}", env!("CARGO_PKG_VERSION")),
"stage": {"w": stage.width.max(1), "h": stage.height.max(1), "fps": num(fps, 1000.0), "bg": stage.background.to_hex()},
"fit": opts.fit,
"scenes": doc.scenes.iter().enumerate().map(|(i, s)| json!({"name": s.name, "tl": i})).collect::<Vec<_>>(),
"symbols": symbols,
"timelines": timelines,
"contents": b.contents,
"paths": b.path_d,
"paints": b.paints,
"images": b.images,
"sounds": b.sounds,
});
let stats = HtmlStats {
timelines: json["timelines"].as_array().map_or(0, Vec::len),
frames,
contents: json["contents"].as_array().map_or(0, Vec::len),
paths: b.paths.len(),
images: json["images"].as_array().map_or(0, Vec::len),
sounds: json["sounds"].as_array().map_or(0, Vec::len),
data_bytes: 0,
code_bytes: PLAYER_JS.len() + CANVAS_JS.len(),
};
let report = b.notes.into_iter().map(|(k, v)| (k.to_string(), v.len())).collect();
Movie { json, paths: b.paths, report, stats }
}
/// Text for HTML content and attributes.
fn escape_html(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
c if c.is_control() => {}
c => out.push(c),
}
}
out
}
/// The movie as one web page: the data, the player and the page code inline, images and
/// sounds embedded, so the file plays from a disk, a server or an e-mail attachment alike.
pub fn to_html(doc: &Document, opts: &HtmlOptions) -> Result<HtmlExport, String> {
let mut m = movie(doc, opts);
// In a <script> element only `</script` and `<!--` could end or confuse it; every `<` in
// the JSON is inside a string, where `<` reads the same.
let data = m.json.to_string().replace('<', "\\u003c");
let title = escape_html(&opts.title);
let bg = doc.stage.background.to_hex();
let (w, h) = (doc.stage.width.max(1), doc.stage.height.max(1));
let mut html = String::with_capacity(data.len() + PLAYER_JS.len() + CANVAS_JS.len() + 1024);
html.push_str("<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n");
html.push_str(&format!("<meta name=\"generator\" content=\"AniCraft {}\">\n<title>{title}</title>\n", env!("CARGO_PKG_VERSION")));
html.push_str(&format!("<style>html,body{{margin:0;height:100%;background:{bg}}}body{{display:flex;align-items:center;justify-content:center;overflow:hidden}}canvas{{display:block;touch-action:none;user-select:none}}</style>\n</head>\n<body>\n"));
html.push_str(&format!("<canvas id=\"anicraft-stage\" width=\"{w}\" height=\"{h}\" role=\"img\" aria-label=\"{title}\"></canvas>\n"));
html.push_str("<script type=\"application/json\" id=\"anicraft-movie\">");
html.push_str(&data);
html.push_str("</script>\n<script>\n");
html.push_str(PLAYER_JS);
html.push('\n');
html.push_str(CANVAS_JS);
html.push_str("</script>\n</body>\n</html>\n");
if html.len() > MAX_HTML_BYTES {
return Err(format!("the page would be {} MB, more than the {} MB limit", html.len() >> 20, MAX_HTML_BYTES >> 20));
}
m.stats.data_bytes = data.len();
Ok(HtmlExport { html, report: m.report, stats: m.stats })
}
#[cfg(test)]
#[path = "html_tests.rs"]
mod tests;
+311
View File
@@ -0,0 +1,311 @@
// AniCraft HTML canvas player: the page (ADR 0028). SPDX-License-Identifier: MIT OR Apache-2.0
//
// Draws what player.js evaluates on a <canvas> 2D context, steps the movie at its frame rate,
// sends the pointer to its buttons and plays its sounds with Web Audio. Drawing follows the
// CPU renderer (crates/render, the oracle): fills by their rule, round-joined strokes of the
// stage-space width, colour effects baked into colours, a symbol that fades or blends as one
// drawn on its own layer first, and masks as the union of their fills.
(function () {
"use strict";
const data = document.getElementById("anicraft-movie");
const canvas = document.getElementById("anicraft-stage");
if (!data || !canvas || !canvas.getContext) return;
const movie = JSON.parse(data.textContent);
const W = movie.stage.w, H = movie.stage.h, fit = movie.fit !== false;
const ctx = canvas.getContext("2d");
const paths = movie.paths.map((d) => new Path2D(d));
const images = movie.images.map((src) => {
const im = new Image();
im.src = src;
return im;
});
const patterns = new Map();
const scratch = document.createElement("canvas").getContext("2d");
// ----- hit tests, by the canvas -----------------------------------------------------------------
const host = {
inFill: function (p, m, x, y, eo) {
const path = paths[p];
if (!path) return false;
scratch.setTransform(m[0], m[1], m[2], m[3], m[4], m[5]);
return scratch.isPointInPath(path, x, y, eo ? "evenodd" : "nonzero");
},
nearStroke: function (p, m, x, y, reach) {
const path = paths[p];
if (!path || !(reach > 0)) return false;
scratch.setTransform(1, 0, 0, 1, 0, 0);
scratch.lineWidth = reach * 2;
scratch.lineJoin = "round";
scratch.lineCap = "round";
return scratch.isPointInStroke(stagePath(path, m), x, y);
},
};
const player = new AniCraft.Player(movie, host);
function stagePath(path, m) {
const out = new Path2D();
out.addPath(path, { a: m[0], b: m[1], c: m[2], d: m[3], e: m[4], f: m[5] });
return out;
}
function css(c) {
const b = (v) => Math.round(Math.min(Math.max(v, 0), 1) * 255);
return "rgba(" + b(c[0]) + "," + b(c[1]) + "," + b(c[2]) + "," + Math.min(Math.max(c[3], 0), 1) + ")";
}
// ----- the canvas size: the stage fitted to the window, sharp on high-density screens ------------
let scale = 1;
function resize() {
const dpr = window.devicePixelRatio || 1;
let w = W, h = H;
if (fit) {
const k = Math.min(window.innerWidth / W, window.innerHeight / H);
if (k > 0 && Number.isFinite(k)) {
w = W * k;
h = H * k;
}
}
canvas.style.width = w + "px";
canvas.style.height = h + "px";
const bw = Math.max(1, Math.round(w * dpr)), bh = Math.max(1, Math.round(h * dpr));
if (canvas.width !== bw || canvas.height !== bh) {
canvas.width = bw;
canvas.height = bh;
pool.length = 0;
}
scale = bw / W;
draw();
}
// ----- drawing ----------------------------------------------------------------------------------
// Offscreen layers for groups and clips, reused frame to frame.
const pool = [];
function layer() {
const c = pool.pop() || document.createElement("canvas");
if (c.width !== canvas.width || c.height !== canvas.height) {
c.width = canvas.width;
c.height = canvas.height;
}
const g = c.getContext("2d");
g.setTransform(1, 0, 0, 1, 0, 0);
g.globalAlpha = 1;
g.globalCompositeOperation = "source-over";
g.clearRect(0, 0, c.width, c.height);
return { canvas: c, ctx: g };
}
function release(l) {
pool.push(l.canvas);
}
// Canvas compositing for each blend mode; Subtract and Invert have none and draw normally.
const BLEND = { normal: "source-over", layer: "source-over", multiply: "multiply", screen: "screen", overlay: "overlay", darken: "darken", lighten: "lighten", hardlight: "hard-light", add: "lighter", difference: "difference", alpha: "destination-in", erase: "destination-out", subtract: "source-over", invert: "source-over" };
function paintStyle(g, f, fx) {
const p = movie.paints[f];
if (!p) return null;
if (p.s) return css(AniCraft.applyEffect(fx, p.s));
if (p.l || p.r) {
const gr = p.l ? g.createLinearGradient(p.l[0], p.l[1], p.l[2], p.l[3]) : g.createRadialGradient(p.r[0], p.r[1], 0, p.r[0], p.r[1], p.r[2]);
for (const s of p.st) gr.addColorStop(s[0], css(AniCraft.applyEffect(fx, [s[1], s[2], s[3], s[4]])));
return gr;
}
if (p.b !== undefined) {
const im = images[p.b];
if (!im || !im.complete || !im.naturalWidth) return "rgba(128,128,128,1)";
const key = f;
let pat = patterns.get(key);
if (!pat) {
pat = g.createPattern(im, p.rep ? "repeat" : "no-repeat");
if (pat && p.m && pat.setTransform) pat.setTransform(new DOMMatrix(p.m));
patterns.set(key, pat);
}
return pat;
}
return null;
}
function draw() {
const stack = [{ ctx: ctx, canvas: canvas }];
const masks = new Map();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = movie.stage.bg;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const k = scale;
const set = (g, m) => g.setTransform(k * m[0], k * m[1], k * m[2], k * m[3], k * m[4], k * m[5]);
player.evaluate({
item: function (it) {
const path = paths[it.p];
if (!path || !AniCraft.finite(it.m)) return;
if (it.masks !== null) {
// Mask artwork: its fill area only, opaque.
const mk = masks.get(it.masks);
if (!mk || it.f < 0) return;
set(mk.ctx, it.m);
mk.ctx.fillStyle = "#000";
mk.ctx.fill(path, it.eo ? "evenodd" : "nonzero");
return;
}
const g = stack[stack.length - 1].ctx;
if (it.f >= 0) {
const style = paintStyle(g, it.f, it.c);
if (style) {
const bitmap = movie.paints[it.f] && movie.paints[it.f].b !== undefined;
g.globalAlpha = bitmap ? Math.min(Math.max(it.c[0], 0), 1) : 1;
set(g, it.m);
g.fillStyle = style;
g.fill(path, it.eo ? "evenodd" : "nonzero");
g.globalAlpha = 1;
}
}
if (it.s) {
const w = it.s[4] * AniCraft.meanScale(it.m) * k;
if (w > 0 && Number.isFinite(w)) {
g.setTransform(k, 0, 0, k, 0, 0);
g.lineWidth = w / k;
g.lineJoin = "round";
g.lineCap = "round";
g.strokeStyle = css(AniCraft.applyEffect(it.c, it.s));
g.stroke(stagePath(path, it.m));
}
}
},
groupBegin: function () {
stack.push(layer());
},
groupEnd: function (_, grp) {
const l = stack.pop();
const g = stack[stack.length - 1].ctx;
g.setTransform(1, 0, 0, 1, 0, 0);
g.globalAlpha = Math.min(Math.max(grp.alpha, 0), 1);
g.globalCompositeOperation = BLEND[grp.blend] || "source-over";
g.drawImage(l.canvas, 0, 0);
g.globalAlpha = 1;
g.globalCompositeOperation = "source-over";
release(l);
},
clipBegin: function () {
stack.push(layer());
},
// A clip that ends without meeting its mask shows nothing.
clipEnd: function () {
release(stack.pop());
},
maskBegin: function (id) {
masks.set(id, layer());
},
maskEnd: function (id, open) {
const mk = masks.get(id);
masks.delete(id);
if (!mk) return;
if (open) {
const l = stack.pop();
l.ctx.setTransform(1, 0, 0, 1, 0, 0);
l.ctx.globalCompositeOperation = "destination-in";
l.ctx.drawImage(mk.canvas, 0, 0);
l.ctx.globalCompositeOperation = "source-over";
const g = stack[stack.length - 1].ctx;
g.setTransform(1, 0, 0, 1, 0, 0);
g.drawImage(l.canvas, 0, 0);
release(l);
}
release(mk);
},
});
}
// ----- sound ------------------------------------------------------------------------------------
// Event and Start sounds play in full from their keyframe; Stream sounds play over their
// keyframe's span; Stop stops the sound. Browsers start audio only after a click or a key.
let audio = null;
const buffers = [];
const voices = [];
function audioOn() {
if (!movie.sounds.length) return;
if (!audio) {
const AC = window.AudioContext || window.webkitAudioContext;
if (!AC) return;
audio = new AC();
movie.sounds.forEach((s, i) => {
const bin = atob(s.data);
const bytes = new Uint8Array(bin.length);
for (let j = 0; j < bin.length; j++) bytes[j] = bin.charCodeAt(j);
audio.decodeAudioData(bytes.buffer).then((b) => (buffers[i] = b), () => console.warn("AniCraft: this browser can't play the sound “" + s.name + "”"));
});
}
if (audio.state === "suspended") audio.resume();
}
function play(sounds) {
if (!audio || audio.state !== "running") return;
for (const [i, sync, repeat, loop, span] of sounds) {
const b = buffers[i];
const playing = voices.filter((v) => v.sound === i && v.end > audio.currentTime);
if (sync === "stop") {
for (const v of playing) v.src.stop();
continue;
}
if (!b || (sync === "start" && playing.length)) continue;
const src = audio.createBufferSource();
src.buffer = b;
src.connect(audio.destination);
const t = audio.currentTime;
let end = t + b.duration * Math.max(repeat, 1);
if (sync === "stream") end = t + span / movie.stage.fps;
src.loop = loop || repeat > 1 || sync === "stream";
src.start(t);
if (!loop || sync === "stream") src.stop(end);
voices.push({ sound: i, src: src, end: loop && sync !== "stream" ? Infinity : end });
}
for (let j = voices.length - 1; j >= 0; j--) if (voices[j].end <= audio.currentTime) voices.splice(j, 1);
}
// ----- playback ---------------------------------------------------------------------------------
function report(r) {
for (const line of r.output) console.log(line);
play(r.sounds);
}
function stagePoint(e) {
const r = canvas.getBoundingClientRect();
return { x: ((e.clientX - r.left) * W) / Math.max(r.width, 1), y: ((e.clientY - r.top) * H) / Math.max(r.height, 1) };
}
function pointer(type, e) {
const p = stagePoint(e);
report(player.input([{ type: type, x: p.x, y: p.y }]));
canvas.style.cursor = player.st.hover ? "pointer" : "default";
draw();
}
canvas.addEventListener("pointermove", (e) => pointer("move", e));
canvas.addEventListener("pointerdown", (e) => {
audioOn();
if (canvas.setPointerCapture) canvas.setPointerCapture(e.pointerId);
pointer("down", e);
});
canvas.addEventListener("pointerup", (e) => pointer("up", e));
canvas.addEventListener("pointerleave", () => {
report(player.input([{ type: "leave" }]));
draw();
});
window.addEventListener("keydown", audioOn);
window.addEventListener("resize", resize);
const dt = 1000 / movie.stage.fps;
let last = null, acc = 0;
function tick(t) {
if (last === null) last = t;
acc += Math.min(t - last, 250);
last = t;
let stepped = false;
while (acc >= dt) {
acc -= dt;
report(player.step([]));
stepped = true;
}
if (stepped) draw();
requestAnimationFrame(tick);
}
// Images first, so the first frame shows them.
Promise.all(images.map((im) => (im.decode ? im.decode().catch(() => {}) : Promise.resolve()))).then(() => {
report(player.start());
resize();
requestAnimationFrame(tick);
});
})();
+764
View File
@@ -0,0 +1,764 @@
// AniCraft HTML canvas player: the core (ADR 0028). SPDX-License-Identifier: MIT OR Apache-2.0
//
// Plays a movie exported by File > Export > HTML Canvas: the instance tree, movie clip
// playheads, frame actions and button events. It is a line-by-line port of the Rust player
// (crates/doc/src/player.rs, the reference) over the exported data, and the tests run it in a
// JavaScript engine against that player. Nothing here touches the page: canvas.js draws and
// listens to the pointer; this file only computes.
//
// The movie data (see crates/render/src/html.rs): every timeline's frames are baked (tweens,
// easing, motion paths and shape morphs already evaluated), so this file never interpolates.
// A frame is a list of layers, bottom first; a layer holds items: shapes (a path, a paint, a
// stroke) and symbol instances (a symbol, its element id, its name and event handlers).
"use strict";
var AniCraft = (function () {
// Budgets, as in the Rust player: a go-to loop ends in a message, not a hang.
const MAX_ACTIONS_PER_STEP = 10000;
const MAX_ENTERS_PER_STEP = 1000;
const MAX_NODES = 10000;
const MAX_OUTPUT_PER_STEP = 1000;
const MAX_EVENTS_PER_STEP = 256;
const MAX_SYMBOL_DEPTH = 32;
const ROOT = 0, GRAPHIC = 1, CLIP = 2, BUTTON = 3;
const KINDS = { graphic: GRAPHIC, movieclip: CLIP, button: BUTTON };
const I = [1, 0, 0, 1, 0, 0];
const NO_EFFECT = [1, 1, 1, 1, 0];
const EMPTY = { l: [] };
// ----- geometry ------------------------------------------------------------------------------
// `p · q`: apply q first, then p (Affine::mul).
function mul(p, q) {
return [p[0] * q[0] + p[2] * q[1], p[1] * q[0] + p[3] * q[1], p[0] * q[2] + p[2] * q[3], p[1] * q[2] + p[3] * q[3], p[0] * q[4] + p[2] * q[5] + p[4], p[1] * q[4] + p[3] * q[5] + p[5]];
}
function finite(m) {
return m.every(Number.isFinite);
}
function meanScale(m) {
return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));
}
// Affine::decompose and Decomposed::compose (T · R · Shear · S).
function decompose(m) {
const [a, b, c, d] = m;
const sx = Math.sqrt(a * a + b * b), r = Math.atan2(b, a), det = a * d - b * c;
let sy, k;
if (sx > 1e-12) {
sy = det / sx;
k = Math.abs(det) > 1e-12 ? (a * c + b * d) / det : 0;
} else {
sy = Math.sqrt(c * c + d * d);
k = 0;
}
return { tx: m[4], ty: m[5], sx: sx, sy: sy, r: r, k: k };
}
function compose(q) {
const c = Math.cos(q.r), s = Math.sin(q.r);
return mul(mul(mul([1, 0, 0, 1, q.tx, q.ty], [c, s, -s, c, 0, 0]), [1, 0, q.k, 1, 0, 0]), [q.sx, 0, 0, q.sy, 0, 0]);
}
// ----- colour effects: [alpha, tint r, g, b, tint amount] ---------------------------------------
// ColorEffect::concat: tints keep the stronger one; alpha multiplies.
function concat(o, i) {
const t = i[4] >= o[4] ? i : o;
return [o[0] * i[0], t[1], t[2], t[3], t[4]];
}
// ColorEffect::apply on straight [r, g, b, a].
function applyEffect(fx, c) {
const k = Math.min(Math.max(fx[4], 0), 1);
const a = Math.min(Math.max(fx[0], 0), 1);
return [c[0] + (fx[1] - c[0]) * k, c[1] + (fx[2] - c[1]) * k, c[2] + (fx[3] - c[2]) * k, c[3] * a];
}
// ----- dictionaries ------------------------------------------------------------------------------
// String-keyed tables on plain objects (no Map: some engines' Map iterators misbehave).
function Dict(pairs) {
this.o = Object.create(null);
for (const [k, v] of pairs || []) this.o[k] = v;
}
Dict.prototype.get = function (k) {
return this.o[k];
};
Dict.prototype.has = function (k) {
return k in this.o;
};
Dict.prototype.set = function (k, v) {
this.o[k] = v;
};
Dict.prototype.delete = function (k) {
delete this.o[k];
};
Dict.prototype.keys = function () {
return Object.keys(this.o);
};
Dict.prototype.values = function () {
return Object.keys(this.o).map((k) => this.o[k]);
};
Dict.prototype.entries = function () {
return Object.keys(this.o).map((k) => [k, this.o[k]]);
};
// ----- instance paths --------------------------------------------------------------------------
// An instance's place: element ids from the main timeline down ([] is the main timeline).
function keyOf(path) {
return path.join(",");
}
// The order of Rust's BTreeMap<Vec<ElementId>, _>: element by element, then shorter first.
function comparePaths(a, b) {
const n = Math.min(a.length, b.length);
for (let i = 0; i < n; i++) {
if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
}
return a.length - b.length;
}
function samePath(a, b) {
return a !== null && b !== null && comparePaths(a, b) === 0;
}
// ----- the movie --------------------------------------------------------------------------------
// Unpacks the exported data: frame tables expanded, symbol kinds as numbers.
function load(movie) {
for (const tl of movie.timelines) {
const frames = [];
for (const [content, count] of tl.f) {
for (let i = 0; i < count && frames.length < tl.n; i++) frames.push(content);
}
tl.frames = frames;
tl.labels = new Dict(tl.lb || []);
}
for (const s of movie.symbols) s.kind = KINDS[s.k] || GRAPHIC;
return movie;
}
function content(M, tl, frame) {
const c = tl.frames[frame];
return c === undefined ? EMPTY : M.contents[c] || EMPTY;
}
// ----- the player state ------------------------------------------------------------------------
function newState() {
return { scene: 0, root: { frame: 0, playing: true }, clips: new Dict(), props: new Dict(), pointer: null, down: false, hover: null, pressed: null, tick: 0 };
}
// Each clip entry: { path, frame, playing }; each props entry: { path, ...overrides }.
function clipFrame(st, key, len) {
const c = st.clips.get(key);
return Math.min(c ? c.frame : 0, Math.max(len, 1) - 1);
}
// Up (0), Over (1) under the pointer, Down (2) while pressed on it.
function buttonFrame(st, path, len) {
const over = samePath(st.hover, path);
const f = over ? (st.down && samePath(st.pressed, path) ? 2 : 1) : 0;
return Math.min(f, Math.max(len, 1) - 1);
}
// Property ranges (anicraft_actions::Property::range).
const RANGES = { x: [-1e6, 1e6], y: [-1e6, 1e6], alpha: [0, 1], visible: [0, 1], rotation: [-36000, 36000], scale_x: [-1000, 1000], scale_y: [-1000, 1000] };
function setProp(ov, p, value) {
const r = RANGES[p];
if (!r || !Number.isFinite(value)) return;
const v = Math.min(Math.max(value, r[0]), r[1]);
if (p === "visible") ov.visible = v !== 0;
else ov[p] = v;
}
// Overrides::apply: the element's transform and alpha with the set properties in place.
function override(ov, m, fx) {
m = m || I;
if (ov.x !== undefined || ov.y !== undefined || ov.rotation !== undefined || ov.scale_x !== undefined || ov.scale_y !== undefined) {
const d = decompose(m);
if (ov.x !== undefined) d.tx = ov.x;
if (ov.y !== undefined) d.ty = ov.y;
if (ov.rotation !== undefined) d.r = (ov.rotation * Math.PI) / 180;
if (ov.scale_x !== undefined) d.sx = ov.scale_x;
if (ov.scale_y !== undefined) d.sy = ov.scale_y;
const c = compose(d);
if (finite(c)) m = c;
}
if (ov.alpha !== undefined) {
fx = (fx || NO_EFFECT).slice();
fx[0] = ov.alpha;
}
return { m: m, c: fx || NO_EFFECT };
}
// ----- the instance tree (player.rs `tree`, `walk`) --------------------------------------------
function tree(M, st) {
const tl = M.scenes[st.scene] ? M.scenes[st.scene].tl : 0;
const out = [{ path: [], key: "", parent: -1, owner: 0, name: "", sym: -1, kind: ROOT, frame: st.root.frame, frames: M.timelines[tl].n, xf: I, hittable: true, events: null }];
walk(M, st, tl, st.root.frame, 0, 0, I, 1, true, out);
return out;
}
function walk(M, st, tli, frame, parent, owner, xf, depth, hittable, out) {
if (depth > MAX_SYMBOL_DEPTH) return;
const base = out[parent].path;
for (const L of content(M, M.timelines[tli], frame).l) {
const hit = hittable && L.mk === undefined;
// Through a camera, a scene's layer is placed by the camera and its depth.
const lxf = L.v || xf;
for (const e of L.e) {
if (out.length >= MAX_NODES) return;
if (e.y === undefined) continue;
const sym = M.symbols[e.y];
if (!sym) continue;
const path = base.concat([e.id]);
const key = keyOf(path);
const ov = st.props.get(key);
const shown = !ov || ov.visible !== false;
const m = ov ? override(ov, e.m, e.c).m : e.m || I;
const len = M.timelines[sym.tl].n;
const kind = sym.kind;
const local = kind === GRAPHIC ? e.g || 0 : kind === CLIP ? clipFrame(st, key, len) : buttonFrame(st, path, len);
const idx = out.length;
const nxf = mul(lxf, m);
out.push({ path: path, key: key, parent: parent, owner: owner, name: e.n || "", sym: e.y, kind: kind, frame: local, frames: len, xf: nxf, hittable: hit && shown, events: e.ev || null });
// A graphic's contents belong to the timeline the graphic is on.
walk(M, st, sym.tl, local, idx, kind === GRAPHIC ? owner : idx, nxf, depth + 1, hit && shown, out);
}
}
}
// ----- evaluation (eval.rs `eval_timeline`) ----------------------------------------------------
// What the player shows at `st`, as a display list like the Rust one: items in drawing
// order, with the clip they are drawn in (`clip`), the clip their fill forms (`masks`) and
// the group they fade with; `clips` holds each clip's parent, `groups` each group. `v`, when
// given, hears every item and where clips and groups open and close (canvas.js draws so).
function evaluate(M, st, v) {
const dl = { items: [], clips: [], groups: [] };
const scene = M.scenes[st.scene];
const tli = scene ? scene.tl : 0;
// A scene seen through its camera: the camera's tint colours everything.
const cx = top(I, 0);
cx.c = content(M, M.timelines[tli], st.root.frame).cc || NO_EFFECT;
evalTimeline(M, tli, st.root.frame, cx, dl, { st: st, path: [] }, v || null);
return dl;
}
function top(xf, depth) {
return { xf: xf, c: NO_EFFECT, depth: depth, clip: null, masks: null, group: null };
}
function evalTimeline(M, tli, frame, cx, dl, play, v) {
if (cx.depth > MAX_SYMBOL_DEPTH) return;
const tl = M.timelines[tli];
// One clip per visible mask layer, nested in the enclosing clip; inside mask artwork
// every layer is artwork.
const slots = [];
if (cx.masks === null) {
for (let k = 0; k < (tl.nm || 0); k++) {
slots.push(dl.clips.length);
dl.clips.push(cx.clip);
}
}
let open = null;
for (const L of content(M, tl, frame).l) {
let clip = cx.clip, masks = cx.masks;
const isMask = cx.masks === null && L.mk !== undefined;
if (isMask) masks = slots[L.mk];
else if (cx.masks === null && L.c !== undefined) clip = slots[L.c];
if (v && cx.masks === null && !isMask) {
// Masked layers draw into their clip; one that never meets its mask stays hidden.
const want = clip !== cx.clip ? clip : null;
if (open !== null && open !== want) {
v.clipEnd(open, false);
open = null;
}
if (want !== null && open === null) {
v.clipBegin(want);
open = want;
}
}
if (v && isMask) v.maskBegin(masks);
const lcx = L.v ? Object.assign({}, cx, { xf: L.v }) : cx;
for (const e of L.e) evalElement(M, e, lcx, clip, masks, dl, play, v);
if (v && isMask) {
v.maskEnd(masks, open === masks);
if (open === masks) open = null;
}
}
if (v && open !== null) v.clipEnd(open, false);
}
function evalElement(M, e, cx, clip, masks, dl, play, v) {
let m = e.m || I, fx = e.c || NO_EFFECT, child = null;
if (e.y !== undefined && play) {
child = { st: play.st, path: play.path.concat([e.id]) };
const ov = play.st.props.get(keyOf(child.path));
if (ov) {
if (ov.visible === false) return;
const o = override(ov, m, fx);
m = o.m;
fx = o.c;
}
}
const xf = mul(cx.xf, m);
if (e.y === undefined) {
const it = { p: e.p, m: xf, f: e.f === undefined ? -1 : e.f, s: e.s || null, eo: !!e.eo, c: concat(cx.c, fx), clip: clip, masks: masks, group: cx.group };
dl.items.push(it);
if (v) v.item(it);
return;
}
const sym = M.symbols[e.y];
if (!sym) return;
const len = M.timelines[sym.tl].n;
let local;
if (sym.kind === GRAPHIC) local = e.g || 0;
else if (child) local = sym.kind === CLIP ? clipFrame(child.st, keyOf(child.path), len) : buttonFrame(child.st, child.path, len);
// Outside the player (a button's hit area): movie clips where the timeline has them,
// buttons on Up.
else local = sym.kind === CLIP ? e.af || 0 : 0;
const fade = Math.min(Math.max(fx[0], 0), 1);
const blend = e.bl || "normal";
let color = concat(cx.c, fx), group = cx.group;
if (masks === null && (fade < 1 - 1e-4 || blend !== "normal" || e.fx)) {
group = dl.groups.length;
dl.groups.push({ parent: cx.group, alpha: fade, blend: blend, clip: clip });
color = concat(cx.c, [1, fx[1], fx[2], fx[3], fx[4]]);
}
if (v && group !== cx.group) v.groupBegin(group, dl.groups[group]);
const inner = { xf: xf, c: color, depth: cx.depth + 1, clip: clip, masks: masks, group: group };
evalTimeline(M, sym.tl, local, inner, dl, child, v);
if (v && group !== cx.group) v.groupEnd(group, dl.groups[group]);
}
// ----- hit testing (player.rs `hit_in`) --------------------------------------------------------
// `host.inFill(path, xf, x, y, evenOdd)` and `host.nearStroke(path, xf, x, y, reach)` answer
// for one path; canvas.js asks the canvas, the tests a polygon test.
function hitIn(M, st, nodes, host, x, y) {
for (let i = nodes.length - 1; i >= 0; i--) {
const n = nodes[i];
const interactive = n.kind === BUTTON || (n.kind === CLIP && n.events);
if (!n.hittable || !interactive) continue;
const sym = M.symbols[n.sym];
if (!sym) continue;
let inside = false;
const probe = {
item: function (it) {
if (inside || it.masks !== null || !finite(it.m)) return;
const fill = it.f >= 0 && host.inFill(it.p, it.m, x, y, it.eo);
inside = fill || (it.s !== null && host.nearStroke(it.p, it.m, x, y, it.s[4] * 0.5 * meanScale(it.m)));
},
clipBegin: function () {},
clipEnd: function () {},
maskBegin: function () {},
maskEnd: function () {},
groupBegin: function () {},
groupEnd: function () {},
};
const dl = { items: [], clips: [], groups: [] };
// The Hit frame (the fourth) when a button has one, else its Up frame.
if (n.kind === BUTTON) evalTimeline(M, sym.tl, n.frames > 3 ? 3 : 0, top(n.xf, 1), dl, null, probe);
else evalTimeline(M, sym.tl, n.frame, top(n.xf, 1), dl, { st: st, path: n.path }, probe);
if (inside) return n.path;
}
return null;
}
// ----- the player (player.rs `Run`) ------------------------------------------------------------
// A player for `movie` (the exported data, as parsed JSON). `host` answers hit tests (see
// hitIn). `start()` shows the first frame, `step(events)` moves one frame on, `input(events)`
// routes pointer events between frames; each returns { output, sounds }: the lines the movie
// wrote (traces, and why an action could not run) and the sounds of the keyframes entered.
// Events: { type: "move" | "down" | "up", x, y } (stage pixels) or { type: "leave" }.
function Player(movie, host) {
this.M = load(movie);
this.host = host;
this.st = newState();
}
Player.prototype.start = function () {
this.st = newState();
const r = new Run(this);
r.refresh();
r.pending.unshift([]);
r.settle();
return r.finish();
};
Player.prototype.step = function (events) {
const r = new Run(this);
this.st.tick += 1;
r.refresh();
r.advance();
r.settle();
for (const e of (events || []).slice(0, MAX_EVENTS_PER_STEP)) r.event(e);
return r.finish();
};
Player.prototype.input = function (events) {
const r = new Run(this);
r.refresh();
for (const e of (events || []).slice(0, MAX_EVENTS_PER_STEP)) r.event(e);
return r.finish();
};
// What the player shows now (see evaluate).
Player.prototype.evaluate = function (v) {
return evaluate(this.M, this.st, v);
};
// The state as plain data, ordered like the Rust player's (for tests and debugging).
Player.prototype.snapshot = function () {
const st = this.st;
const clips = Array.from(st.clips.values()).sort((a, b) => comparePaths(a.path, b.path)).map((c) => [c.path, c.frame, c.playing]);
const props = Array.from(st.props.values()).sort((a, b) => comparePaths(a.path, b.path)).map((p) => {
const o = {};
for (const k of Object.keys(p)) if (k !== "path") o[k] = p[k];
return [p.path, o];
});
return { scene: st.scene, frame: st.root.frame, playing: st.root.playing, clips: clips, props: props, hover: st.hover, pressed: st.pressed, down: st.down };
};
function Run(player) {
this.M = player.M;
this.host = player.host;
this.st = player.st;
this.nodes = [];
this.dirty = true;
this.pending = [];
this.actions = 0;
this.enters = 0;
this.halted = false;
this.output = [];
this.dropped = 0;
this.sounds = [];
}
Run.prototype.out = function (line) {
if (this.output.length < MAX_OUTPUT_PER_STEP) this.output.push(line);
else this.dropped += 1;
};
Run.prototype.halt = function (why) {
if (!this.halted) {
this.halted = true;
this.out("Stopped running actions this frame: " + why + " (a go-to loop?)");
}
};
Run.prototype.sceneTimeline = function (s) {
const sc = this.M.scenes[s];
return this.M.timelines[sc ? sc.tl : 0];
};
// Rebuilds the instance tree after a change: movie clips that appeared start (and enter
// their first frame), those that left are forgotten.
Run.prototype.refresh = function () {
if (!this.dirty) return;
this.dirty = false;
const st = this.st;
if (st.scene >= this.M.scenes.length) st.scene = 0;
const n = this.sceneTimeline(st.scene).n;
st.root.frame = Math.min(st.root.frame, Math.max(n - 1, 0));
this.nodes = tree(this.M, st);
const live = new Dict();
const all = new Dict();
for (const nd of this.nodes) {
all.set(nd.key, true);
if (nd.kind === CLIP && !live.has(nd.key)) live.set(nd.key, nd.path);
}
for (const k of Array.from(st.clips.keys())) if (!live.has(k)) st.clips.delete(k);
const born = Array.from(live.entries()).filter(([k]) => !st.clips.has(k)).sort((a, b) => comparePaths(a[1], b[1]));
for (const [k, path] of born) {
st.clips.set(k, { path: path, frame: 0, playing: true });
this.queue(path);
}
for (const k of Array.from(st.props.keys())) if (!all.has(k)) st.props.delete(k);
if (st.hover !== null && !all.has(keyOf(st.hover))) st.hover = null;
if (st.pressed !== null && !all.has(keyOf(st.pressed))) st.pressed = null;
};
Run.prototype.queue = function (path) {
if (!this.pending.some((p) => samePath(p, path))) this.pending.push(path);
};
Run.prototype.indexOf = function (path) {
const key = keyOf(path);
return this.nodes.findIndex((n) => n.key === key && n.path.length === path.length);
};
// Every playing timeline one frame on.
Run.prototype.advance = function () {
const st = this.st;
if (st.root.playing) {
const n = this.sceneTimeline(st.scene).n;
let scene = st.scene, frame;
if (st.root.frame + 1 < n) frame = st.root.frame + 1;
else if (st.scene + 1 < this.M.scenes.length) {
scene = st.scene + 1;
frame = 0;
} else {
scene = 0;
frame = 0;
}
if (scene !== st.scene || frame !== st.root.frame) {
st.scene = scene;
st.root.frame = frame;
this.queue([]);
}
}
const lens = new Dict();
for (const nd of this.nodes) if (nd.kind === CLIP && !lens.has(nd.key)) lens.set(nd.key, nd.frames);
const moved = [];
const clips = Array.from(st.clips.entries()).sort((a, b) => comparePaths(a[1].path, b[1].path));
for (const [k, c] of clips) {
if (!c.playing) continue;
const len = Math.max(lens.has(k) ? lens.get(k) : 1, 1);
const next = (c.frame + 1) % len;
if (next !== c.frame) {
c.frame = next;
moved.push(c.path);
}
}
for (const p of moved) this.queue(p);
this.dirty = true;
};
Run.prototype.settle = function () {
for (;;) {
this.refresh();
if (this.halted) {
this.pending = [];
return;
}
const path = this.pending.shift();
if (path === undefined) return;
this.enters += 1;
if (this.enters > MAX_ENTERS_PER_STEP) {
this.halt("more than " + MAX_ENTERS_PER_STEP + " frames entered");
continue;
}
this.enter(path);
}
};
Run.prototype.timelineOf = function (i) {
const n = this.nodes[i];
if (!n) return null;
if (n.kind === ROOT) return this.sceneTimeline(this.st.scene);
if (n.kind === CLIP) {
const s = this.M.symbols[n.sym];
return s ? this.M.timelines[s.tl] : null;
}
return null;
};
// Runs what the keyframes starting at the timeline's frame hold, top layer first.
Run.prototype.enter = function (path) {
const i = this.indexOf(path);
if (i < 0) return;
const tl = this.timelineOf(i);
if (!tl) return;
const frame = this.nodes[i].frame;
for (const s of (tl.snd && tl.snd[frame]) || []) this.sounds.push(s);
for (const script of (tl.a && tl.a[frame]) || []) {
if (Array.isArray(script)) this.runList(path, script);
else this.out("Frame script " + script.plugin + " not run: frame scripts are not exported");
}
};
Run.prototype.runList = function (owner, list) {
for (const a of list) {
if (this.halted) return;
this.actions += 1;
if (this.actions > MAX_ACTIONS_PER_STEP) {
this.halt("more than " + MAX_ACTIONS_PER_STEP + " actions");
return;
}
this.exec(owner, a);
}
};
// The node `a`'s target names, seen from timeline node `from`: [index] or [-1, why].
Run.prototype.resolve = function (from, a) {
if (a.e !== undefined) return [-1, a.e];
let cur = from;
for (const seg of a.t || []) {
if (seg === "^") cur = 0;
else if (seg === "..") {
const n = this.nodes[cur];
if (!n || n.kind === ROOT) return [-1, "the main timeline has no parent"];
cur = n.owner;
} else {
const c = cur;
const j = this.nodes.findIndex((n, k) => k !== c && n.owner === c && n.name === seg);
if (j < 0) return [-1, "no instance named “" + seg + "” here"];
cur = j;
}
}
return [cur];
};
Run.prototype.exec = function (owner, a) {
this.refresh();
const from = this.indexOf(owner);
if (from < 0) return;
const st = this.st;
switch (a.op) {
case "trace":
this.out(a.msg || "");
return;
case "next_scene":
case "prev_scene": {
const s = a.op === "next_scene" ? st.scene + 1 : st.scene - 1;
if (s >= 0 && s < this.M.scenes.length) this.gotoRoot(s, 0);
return;
}
case "set_property": {
const [i, err] = this.resolve(from, a);
if (i < 0) return this.out(a.d + ": " + err);
if (i === 0) return this.out(a.d + ": the main timeline has no " + a.pl + " to set");
const n = this.nodes[i];
let ov = st.props.get(n.key);
if (!ov) {
ov = { path: n.path };
st.props.set(n.key, ov);
}
setProp(ov, a.p, a.v);
this.dirty = true;
return;
}
}
const [i, err] = this.resolve(from, a);
if (i < 0) return this.out(a.d + ": " + err);
const node = this.nodes[i];
if (!node) return;
if (node.kind !== ROOT && node.kind !== CLIP) {
const what = node.kind === BUTTON ? "a button" : "a graphic";
return this.out(a.d + ": “" + node.name + "” is " + what + "; only movie clips and the main timeline have a playhead");
}
const path = node.path, frame = node.frame, frames = Math.max(node.frames, 1);
switch (a.op) {
case "stop":
case "play":
this.setPlaying(path, a.op === "play");
return;
case "next_frame":
case "prev_frame": {
const f = a.op === "next_frame" ? Math.min(frame + 1, frames - 1) : Math.max(frame - 1, 0);
this.setPlaying(path, false);
this.gotoFrame(path, null, f);
return;
}
case "goto_and_play":
case "goto_and_stop": {
const [s, f, why] = this.gotoTarget(path, a);
if (why !== undefined) return this.out(a.d + ": " + why);
this.setPlaying(path, a.op === "goto_and_play");
this.gotoFrame(path, s, f);
return;
}
}
};
// Where a go-to lands: [scene or null, frame] or [_, _, why].
Run.prototype.gotoTarget = function (path, a) {
const M = this.M;
let scene = null, tl;
if (path.length === 0) {
if (a.s !== undefined) {
let s = M.scenes.findIndex((x) => x.name === a.s);
if (s < 0) s = M.scenes.findIndex((x) => asciiLower(x.name) === asciiLower(a.s));
if (s < 0) return [null, 0, "no scene named “" + a.s + "”"];
scene = s;
} else scene = this.st.scene;
tl = this.sceneTimeline(scene);
} else {
if (a.s !== undefined) return [null, 0, "only the main timeline has scenes"];
const i = this.indexOf(path);
if (i < 0) return [null, 0, "the timeline is gone"];
tl = this.timelineOf(i);
if (!tl) return [null, 0, "not a timeline"];
}
if (typeof a.f === "number") return [scene, Math.min(a.f, Math.max(tl.n - 1, 0))];
const label = String(a.f);
if (tl.labels.has(label)) return [scene, tl.labels.get(label)];
// The main timeline: a label in another scene, when no scene was named.
if (path.length === 0 && a.s === undefined) {
for (let s = 0; s < M.scenes.length; s++) {
const other = M.timelines[M.scenes[s].tl];
if (other.labels.has(label)) return [s, other.labels.get(label)];
}
}
return [null, 0, "no frame labelled “" + label + "”"];
};
Run.prototype.setPlaying = function (path, on) {
if (path.length === 0) this.st.root.playing = on;
else {
const c = this.st.clips.get(keyOf(path));
if (c) c.playing = on;
}
};
Run.prototype.gotoRoot = function (scene, frame) {
const st = this.st;
if (scene !== st.scene || frame !== st.root.frame) {
st.scene = scene;
st.root.frame = frame;
this.queue([]);
this.dirty = true;
}
};
Run.prototype.gotoFrame = function (path, scene, frame) {
if (path.length === 0) return this.gotoRoot(scene === null ? this.st.scene : scene, frame);
const c = this.st.clips.get(keyOf(path));
if (c && c.frame !== frame) {
c.frame = frame;
this.queue(path);
this.dirty = true;
}
};
Run.prototype.event = function (e) {
this.refresh();
const st = this.st;
switch (e.type) {
case "move":
this.pointer(e);
break;
case "down":
this.pointer(e);
st.down = true;
st.pressed = st.hover;
this.dirty = true;
if (st.hover !== null) this.fire(st.hover, "press");
break;
case "up": {
this.pointer(e);
st.down = false;
const pressed = st.pressed;
st.pressed = null;
this.dirty = true;
if (st.hover !== null) {
const h = st.hover;
this.fire(h, "release");
if (samePath(pressed, h)) this.fire(h, "click");
}
break;
}
case "leave":
this.pointer(null);
break;
}
};
// Moves the pointer: what it leaves gets Out, what it reaches gets Over.
Run.prototype.pointer = function (p) {
this.refresh();
const st = this.st;
st.pointer = p ? { x: p.x, y: p.y } : null;
const now = p ? hitIn(this.M, st, this.nodes, this.host, p.x, p.y) : null;
const same = now === null ? st.hover === null : samePath(now, st.hover);
if (!same) {
const old = st.hover;
st.hover = now;
this.dirty = true;
if (old !== null) this.fire(old, "out");
if (now !== null) this.fire(now, "over");
}
};
// Runs an instance's handler for `event`, in the timeline the instance is on.
Run.prototype.fire = function (path, event) {
this.refresh();
const i = this.indexOf(path);
if (i < 0) return;
const n = this.nodes[i];
const h = (n.events || []).find((x) => x[0] === event);
if (!h) return;
const owner = this.nodes[n.owner];
if (!owner) return;
this.runList(owner.path, h[1]);
this.settle();
};
Run.prototype.finish = function () {
this.refresh();
if (this.dropped > 0) this.output.push("… " + this.dropped + " more lines");
return { output: this.output, sounds: this.sounds };
};
function asciiLower(s) {
return s.replace(/[A-Z]/g, (c) => c.toLowerCase());
}
return { Player: Player, evaluate: evaluate, applyEffect: applyEffect, mul: mul, meanScale: meanScale, finite: finite };
})();
+542
View File
@@ -0,0 +1,542 @@
use super::*;
use anicraft_doc::actions::{ButtonEvent, EventHandler, PluginScript, Property, Target};
use anicraft_doc::player::{Event, NoScripts, PlayerState, start, step};
use anicraft_doc::{ElementId, GradientStop, Keyframe, LayerId, LoopMode, Scene, Shape, Symbol, Tween, evaluate_player, sample};
use anicraft_geom::Vec2;
use boa_engine::{Context, Source};
// ----- fixtures ---------------------------------------------------------------------------------
fn rect(id: u64, x: f32, y: f32, w: f32, h: f32, c: u32) -> Arc<Element> {
Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(x, y, w, h), Paint::Solid(Rgba::hex(c)))) })
}
fn inst(id: u64, symbol: u64, name: &str, m: Affine, events: Vec<EventHandler>) -> Arc<Element> {
Arc::new(Element { id: ElementId(id), name: name.into(), transform: m, color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: SymbolId(symbol), loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events } })
}
fn kf(start: u32, duration: u32, elements: Vec<Arc<Element>>, actions: Vec<Action>, label: &str) -> Arc<Keyframe> {
let mut k = Keyframe::new(start, duration);
k.elements = elements;
k.label = label.into();
k.script = (!actions.is_empty()).then_some(FrameScript::Actions(actions));
Arc::new(k)
}
fn tweened(k: Arc<Keyframe>) -> Arc<Keyframe> {
let mut k = (*k).clone();
k.tween = Some(Tween::default());
Arc::new(k)
}
fn layer(id: u64, keys: Vec<Arc<Keyframe>>) -> Arc<Layer> {
let mut l = Layer::new(LayerId(id), format!("L{id}"));
l.keyframes = keys;
Arc::new(l)
}
fn symbol(id: u64, kind: SymbolKind, layers: Vec<Arc<Layer>>) -> Arc<Symbol> {
Arc::new(Symbol { id: SymbolId(id), name: format!("S{id}"), kind, timeline: Timeline { layers } })
}
fn this() -> Target {
Target::this()
}
fn on(event: ButtonEvent, actions: Vec<Action>) -> EventHandler {
EventHandler { event, actions }
}
/// A self-authored interactive movie that exercises the player: a door movie clip with labels
/// and stops, a tweened slide inside it, a button with all four states that opens the door and
/// fades it on hover, a nested clip addressed by a dotted path, a looping graphic under a mask,
/// a faded group, a gradient, a target that doesn't exist, and a second scene that goes back.
fn fixture() -> Document {
let mut d = Document { stage: anicraft_doc::Stage { width: 640, height: 360, fps: 24.0, background: Rgba::hex(0x223344) }, ..Document::default() };
// The door: closed (stop), opening (a slide), open (stop, trace).
let slide_a = rect(1001, 0.0, 0.0, 80.0, 120.0, 0x8b5a2b);
let mut slide_b = (*slide_a).clone();
slide_b.transform = Affine::translate(60.0, 0.0);
let door = symbol(100, SymbolKind::MovieClip, vec![
layer(101, vec![kf(0, 1, vec![], vec![Action::Stop { target: this() }], "closed"), kf(1, 4, vec![], vec![], "opening"), kf(5, 1, vec![], vec![Action::Stop { target: this() }, Action::Trace { message: "door open".into() }], "open")]),
layer(102, vec![kf(0, 1, vec![slide_a.clone()], vec![], ""), tweened(kf(1, 4, vec![slide_a], vec![], "")), kf(5, 1, vec![Arc::new(slide_b)], vec![], "")]),
]);
// The knob: Up, Over, Down, Hit.
let knob = symbol(200, SymbolKind::Button, vec![layer(201, vec![kf(0, 1, vec![rect(2001, -20.0, -20.0, 40.0, 40.0, 0x3d8bfd)], vec![], ""), kf(1, 1, vec![rect(2002, -20.0, -20.0, 40.0, 40.0, 0x6aa8ff)], vec![], ""), kf(2, 1, vec![rect(2003, -20.0, -20.0, 40.0, 40.0, 0x2a64c0)], vec![], ""), kf(3, 1, vec![rect(2004, -25.0, -25.0, 50.0, 50.0, 0)], vec![], "")])]);
// A looping three-frame graphic.
let mut red = (*rect(3001, 0.0, 0.0, 30.0, 30.0, 0xff0000)).clone();
red.color = ColorEffect { alpha: 0.8, tint: Rgba::hex(0xffffff), tint_amount: 0.2 };
let blink = symbol(300, SymbolKind::Graphic, vec![layer(301, vec![kf(0, 1, vec![Arc::new(red)], vec![], ""), kf(1, 1, vec![rect(3002, 0.0, 0.0, 30.0, 30.0, 0x00ff00)], vec![], ""), kf(2, 1, vec![rect(3003, 0.0, 0.0, 30.0, 30.0, 0x0000ff)], vec![], "")])]);
// A panel clip holding its own door (panel.door), that plays on and talks to its parent.
let panel = symbol(400, SymbolKind::MovieClip, vec![
layer(401, vec![kf(0, 2, vec![], vec![], ""), kf(2, 2, vec![], vec![Action::Trace { message: "panel frame 3".into() }, Action::SetProperty { target: Target::new("parent.door"), property: Property::X, value: 250.0 }], "")]),
layer(402, vec![kf(0, 4, vec![inst(4001, 100, "door", Affine::translate(10.0, 10.0), vec![])], vec![], "")]),
]);
d.library = vec![door, knob, blink, panel];
let open_door = vec![Action::GotoAndPlay { target: Target::new("door"), frame: FrameRef::Label("opening".into()), scene: None }, Action::Play { target: Target::new("panel.door") }];
let knob_events = vec![
on(ButtonEvent::Click, open_door),
on(ButtonEvent::Over, vec![Action::SetProperty { target: Target::new("door"), property: Property::Alpha, value: 0.5 }]),
on(ButtonEvent::Out, vec![Action::SetProperty { target: Target::new("door"), property: Property::Alpha, value: 1.0 }]),
on(ButtonEvent::Press, vec![Action::Trace { message: "pressed".into() }]),
on(ButtonEvent::Release, vec![Action::GotoAndStop { target: Target::new("panel"), frame: FrameRef::Number(99), scene: None }]),
];
let mut faded = (*inst(5003, 300, "", Affine::translate(500.0, 40.0), vec![])).clone();
faded.color = ColorEffect { alpha: 0.5, tint: Rgba::hex(0x00ffff), tint_amount: 0.6 };
let gradient = Arc::new(Element {
id: ElementId(5004),
name: String::new(),
transform: Affine::translate(20.0, 300.0),
color: ColorEffect { alpha: 1.0, tint: Rgba::hex(0xff00ff), tint_amount: 0.25 },
kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 100.0, 40.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(100.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xffffff) }, GradientStop { offset: 1.0, color: Rgba::hex(0x000000) }] }).with_stroke(Rgba::hex(0xffff00), 2.0)),
});
let mut mask = Layer::new(LayerId(6), "mask");
mask.kind = LayerKind::Mask;
mask.keyframes = vec![kf(0, 30, vec![rect(5005, 400.0, 0.0, 20.0, 100.0, 0)], vec![], "")];
let mut masked = Layer::new(LayerId(7), "masked");
masked.parent = Some(LayerId(6));
masked.keyframes = vec![kf(0, 30, vec![inst(5006, 300, "", Affine::translate(395.0, 30.0), vec![])], vec![], "")];
d.timeline_mut(0).layers = vec![
layer(1, vec![
kf(0, 3, vec![], vec![Action::Trace { message: "start".into() }], ""),
kf(3, 7, vec![], vec![Action::Stop { target: Target::new("ghost") }, Action::Stop { target: Target::new("panel") }], "mid"),
kf(10, 20, vec![], vec![], ""),
kf(29, 1, vec![], vec![Action::GotoAndPlay { target: this(), frame: FrameRef::Label("back".into()), scene: None }], ""),
]),
layer(2, vec![kf(0, 30, vec![inst(5001, 200, "knob", Affine::translate(100.0, 100.0), knob_events)], vec![], "")]),
layer(3, vec![kf(0, 30, vec![inst(5002, 100, "door", Affine::translate(300.0, 100.0), vec![]), inst(5007, 400, "panel", Affine::translate(300.0, 240.0), vec![]), Arc::new(faded), gradient], vec![], "")]),
Arc::new(mask),
Arc::new(masked),
];
// Scene 2 has the "back" label and returns to the first scene's "mid".
let mut two = Scene::new("Two");
two.timeline.layers = vec![layer(8, vec![kf(0, 2, vec![rect(6001, 0.0, 0.0, 640.0, 360.0, 0x112233)], vec![], "back"), kf(2, 1, vec![], vec![Action::GotoAndStop { target: this(), frame: FrameRef::Label("mid".into()), scene: Some("scene 1".into()) }], "")])];
d.scenes.push(Arc::new(two));
d.next_id = 10_000;
d.sanitize();
d
}
// ----- the JavaScript player in Boa --------------------------------------------------------------
/// Hit tests for the JS player, over the exported paths flattened in Rust (what `Path::contains`
/// and `distance_to_edge` test), in place of the browser's canvas.
const HOST_JS: &str = r#"
function xf(m, q) { return [m[0] * q[0] + m[2] * q[1] + m[4], m[1] * q[0] + m[3] * q[1] + m[5]]; }
var host = {
inFill: function (p, m, x, y, eo) {
var wind = 0, cross = 0;
for (var line of (POLYS[p] || [])) {
var pts = line.p.map(function (q) { return xf(m, q); });
for (var i = 0; i < pts.length; i++) {
var a = pts[i], b = pts[(i + 1) % pts.length];
if ((a[1] <= y) !== (b[1] <= y)) {
var t = (y - a[1]) / (b[1] - a[1]);
if (a[0] + t * (b[0] - a[0]) > x) { cross++; wind += b[1] > a[1] ? 1 : -1; }
}
}
}
return eo ? cross % 2 === 1 : wind !== 0;
},
nearStroke: function (p, m, x, y, reach) {
for (var line of (POLYS[p] || [])) {
var pts = line.p.map(function (q) { return xf(m, q); });
var n = line.c ? pts.length : pts.length - 1;
for (var i = 0; i < n; i++) {
var a = pts[i], b = pts[(i + 1) % pts.length];
var dx = b[0] - a[0], dy = b[1] - a[1], l = dx * dx + dy * dy;
var t = l > 0 ? Math.max(0, Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy) / l)) : 0;
var ex = a[0] + t * dx - x, ey = a[1] + t * dy - y;
if (Math.sqrt(ex * ex + ey * ey) <= reach) return true;
}
}
return false;
}
};
"#;
struct Js {
ctx: Context,
}
impl Js {
fn new(m: &Movie) -> Js {
let mut ctx = Context::default();
ctx.eval(Source::from_bytes(PLAYER_JS)).unwrap_or_else(|e| panic!("player.js: {e}"));
ctx.eval(Source::from_bytes(HOST_JS)).unwrap();
let polys: Vec<Value> = m.paths.iter().map(|p| Value::Array(p.flatten(&Affine::IDENTITY, 0.05).into_iter().map(|l| json!({"c": l.closed, "p": l.points.iter().map(|q| json!([q.x, q.y])).collect::<Vec<_>>()})).collect())).collect();
let setup = format!("var POLYS = {}; var P = new AniCraft.Player({}, host);", Value::Array(polys), m.json);
ctx.eval(Source::from_bytes(&setup)).unwrap_or_else(|e| panic!("setup: {e}"));
Js { ctx }
}
fn eval(&mut self, code: &str) -> Value {
let v = self.ctx.eval(Source::from_bytes(&format!("JSON.stringify({code})"))).unwrap_or_else(|e| panic!("{code}: {e}"));
let s = v.to_string(&mut self.ctx).unwrap().to_std_string_escaped();
serde_json::from_str(&s).unwrap_or_else(|e| panic!("{code}: {e}: {s}"))
}
}
fn js_events(events: &[Event]) -> String {
let list: Vec<Value> = events
.iter()
.map(|e| match e {
Event::Move(p) => json!({"type": "move", "x": p.x, "y": p.y}),
Event::Down(p) => json!({"type": "down", "x": p.x, "y": p.y}),
Event::Up(p) => json!({"type": "up", "x": p.x, "y": p.y}),
Event::Leave => json!({"type": "leave"}),
})
.collect();
Value::Array(list).to_string()
}
fn ids(p: &[ElementId]) -> Value {
Value::Array(p.iter().map(|e| json!(e.0)).collect())
}
/// The Rust state in the shape of the JS player's `snapshot()` (props compared apart).
fn snapshot(st: &PlayerState) -> Value {
json!({
"scene": st.scene, "frame": st.root.frame, "playing": st.root.playing,
"clips": st.clips.iter().map(|(p, c)| json!([ids(p), c.frame, c.playing])).collect::<Vec<_>>(),
"hover": st.hover.as_deref().map(ids), "pressed": st.pressed.as_deref().map(ids), "down": st.down,
})
}
fn props_of_rust(st: &PlayerState) -> Vec<String> {
let mut out = Vec::new();
for (p, o) in &st.props {
let f = |k: &str, v: Option<f32>| v.map(|v| format!("{}:{k}={:.3}", ids(p), v));
out.extend([f("x", o.x), f("y", o.y), f("alpha", o.alpha), f("rotation", o.rotation), f("scale_x", o.scale_x), f("scale_y", o.scale_y)].into_iter().flatten());
if let Some(v) = o.visible {
out.push(format!("{}:visible={v}", ids(p)));
}
}
out.sort();
out
}
fn props_of_js(snap: &Value) -> Vec<String> {
let mut out = Vec::new();
for e in snap["props"].as_array().unwrap() {
let path = &e[0];
for (k, v) in e[1].as_object().unwrap() {
out.push(match v {
Value::Bool(b) => format!("{path}:{k}={b}"),
v => format!("{path}:{k}={:.3}", v.as_f64().unwrap()),
});
}
}
out.sort();
out
}
fn close(a: f64, b: f32, tol: f64) -> bool {
(a - f64::from(b)).abs() <= tol
}
/// The JS player's display list against `evaluate_player` at the same state: the same items in
/// the same order, with the same paths, placement, paints, colour effects, clips and groups.
fn same_display_list(js: &mut Js, m: &Movie, doc: &Document, st: &PlayerState, when: &str) {
let dl = evaluate_player(doc, st);
let ours = js.eval("P.evaluate()");
let items: Vec<&anicraft_doc::DisplayItem> = dl.items.iter().filter(|i| !i.guide).collect();
let theirs = ours["items"].as_array().unwrap();
assert_eq!(theirs.len(), items.len(), "{when}: item count");
for (k, (a, b)) in theirs.iter().zip(&items).enumerate() {
let p = a["p"].as_u64().unwrap() as usize;
assert_eq!(*m.paths[p], *b.path, "{when}: item {k} path");
let mj: Vec<f64> = a["m"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
for (i, (x, y)) in mj.iter().zip(b.transform.m).enumerate() {
assert!(close(*x, y, if i < 4 { 1e-3 } else { 1e-2 }), "{when}: item {k} transform {mj:?} vs {:?}", b.transform.m);
}
let fill = a["f"].as_i64().unwrap();
assert_eq!(fill >= 0, b.fill.is_some(), "{when}: item {k} fill");
if let (Some(Paint::Solid(c)), true) = (&b.fill, fill >= 0) {
let s = &m.json["paints"][fill as usize]["s"];
for (x, y) in s.as_array().unwrap().iter().zip([c.r, c.g, c.b, c.a]) {
assert!(close(x.as_f64().unwrap(), y, 1e-3), "{when}: item {k} colour");
}
}
assert_eq!(a["s"].is_array(), b.stroke.is_some(), "{when}: item {k} stroke");
let c = &a["c"];
for (i, y) in [b.color.alpha, b.color.tint.r, b.color.tint.g, b.color.tint.b, b.color.tint_amount].into_iter().enumerate() {
assert!(close(c[i].as_f64().unwrap(), y, 1e-3), "{when}: item {k} colour effect {c} vs {:?}", b.color);
}
let idx = |v: &Value| v.as_u64().map(|x| x as u32);
assert_eq!((idx(&a["clip"]), idx(&a["masks"]), idx(&a["group"])), (b.clip, b.masks, b.group), "{when}: item {k} clip, mask and group");
}
let clips: Vec<Option<u32>> = ours["clips"].as_array().unwrap().iter().map(|v| v.as_u64().map(|x| x as u32)).collect();
assert_eq!(clips, dl.clip_parents, "{when}: clips");
let groups = ours["groups"].as_array().unwrap();
assert_eq!(groups.len(), dl.groups.len(), "{when}: groups");
for (a, b) in groups.iter().zip(&dl.groups) {
assert!(close(a["alpha"].as_f64().unwrap(), b.alpha, 1e-3), "{when}: group alpha");
assert_eq!(a["blend"], b.blend.key(), "{when}: group blend");
assert_eq!((a["parent"].as_u64().map(|x| x as u32), a["clip"].as_u64().map(|x| x as u32)), (b.parent, b.clip), "{when}: group nesting");
}
}
/// Runs `doc` in both players through `script` (per step: events after the frame, and pointer
/// events routed between frames), comparing state, output and display list at every step.
fn compare(doc: &Document, script: &[(Vec<Event>, Vec<Event>)]) -> Vec<String> {
let m = movie(doc, &HtmlOptions::default());
let mut js = Js::new(&m);
let r = start(doc, &mut NoScripts);
let out = js.eval("P.start().output");
assert_eq!(out, json!(r.output), "start: output");
let mut lines = r.output.clone();
let mut st = r.state;
for (i, (between, after)) in script.iter().enumerate() {
let when = format!("step {}", i + 1);
if !between.is_empty() {
let r = anicraft_doc::player::input(doc, &st, between, &mut NoScripts);
assert_eq!(js.eval(&format!("P.input({}).output", js_events(between))), json!(r.output), "{when}: input output");
lines.extend(r.output.iter().cloned());
st = r.state;
}
let r = step(doc, &st, after, &mut NoScripts);
assert_eq!(js.eval(&format!("P.step({}).output", js_events(after))), json!(r.output), "{when}: output");
lines.extend(r.output.iter().cloned());
st = r.state;
let snap = js.eval("P.snapshot()");
let mut lean = snap.clone();
lean.as_object_mut().unwrap().remove("props");
assert_eq!(lean, snapshot(&st), "{when}: state");
assert_eq!(props_of_js(&snap), props_of_rust(&st), "{when}: properties");
same_display_list(&mut js, &m, doc, &st, &when);
}
lines
}
fn at(x: f32, y: f32) -> Vec2 {
Vec2::new(x, y)
}
// ----- the tests --------------------------------------------------------------------------------
#[test]
fn the_js_player_plays_the_fixture_frame_for_frame_like_the_rust_player() {
let doc = fixture();
let none = || (vec![], vec![]);
let mut script: Vec<(Vec<Event>, Vec<Event>)> = (0..2).map(|_| none()).collect();
// Hover the knob between frames (Over: the door fades), press and release on it (a click
// opens both doors), wander off (Out), then click again while it is open.
script.push((vec![Event::Move(at(100.0, 100.0))], vec![]));
script.push((vec![Event::Down(at(101.0, 99.0))], vec![]));
script.push((vec![], vec![Event::Up(at(102.0, 101.0))]));
script.extend((0..6).map(|_| none()));
script.push((vec![Event::Move(at(10.0, 10.0))], vec![]));
script.push((vec![], vec![Event::Down(at(122.0, 122.0)), Event::Up(at(122.0, 122.0))]));
script.push((vec![Event::Move(at(124.0, 76.0)), Event::Leave], vec![]));
// On through the end of scene 1, scene 2 and back.
script.extend((0..30).map(|_| none()));
let lines = compare(&doc, &script);
for want in ["start", "pressed", "door open", "panel frame 3", "Stop (ghost): no instance named “ghost” here"] {
assert!(lines.iter().any(|l| l == want), "the fixture never wrote {want:?}: {lines:?}");
}
}
#[test]
fn the_js_player_plays_the_interactive_sample_like_the_rust_player() {
let doc = sample::interactive();
let mut script: Vec<(Vec<Event>, Vec<Event>)> = vec![(vec![], vec![]); 3];
script.push((vec![Event::Move(at(640.0, 400.0))], vec![]));
script.push((vec![Event::Down(at(640.0, 400.0))], vec![Event::Up(at(640.0, 400.0))]));
script.extend(vec![(vec![], vec![]); 40]);
assert!(compare(&doc, &script).iter().any(|l| l == "The show starts"), "the Play button starts the show");
}
#[test]
fn the_js_player_matches_on_the_demo_and_on_go_to_loops() {
// No actions: the movie loops; every movie clip and graphic follows.
let demo = sample::demo();
compare(&demo, &vec![(vec![], vec![]); 60]);
// A frame that goes to itself and back runs into the budget, in both players alike.
let mut d = Document::default();
d.timeline_mut(0).layers = vec![layer(1, vec![
kf(0, 1, vec![], vec![Action::GotoAndPlay { target: this(), frame: FrameRef::Number(1), scene: None }], ""),
kf(1, 1, vec![], vec![Action::GotoAndPlay { target: this(), frame: FrameRef::Number(0), scene: None }, Action::SetProperty { target: this(), property: Property::X, value: 1.0 }, Action::NextFrame { target: Target::new("_root.nobody") }], ""),
])];
d.sanitize();
compare(&d, &vec![(vec![], vec![]); 3]);
}
#[test]
fn the_camera_and_layer_depth_come_across_and_buttons_answer_through_them() {
// The fixture through a camera that pans, zooms, turns and tints over frames 1-20, with a
// layer behind the stage (parallax): the knob is clicked where the camera shows it.
let mut doc = fixture();
let stage = doc.stage;
let mut far = anicraft_doc::Camera::rest(&stage);
far.center = Vec2::new(260.0, 150.0);
far.zoom = 1.5;
far.rotation = 0.2;
far.tint = Rgba::hex(0x3366ff);
far.tint_amount = 0.3;
let rest = anicraft_doc::Camera::rest(&stage).to_element(ElementId(7001));
let near = far.to_element(ElementId(7001));
let mut cam = Layer::new(LayerId(70), "Camera");
cam.kind = LayerKind::Camera;
cam.keyframes = vec![tweened(kf(0, 20, vec![Arc::new(rest)], vec![], "")), kf(20, 10, vec![Arc::new(near)], vec![], "")];
let tl = doc.timeline_mut(0);
tl.layers.insert(0, Arc::new(cam));
Arc::make_mut(&mut tl.layers[3]).depth = 200.0;
doc.sanitize();
let m = movie(&doc, &HtmlOptions::default());
let first = &m.json["timelines"][0];
assert!(m.json["contents"].as_array().unwrap().iter().any(|c| c["cc"].is_array()), "the camera's tint is baked");
assert!(first["f"].as_array().unwrap().len() > 15, "the camera moves every frame");
// Where the knob is on screen once the camera has arrived.
let knob = far.view(&stage, 0.0).apply(Vec2::new(100.0, 100.0));
let mut script: Vec<(Vec<Event>, Vec<Event>)> = vec![(vec![], vec![]); 22];
script.push((vec![Event::Move(knob), Event::Down(knob)], vec![Event::Up(knob)]));
script.extend(vec![(vec![], vec![]); 6]);
let lines = compare(&doc, &script);
assert!(lines.iter().any(|l| l == "door open"), "the click reached the knob through the camera: {lines:?}");
}
#[test]
fn the_page_holds_the_movie_and_the_player_and_nothing_can_close_its_scripts() {
let doc = fixture();
let e = to_html(&doc, &HtmlOptions { title: "Doors </script> & \"knobs\"".into(), ..Default::default() }).unwrap();
assert!(e.html.starts_with("<!DOCTYPE html>"));
assert!(e.html.contains("<title>Doors &lt;/script&gt; &amp; &quot;knobs&quot;</title>"));
for js in [PLAYER_JS, CANVAS_JS] {
assert!(!js.to_ascii_lowercase().contains("</script") && !js.contains("<!--"), "a script source would end its element");
}
// Exactly the three scripts' closing tags, and the data reads back as the movie.
assert_eq!(e.html.matches("</script>").count(), 2);
let start = e.html.find("id=\"anicraft-movie\">").unwrap() + "id=\"anicraft-movie\">".len();
let end = start + e.html[start..].find("</script>").unwrap();
let back: Value = serde_json::from_str(&e.html[start..end]).unwrap();
assert_eq!(back, movie(&doc, &HtmlOptions::default()).json);
assert_eq!(back["v"], FORMAT_VERSION);
assert_eq!(back["scenes"].as_array().unwrap().len(), 2);
assert_eq!((back["stage"]["w"].as_u64(), back["stage"]["fps"].as_f64()), (Some(640), Some(24.0)));
assert_eq!(e.stats.data_bytes, end - start);
assert!(e.report.is_empty(), "nothing lost: {:?}", e.report);
// The page code needs a browser to run, but it must compile.
let mut ctx = Context::default();
ctx.eval(Source::from_bytes(&format!("new Function({})", json!(CANVAS_JS)))).unwrap_or_else(|e| panic!("canvas.js: {e}"));
}
#[test]
fn frames_are_baked_and_stored_once() {
let doc = sample::demo();
let m = movie(&doc, &HtmlOptions::default());
let frames = doc.frame_count() as usize;
assert_eq!(m.json["timelines"][0]["n"].as_u64(), Some(frames as u64));
assert!(m.stats.frames >= frames && m.stats.contents <= m.stats.frames, "{:?}", m.stats);
// A keyframe held over many frames is one stored frame.
let mut still = Document::default();
{
let l = Arc::make_mut(&mut still.timeline_mut(0).layers[0]);
l.keyframes = vec![kf(0, 50, vec![rect(9, 0.0, 0.0, 10.0, 10.0, 0xff0000)], vec![], "")];
}
let s = movie(&still, &HtmlOptions::default());
assert_eq!((s.stats.frames, s.stats.contents, s.json["timelines"][0]["f"].clone()), (50, 1, json!([[0, 50]])));
// Runs add up to each timeline's length.
for tl in m.json["timelines"].as_array().unwrap() {
let total: u64 = tl["f"].as_array().unwrap().iter().map(|r| r[1].as_u64().unwrap()).sum();
assert_eq!(Some(total), tl["n"].as_u64());
}
// A still shape over many frames is one path; a tween moves its transform, not its path.
assert!(m.stats.paths < 40, "{:?}", m.stats);
// Unused library symbols stay out.
let mut d = doc.clone();
d.library.push(Arc::new(Symbol { id: SymbolId(999_999), name: "unused".into(), kind: SymbolKind::Graphic, timeline: Timeline::default() }));
assert_eq!(movie(&d, &HtmlOptions::default()).json["symbols"], m.json["symbols"]);
}
#[test]
fn variable_width_strokes_become_filled_outlines() {
use anicraft_doc::{ProfilePreset, Stroke};
let mut doc = Document::default();
let shape = Shape { path: Arc::new(Path::line(Vec2::new(10.0, 10.0), Vec2::new(200.0, 10.0))), fill: None, stroke: Some(Stroke::new(Rgba::hex(0x00ff00), 10.0).with_profile(ProfilePreset::TaperEnd.profile())), fill_rule: FillRule::NonZero };
let el = Element { id: ElementId(77), name: String::new(), transform: Affine::translate(5.0, 0.0), color: Default::default(), kind: ElementKind::Shape(shape) };
Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements.push(Arc::new(el));
let m = movie(&doc, &HtmlOptions::default());
let items = &m.json["contents"][0]["l"][0]["e"];
assert_eq!(items.as_array().unwrap().len(), 1);
assert!(items[0]["f"].is_u64() && items[0]["s"].is_null(), "{items}");
assert!(items[0]["m"].is_null(), "the outline is already in place");
}
#[test]
fn what_does_not_carry_across_is_reported() {
let mut doc = fixture();
let tl = doc.timeline_mut(0);
let l = Arc::make_mut(&mut tl.layers[2]);
let k = l.keyframe_mut(0).unwrap();
if let ElementKind::Symbol { filters, blend, .. } = &mut Arc::make_mut(&mut k.elements[0]).kind {
filters.push(anicraft_doc::Filter::Blur { blur_x: 4.0, blur_y: 4.0, quality: 1 });
*blend = BlendMode::Subtract;
}
Arc::make_mut(&mut tl.layers[0]).keyframe_mut(1).unwrap().script = Some(FrameScript::Plugin(PluginScript { id: "org.example.menu".into(), entry: "main".into() }));
let m = movie(&doc, &HtmlOptions::default());
assert_eq!(m.report.get(FILTERS), Some(&1));
assert_eq!(m.report.get(BLENDS), Some(&1));
assert_eq!(m.report.get(PLUGIN_SCRIPTS), Some(&1));
// The player says so when the frame script's keyframe is entered.
let mut js = Js::new(&m);
js.eval("P.start()");
let lines: Vec<Value> = (0..3).map(|_| js.eval("P.step([]).output")).collect();
assert!(lines[2].to_string().contains("Frame script org.example.menu · main not run"), "{lines:?}");
}
#[test]
fn bitmaps_and_sounds_are_embedded_once() {
let mut doc = Document::default();
let png = {
let mut out = Vec::new();
let mut enc = png::Encoder::new(&mut out, 1, 1);
enc.set_color(png::ColorType::Rgba);
enc.set_depth(png::BitDepth::Eight);
enc.write_header().unwrap().write_image_data(&[255, 0, 0, 255]).unwrap();
out
};
let bitmap = anicraft_doc::Bitmap::from_png(anicraft_doc::BitmapId(50), "dot", png).unwrap();
doc.bitmaps.push(Arc::new(bitmap));
let wav = anicraft_doc::audio::wav::encode(8000, 1, &[0.0; 80], anicraft_doc::audio::wav::Bits::Int16);
doc.sounds.push(Arc::new(anicraft_doc::Sound::from_data(anicraft_doc::SoundId(60), "beep", wav).unwrap()));
let fill = Paint::Bitmap { bitmap: anicraft_doc::BitmapId(50), repeat: true, matrix: Affine::scale(2.0, 2.0) };
let a = Element { id: ElementId(70), name: String::new(), transform: Affine::IDENTITY, color: Default::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 10.0, 10.0), fill.clone())) };
let b = Element { id: ElementId(71), kind: ElementKind::Shape(Shape::filled(Path::rect(20.0, 0.0, 10.0, 10.0), fill)), ..a.clone() };
{
let k = Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap();
k.elements = vec![Arc::new(a), Arc::new(b)];
k.sound = Some(anicraft_doc::FrameSound::new(anicraft_doc::SoundId(60)));
}
let m = movie(&doc, &HtmlOptions::default());
assert_eq!(m.stats.images, 1);
assert!(m.json["images"][0].as_str().unwrap().starts_with("data:image/png;base64,iVBOR"));
assert_eq!(m.json["paints"][0], json!({"b": 0, "rep": true, "m": [2, 0, 0, 2, 0, 0]}));
assert_eq!(m.json["sounds"][0]["mime"], "audio/wav");
assert_eq!(m.json["timelines"][0]["snd"]["0"], json!([[0, "event", 1, false, 1]]));
// The player hands the frame's sounds to the page.
let mut js = Js::new(&m);
assert_eq!(js.eval("P.start().sounds"), json!([[0, "event", 1, false, 1]]));
let silent = movie(&doc, &HtmlOptions { sound: false, ..Default::default() });
assert_eq!((silent.stats.sounds, silent.json["timelines"][0].get("snd")), (0, None));
}
#[test]
fn hostile_documents_export_without_panicking() {
let mut doc = Document::default();
let bad = Element { id: ElementId(5), name: "x".into(), transform: Affine { m: [f32::NAN, 0.0, 0.0, 1.0, f32::INFINITY, 0.0] }, color: ColorEffect { alpha: f32::NAN, tint: Rgba::new(f32::NAN, 2.0, -1.0, 1.0), tint_amount: f32::INFINITY }, kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, f32::NAN, 1.0), Paint::Radial { center: Vec2::ZERO, radius: -5.0, stops: vec![GradientStop { offset: f32::NAN, color: Rgba::BLACK }] })) };
let fine = Element { id: ElementId(6), transform: Affine::IDENTITY, ..bad.clone() };
let missing = inst(7, 12345, "ghost", Affine::IDENTITY, vec![]);
Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements = vec![Arc::new(bad), Arc::new(fine), missing];
let e = to_html(&doc, &HtmlOptions::default()).unwrap();
assert!(!e.html.contains("NaN") && !e.html.contains("inf"), "numbers stay finite");
let m = movie(&doc, &HtmlOptions::default());
assert_eq!(m.json["paths"][0], "", "a path with a NaN point is left empty");
let mut js = Js::new(&m);
js.eval("P.start()");
js.eval("P.step([{type: 'move', x: 1, y: 1}])");
// An empty document is a one-frame movie.
let m = movie(&Document::default(), &HtmlOptions::default());
assert_eq!(m.json["timelines"][0]["n"], 1);
}
+1
View File
@@ -8,6 +8,7 @@ pub mod paint;
pub mod raster;
pub mod stroke;
mod filters;
pub mod html;
pub mod lottie;
pub mod svg;
+179
View File
@@ -0,0 +1,179 @@
# ADR 0028: HTML canvas export
* Status: accepted (2026-11-09), first slice
* Relates to: ADR 0024 (frame actions, the action IR and the pure player), ADR 0027 (camera
layer and layer depth), ADR 0013
(ActionScript), ADR 0010 (mask layers), ADR 0016 (motion tweens), ADR 0018 (variable-width
strokes), ADR 0020 (audio), ADR 0002 (the CPU renderer is the oracle), roadmap M6
## Context
Animate's most used publish target today is HTML5 Canvas: a web page that plays the movie,
buttons and timeline scripts included. Our users expect File › Export to give them that, as a
file they can open in a browser, put on a server or send to someone. ADR 0024 gave us the
interactivity model: a typed action IR and a pure, budgeted player in `anicraft-doc`. This
ADR decides what the page contains, how the movie's data is represented, how the browser runs
the player's semantics, and how we keep the browser's behaviour equal to ours.
## Decision
### One self-contained `.html` file
The page holds the movie's data as JSON (in a `<script type="application/json">`), the player
and the page code inline, images as PNG data URIs and sounds as base64. One file, no folder.
* **It opens from a disk.** Browsers refuse `fetch` and `XMLHttpRequest` of local files
(`file://`), so an `.html` + `.json` + assets layout would play only from a web server: the
first thing an artist does with an export, double-clicking it, would show nothing. Inline
data and data URIs have no such limit.
* **It travels as one thing.** Upload it, attach it, drop it in a CMS: nothing to keep together.
* **The cost is small.** Base64 adds a third to images and sounds; vector data dominates most
movies, and a server's gzip takes back most of base64's overhead. A separate-assets layout
can come later as an option for large bitmap-heavy movies (see Not yet).
JSON inside `<script>` can only be ended early by `</script`; every `<` in it is inside a
string, so the exporter writes it as `<`, which JSON reads the same. A test checks that
the script sources themselves contain neither `</script` nor `<!--`.
### Baked frames, interactive tree
Two halves with different needs:
* **What a timeline shows at its frame N** depends only on the document: tweens, easing,
motion tweens' property curves, motion guides, shape morphs with hints. The exporter
**bakes** it: every timeline the movie uses (each scene's and each reachable symbol's) is
evaluated frame by frame with the same `evaluate_guided` the renderer uses, into a list of
layers (bottom first) holding items: shapes (path, paint, stroke, fill rule, transform,
colour effect) and symbol instances (symbol, element id, name, transform, colour effect,
blend, event handlers, and for graphics their own baked frame).
* **Which frame each timeline is on** depends on playback: movie clips have their own
playheads, buttons their pointer state, actions jump around and set properties. That is
the player's job, at run time, in the browser.
Baking rather than interpolating in JavaScript, because:
* **Fidelity.** The browser shows exactly AniCraft's frames. A JS interpolator would have to
reimplement easing presets and custom curves, motion-tween property tracks, guide-path
walking with orientation, and shape morphing with hints (`anicraft-geom::morph` alone is
~900 lines): a second implementation to drift from the first, for every feature added later.
* **Size stays reasonable.** Three tables make it compact: paths are stored once (by pointer,
then by their rounded data), paints once, and identical frames once, as runs per timeline.
A shape held on a keyframe over 50 frames is one path, one paint and one stored frame. A
classic tween of a symbol costs a transform per frame (six numbers). Only shape tweens
store a path per frame, which is what they are. Numbers are rounded to 1/1000 px (1e-5 for
the linear part of transforms), below anything visible.
* **The player stays tiny.** It never interpolates: it walks the instance tree, picks frames
and composes transforms.
**The camera** (ADR 0027) is baked the same way: a scene frame seen through its camera carries
the camera's tint (`cc`), and each of its layers the view for its depth (`v`: the camera's
pan, zoom and turn with the layer's parallax), which the player uses in place of the identity
for that layer, in drawing and in hit tests, as `evaluate_player` and `player::tree` do.
Like Lottie export (frame-accurate, not re-keyed), the movie is exact at the cost of not being
"editable" as keyframes; the HTML is a publish target, not an interchange format.
### The player: a port of the Rust player, checked against it
`crates/render/src/html/player.js` is a line-by-line port of `crates/doc/src/player.rs`
(state, `start`/`step`/`input`, `refresh`, `advance`, `settle`, `enter`, `exec`, `resolve`,
`goto_target`, pointer routing and `hit_in`) and of `eval_timeline` (clip and group numbering,
colour-effect concatenation, script-set property overrides), over the baked data. The same
budgets (actions, entered frames, nodes, output lines, events per step) bound it, and the same
iteration orders (Rust's `BTreeMap` order of instance paths, top layer first for scripts) keep
the order in which actions run identical. Messages are the Rust player's, word for word; the
exporter writes each action's description so they can be.
Targets are resolved to steps at export time (`^` the main timeline, `..` up, a name), so the
JS doesn't parse paths; a malformed target carries its error message instead.
**Test strategy.** A permissive pure-Rust JavaScript engine exists: **Boa** (`boa_engine`,
Unlicense OR MIT, crates.io, default features off). It is a **dev-dependency of
`anicraft-render` only**, never in the app or CLI: 66 crates in `Cargo.lock`, all under
licences `deny.toml` already allows, about 35 s added once to a clean test build. Tests run
`player.js` in Boa and drive both players through the same scripts (frames, pointer moves,
presses and releases, between frames and within steps), comparing at every step:
* the state (scene, frame, playing, every movie clip's playhead, hover and pressed instance,
script-set properties),
* the output lines (traces and error messages),
* and the **display list**: the JS player's evaluation against `evaluate_player` at the same
state, item by item (path, stage transform, paint, colour effect, clip, mask and group) and
the clip and group tables. This is how the export is "verified visually" without a
browser: what the canvas code draws is checked against what the CPU renderer draws.
Fixtures: a self-authored interactive movie (a door movie clip with labels and stops, a
four-state button with click/press/release/over/out handlers, a nested clip addressed as
`panel.door` that talks to `parent`, a looping graphic under a mask, a faded and tinted group,
a gradient with a stroke, a target that doesn't exist, two scenes that jump between each other
by label and scene name), the interactive sample, the demo movie and a go-to loop that runs
into the budget. Mutating the JS player (button states, click detection, frame clamping, tint
order, name lookup) makes these tests fail. Hit tests use a host interface (`inFill`,
`nearStroke`): the browser answers with the canvas's `isPointInPath`/`isPointInStroke`, the
tests with a polygon test over the same flattened paths `Path::contains` uses.
`canvas.js` (drawing, timing, pointer, sound) needs a DOM, so the tests only compile it.
### Drawing on canvas 2D (`canvas.js`)
It follows the CPU renderer, the oracle:
* fills by their rule (`nonzero`/`evenodd`) under the item's transform; gradients are canvas
gradients in the shape's local space (the transform applies to them as in the renderer),
stop colours with the colour effect applied; bitmaps are patterns (repeat or once) with
their matrix;
* strokes in stage space with the stage-space width (`width × mean scale`), round joins and
caps, as the renderer and the SVG export do; variable-width strokes are exported as the
filled outline the renderer fills (in the element's parent space);
* a symbol that fades, blends or has filters draws into its own offscreen layer, which is
composited at its alpha with the blend mode (`multiply`, `screen`, `overlay`, `darken`,
`lighten`, `hard-light`, `lighter` for Add, `difference`, `destination-in` for Alpha,
`destination-out` for Erase), so overlaps don't show through;
* a mask layer's masked layers draw into an offscreen layer; the mask's fills (opaque, strokes
and opacity ignored) draw into another, which cuts the first with `destination-in`. Nesting
follows the timelines. A clip that never meets its mask shows nothing, like an empty mask on
the stage;
* the canvas fills the window keeping the stage's aspect ratio (option `fit`, default on) at
the screen's pixel density; the page background is the stage colour.
Timing: a `requestAnimationFrame` loop steps the player at the document frame rate (fixed
step, at most 250 ms caught up at once). Pointer events go to `input()` at once, between
frames, as in Test Movie. Traces go to the browser console.
### Sound (approximation, optional)
Sounds on keyframes the player enters are handed to the page with each step (the player stays
pure). Event sounds play in full (Repeat ×N, Loop), Start skips a sound already playing, Stop
stops it, Stream plays over its keyframe's span (it does not follow go-tos). Browsers start
audio only after a user gesture, so sound starts with the first click or key. Formats are
those the browser decodes (WAV and MP3 everywhere, Ogg Vorbis not in Safari). `sound: false`
leaves sounds out.
### Command and UI
`file.export_html {path, title?, sound?, fit?, confirm?}` in File › Export › Export HTML
Canvas…; replacing a file asks first (ADR 0004 tier 1, like every export). It reports the
size, the frames stored and what was approximated. Headless: `anicraft-cli exec … file.export_html`.
### Not carried across (reported)
Filters (drawn without them), Subtract and Invert blending (drawn normally), tints on bitmap
fills, and **plug-in frame scripts** (they need the WebAssembly plug-in host; the page logs
that they didn't run, as Test Movie does without plug-ins). Outline-mode layers are drawn in
full: outline mode is an authoring view, as in Animate's publish.
## Not yet
Filters via `ctx.filter`; a folder layout (`.html` + `.js` + assets) for bitmap-heavy movies;
keyboard focus and Enter/Space on buttons; a loading poster; hit tests that respect masks
(the Rust player doesn't either); stream sounds that follow the playhead; frame-script
plug-ins in the browser (wasm in the page through the same ABI); ActionScript (ADR 0013 tiers).
## Consequences
* The browser's behaviour has a reference: a change to `player.rs` that isn't mirrored in
`player.js` fails the comparison tests.
* `instance_start` and `guide_walk` become public in `anicraft-doc`, so the exporter evaluates
exactly as the renderer does.
* `FORMAT_VERSION` (the `v` field) versions the embedded data; a page always carries the
player that reads it, so old pages keep playing.
+11
View File
@@ -50,6 +50,16 @@ cargo deny check advisories # RustSec security advisories (needs ne
user's own files: AniCraft ships none in the binary; the sample plug-ins are source under
`examples/plugins` (MIT OR Apache-2.0).
### HTML canvas export (2026-11-09, ADR 0028)
Tests only: `boa_engine` 0.21 (a JavaScript engine in pure Rust, Unlicense OR MIT) and its tree
(`boa_*`, `icu_*` and `zerovec`-family crates under Unicode-3.0 or MIT/Apache-2.0, `ryu-js`
Apache-2.0 OR BSL-1.0, `regress`, `intrusive-collections`, `num-bigint`, `time` and others
under MIT/Apache-2.0), as a dev-dependency of `anicraft-render`: the tests run the exported
page's player in it. Nothing of it is in the app or the CLI. No new licence. The page's
JavaScript is our own code (`crates/render/src/html/`), MIT OR Apache-2.0 like the rest, and
uses no npm packages.
### Sound (2026-11-09, ADR 0020)
The audio slice adds, all permissive and from crates.io: `lewton` (Ogg Vorbis decoding, MIT OR
@@ -120,6 +130,7 @@ No new crate. The installers are built with tools that are not Rust dependencies
| WebAssembly (plug-ins, ADR 0017) | W3C standard under the W3C Royalty-Free Patent Policy. | Allowed. Interpreted by `wasmi` (no code generation). |
| SWF export (optional) | Adobe published the SWF specification and lifted its use restrictions in 2009 (Open Screen Project). | Allowed, low priority. |
| Lottie | Open specification (Lottie Animation Community, Linux Foundation). | Allowed. |
| HTML canvas export (ADR 0028) | HTML, the canvas 2D context and Web Audio are W3C/WHATWG standards under royalty-free policies. | Allowed. The page's player and drawing code are our own, written from those specifications and our own Rust player; nothing taken from Adobe's CreateJS runtime or other publishers' output. |
## 5. Trademarks
+5 -5
View File
@@ -13,10 +13,10 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, onion skin (±2 frames), looping playback. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. Headless: `timeline.create_motion_tween`, `motion.*`. Not yet: motion paths on the stage, retiming keys, rescaling keys with the span, XFL motion-tween import. **Camera layer** (ADR 0027): the camera button in the timeline header or the Camera tool (C) adds a Camera layer on top; its frame shows on the stage in orange; drag to pan, turn with the round handle, wheel to zoom (one undo step per drag); Properties › Camera (position, zoom, rotation, tint, reset); keyframes and classic or motion tweens animate it; layer Depth gives pan parallax; View › Preview Through Camera shows the movie's picture (artwork tLine truncated
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. No brush or merge drawing yet. |
| Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `<settings>/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. |
| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). Not yet: ActionScript (ADR 0013 tiers), HTML canvas export, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. |
| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. Not yet: ActionScript (ADR 0013 tiers), filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. |
| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. |
| Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). Not yet: sound effects (fades, panning, envelopes) and per-layer volume/mute, sounds inside symbols, sounds from XFL, audio in Lottie/HTML, lossless compression of stored WAVs, latency compensation. |
| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). No per-character styles or motion tweens from XFL yet; frame scripts are counted in the import report but not kept yet (ADR 0013); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; soft masks, per-character positions, text on a path and dashes are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). |
| Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). Not yet: sound effects (fades, panning, envelopes) and per-layer volume/mute, sounds inside symbols, sounds from XFL, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, latency compensation. |
| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Animate's own bitmap encodings are not public and are reported, not decoded. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). No per-character styles or motion tweens from XFL yet; frame scripts are counted in the import report but not kept yet (ADR 0013); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; soft masks, per-character positions, text on a path and dashes are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): frame-accurate rather than re-keyed: each frame is evaluated, artwork that persists (same layer, element, occurrence and path structure) becomes one shape layer with outlines baked to stage space, and whatever changes (outlines, colours, gradient points, stroke width, opacity, masks as layer masks) is written as hold keyframes where it changes; one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). |
| Tests | 133 tests (adds point editing, closed-path anchors, curve fitting, pen/pencil/subselection commands, the Pen's path data, frame ranges, keyframe moves, range confirmations, frame selection and the frame clipboard): unit, analytic render, band/determinism, robustness fuzz over all commands, round trip (v1 and v2 files), structural sharing and history budget, render-service equivalence, confirmations, clipboard, transforms and align, GIF decode and timing, free-transform maths, UI-guideline enforcement, CLI. |
| Ease of use & safety | **Visual language** (ADR 0008, revised): graphite palette, corners by role (square structure, softened controls, rounder menus and dialogs with soft depth), borders only between layout regions, flat buttons with a visible focus ring, vibrant timeline blocks (mint artwork, violet tweens), sentence-case headings, **collapsible sections with rules** (Preferences, Properties, dock, shortcut sheet), **Lucide icons** stroked as vectors via a new full SVG path reader; click targets ≥ 28 px (tools 40, rows 28, toggles 24); palette contrast, target sizes and "no raw colours or radii" are enforced by tests. Product principles written (`docs/product-principles.md`). Tiered destructive-action confirmations, enforced in the engine (ADR 0004). Unsaved-changes guard on close/new/open. **Crash-recovery autosave** (ADR 0015): unsaved work is copied in the background (every minute or 25 changes by default; Preferences › Files › Autosave, with an off switch) to `Recovery` in the settings folder, atomically and never over the user's file; an OS file lock per running window tells crashed sessions from open ones; the next start offers what was left behind in a non-blocking window (Restore as unsaved work with its original path, Discard with a second click, Later; File › Recover Autosaved Documents… brings it back); saves and clean exits remove the copy; headless `file.recovery_list/recover/discard_recovery/autosave`. Not yet: several open documents, older copies, the undo history. Overwrite checks for saves and exports. "Ctrl+Z to undo" hints. Command palette (Ctrl+K). Shortcut sheet (F1). Right-click menus on stage, frames and layers. Save As (Ctrl+Shift+S). **Shortcut editor** (F1): every menu command, tool and view key can be rebound, given extra keys or unbound; recording asks before taking a key from another action, reserved keys (palette, editor, Preferences, quit, play, Esc, Space, Tab) stay fixed, per-action and global reset; only the changes are saved in preferences, so untouched actions follow new defaults; menus, tooltips and the palette show the keys in effect. |
| Platforms & preferences | ADR 0006 platform layer: ⌘ shortcut labels and an AniCraft app menu with a unified title bar on macOS; Exit and Preferences (Ctrl+U) on Windows and Linux; native file dialogs (XDG portal on Linux, with a fallback switch); wgpu with automatic OpenGL fallback; per-OS settings folder. **Preferences** window: theme (Graphite or High contrast), interface and data fonts (bundled default or any installed font), interface scale (75–200 %), stage render mode, file dialogs, reset confirmations. Edits render live (fixed the missing-repaint bug). Not yet: native macOS NSMenu, macOS/Linux CI runners. Verified on Windows only so far. |
@@ -35,7 +35,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
| **M3** | GPU stage *(in progress)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); next: no-readback textures, masks/groups/blend modes on the GPU, GPU binning; becomes the default stage renderer once it covers the display list and is faster everywhere. |
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. |
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output; effects, volume and sounds in symbols later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. |
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); HTML canvas runtime export; command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: tier 1 keeps scripts (XFL frame scripts and class names stored verbatim, Actions panel, `script.*` commands); tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts. The full language, the `flash.*` API and SWF bytecode are not planned. |
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: tier 1 keeps scripts (XFL frame scripts and class names stored verbatim, Actions panel, `script.*` commands); tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts. The full language, the `flash.*` API and SWF bytecode are not planned. |
| **M7** | Advanced animation | Bone/IK tool; ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens) and brush library; asset warp; graph-based easing presets library. |
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); web build (wasm) of the editor; localisation; accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. |
@@ -56,7 +56,7 @@ titled with its milestone.
| M3 | GPU stage: no-readback textures, then masks, group opacity and blend modes on the GPU (first slice ✅, ADR 0019) | CPU oracle, tiled stage, GPU stage first slice |
| M4 | Text from Animate files | XFL import, text engine (M5 first slice) |
| M5 | Audio layers: import, waveform, playback sync | timeline, layers |
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); next: HTML canvas runtime export | command registry, plug-in host, action IR and player |
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); next: command macros | command registry, plug-in host, action IR and player |
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027); next: Brush tool and brush library | strokes, Pen and Pencil, width profiles, timeline evaluation |
| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe |
+12
View File
@@ -658,6 +658,12 @@ impl App {
crate::test_movie::demo_pointer(self);
}
}
Some("exporthtml") => {
// File › Export › Export HTML Canvas… on the interactive sample (the in-app
// prompt: screenshots never open native dialogs).
self.perform("file.new_sample", json!({"which": "interactive"}));
self.invoke("file.export_html");
}
Some("select") => {
// The top layer's artwork selected, for its Properties.
self.run("layer.select", json!({"index": 0}));
@@ -919,6 +925,11 @@ impl App {
self.status_ok(format!("{n} {what} {place}. {report} {undo} to undo."));
}
"file.export_sprite_sheet" => self.status_ok(format!("Exported {} frames to {} ({}×{} grid) and its frame map {}", v["frames"], v["written"].as_str().unwrap_or(""), v["columns"], v["rows"], v["map"].as_str().unwrap_or(""))),
"file.export_html" => {
let report = v["report"].as_str().filter(|r| !r.is_empty()).map(|r| format!(" {r}")).unwrap_or_default();
let kb = v["bytes"].as_u64().unwrap_or(0).div_ceil(1024);
self.status_ok(format!("Exported {} ({} frames, {kb} KB): open it in a web browser.{report}", v["written"].as_str().unwrap_or(""), v["frames"]));
}
"file.export_lottie" => {
let report = v["report"].as_str().filter(|r| !r.is_empty()).map(|r| format!(" {r}")).unwrap_or_default();
self.status_ok(format!("Exported {} ({} frames, {} layers).{report}", v["written"].as_str().unwrap_or(""), v["frames"], v["layers"]));
@@ -1022,6 +1033,7 @@ impl App {
"file.export_sprite_sheet" => Some(("Export sprite sheet (PNG + JSON frame map)", "path", "sprites.png".to_string())),
"file.export_video" => Some(("Export video (.webm or .mp4, made with your ffmpeg)", "path", "animation.webm".to_string())),
"file.export_lottie" => Some(("Export Lottie animation (JSON, for web and apps)", "path", "animation.json".to_string())),
"file.export_html" => Some(("Export HTML canvas (one web page)", "path", "movie.html".to_string())),
"file.export_audio" => Some(("Export audio (the movie's soundtrack as a WAV)", "path", "soundtrack.wav".to_string())),
"file.import_to_library" => Some(("Import to library (WAV, OGG or MP3 sound; PNG or JPEG image)", "path", "sound.wav".to_string())),
"file.import" => Some(("Import to stage (SVG, PNG or JPEG; WAV, OGG or MP3 onto a new layer)", "path", "drawing.svg".to_string())),
+1 -1
View File
@@ -194,7 +194,7 @@ impl Entry {
/// Commands the palette can run without extra input (everything optional, or prompted).
fn runnable(c: &CommandSpec) -> bool {
if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install") {
if matches!(c.id, "file.open" | "file.recovery_list" | "file.save_as" | "file.import" | "file.export_png" | "file.export_gif" | "file.export_svg" | "file.export_sprite_sheet" | "file.export_video" | "file.export_lottie" | "file.export_html" | "file.export_png_sequence" | "modify.convert_to_symbol" | "layer.rename" | "scene.rename" | "plugin.install") {
return true;
}
let inner = c.params.trim().trim_start_matches('{').trim_end_matches('}');
+1 -1
View File
@@ -134,7 +134,7 @@ fn main() -> eframe::Result {
}
"--help" | "-h" => {
println!(
"anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale <percent>] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|hints|hintsend|camera|cameraview|filters|prefs|licenses|zoom|recovery|plugins|actions|testmovie]\n\
"anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale <percent>] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|hints|hintsend|camera|cameraview|filters|prefs|licenses|zoom|recovery|plugins|actions|testmovie|exporthtml]\n\
--renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\
--open shows a panel at start (handy with --screenshot for visual checks)\n\
ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer, in builds with the gpu-stage feature (ADR 0019)\n\
+1
View File
@@ -158,6 +158,7 @@ pub fn filters(cmd: &str) -> (&'static str, &'static [&'static str]) {
"file.export_gif" => ("Animated GIF", &["gif"]),
"file.export_svg" => ("SVG image", &["svg"]),
"file.export_lottie" => ("Lottie animation", &["json"]),
"file.export_html" => ("Web page", &["html", "htm"]),
"file.import" => ("Drawing, image or sound", &["svg", "png", "jpg", "jpeg", "wav", "ogg", "mp3"]),
"file.import_to_library" => ("Sound or image", &["wav", "ogg", "mp3", "png", "jpg", "jpeg"]),
"file.export_audio" => ("WAV sound", &["wav"]),