diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc8b12a..ea3ce72 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,7 +52,7 @@ jobs: (cd .host/code-snippets && ./animathio_2.1.0_x86_64.AppImage --appimage-extract > /dev/null) python3 community/code-snippets/smoke.py .host/code-snippets/squashfs-root/usr/bin/animathio-cli target/plugins - name: Get released AniMathIO 2.3.0 - id: molecule-host + id: host-2-3-0 uses: ./.github/actions/animathio-cli with: github-token: ${{ github.token }} @@ -61,8 +61,12 @@ jobs: sha256: ca7d4e613a7ec049bdb9aa8ecf6fc63ddae2ce10c70b2ec26632569a9ebdd148 - name: Test Molecule Studio on released 2.3.0 env: - ANIMATHIO_CLI: ${{ steps.molecule-host.outputs.cli }} + ANIMATHIO_CLI: ${{ steps.host-2-3-0.outputs.cli }} run: python3 community/molecule/smoke.py "$ANIMATHIO_CLI" target/plugins + - name: Test Ray Optics on released 2.3.0 + env: + ANIMATHIO_CLI: ${{ steps.host-2-3-0.outputs.cli }} + run: python3 community/optics/smoke.py "$ANIMATHIO_CLI" target/plugins - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: plugins diff --git a/README.md b/README.md index a5a15b3..a7f56d8 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ MIT licensed, like AniMathIO. Plugins are sandboxed WebAssembly components. | --- | --- | --- | --- | --- | --- | | [Code Snippets](https://github.com/AniMathIO/plugins/tree/HEAD/community/code-snippets) | AniMathIO | Syntax-highlighted code with type-on reveal and token morph animations | MIT AND OFL-1.1 | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/code-snippets) | | [Molecule Studio](https://github.com/AniMathIO/plugins/tree/HEAD/community/molecule) | AniMathIO | Self-drawing 2D molecular structures and reactions from SMILES, with CPK colors and wedge/dash stereo | MIT | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/molecule) | +| [Ray Optics](https://github.com/AniMathIO/plugins/tree/HEAD/community/optics) | AniMathIO | Animated lens and mirror rays, Snell refraction, total internal reflection and prism dispersion | MIT | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/optics) | Install from the editor's Plugins tab in AniMathIO 2.2+, or manually as described diff --git a/community-plugins.json b/community-plugins.json index b2aef28..7de951e 100644 --- a/community-plugins.json +++ b/community-plugins.json @@ -21,6 +21,16 @@ "path": "community/molecule", "license": "MIT", "min_abi": "1.1.0" + }, + { + "id": "io.github.animathio.optics", + "name": "Ray Optics", + "author": "AniMathIO", + "description": "Animated lens and mirror rays, Snell refraction, total internal reflection and prism dispersion", + "repo": "AniMathIO/plugins", + "path": "community/optics", + "license": "MIT", + "min_abi": "1.1.0" } ], "delisted": [] diff --git a/community/optics/Cargo.lock b/community/optics/Cargo.lock new file mode 100644 index 0000000..c4861a8 --- /dev/null +++ b/community/optics/Cargo.lock @@ -0,0 +1,834 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "auditable-serde" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7bf8143dfc3c0258df908843e169b5cc5fcf76c7718bd66135ef4a9cd558c5" +dependencies = [ + "semver", + "serde", + "serde_json", + "topological-sort", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[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.10", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "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", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[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", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "optics" +version = "0.1.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[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.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "topological-sort" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea68304e134ecd095ac6c3574494fc62b909f416c4fca77e440530221e549d3d" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +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 = "wasm-encoder" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bb72f02e7fbf07183443b27b0f3d4144abf8c114189f2e088ed95b696a7822" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce1ef0faabbbba6674e97a56bee857ccddf942785a336c8b47b42373c922a91d" +dependencies = [ + "anyhow", + "auditable-serde", + "flate2", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "url", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f51cad774fb3c9461ab9bccc9c62dfb7388397b5deda31bf40e8108ccd678b2" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e7091ed6c9abfa4e0a2ef3b39d0539da992d841fcf32c255f64fb98764ffee5" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "398c650cec1278cfb72e214ba26ef3440ab726e66401bd39c04f465ee3979e6b" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68faed92ae696b93ea9a7b67ba6c37bf09d72c6d9a70fa824a743c3020212f11" +dependencies = [ + "bitflags", + "futures", + "once_cell", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83903c8dcd8084a8a67ae08190122cf0e25dc37bdc239070a00f47e22d3f0aae" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7bf7f20495bcc7dc9f24c5fbcac9e919ca5ebdb7a1b1841d74447d3c8dd0c60" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "635c3adc595422cbf2341a17fb73a319669cc8d33deed3a48368a841df86b676" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddf445ed5157046e4baf56f9138c124a0824d4d1657e7204d71886ad8ce2fc11" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[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.10", + "synstructure", +] + +[[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.10", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "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.10", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/community/optics/Cargo.toml b/community/optics/Cargo.toml new file mode 100644 index 0000000..aed9b8a --- /dev/null +++ b/community/optics/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "optics" +version = "0.1.0" +edition = "2021" +license = "MIT" +publish = false + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +wit-bindgen = "=0.40.0" + +[profile.release] +opt-level = 3 +lto = true +strip = "debuginfo" + +[workspace] diff --git a/community/optics/NOTICE b/community/optics/NOTICE new file mode 100644 index 0000000..5ce4686 --- /dev/null +++ b/community/optics/NOTICE @@ -0,0 +1,25 @@ +Ray Optics for AniMathIO +Copyright (c) 2026 AniMathIO contributors. MIT (see ../../LICENSE). + +Behavioral reference: Ray Optics Simulation by Rick Tu and contributors +https://github.com/ricktu288/ray-optics/tree/9dd7706097ec8b93171e04e7985be12c3309533c +Version 5.5.0, commit 9dd7706097ec8b93171e04e7985be12c3309533c, Apache License 2.0. + +Studied src/core/geometry.js for ray/segment intersections, +src/core/sceneObjs/glass/IdealLens.js for signed ideal-lens bending, +src/core/sceneObjs/mirror/ArcMirror.js for the signed paraxial R/2 focal +distance, src/core/sceneObjs/glass/Glass.js for boundary refraction and +wavelength-dependent index, and src/core/PrimitiveBasedSimulator.js for +the per-ray interaction-depth limit. + +The plugin reimplements these ideas with Rust vector geometry, nearest-face +tracing, Snell transmission and total internal reflection, and a bounded +prism trace per wavelength. The principal-ray construction and animation, +labels, rendering and approximate spectral palette are written for AniMathIO. +The formulas for conjugate distances, refraction and Cauchy dispersion are +textbook material. No upstream JavaScript, GPU code, scenes or assets are +copied. The Apache license text is retained in assets/ray-optics-LICENSE +and packaged as licenses/ray-optics-LICENSE. + +The component uses wit-bindgen 0.40.0 (MIT OR Apache-2.0) for AniMathIO ABI +bindings. Resolved Rust dependencies are listed in Cargo.lock. diff --git a/community/optics/README.md b/community/optics/README.md new file mode 100644 index 0000000..64cffd7 --- /dev/null +++ b/community/optics/README.md @@ -0,0 +1,122 @@ +# Ray Optics + +Animated optics diagrams for AniMathIO 2. Plugin ID `io.github.animathio.optics`, +ABI **1.1.0**, verified with the released AniMathIO **2.3.0** Linux CLI. + +## Build and use + +```sh +rustup target add wasm32-wasip2 +bash community/optics/build.sh +export ANIMATHIO_PLUGIN_DIR="$PWD/community/optics/target" +``` + +Run from the plugins repository root. The build produces +`community/optics/target/optics.amplugin`. To test a local build, start AniMathIO +with the directory above, add **Ray Optics** from the Library, and choose a +setup in the inspector. The plugin draws on a transparent canvas. The default +palette is designed for a dark project background. + +Keyframe `progress` from 0 at the start to 1 at the end to draw the rays in +order of propagation. On `tir`, the same curve also sweeps the incidence +angle from 0° to `angle_deg`. At the critical angle the transmitted ray grazes +the interface. Above it, only the reflected ray remains. Other numeric +parameters, such as lens distance or refractive index, can be keyframed +independently. + +## Setups + +| Setup | What it shows | +| --- | --- | +| `lens-diagram` | Parallel, optical-centre and focal rays for a converging or diverging thin lens, with F/2F markers and the object and image arrows. | +| `mirror` | Parallel, vertex and focal rays for a concave or convex mirror, with its focal point F and centre of curvature C. | +| `refraction` | Transmission through a parallel slab, incidence and transmission angles measured from the normal, and Snell's equation. The exit ray is parallel to the incident ray when both faces transmit. | +| `tir` | An angle sweep from the lower medium into the upper medium, with the critical angle marked when one exists. Media follow the same convention as `refraction`: n₁ is the medium the ray starts in (the slab, labelled below the interface) and n₂ the one it would transmit into, with `sin θc = n₂/n₁` shown above the interface, clear of the ray sweep. The reflected branch below that threshold uses schematic brightness. | +| `dispersion` | An incident white beam in air and wavelength-dependent refraction through an equilateral prism. Shorter wavelengths have higher indices and, in the default setup, bend farther toward the base. | + +Real images are where solid outgoing rays converge. Virtual images use dashed +back-projections and a dashed image arrow. The lens bends rays at its optical +plane, and the spherical mirror uses its vertex plane and the paraxial relation +`f = R/2`. A ray that would miss the on-screen aperture is omitted. With the +object at the focus, the outgoing rays are parallel and the label shows +**Image at infinity**. Strongly magnified conjugates — a concave mirror or +converging lens with the object between F and 2F, or inside F — shrink the +whole construction (focal length, distances and heights together) until the +image arrow and all three rays fit, so the magnified image always stays on the +diagram. For the geometric conventions, see OpenStax on [thin lenses](https://openstax.org/books/university-physics-volume-3/pages/2-4-thin-lenses) +and [spherical mirrors](https://openstax.org/books/university-physics-volume-3/pages/2-2-spherical-mirrors). + +## Parameters + +| Parameter | Default | Meaning | +| --- | --- | --- | +| `setup` | `lens-diagram` | One of the five setups above. | +| `progress` | 1 | Ray reveal from 0 to 1. Also sweeps incidence in `tir`. | +| `lens_type` | `converging` | `converging` or `diverging`, which selects the sign of the focal length. | +| `focal_length` | 20 | Lens focal length magnitude, 5–50% of the canvas short edge. | +| `object_distance` | 35 | Positive distance from the optic, 5–90% of the short edge. The value is limited to the visible diagram on narrow canvases. | +| `object_height` | 15 | Object arrow height, 2–30% of the short edge. | +| `curvature` | 30 | Signed mirror radius, −50 to 50% of the short edge. Negative is convex. Zero and positive values are concave. Magnitudes below 10 use a radius of 10%. | +| `index_1` | 1.0 | Surrounding medium index, 1.0–2.5. Light enters from this medium in `refraction` and from `index` in `tir`. | +| `index` | 1.5 | Slab, lower medium, or prism index, 1.0–2.5. In `dispersion` this is the index at 550 nm. | +| `angle_deg` | 45 | Incidence from the normal, 0–89°. In `tir` it sets the sweep's endpoint. | +| `ray_count` | 12 | 1–64 spectral samples. One sample uses 550 nm. | +| `show_normal` | true | Draw the dashed surface normal in `refraction` and `tir`. | +| `show_labels` | true | Show diagram, image and angle labels. | +| `show_focal` | true | Draw lens or mirror focal markers. | +| `spectrum` | true | Trace colored wavelengths. Switch off for one 550 nm ray in the accent color. | +| `accent` | `#FFCD42FF` | Color and opacity of the main rays. | + +The prism uses a two-term Cauchy curve calibrated at 550 nm whose coefficient +`B = 0.008 µm² · (n − 1)` scales with n − 1: about 0.004 µm² at n = 1.5 +(BK7-like), proportionally weaker for lower indices, and exactly zero at an +index of 1, which is why vacuum disperses nothing. The spectrum +uses approximate display colors sampled from 400 to 700 nm. A ray that strikes +a prism corner ends there because the corner has no unique surface normal. +The tracer caps interactions at 8 per ray and budgets 256 segments across a +frame. Glass and prism paths follow the transmitted ray whenever one exists and +continue along the reflected ray during total internal reflection. + +## Screenshots + +Rendered at 1280×720 using AniMathIO 2.3.0. The [screenshots directory](screenshots) +also contains 0%, 25%, 50% and 75% frames for each setup. + +| Converging lens | Diverging lens | Converging lens with object inside focus | +| --- | --- | --- | +| ![Inverted real image](screenshots/lens-converging-100.png) | ![Upright virtual image](screenshots/lens-diverging.png) | ![Magnified upright virtual image](screenshots/lens-magnifier.png) | + +| Concave mirror | Convex mirror | Concave mirror with object inside focus | +| --- | --- | --- | +| ![Reflected rays converge in front of the mirror](screenshots/mirror-concave-100.png) | ![Back-projections converge behind the mirror](screenshots/mirror-convex.png) | ![Magnified virtual image behind the mirror](screenshots/mirror-concave-virtual.png) | + +| Refraction | Below the critical angle | Above the critical angle | Prism dispersion | +| --- | --- | --- | --- | +| ![Snell's law at a slab](screenshots/refraction-100.png) | ![Transmitted and reflected rays](screenshots/tir-075.png) | ![Only the reflected ray](screenshots/tir-100.png) | ![Violet bends farther toward the base than red](screenshots/dispersion-100.png) | + +Magnified conjugates shrink to fit instead of leaving the diagram: + +| Lens, object between F and 2F | Mirror, object between C and F | Mirror, object inside F | +| --- | --- | --- | +| ![Magnified real image from a converging lens](screenshots/lens-magnified-real.png) | ![Magnified inverted real image from a concave mirror](screenshots/mirror-magnified.png) | ![Magnified virtual image behind the mirror at the default height](screenshots/mirror-concave-virtual.png) | + +## Verification and credits + +```sh +CARGO_BUILD_JOBS=2 CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0 \ + cargo test --manifest-path community/optics/Cargo.toml --locked +python3 community/optics/smoke.py /path/to/animathio-cli community/optics/target --screenshots +``` + +The smoke script needs Pillow and a released 2.3.0 CLI. It verifies progressive +rendering, repeat PNG bytes for each setup, parameter toggles, magnified mirror +and lens conjugates, a sampled +keyframe, a portrait render, and a 64-ray prism under the host's default +limits. Frames depend only on the evaluated parameters and canvas size. +The component emits vector paths and host-rendered text. It calls no host +imports and uses no filesystem, network, clocks or randomness. + +The Rust tracer draws on the behavior of **Ray Optics Simulation** by Rick Tu +and contributors, version 5.5.0, under Apache-2.0. See the [NOTICE](NOTICE) for +the source files studied and the [upstream license](assets/ray-optics-LICENSE) +for its terms. The plugin code is [MIT](../../LICENSE). diff --git a/community/optics/assets/ray-optics-LICENSE b/community/optics/assets/ray-optics-LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/community/optics/assets/ray-optics-LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/community/optics/build.sh b/community/optics/build.sh new file mode 100644 index 0000000..a9a24aa --- /dev/null +++ b/community/optics/build.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +export CARGO_BUILD_JOBS=2 CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0 +export CARGO_TARGET_DIR="$PWD/target" +runner=(cargo) +if [[ "$OSTYPE" == linux* ]]; then runner=(nice -n 19 ionice -c3 cargo); fi +"${runner[@]}" build --target wasm32-wasip2 --release --locked +python3 - <<'PACKAGE' +import pathlib, tomllib, zipfile +root = pathlib.Path('.') +name = tomllib.loads((root / 'Cargo.toml').read_text())['package']['name'] +out = root / 'target' / (name + '.amplugin') +with zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) as z: + z.write('plugin.toml', 'plugin.toml') + z.write('NOTICE', 'NOTICE') + z.write('../../LICENSE', 'LICENSE') + z.write('assets/ray-optics-LICENSE', 'licenses/ray-optics-LICENSE') + z.write(f"target/wasm32-wasip2/release/{name.replace('-', '_')}.wasm", 'plugin.wasm') +print(out) +PACKAGE diff --git a/community/optics/plugin.toml b/community/optics/plugin.toml new file mode 100644 index 0000000..9802a43 --- /dev/null +++ b/community/optics/plugin.toml @@ -0,0 +1,7 @@ +api_version = "1.1.0" +id = "io.github.animathio.optics" +name = "Ray Optics" +version = "0.1.0" +description = "Animated ray-optics diagrams: thin lens and mirror principal rays, Snell refraction, total internal reflection and prism dispersion" +kinds = ["clip-source"] +capabilities = [] diff --git a/community/optics/screenshots/dispersion-000.png b/community/optics/screenshots/dispersion-000.png new file mode 100644 index 0000000..1bc0411 Binary files /dev/null and b/community/optics/screenshots/dispersion-000.png differ diff --git a/community/optics/screenshots/dispersion-025.png b/community/optics/screenshots/dispersion-025.png new file mode 100644 index 0000000..76523d6 Binary files /dev/null and b/community/optics/screenshots/dispersion-025.png differ diff --git a/community/optics/screenshots/dispersion-050.png b/community/optics/screenshots/dispersion-050.png new file mode 100644 index 0000000..d948b60 Binary files /dev/null and b/community/optics/screenshots/dispersion-050.png differ diff --git a/community/optics/screenshots/dispersion-075.png b/community/optics/screenshots/dispersion-075.png new file mode 100644 index 0000000..07020c4 Binary files /dev/null and b/community/optics/screenshots/dispersion-075.png differ diff --git a/community/optics/screenshots/dispersion-100.png b/community/optics/screenshots/dispersion-100.png new file mode 100644 index 0000000..178ef3c Binary files /dev/null and b/community/optics/screenshots/dispersion-100.png differ diff --git a/community/optics/screenshots/lens-converging-000.png b/community/optics/screenshots/lens-converging-000.png new file mode 100644 index 0000000..420d256 Binary files /dev/null and b/community/optics/screenshots/lens-converging-000.png differ diff --git a/community/optics/screenshots/lens-converging-025.png b/community/optics/screenshots/lens-converging-025.png new file mode 100644 index 0000000..9f51ab7 Binary files /dev/null and b/community/optics/screenshots/lens-converging-025.png differ diff --git a/community/optics/screenshots/lens-converging-050.png b/community/optics/screenshots/lens-converging-050.png new file mode 100644 index 0000000..b7579b7 Binary files /dev/null and b/community/optics/screenshots/lens-converging-050.png differ diff --git a/community/optics/screenshots/lens-converging-075.png b/community/optics/screenshots/lens-converging-075.png new file mode 100644 index 0000000..0b9aa86 Binary files /dev/null and b/community/optics/screenshots/lens-converging-075.png differ diff --git a/community/optics/screenshots/lens-converging-100.png b/community/optics/screenshots/lens-converging-100.png new file mode 100644 index 0000000..fd90c65 Binary files /dev/null and b/community/optics/screenshots/lens-converging-100.png differ diff --git a/community/optics/screenshots/lens-diverging.png b/community/optics/screenshots/lens-diverging.png new file mode 100644 index 0000000..ce577ac Binary files /dev/null and b/community/optics/screenshots/lens-diverging.png differ diff --git a/community/optics/screenshots/lens-magnified-real.png b/community/optics/screenshots/lens-magnified-real.png new file mode 100644 index 0000000..67a5010 Binary files /dev/null and b/community/optics/screenshots/lens-magnified-real.png differ diff --git a/community/optics/screenshots/lens-magnifier.png b/community/optics/screenshots/lens-magnifier.png new file mode 100644 index 0000000..5a0efa3 Binary files /dev/null and b/community/optics/screenshots/lens-magnifier.png differ diff --git a/community/optics/screenshots/mirror-concave-000.png b/community/optics/screenshots/mirror-concave-000.png new file mode 100644 index 0000000..d7c1d7c Binary files /dev/null and b/community/optics/screenshots/mirror-concave-000.png differ diff --git a/community/optics/screenshots/mirror-concave-025.png b/community/optics/screenshots/mirror-concave-025.png new file mode 100644 index 0000000..b3ef5c1 Binary files /dev/null and b/community/optics/screenshots/mirror-concave-025.png differ diff --git a/community/optics/screenshots/mirror-concave-050.png b/community/optics/screenshots/mirror-concave-050.png new file mode 100644 index 0000000..1b12a17 Binary files /dev/null and b/community/optics/screenshots/mirror-concave-050.png differ diff --git a/community/optics/screenshots/mirror-concave-075.png b/community/optics/screenshots/mirror-concave-075.png new file mode 100644 index 0000000..b9dd358 Binary files /dev/null and b/community/optics/screenshots/mirror-concave-075.png differ diff --git a/community/optics/screenshots/mirror-concave-100.png b/community/optics/screenshots/mirror-concave-100.png new file mode 100644 index 0000000..fce3a2a Binary files /dev/null and b/community/optics/screenshots/mirror-concave-100.png differ diff --git a/community/optics/screenshots/mirror-concave-virtual.png b/community/optics/screenshots/mirror-concave-virtual.png new file mode 100644 index 0000000..cfbdb42 Binary files /dev/null and b/community/optics/screenshots/mirror-concave-virtual.png differ diff --git a/community/optics/screenshots/mirror-convex.png b/community/optics/screenshots/mirror-convex.png new file mode 100644 index 0000000..0a91a4c Binary files /dev/null and b/community/optics/screenshots/mirror-convex.png differ diff --git a/community/optics/screenshots/mirror-magnified.png b/community/optics/screenshots/mirror-magnified.png new file mode 100644 index 0000000..9f2f98a Binary files /dev/null and b/community/optics/screenshots/mirror-magnified.png differ diff --git a/community/optics/screenshots/refraction-000.png b/community/optics/screenshots/refraction-000.png new file mode 100644 index 0000000..01fcf51 Binary files /dev/null and b/community/optics/screenshots/refraction-000.png differ diff --git a/community/optics/screenshots/refraction-025.png b/community/optics/screenshots/refraction-025.png new file mode 100644 index 0000000..efe1e2f Binary files /dev/null and b/community/optics/screenshots/refraction-025.png differ diff --git a/community/optics/screenshots/refraction-050.png b/community/optics/screenshots/refraction-050.png new file mode 100644 index 0000000..5ea8e34 Binary files /dev/null and b/community/optics/screenshots/refraction-050.png differ diff --git a/community/optics/screenshots/refraction-075.png b/community/optics/screenshots/refraction-075.png new file mode 100644 index 0000000..d443805 Binary files /dev/null and b/community/optics/screenshots/refraction-075.png differ diff --git a/community/optics/screenshots/refraction-100.png b/community/optics/screenshots/refraction-100.png new file mode 100644 index 0000000..0f93d62 Binary files /dev/null and b/community/optics/screenshots/refraction-100.png differ diff --git a/community/optics/screenshots/tir-000.png b/community/optics/screenshots/tir-000.png new file mode 100644 index 0000000..301b420 Binary files /dev/null and b/community/optics/screenshots/tir-000.png differ diff --git a/community/optics/screenshots/tir-025.png b/community/optics/screenshots/tir-025.png new file mode 100644 index 0000000..dbf9756 Binary files /dev/null and b/community/optics/screenshots/tir-025.png differ diff --git a/community/optics/screenshots/tir-050.png b/community/optics/screenshots/tir-050.png new file mode 100644 index 0000000..9543248 Binary files /dev/null and b/community/optics/screenshots/tir-050.png differ diff --git a/community/optics/screenshots/tir-075.png b/community/optics/screenshots/tir-075.png new file mode 100644 index 0000000..34bf9f8 Binary files /dev/null and b/community/optics/screenshots/tir-075.png differ diff --git a/community/optics/screenshots/tir-100.png b/community/optics/screenshots/tir-100.png new file mode 100644 index 0000000..90e2dbd Binary files /dev/null and b/community/optics/screenshots/tir-100.png differ diff --git a/community/optics/smoke.py b/community/optics/smoke.py new file mode 100644 index 0000000..5b34517 --- /dev/null +++ b/community/optics/smoke.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Released-host integration checks. All files stay under this plugin's target/. +Usage: python3 smoke.py /path/to/animathio-cli /path/to/plugin-dir [--screenshots] +""" +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import zipfile +from PIL import Image + +ROOT = Path(__file__).resolve().parent +WORK = ROOT / 'target' / 'smoke' +WORK.mkdir(parents=True, exist_ok=True) +CLI = str(Path(sys.argv[1]).resolve()) +PLUGIN_ID = 'io.github.animathio.optics' + +plugins_dir = Path(sys.argv[2]).resolve() +if not any(plugins_dir.glob('*.amplugin')): + raise SystemExit('pass the directory containing the built optics.amplugin') +ENV = dict(os.environ, ANIMATHIO_PLUGIN_DIR=str(plugins_dir), + ANIMATHIO_PLUGIN_SETTINGS=str(WORK / 'community-plugins.json'), + ANIMATHIO_USER_PLUGIN_DIR=str(WORK / 'user-plugins'), + XDG_CONFIG_HOME=str(WORK / 'config'), XDG_CACHE_HOME=str(WORK / 'cache'), + XDG_DATA_HOME=str(WORK / 'data'), + ANIMATHIO_AUDIO='none', PIPEWIRE_REMOTE='animathio-silent-no-such-remote', + PULSE_SERVER='unix:/nonexistent/animathio-silent', SDL_AUDIODRIVER='dummy') + +def run(*args): + result = subprocess.run([CLI, *map(str, args)], env=ENV, text=True, capture_output=True, timeout=120) + if result.returncode or any(s in result.stderr.lower() for s in ['failed', 'trap', 'placeholder', 'not loaded']): + raise RuntimeError(result.stdout + result.stderr) + return result.stdout + +sample = WORK / 'sample.amio' +sample.unlink(missing_ok=True) +run('new-sample', '-o', sample) +with zipfile.ZipFile(sample) as z: + project = json.loads(z.read('project.json')) +project['assets'] = {} +project['width'] = 1280 +project['height'] = 720 +project['background'] = [17, 20, 28, 255] +project['tracks'] = project['tracks'][:1] +clip = project['tracks'][0]['clips']['1'] +clip['animations'] = [] +clip['effects'] = [] + +def render(name, frame=0, **params): + clip['kind'] = {'Plugin': {'plugin_id': PLUGIN_ID, + 'params': dict(params)}} + file = WORK / (name + '.amio') + with zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED) as z: + z.writestr('project.json', json.dumps(project)) + png = WORK / (name + '.png') + png.unlink(missing_ok=True) + run('render', file, '--frame', frame, '-o', png) + image = Image.open(io.BytesIO(png.read_bytes())).convert('RGB') + # A placeholder or blank canvas must not pass as a successful render: + # require a real spread of pixels away from the project background. + colors = dict((rgb, count) for count, rgb in image.getcolors(image.width * image.height)) + drawn = sum(count for rgb, count in colors.items() + if max(abs(rgb[0] - 17), abs(rgb[1] - 20), abs(rgb[2] - 28)) > 30) + assert drawn > 300, name + print('PASS', name) + return image + +# Every setup at five progress steps; rays must grow (frames differ) and the +# rendering must be byte-deterministic on repeat. +frames = {} +for setup in ['lens-diagram', 'refraction', 'tir', 'mirror', 'dispersion']: + for p in [0, 0.25, 0.5, 0.75, 1]: + name = f'{setup}-{int(p * 100):03}' + frames[name] = render(name, setup=setup, progress=p) + pngs = [(WORK / f'{setup}-{p:03}.png').read_bytes() for p in [0, 25, 50, 75, 100]] + assert len(set(pngs)) == 5, setup + render(f'{setup}-repeat', setup=setup, progress=0.5) + assert pngs[2] == (WORK / f'{setup}-repeat.png').read_bytes(), setup + +# Parameter variations that must change the picture. +frames['lens-diverging'] = render('lens-diverging', setup='lens-diagram', progress=1, lens_type='diverging') +assert frames['lens-diagram-100'].tobytes() != frames['lens-diverging'].tobytes() +frames['lens-magnifier'] = render('lens-magnifier', setup='lens-diagram', progress=1, object_distance=12, object_height=10, focal_length=20) +assert frames['lens-diagram-100'].tobytes() != frames['lens-magnifier'].tobytes() +frames['lens-at-focus'] = render('lens-at-focus', setup='lens-diagram', object_distance=20) +frames['mirror-concave-virtual'] = render('mirror-concave-virtual', setup='mirror', object_distance=10) +frames['mirror-convex'] = render('mirror-convex', setup='mirror', progress=1, curvature=-30) +assert frames['mirror-100'].tobytes() != frames['mirror-convex'].tobytes() +# Magnified conjugates must stay on the diagram: the object between C and F +# (real, inverted, magnified) and between F and the mirror in the lens case. +frames['mirror-magnified'] = render('mirror-magnified', setup='mirror', progress=1, object_distance=20) +assert frames['mirror-100'].tobytes() != frames['mirror-magnified'].tobytes() +frames['lens-magnified-real'] = render('lens-magnified-real', setup='lens-diagram', progress=1, object_distance=25) +assert frames['lens-diagram-100'].tobytes() != frames['lens-magnified-real'].tobytes() +frames['refraction-steep'] = render('refraction-steep', setup='refraction', progress=1, angle_deg=70) +assert frames['refraction-100'].tobytes() != frames['refraction-steep'].tobytes() +frames['refraction-no-labels'] = render('refraction-no-labels', setup='refraction', progress=1, show_labels=False) +assert frames['refraction-100'].tobytes() != frames['refraction-no-labels'].tobytes() +frames['refraction-no-normal'] = render('refraction-no-normal', setup='refraction', progress=1, show_normal=False) +assert frames['refraction-100'].tobytes() != frames['refraction-no-normal'].tobytes() +frames['tir-past-critical'] = render('tir-past-critical', setup='tir', progress=1, angle_deg=60, index=1.5) +assert frames['tir-100'].tobytes() != frames['tir-past-critical'].tobytes() +frames['dispersion-single'] = render('dispersion-single', setup='dispersion', progress=1, spectrum=False) +assert frames['dispersion-100'].tobytes() != frames['dispersion-single'].tobytes() +frames['dispersion-few'] = render('dispersion-few', setup='dispersion', progress=1, ray_count=5) +assert frames['dispersion-100'].tobytes() != frames['dispersion-few'].tobytes() +render('dispersion-high-count', setup='dispersion', progress=1, ray_count=64) +render('dispersion-internal-bounce', setup='dispersion', progress=1, angle_deg=5, index=1.75, ray_count=64) +render('dispersion-corner', setup='dispersion', angle_deg=0) +frames['dispersion-flint'] = render('dispersion-flint', setup='dispersion', progress=1, index=1.9) +assert frames['dispersion-100'].tobytes() != frames['dispersion-flint'].tobytes() +render('tir-tir-impossible', setup='tir', progress=1, index=1.0, index_1=1.4) # no TIR, still draws +render('accent', setup='lens-diagram', progress=1, accent=[120, 255, 120, 255]) + +# Host sampling of a keyframed progress must reproduce the static midpoint. +clip['animations'] = [{'target': {'Param': 'progress'}, 'keys': { + '0': {'value': {'Number': 0.0}, 'interpolation': 'Linear'}, + '705600000': {'value': {'Number': 1.0}, 'interpolation': 'Hold'}}}] +assert frames['dispersion-050'].tobytes() == render('keyframed', frame=15, setup='dispersion', progress=0).tobytes() +clip['animations'] = [] + +# A portrait-ish canvas keeps the layout sane (min-edge scaling). +project['width'], project['height'] = 720, 1280 +render('portrait', setup='lens-diagram', progress=1) +project['width'], project['height'] = 1280, 720 +if '--screenshots' in sys.argv: + out = ROOT / 'screenshots' + out.mkdir(exist_ok=True) + names = { + 'lens-diagram': 'lens-converging', + 'refraction': 'refraction', + 'tir': 'tir', + 'mirror': 'mirror-concave', + 'dispersion': 'dispersion', + } + for setup, label in names.items(): + for p in [0, 25, 50, 75, 100]: + frames[f'{setup}-{p:03}'].save(out / f'{label}-{p:03}.png', optimize=True) + for name in ['lens-diverging', 'lens-magnifier', 'lens-magnified-real', 'mirror-convex', 'mirror-concave-virtual', 'mirror-magnified']: + frames[name].save(out / f'{name}.png', optimize=True) +print('All released-host checks passed') diff --git a/community/optics/src/diagram.rs b/community/optics/src/diagram.rs new file mode 100644 index 0000000..efb0367 --- /dev/null +++ b/community/optics/src/diagram.rs @@ -0,0 +1,600 @@ +use std::f64::consts::FRAC_PI_2; + +use crate::draw::{Painter, Palette, Rgba}; +use crate::geom::{self, conjugates, eased, fmt, partial_polyline, V}; +use crate::spectrum; +use crate::trace::{self, Surface}; + +const OUTLINE: Rgba = Rgba::new(215, 222, 235, 220); + +fn phase(progress: f64, start: f64, end: f64) -> f64 { + eased((progress - start) / (end - start)) +} + +pub struct Diagram<'a> { + pub painter: &'a mut Painter, + pub palette: &'a Palette, + pub progress: f64, + pub unit: f64, + pub half_width: f64, + pub half_height: f64, + pub labels: bool, + pub normal: bool, + pub focal: bool, +} + +#[derive(Debug)] +pub struct PrincipalRay { + pub hit: V, + pub outgoing: V, +} + +/// Object to the left, y up. `side` is +1 for transmission and -1 for +/// reflection. Slopes are measured along the outgoing propagation axis. +pub fn principal_rays( + f: f64, + distance: f64, + height: f64, + side: f64, + image_height: Option, +) -> [Option; 3] { + let ray = |y, slope| PrincipalRay { + hit: V::new(0.0, y), + outgoing: V::new(side, slope).unit(), + }; + [ + Some(ray(height, -height / f)), + Some(ray(0.0, -height / distance)), + image_height.map(|y| ray(y, 0.0)), + ] +} + +/// Equilateral prism, with the incident ray aimed at the middle of its left +/// face. Positive incidence rotates the inward normal toward the apex. +pub fn prism_beam(unit: f64, angle: f64) -> ([V; 3], V, V) { + let side = 0.45 * unit; + let height = side * 3.0_f64.sqrt() / 2.0; + let center = V::new(-0.08 * unit, 0.0); + let corners = [ + center + V::new(0.0, height * 2.0 / 3.0), + center + V::new(-side / 2.0, -height / 3.0), + center + V::new(side / 2.0, -height / 3.0), + ]; + let normal = (corners[1] - corners[0]).unit().perp(); + let (sin, cos) = angle.sin_cos(); + let incident = normal * cos + normal.perp() * sin; + (corners, corners[0].lerp(corners[1], 0.5), incident) +} + +/// Shrink a magnified principal-ray construction to the diagram bounds by +/// scaling the focal length, the distances and the heights together. The +/// thin-lens/mirror equations are scale invariant, so the magnification and +/// every angle stay the same while the image arrow and the third (focal or +/// centre) ray, which hit the element at m·height, come back on screen. This +/// is what keeps concave-mirror setups between C and F, or inside F, showing +/// their (strongly magnified) image instead of dropping it. +fn conjugate_fit_divisor(image: Option, unit: f64, half_width: f64) -> f64 { + let Some(point) = image else { + return 1.0; + }; + // 98% of the image-arrow guard in `principal`, so the scaled result can + // never sit exactly on the cut-off; the ray budget is the 0.36·unit + // aperture with its own margin. + (point.x.abs() / (0.98 * (half_width - 0.075 * unit))) + .max(point.y.abs() / (0.98 * 0.39 * unit)) + .max(point.y.abs() / (0.85 * 0.36 * unit)) + .max(1.0) +} + +impl Diagram<'_> { + fn font(&self) -> f64 { + (0.031 * self.unit).max(1.0) + } + + fn width(&self) -> f64 { + (0.004 * self.unit).max(0.6) + } + + fn guide(&mut self, from: V, to: V, color: Rgba) { + self.painter.dashed( + from, + to, + self.width() * 0.44, + 0.010 * self.unit, + 0.008 * self.unit, + color, + ); + } + + fn label(&mut self, text: &str, at: V, opacity: f64) { + if self.labels { + self.painter.label( + text, + at, + self.font(), + self.palette.label.with_alpha(opacity), + ); + } + } + + /// Point along a ray at the edge of the padded diagram bounds. + fn edge(&self, pos: V, dir: V, margin: f64) -> V { + fn limit(x: f64, dx: f64, half: f64) -> f64 { + if dx.abs() < 1e-12 { + f64::INFINITY + } else { + (half.copysign(dx) - x) / dx + } + } + let distance = limit(pos.x, dir.x, self.half_width - margin).min(limit( + pos.y, + dir.y, + self.half_height.min(self.unit * 0.50) - margin, + )); + pos + dir * distance.max(0.0) + } + + fn arrow(&mut self, a: V, b: V, fraction: f64, color: Rgba) { + let length = (b - a).length(); + if length >= 0.045 * self.unit { + self.painter + .arrow_head(a.lerp(b, fraction), b - a, 0.014 * self.unit, color); + } + } + + fn grow_ray(&mut self, points: &[V], growth: f64, color: Rgba, arrows: bool) { + let width = self.width(); + self.painter + .stroke(&partial_polyline(points, growth), width, color); + if arrows && growth >= 1.0 { + for leg in points.windows(2) { + self.arrow(leg[0], leg[1], 0.55, color); + } + } + } + + pub fn principal(&mut self, f: f64, distance: f64, object_height: f64, mirror: bool) { + let u = self.unit; + let side = if mirror { -1.0 } else { 1.0 }; + let distance = distance.min(self.half_width - 0.10 * u); + // Classify the conjugate at the original scale, before fitting can + // shrink the focal gap below the near-infinity tolerance. + let image = conjugates(f, distance).map(|(d, m)| V::new(side * d, m * object_height)); + let fit = conjugate_fit_divisor(image, u, self.half_width); + let (f, distance, object_height) = (f / fit, distance / fit, object_height / fit); + let object = V::new(-distance, 0.0); + let tip = V::new(-distance, object_height); + let image = image.map(|point| point / fit); + let aperture = 0.36 * u; + let rays = principal_rays(f, distance, object_height, side, image.map(|p| p.y)); + let height = rays + .iter() + .flatten() + .filter(|r| r.hit.y.abs() <= aperture) + .map(|r| r.hit.y.abs()) + .fold(0.19 * u, f64::max) + + 0.025 * u; + let color = self.palette.ray; + let object_color = self.palette.object; + let image_color = self.palette.image; + let progress = self.progress; + let labels = phase(progress, 0.74, 1.0); + let name = match (mirror, f > 0.0) { + (true, true) => "Concave mirror", + (true, false) => "Convex mirror", + (false, true) => "Converging lens", + (false, false) => "Diverging lens", + }; + + self.guide( + V::new(-self.half_width, 0.0), + V::new(self.half_width, 0.0), + self.palette.construction, + ); + self.element(height, f > 0.0, mirror); + self.painter + .arrow_line(object, tip, self.width(), 0.022 * u, object_color); + self.label(name, V::new(0.0, 0.452 * u), labels); + self.label("Object", tip + V::new(-0.040 * u, 0.051 * u), labels); + + if self.focal { + let mut marker = |x: f64, name: &str| { + if x.abs() <= self.half_width - 0.05 * u { + self.painter + .dot(V::new(x, 0.0), 0.005 * u, self.palette.marker); + self.label(name, V::new(x, -0.048 * u), labels); + } + }; + if mirror { + marker(-f, "F"); + marker(-2.0 * f, "C"); + } else { + marker(-f.abs(), "F"); + marker(f.abs(), "F′"); + marker(-2.0 * f.abs(), "2F"); + marker(2.0 * f.abs(), "2F′"); + } + } + + // Draw each incident leg and its continuation as one growing ray. + // Back-projections start only once the physical ray hits the element. + for (ray, (start, finish)) in + rays.into_iter() + .zip([(0.02, 0.34), (0.19, 0.52), (0.36, 0.69)]) + { + let Some(ray) = ray.filter(|r| r.hit.y.abs() <= aperture) else { + continue; + }; + let end = self.edge(ray.hit, ray.outgoing, 0.04 * u); + let growth = phase(progress, start, finish); + self.grow_ray(&[tip, ray.hit, end], growth, color, true); + if let Some(point) = image.filter(|p| side * p.x < 0.0) { + let incoming_length = (tip - ray.hit).length(); + let interaction = incoming_length / (incoming_length + (end - ray.hit).length()); + let limit = self.edge(ray.hit, -ray.outgoing, 0.035 * u); + let end = if (point - ray.hit).length() < (limit - ray.hit).length() { + point + } else { + limit + }; + self.guide( + ray.hit, + ray.hit.lerp(end, phase(growth, interaction, 1.0)), + color.with_alpha(0.72), + ); + } + } + + match image { + Some(point) + if point.x.abs() <= self.half_width - 0.075 * u && point.y.abs() <= 0.39 * u => + { + let real = side * point.x > 0.0; + let growth = phase(progress, 0.71, 0.88); + let base = V::new(point.x, 0.0); + let end = base.lerp(point, growth); + if growth > 0.0 { + if !real { + self.guide(base, end, image_color); + } else { + self.painter.stroke(&[base, end], self.width(), image_color); + } + } + if growth >= 1.0 && (point - base).length() > 0.002 * u { + self.painter.arrow_head( + point, + point - base, + (point.y.abs() * 0.45).min(0.022 * u), + image_color, + ); + } + let (label, y) = if real { + ("Real image", point.y - 0.062 * u) + } else if point.y < 0.09 * u && !mirror { + ("Virtual image", -0.114 * u) + } else { + ("Virtual image", point.y + 0.050 * u) + }; + let x = if real { + point.x - 0.105 * u * side + } else { + point.x + }; + let x = x.clamp(-self.half_width + 0.132 * u, self.half_width - 0.132 * u); + self.label(label, V::new(x, y), labels); + } + // Defensive: fitting scales finite conjugates inside the + // guard above, so this arm only catches a future regression. + Some(point) => self.label( + if side * point.x < 0.0 { + "Virtual image beyond frame" + } else { + "Real image beyond frame" + }, + V::new(0.0, -0.45 * u), + labels, + ), + None => self.label("Image at infinity", V::new(0.0, -0.45 * u), labels), + } + } + + fn element(&mut self, height: f64, positive: bool, mirror: bool) { + let u = self.unit; + let width = self.width() * 0.56; + if mirror { + // The reflecting plane is the paraxial reference. The hatched + // silhouette behind it distinguishes concave and convex elements. + let profile = |t: f64| { + let sag = if positive { 1.0 - t * t } else { t * t }; + V::new((0.004 + 0.030 * sag) * u, height * t) + }; + let back: Vec<_> = (-16..=16).map(|i| profile(f64::from(i) / 16.0)).collect(); + let mut cross_section = vec![V::new(0.0, -height)]; + cross_section.extend(&back); + cross_section.push(V::new(0.0, height)); + self.painter + .fill_polygon(&cross_section, self.palette.glass); + cross_section.push(cross_section[0]); + self.painter.stroke(&cross_section, width, OUTLINE); + for i in -5..=5 { + let t = f64::from(i) / 5.0; + let a = profile(t); + self.painter.stroke( + &[a, a + V::new(0.018 * u, 0.009 * u)], + width, + self.palette.construction, + ); + } + } else { + let profile = |i: i32| { + let t = f64::from(i) / 16.0; + let x = if positive { + 0.041 * (1.0 - t * t) + } else { + 0.012 + 0.030 * t * t + }; + V::new(x * u, height * t) + }; + let mut outline: Vec<_> = (-16..=16).map(profile).collect(); + outline.extend((-16..=16).rev().map(|i| { + let q = profile(i); + V::new(-q.x, q.y) + })); + self.painter.fill_polygon(&outline, self.palette.glass); + outline.push(outline[0]); + self.painter.stroke(&outline, width, OUTLINE); + } + } + + fn slab(&mut self, top: f64, bottom: f64, lower_face: bool) { + let x = self.half_width; + let corners = [ + V::new(-x, top), + V::new(x, top), + V::new(x, bottom), + V::new(-x, bottom), + ]; + self.painter.fill_polygon(&corners, self.palette.glass); + self.painter + .stroke(&corners[..2], self.width() * 0.53, OUTLINE); + if lower_face { + self.painter + .stroke(&corners[2..], self.width() * 0.53, OUTLINE); + } + } + + fn arc(&mut self, center: V, radius: f64, normal_angle: f64, angle: f64, growth: f64) { + if growth > 0.0 && angle.abs() > 1e-6 { + self.painter.arc( + center, + radius * self.unit, + normal_angle, + normal_angle + angle * growth, + self.width() * 0.50, + self.palette.marker, + ); + } + } + + pub fn refraction(&mut self, outside: f64, inside: f64, angle: f64) { + let u = self.unit; + let top = 0.12 * u; + let bottom = -0.17 * u; + let hit = V::new(-0.17 * u, top); + let (sin, cos) = angle.sin_cos(); + let incident = V::new(sin, -cos); + let source = self.edge(hit, -incident, 0.05 * u); + let x = self.half_width; + let surfaces = [ + Surface { + a: V::new(-x, top), + b: V::new(x, top), + }, + Surface { + a: V::new(-x, bottom), + b: V::new(x, bottom), + }, + ]; + let trace = trace::trace(source, incident, &surfaces, outside, inside, 4); + self.slab(top, bottom, true); + if self.normal { + self.guide( + hit + V::new(0.0, -0.195 * u), + hit + V::new(0.0, 0.215 * u), + self.palette.construction, + ); + } + let mut points = vec![source]; + points.extend(trace.hits); + if let Some(dir) = trace.onward { + let last = *points.last().unwrap(); + points.push(self.edge(last, dir, if trace.inside { 0.0 } else { 0.025 * u })); + } + self.grow_ray( + &points, + phase(self.progress, 0.02, 0.73), + self.palette.ray, + true, + ); + + let arcs = phase(self.progress, 0.50, 0.80); + let labels = phase(self.progress, 0.72, 1.0); + self.arc(hit, 0.084, FRAC_PI_2, angle, arcs); + self.label( + &format!("θ₁ = {}°", fmt(angle.to_degrees(), 1)), + hit + V::new(0.125 * u, 0.16 * u), + labels, + ); + self.label( + &format!("n₁ = {}", fmt(outside, 2)), + V::new(0.31 * u, 0.25 * u), + labels, + ); + self.label( + &format!("n₂ = {}", fmt(inside, 2)), + V::new(-0.33 * u, -0.095 * u), + labels, + ); + if let Some(transmitted) = geom::snell_angles(angle, outside, inside) { + self.arc(hit, 0.102, -FRAC_PI_2, transmitted, arcs); + self.label( + &format!("θ₂ = {}°", fmt(transmitted.to_degrees(), 1)), + hit + V::new(0.25 * u, -0.19 * u), + labels, + ); + self.label("n₁ sin θ₁ = n₂ sin θ₂", V::new(0.03 * u, 0.415 * u), labels); + } else { + self.arc(hit, 0.102, FRAC_PI_2, -angle, arcs); + self.label( + "Total internal reflection", + V::new(0.03 * u, 0.415 * u), + labels, + ); + } + } + + pub fn total_internal_reflection(&mut self, outside: f64, inside: f64, max_angle: f64) { + let u = self.unit; + let hit = V::new(-0.055 * u, 0.0); + let angle = max_angle * eased(self.progress); + let (sin, cos) = angle.sin_cos(); + let incident = V::new(sin, cos); + let reflected = geom::reflect(incident, V::new(0.0, 1.0)); + let transmitted = geom::refract(incident, V::new(0.0, 1.0), inside, outside); + let ray = self.palette.ray; + + self.slab(0.0, -self.half_height, false); + if self.normal { + self.guide( + hit - V::new(0.0, 0.28 * u), + hit + V::new(0.0, 0.24 * u), + self.palette.construction, + ); + } + let start = self.edge(hit, -incident, 0.05 * u); + self.grow_ray(&[start, hit], phase(self.progress, 0.0, 0.30), ray, true); + let branch = phase(self.progress, 0.30, 0.58); + if let Some(dir) = transmitted { + self.grow_ray(&[hit, self.edge(hit, dir, 0.05 * u)], branch, ray, true); + } + if inside != outside { + let color = ray.with_alpha(if transmitted.is_some() { 0.35 } else { 1.0 }); + self.grow_ray( + &[hit, self.edge(hit, reflected, 0.05 * u)], + branch, + color, + true, + ); + } + let markers = phase(self.progress, 0.26, 0.51); + self.arc(hit, 0.12, -FRAC_PI_2, -angle, markers); + self.label( + &format!("θ₁ = {}°", fmt(angle.to_degrees(), 1)), + start.lerp(hit, 0.52) + incident.perp() * (0.10 * u), + markers, + ); + // The ray starts in the slab, so the incident medium n₁ is the lower + // one — the same n₁ = incident-medium convention as the refraction + // setup, which is why the two labels swap sides relative to `outside` + // and `inside` there. + self.label( + &format!("n₁ = {}", fmt(inside, 2)), + V::new(0.34 * u, -0.24 * u), + markers, + ); + self.label( + &format!("n₂ = {}", fmt(outside, 2)), + V::new(-0.33 * u, 0.28 * u), + markers, + ); + if let Some(critical) = geom::critical_angle(inside, outside) { + let (s, c) = critical.sin_cos(); + self.guide( + hit, + hit - V::new(s, c) * (0.22 * u * markers), + self.palette.marker.with_alpha(0.72), + ); + // Above the slab and left of the hit, outside both ray sweeps. + self.label( + &format!("sin θc = n₂/n₁ → θc = {}°", fmt(critical.to_degrees(), 1)), + V::new(-0.28 * u, 0.36 * u), + markers, + ); + } + if transmitted.is_none() { + self.label("Total internal reflection", V::new(0.0, 0.40 * u), markers); + } + } + + pub fn dispersion(&mut self, index: f64, angle: f64, count: usize, spectrum_on: bool) { + let u = self.unit; + let (corners, entry, incident) = prism_beam(u, angle); + let [top, left, right] = corners; + self.painter.fill_polygon(&corners, self.palette.glass); + self.painter + .stroke(&[top, left, right, top], self.width() * 0.52, OUTLINE); + let surfaces = [ + Surface { a: top, b: left }, + Surface { a: left, b: right }, + Surface { a: right, b: top }, + ]; + let wavelengths = spectrum::sample_wavelengths(if spectrum_on { count } else { 1 }); + let budget = trace::MAX_SEGMENTS / wavelengths.len(); + let source = self.edge(entry, -incident, 0.045 * u); + let white = self.palette.white_beam; + self.grow_ray( + &[source, entry], + phase(self.progress, 0.02, 0.27), + white, + true, + ); + + let growth = phase(self.progress, 0.27, 0.91); + let labels = phase(self.progress, 0.90, 1.0); + let mut exits = Vec::new(); + for wavelength in wavelengths { + let n = spectrum::index_at(index, wavelength); + let trace = trace::trace(source, incident, &surfaces, 1.0, n, budget); + let mut path = trace.hits; + if let (Some(&last), Some(dir)) = (path.last(), trace.onward) { + let end = self.edge(last, dir, 0.04 * u); + path.push(end); + if !trace.inside && path.len() >= 3 { + exits.push((wavelength, last, end, dir)); + } + } + let color = if spectrum_on { + let (r, g, b) = spectrum::wavelength_rgb(wavelength); + Rgba::new(r, g, b, 255) + } else { + self.palette.ray + }; + self.grow_ray(&path, growth, color, !spectrum_on); + } + self.label( + &format!("n (550 nm) = {}", fmt(index, 2)), + V::new(0.0, 0.39 * u), + labels, + ); + if spectrum_on { + if let [first, .., last] = exits.as_slice() { + let (_, a, b, dir) = *first; + let (_, c, d, _) = *last; + // Label only separated exits; a tight fan would overlap the text. + if (b - d).length() > 0.032 * u { + let side = (b - d).dot(dir.perp()).signum(); + self.label( + &format!("{:.0} nm", first.0), + a.lerp(b, 0.72) + dir.perp() * (side * 0.047 * u), + labels, + ); + self.label( + &format!("{:.0} nm", last.0), + c.lerp(d, 0.72) - dir.perp() * (side * 0.047 * u), + labels, + ); + } + } + } + } +} diff --git a/community/optics/src/draw.rs b/community/optics/src/draw.rs new file mode 100644 index 0000000..66682fe --- /dev/null +++ b/community/optics/src/draw.rs @@ -0,0 +1,250 @@ +//! Scene emission: converts math-frame geometry into AniMathIO vector draw +//! commands in canvas coordinates (y down). Text uses the host-shaped +//! `TextRun` (embedded DejaVu Sans), so labels render identically everywhere. +//! Element counts are bounded by `MAX_ELEMENTS`. + +use super::{ + Color, DrawCommand, PathVerb, Point, Size, StrokeCap, StrokeJoin, StrokeStyle, TextAlignment, + TextElement, +}; +use crate::geom::V; + +pub const MAX_ELEMENTS: usize = 4_000; +const MAX_DASHES_PER_LINE: usize = 160; +const ARC_POINTS: usize = 48; + +/// Straight-alpha RGBA colour. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Rgba { + pub r: u8, + pub g: u8, + pub b: u8, + pub a: u8, +} + +impl Rgba { + pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self { + Self { r, g, b, a } + } + pub fn with_alpha(self, alpha: f64) -> Self { + let a = (self.a as f64 * alpha.clamp(0.0, 1.0)).round() as i64; + Self { + a: a.clamp(0, 255) as u8, + ..self + } + } + fn wit(self) -> Color { + Color { + r: self.r, + g: self.g, + b: self.b, + a: self.a, + } + } +} + +/// Palette: construction lines are muted, rays take the accent colour, the +/// object/image arrows and glass fills are fixed teaching-diagram colours. +pub struct Palette { + pub ray: Rgba, + pub construction: Rgba, + pub label: Rgba, + pub object: Rgba, + pub image: Rgba, + pub glass: Rgba, + pub marker: Rgba, + pub white_beam: Rgba, +} + +impl Palette { + pub fn new(accent: Color) -> Self { + Self { + ray: Rgba::new(accent.r, accent.g, accent.b, accent.a), + construction: Rgba::new(150, 158, 172, 150), + label: Rgba::new(205, 210, 220, 255), + object: Rgba::new(235, 238, 245, 255), + image: Rgba::new(126, 226, 142, 255), + glass: Rgba::new(96, 165, 250, 38), + marker: Rgba::new(103, 200, 235, 255), + white_beam: Rgba::new(250, 248, 240, 255), + } + } +} + +/// Emits ordered draw commands. All geometry comes in through the y-up math +/// frame; `pt` converts to canvas pixels. +pub struct Painter { + pub elements: Vec, + width: f32, + height: f32, + full: bool, +} + +impl Painter { + pub fn new(size: Size) -> Self { + Self { + elements: Vec::new(), + width: size.width as f32, + height: size.height as f32, + full: false, + } + } + + /// Math frame (origin canvas centre, y up) to canvas pixels. + pub fn pt(&self, v: V) -> Point { + Point { + x: self.width * 0.5 + v.x as f32, + y: self.height * 0.5 - v.y as f32, + } + } + + pub fn push(&mut self, cmd: DrawCommand) -> bool { + if self.elements.len() >= MAX_ELEMENTS { + self.full = true; + return false; + } + self.elements.push(cmd); + true + } + + pub fn is_full(&self) -> bool { + self.full + } + + /// Solid polyline stroke through math-frame points. + pub fn stroke(&mut self, points: &[V], width: f64, color: Rgba) { + if points.len() < 2 { + return; + } + let path: Vec = points + .iter() + .enumerate() + .map(|(i, p)| { + let pt = self.pt(*p); + if i == 0 { + PathVerb::MoveTo(pt) + } else { + PathVerb::LineTo(pt) + } + }) + .collect(); + self.push(DrawCommand::StrokePath(( + path, + StrokeStyle { + width: width as f32, + color: color.wit(), + cap: StrokeCap::Round, + join: StrokeJoin::Round, + }, + ))); + } + + /// Dashed line between two math-frame points (the scene format has no dash + /// attribute, so this emits short strokes; bounded per line). + pub fn dashed(&mut self, a: V, b: V, width: f64, dash: f64, gap: f64, color: Rgba) { + let total = (b - a).length(); + if total < 1e-9 { + return; + } + let dir = (b - a).unit(); + let period = (dash + gap).max(total / MAX_DASHES_PER_LINE as f64); + let count = ((total / period).ceil() as usize).min(MAX_DASHES_PER_LINE); + let mut s = 0.0; + for _ in 0..count { + if s >= total { + break; + } + let e = s + dash.min(total - s); + self.stroke(&[a + dir * s, a + dir * e], width, color); + s += period; + } + } + + /// Filled arrow head at `tip`, pointing along `dir`, size in pixels. + pub fn arrow_head(&mut self, tip: V, dir: V, size: f64, color: Rgba) { + let d = dir.unit(); + let side = d.perp() * (size * 0.5); + let base = tip - d * size; + let path = vec![ + PathVerb::MoveTo(self.pt(tip)), + PathVerb::LineTo(self.pt(base + side)), + PathVerb::LineTo(self.pt(base - side)), + PathVerb::Close, + ]; + self.push(DrawCommand::FillPath((path, color.wit()))); + } + + /// Line with an arrow head at the end (object/image arrows). + pub fn arrow_line(&mut self, from: V, to: V, width: f64, head: f64, color: Rgba) { + self.stroke(&[from, to], width, color); + self.arrow_head(to, to - from, head, color); + } + + /// Filled convex polygon (glass bodies). + pub fn fill_polygon(&mut self, points: &[V], color: Rgba) { + if points.len() < 3 { + return; + } + let path: Vec = points + .iter() + .enumerate() + .map(|(i, p)| { + let pt = self.pt(*p); + if i == 0 { + PathVerb::MoveTo(pt) + } else { + PathVerb::LineTo(pt) + } + }) + .collect(); + let mut path = path; + path.push(PathVerb::Close); + self.push(DrawCommand::FillPath((path, color.wit()))); + } + + /// Circle arc centred at `c` from `start` to `end` radians (math frame). + pub fn arc(&mut self, c: V, radius: f64, start: f64, end: f64, width: f64, color: Rgba) { + let steps = ARC_POINTS; + let mut points = Vec::with_capacity(steps + 1); + for i in 0..=steps { + let a = start + (end - start) * i as f64 / steps as f64; + points.push(V::new(c.x + radius * a.cos(), c.y + radius * a.sin())); + } + self.stroke(&points, width, color); + } + + /// Small filled dot (focal markers, hit points). + pub fn dot(&mut self, at: V, radius: f64, color: Rgba) { + let steps = 20; + let mut path = Vec::with_capacity(steps + 2); + for i in 0..=steps { + let a = std::f64::consts::TAU * i as f64 / steps as f64; + let p = V::new(at.x + radius * a.cos(), at.y + radius * a.sin()); + let verb = if i == 0 { + PathVerb::MoveTo(self.pt(p)) + } else { + PathVerb::LineTo(self.pt(p)) + }; + path.push(verb); + } + path.push(PathVerb::Close); + self.push(DrawCommand::FillPath((path, color.wit()))); + } + + /// Host-shaped, horizontally centred text. Canvas text starts at the top + /// of its line box; offset that box to put the glyphs near `at`. + pub fn label(&mut self, text: &str, at: V, font_size: f64, color: Rgba) { + if color.a == 0 || text.is_empty() { + return; + } + let p = self.pt(at); + self.push(DrawCommand::TextRun(TextElement { + align: TextAlignment::Center, + text: text.to_string(), + font_size: font_size as f32, + x: p.x - self.width * 0.5, + y: p.y - font_size as f32 * 0.63, + color: color.wit(), + })); + } +} diff --git a/community/optics/src/geom.rs b/community/optics/src/geom.rs new file mode 100644 index 0000000..a61ad6f --- /dev/null +++ b/community/optics/src/geom.rs @@ -0,0 +1,209 @@ +//! Pure 2D geometry and optics math. All of it is textbook vector algebra; the +//! refraction/reflection conventions follow the tracing behaviour studied in +//! ricktu288/ray-optics (Apache-2.0; see NOTICE). Computed in a right-handed, +//! y-up math frame; the caller converts to canvas coordinates on emission. + +use std::ops::{Add, Div, Mul, Neg, Sub}; + +/// Finite 2D vector / point. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct V { + pub x: f64, + pub y: f64, +} + +impl V { + pub const fn new(x: f64, y: f64) -> Self { + Self { x, y } + } + pub fn dot(self, o: Self) -> f64 { + self.x * o.x + self.y * o.y + } + pub fn perp(self) -> Self { + // Rotate 90 degrees counter-clockwise. + Self::new(-self.y, self.x) + } + pub fn length2(self) -> f64 { + self.dot(self) + } + pub fn length(self) -> f64 { + self.length2().sqrt() + } + pub fn unit(self) -> Self { + let len = self.length(); + if len > 1e-12 { + self / len + } else { + Self::new(1.0, 0.0) + } + } + pub fn lerp(self, o: Self, t: f64) -> Self { + self + (o - self) * t + } + /// Smallest positive solution t with `self + dir * t` on segment `[a, b]`; + /// `t` is along the ray, the hit point is `self + dir * t`. + pub fn ray_segment_hit(self, dir: Self, a: Self, b: Self) -> Option { + let e = b - a; + let denom = dir.perp().dot(e); + if denom.abs() < 1e-12 { + return None; + } + let t = (a - self).perp().dot(e) / denom; + let u = (a - self).perp().dot(dir) / denom; + if t > 1e-9 && (-1e-9..=1.0 + 1e-9).contains(&u) { + Some(t) + } else { + None + } + } +} + +impl Add for V { + type Output = Self; + fn add(self, o: Self) -> Self { + Self::new(self.x + o.x, self.y + o.y) + } +} +impl Sub for V { + type Output = Self; + fn sub(self, o: Self) -> Self { + Self::new(self.x - o.x, self.y - o.y) + } +} +impl Mul for V { + type Output = Self; + fn mul(self, k: f64) -> Self { + Self::new(self.x * k, self.y * k) + } +} +impl Div for V { + type Output = Self; + fn div(self, k: f64) -> Self { + Self::new(self.x / k, self.y / k) + } +} +impl Neg for V { + type Output = Self; + fn neg(self) -> Self { + Self::new(-self.x, -self.y) + } +} + +/// Intersection of the lines `(a1, a2)` and `(b1, b2)`, if not parallel. +#[cfg(test)] +pub fn lines_intersection(a1: V, a2: V, b1: V, b2: V) -> Option { + let e = a2 - a1; + let f = b2 - b1; + let denom = e.perp().dot(f); + if denom.abs() < 1e-12 { + return None; + } + let t = (b1 - a1).perp().dot(f) / denom; + Some(a1 + e * t) +} + +/// Mirror reflection of unit direction `d` about unit normal `n`. +pub fn reflect(d: V, n: V) -> V { + d - n * (2.0 * d.dot(n)) +} + +/// Refraction of unit direction `d` across a surface with unit normal `n` +/// oriented against the incident ray (`d.dot(n) < 0`), from medium `n1` into +/// medium `n2` (Snell's law). Returns `None` on total internal reflection. +/// Same convention as the ray-optics tracing engine: the normal is flipped to +/// face the incident side, so boundary orientation never matters. +pub fn refract(d: V, n: V, n1: f64, n2: f64) -> Option { + if n1 == n2 { + return Some(d); + } + let tangent = n.perp(); + let sin_t = (n1 / n2) * d.dot(tangent); + if sin_t.abs() > 1.0 + 1e-12 { + return None; + } + let sin_t = sin_t.clamp(-1.0, 1.0); + let normal = if d.dot(n) > 0.0 { -n } else { n }; + Some(tangent * sin_t - normal * (1.0 - sin_t * sin_t).sqrt()) +} + +/// Snell angle pair in radians: `n1 * sin(i) = n2 * sin(t)`, `None` on TIR. +pub fn snell_angles(incident: f64, n1: f64, n2: f64) -> Option { + let (sin, cos) = incident.sin_cos(); + refract(V::new(sin, -cos), V::new(0.0, 1.0), n1, n2).map(|ray| ray.x.asin()) +} + +/// Critical angle (radians) for light going from `n_dense` into `n_rare`, +/// `None` when no total internal reflection is possible. +pub fn critical_angle(n_dense: f64, n_rare: f64) -> Option { + if n_dense <= n_rare { + None + } else { + Some((n_rare / n_dense).asin()) + } +} + +/// Thin lens / spherical mirror conjugate distances. `f` is the signed focal +/// length, `d_o` the object distance from the element. Returns +/// `(d_i, magnification)` from `1/f = 1/d_o + 1/d_i`, `m = -d_i / d_o`. +/// Positive `d_i` is a real image on the transmission (lens) / reflection +/// (mirror, in front) side; negative means a virtual image. +pub fn conjugates(f: f64, d_o: f64) -> Option<(f64, f64)> { + if f.abs() < 1e-12 || (d_o - f).abs() < 1e-9 { + return None; // Object at the focal plane images at infinity. + } + let d_i = f * d_o / (d_o - f); + let m = -d_i / d_o; + Some((d_i, m)) +} + +/// Total polyline length. +pub fn polyline_length(points: &[V]) -> f64 { + points.windows(2).map(|w| (w[1] - w[0]).length()).sum() +} + +/// Prefix of the polyline that covers fraction `t` of its total length. `t <= 0` +/// yields an empty vector, `t >= 1` the whole polyline; intermediate values cut +/// the crossing segment at exact length. This is what makes every ray grow with +/// the animation parameter. +pub fn partial_polyline(points: &[V], t: f64) -> Vec { + if points.len() < 2 || t <= 0.0 { + return Vec::new(); + } + if t >= 1.0 { + return points.to_vec(); + } + let total = polyline_length(points); + let mut budget = total * t; + let mut out = vec![points[0]]; + for w in points.windows(2) { + let seg = (w[1] - w[0]).length(); + if seg <= 1e-12 { + continue; + } + if budget >= seg { + out.push(w[1]); + budget -= seg; + } else { + out.push(w[0].lerp(w[1], budget / seg)); + break; + } + } + out +} + +/// Smooth 0..1 easing (smoothstep) with the input clamped. +pub fn eased(t: f64) -> f64 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// Format a float for a diagram label: fixed decimals, ASCII only, `-0` cleaned. +pub fn fmt(value: f64, decimals: usize) -> String { + let mut text = format!("{value:.decimals$}"); + if text == "-0" + || text.starts_with("-0.") && text.trim_start_matches("-0.").parse::() == Ok(0.0) + { + text = text.trim_start_matches('-').to_string(); + } + text +} diff --git a/community/optics/src/lib.rs b/community/optics/src/lib.rs new file mode 100644 index 0000000..b38a1cb --- /dev/null +++ b/community/optics/src/lib.rs @@ -0,0 +1,331 @@ +//! Ray Optics — animated ray-optics diagrams for AniMathIO. +//! Behavioral/structural reference: ricktu288/ray-optics (Apache-2.0); the +//! tracing ideas were studied and reimplemented in Rust, no upstream source +//! is copied. See NOTICE. +wit_bindgen::generate!({ path: "wit", world: "source-plugin" }); +use animathio::plugin::types::*; + +mod diagram; +mod draw; +mod geom; +mod spectrum; +mod trace; + +use draw::{Painter, Palette}; + +const VERSION: &str = "0.1.0"; +const DESCRIPTION: &str = "Animated ray-optics diagrams: thin lens and mirror principal rays, Snell refraction, total internal reflection and prism dispersion"; +const SETUPS: [&str; 5] = ["lens-diagram", "refraction", "tir", "mirror", "dispersion"]; +const MAX_WAVELENGTH_SAMPLES: usize = spectrum::MAX_SPECTRAL_RAYS; +const MAX_ELEMENTS: usize = draw::MAX_ELEMENTS; + +struct RayOptics; + +fn error(message: &str) -> Diagnostic { + Diagnostic { + code: "invalid-input".into(), + message: message.into(), + metadata: vec![], + } +} + +fn string<'a>(params: &'a [ParamEntry], id: &str, default: &'a str) -> &'a str { + params + .iter() + .find(|p| p.id == id) + .and_then(|p| match &p.value { + ParamValue::String(s) | ParamValue::EnumChoice(s) => Some(s.as_str()), + _ => None, + }) + .unwrap_or(default) +} + +fn number( + params: &[ParamEntry], + id: &str, + default: f64, + min: f64, + max: f64, +) -> Result { + let n = params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Number(n) => Some(n), + _ => None, + }) + .unwrap_or(default); + if !n.is_finite() { + return Err(error("Numeric parameters must be finite")); + } + Ok(n.clamp(min, max)) +} + +fn boolean(params: &[ParamEntry], id: &str, default: bool) -> bool { + params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Bool(b) => Some(b), + _ => None, + }) + .unwrap_or(default) +} + +fn color(params: &[ParamEntry], id: &str, default: Color) -> Color { + params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Color(c) => Some(c), + _ => None, + }) + .unwrap_or(default) +} + +fn num_param(id: &str, label: &str, min: f64, max: f64, default: f64, step: f64) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Number(NumberRange { + min, + max, + default, + step, + }), + } +} +fn enum_param(id: &str, label: &str, options: &[&str], default: &str) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::EnumChoice(EnumParam { + options: options.iter().map(|s| (*s).into()).collect(), + default: default.into(), + }), + } +} +fn bool_param(id: &str, label: &str, default: bool) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Bool(BoolParam { default }), + } +} +fn color_param(id: &str, label: &str, default: Color) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Color(ColorParam { default }), + } +} + +fn validate_setup(setup: &str) -> Result<&'static str, Diagnostic> { + SETUPS + .iter() + .find(|s| **s == setup) + .copied() + .ok_or_else(|| error("Unsupported setup")) +} + +/// Signed paraxial focal length (f = R/2) of the mirror setup from the +/// `curvature` parameter, in percent of the canvas short edge. Negative +/// curvature is a convex mirror and gets a negative focal length; magnitudes +/// below the 10% radius floor use the floored radius, so 0 is concave. +fn mirror_focal(curvature: f64, unit: f64) -> f64 { + let radius = curvature.abs().max(10.0) / 100.0 * unit; + if curvature < 0.0 { + -radius / 2.0 + } else { + radius / 2.0 + } +} + +impl Guest for RayOptics { + fn describe() -> Manifest { + Manifest { + name: "Ray Optics".into(), + version: VERSION.into(), + description: DESCRIPTION.into(), + kinds: vec!["clip-source".into()], + metadata: vec![ + ("param.focal_length.unit".into(), "% of short edge".into()), + ( + "param.object_distance.unit".into(), + "% of short edge".into(), + ), + ("param.object_height.unit".into(), "% of short edge".into()), + ( + "param.curvature.unit".into(), + "% of short edge (radius)".into(), + ), + ("param.angle_deg.unit".into(), "degrees".into()), + ( + "param.progress.description".into(), + "drives ray growth and the TIR angle sweep".into(), + ), + ( + "param.ray_count.description".into(), + "spectral sample count in dispersion".into(), + ), + ], + params: vec![ + enum_param("setup", "Setup", &SETUPS, "lens-diagram"), + num_param("progress", "Progress", 0.0, 1.0, 1.0, 0.01), + enum_param( + "lens_type", + "Lens type", + &["converging", "diverging"], + "converging", + ), + num_param("focal_length", "Focal length (%)", 5.0, 50.0, 20.0, 0.5), + num_param( + "object_distance", + "Object distance (%)", + 5.0, + 90.0, + 35.0, + 0.5, + ), + num_param("object_height", "Object height (%)", 2.0, 30.0, 15.0, 0.5), + num_param( + "index_1", + "Index n₁ (surrounding medium)", + 1.0, + 2.5, + 1.0, + 0.01, + ), + num_param("index", "Index n₂ (element)", 1.0, 2.5, 1.5, 0.01), + num_param( + "curvature", + "Signed mirror radius (%)", + -50.0, + 50.0, + 30.0, + 0.5, + ), + num_param("angle_deg", "Incidence angle (°)", 0.0, 89.0, 45.0, 0.5), + num_param( + "ray_count", + "Spectral rays", + 1.0, + MAX_WAVELENGTH_SAMPLES as f64, + 12.0, + 1.0, + ), + bool_param("show_normal", "Show normal", true), + bool_param("show_labels", "Show labels", true), + bool_param("show_focal", "Show focal markers", true), + bool_param("spectrum", "Disperse into spectrum", true), + color_param( + "accent", + "Ray colour", + Color { + r: 255, + g: 205, + b: 66, + a: 255, + }, + ), + ], + } + } + + fn render_clip( + params: Vec, + _time_ticks: i64, + size: Size, + ) -> Result { + render(¶ms, size) + } +} + +fn render(params: &[ParamEntry], size: Size) -> Result { + if size.width == 0 || size.height == 0 { + return Err(error("Canvas dimensions must be positive")); + } + let setup = validate_setup(string(params, "setup", "lens-diagram"))?; + let progress = number(params, "progress", 1.0, 0.0, 1.0)?; + let unit = (size.width.min(size.height)) as f64; + let half_width = size.width as f64 / 2.0; + let half_height = size.height as f64 / 2.0; + + // Shared geometry parameters (percent-of-short-edge scaling keeps the + // diagrams resolution independent). + let focal = number(params, "focal_length", 20.0, 5.0, 50.0)? / 100.0 * unit; + let lens_sign = match string(params, "lens_type", "converging") { + "converging" => 1.0, + "diverging" => -1.0, + _ => return Err(error("Unsupported lens type")), + }; + let object_distance = number(params, "object_distance", 35.0, 5.0, 90.0)? / 100.0 * unit; + let object_height = number(params, "object_height", 15.0, 2.0, 30.0)? / 100.0 * unit; + let index_1 = number(params, "index_1", 1.0, 1.0, 2.5)?; + let index = number(params, "index", 1.5, 1.0, 2.5)?; + let curvature = number(params, "curvature", 30.0, -50.0, 50.0)?; + let mirror_focal = mirror_focal(curvature, unit); + let angle = number(params, "angle_deg", 45.0, 0.0, 89.0)?.to_radians(); + let ray_count = number( + params, + "ray_count", + 12.0, + 1.0, + MAX_WAVELENGTH_SAMPLES as f64, + )? + .round() as usize; + let show_normal = boolean(params, "show_normal", true); + let show_labels = boolean(params, "show_labels", true); + let show_focal = boolean(params, "show_focal", true); + let spectrum_on = boolean(params, "spectrum", true); + let accent = color( + params, + "accent", + Color { + r: 255, + g: 205, + b: 66, + a: 255, + }, + ); + + let palette = Palette::new(accent); + let mut painter = Painter::new(size); + let mut diagram = diagram::Diagram { + painter: &mut painter, + palette: &palette, + progress, + unit, + half_width, + half_height, + labels: show_labels, + normal: show_normal, + focal: show_focal, + }; + match setup { + "lens-diagram" => { + diagram.principal(lens_sign * focal, object_distance, object_height, false) + } + "mirror" => diagram.principal(mirror_focal, object_distance, object_height, true), + "refraction" => diagram.refraction(index_1, index, angle), + "tir" => diagram.total_internal_reflection(index_1, index, angle), + "dispersion" => diagram.dispersion(index, angle, ray_count, spectrum_on), + _ => return Err(error("Unsupported setup")), + } + if painter.is_full() { + return Err(Diagnostic { + code: "limit-exceeded".into(), + message: format!("scene exceeds {MAX_ELEMENTS} elements"), + metadata: vec![], + }); + } + Ok(Scene { + coordinate_space: CoordinateSpace::Canvas, + elements: painter.elements, + }) +} + +export!(RayOptics); + +#[cfg(test)] +mod tests; diff --git a/community/optics/src/spectrum.rs b/community/optics/src/spectrum.rs new file mode 100644 index 0000000..d06e1c3 --- /dev/null +++ b/community/optics/src/spectrum.rs @@ -0,0 +1,74 @@ +//! Wavelength-dependent refraction and spectral colours for the dispersion +//! setup. The index model is a two-term Cauchy equation calibrated so the +//! 550 nm index equals the plugin's `index` parameter. The colour mapping is +//! the standard piecewise approximation of the spectral locus (400–700 nm); +//! it is a display approximation, not a colorimetric conversion. + +/// Cauchy dispersion strength (µm²) of a glass whose 550 nm index is 1.5 — +/// about BK7 (B ≈ 0.004 µm²). The coefficient scales with n − 1, so weaker +/// media disperse proportionally less and an index of exactly 1 (vacuum) +/// disperses nothing. +const CAUCHY_B_AT_1_5: f64 = 0.004; +/// Reference index the coefficient above is quoted at. +const REFERENCE_N: f64 = 1.5; +/// Reference wavelength (µm) the plugin's `index` parameter is calibrated at. +const REFERENCE_UM: f64 = 0.55; + +/// Refractive index at `lambda_nm` for a medium whose 550 nm index is `base`. +pub fn index_at(base: f64, lambda_nm: f64) -> f64 { + let lambda_um = lambda_nm / 1000.0; + let b = CAUCHY_B_AT_1_5 * (base - 1.0) / (REFERENCE_N - 1.0); + let a = base - b / (REFERENCE_UM * REFERENCE_UM); + (a + b / (lambda_um * lambda_um)).max(1.0) +} + +/// Approximate sRGB colour of a monochromatic 400–700 nm light, gamma-naive +/// and clamped. Outside the range the nearest end colour is returned. +pub fn wavelength_rgb(lambda_nm: f64) -> (u8, u8, u8) { + let lambda_nm = lambda_nm.clamp(400.0, 700.0); + let (r, g, b) = raw_rgb(lambda_nm); + let intensity = if lambda_nm > 660.0 { + 1.0 - 0.35 * (lambda_nm - 660.0) / 40.0 + } else if lambda_nm < 430.0 { + 1.0 - 0.35 * (430.0 - lambda_nm) / 30.0 + } else { + 1.0 + }; + let channel = |v: f64| (255.0 * intensity * v).round() as u8; + (channel(r), channel(g), channel(b)) +} + +fn raw_rgb(lambda_nm: f64) -> (f64, f64, f64) { + let (r, g, b) = if (380.0..440.0).contains(&lambda_nm) { + (-(lambda_nm - 440.0) / 60.0, 0.0, 1.0) + } else if (440.0..490.0).contains(&lambda_nm) { + (0.0, (lambda_nm - 440.0) / 50.0, 1.0) + } else if (490.0..510.0).contains(&lambda_nm) { + (0.0, 1.0, -(lambda_nm - 510.0) / 20.0) + } else if (510.0..580.0).contains(&lambda_nm) { + ((lambda_nm - 510.0) / 70.0, 1.0, 0.0) + } else if (580.0..645.0).contains(&lambda_nm) { + (1.0, -(lambda_nm - 645.0) / 65.0, 0.0) + } else if (645.0..780.0).contains(&lambda_nm) { + (1.0, 0.0, 0.0) + } else if lambda_nm < 380.0 { + (0.0, 0.0, 1.0) + } else { + (1.0, 0.0, 0.0) + }; + (r, g, b) +} + +/// The dispersion sample wavelengths for `count` rays, violet 400 nm first and +/// red 700 nm last, evenly spaced. `count` is clamped to 1..=64. +pub fn sample_wavelengths(count: usize) -> Vec { + let count = count.clamp(1, MAX_SPECTRAL_RAYS); + if count == 1 { + return vec![REFERENCE_UM * 1000.0]; + } + (0..count) + .map(|i| 400.0 + (700.0 - 400.0) * i as f64 / (count - 1) as f64) + .collect() +} + +pub const MAX_SPECTRAL_RAYS: usize = 64; diff --git a/community/optics/src/tests.rs b/community/optics/src/tests.rs new file mode 100644 index 0000000..08847bd --- /dev/null +++ b/community/optics/src/tests.rs @@ -0,0 +1,665 @@ +use super::*; +use crate::diagram; +use crate::geom::{self, V}; + +fn params(values: &[(&str, ParamValue)]) -> Vec { + values + .iter() + .map(|(id, value)| ParamEntry { + id: (*id).into(), + value: value.clone(), + }) + .collect() +} + +fn scene(p: &[ParamEntry]) -> Scene { + render( + p, + Size { + width: 1280, + height: 720, + }, + ) + .unwrap() +} + +fn texts(scene: &Scene) -> Vec<&str> { + scene + .elements + .iter() + .filter_map(|e| match e { + DrawCommand::TextRun(t) => Some(t.text.as_str()), + _ => None, + }) + .collect() +} + +/// Every emitted coordinate must be finite and stay on the canvas, including +/// the degenerate near-focus cases. +fn assert_finite_and_on_canvas(scene: &Scene, size: Size) { + let (width, height) = (f64::from(size.width), f64::from(size.height)); + let ok = |x: f64, y: f64, what: &str| { + assert!( + x.is_finite() && y.is_finite(), + "non-finite {what} ({x}, {y})" + ); + assert!( + (0.0..=width).contains(&x) && (0.0..=height).contains(&y), + "off-canvas {what} ({x}, {y})" + ); + }; + for element in &scene.elements { + match element { + DrawCommand::StrokePath((verbs, _)) | DrawCommand::FillPath((verbs, _)) => { + for verb in verbs { + match verb { + PathVerb::MoveTo(p) | PathVerb::LineTo(p) => { + ok(f64::from(p.x), f64::from(p.y), "path point") + } + PathVerb::QuadTo((a, b)) => { + for p in [a, b] { + ok(f64::from(p.x), f64::from(p.y), "quadratic point"); + } + } + PathVerb::CubicTo((a, b, c)) => { + for p in [a, b, c] { + ok(f64::from(p.x), f64::from(p.y), "cubic point"); + } + } + PathVerb::Close => {} + } + } + } + // Painter::label stores the horizontal offset from canvas centre. + DrawCommand::TextRun(t) => ok(width / 2.0 + f64::from(t.x), f64::from(t.y), "text"), + } + } +} + +const TINY: f64 = 1e-9; + +#[test] +fn snell_law_round_trip() { + // Refraction direction obeys n1 sin(i) = n2 sin(t) across many pairs. + for &(n1, n2) in &[ + (1.0, 1.5), + (1.5, 1.0), + (1.0, 2.42), + (1.33, 1.5), + (1.5, 1.33), + ] { + for deg in [0.0f64, 5.0, 17.0, 30.0, 45.0, 60.0, 80.0] { + let i = deg.to_radians(); + let d = V::new(i.sin(), -i.cos()); + let n = V::new(0.0, 1.0); + if let Some(t) = geom::refract(d, n, n1, n2) { + let sin_i = i.sin(); + let sin_t = t.x; // unit vector: x component is the sine + assert!( + (n1 * sin_i - n2 * sin_t).abs() < 1e-6, + "snell violated for {n1}->{n2} at {deg}deg" + ); + // The ray crosses the surface: keeps heading against the normal. + assert!(t.dot(n) < 0.0, "refracted ray must cross the surface"); + } else { + // TIR only from denser to rarer, past the critical angle. + let crit = geom::critical_angle(n1, n2).unwrap_or(f64::INFINITY); + assert!(n1 > n2 && i > crit); + } + } + } +} + +#[test] +fn snell_angles_match_vector_refraction() { + for deg in [1.0f64, 10.0, 33.0, 55.0] { + let i = deg.to_radians(); + let vector = geom::refract(V::new(i.sin(), -i.cos()), V::new(0.0, 1.0), 1.0, 1.5).unwrap(); + let angle = geom::snell_angles(i, 1.0, 1.5).unwrap(); + assert!((vector.x - angle.sin()).abs() < 1e-9); + } + // 1.5 -> 1.0 past 41.8 degrees: TIR. + assert!(geom::snell_angles(41.80f64.to_radians(), 1.5, 1.0).is_some()); + assert!(geom::snell_angles(41.82f64.to_radians(), 1.5, 1.0).is_none()); +} + +#[test] +fn total_internal_reflection_threshold_is_critical_angle() { + let crit: f64 = (1.0f64 / 1.5).asin(); + assert!((geom::critical_angle(1.5, 1.0).unwrap() - crit).abs() < 1e-12); + assert!(geom::critical_angle(1.0, 1.5).is_none()); + assert!(geom::critical_angle(1.5, 1.5).is_none()); + let below: f64 = 41.0f64.to_radians(); + let above = crit + 1e-7; + let d_below = V::new(below.sin(), -below.cos()); + let d_at = V::new(crit.sin(), -crit.cos()); + let d_above = V::new(above.sin(), -above.cos()); + let n = V::new(0.0, 1.0); + assert!(geom::refract(d_below, n, 1.5, 1.0).is_some()); + let grazing = geom::refract(d_at, n, 1.5, 1.0).expect("critical ray grazes the interface"); + assert!((grazing.x - 1.0).abs() < TINY && grazing.y.abs() < TINY); + assert!(geom::refract(d_above, n, 1.5, 1.0).is_none()); + // The reflected ray keeps its magnitude and mirrors about the normal. + let r = geom::reflect(d_above, n); + assert!((r.length() - 1.0).abs() < 1e-12); + assert!((r.x - d_above.x).abs() < 1e-12); + assert!((r.y + d_above.y).abs() < 1e-12); +} + +#[test] +fn thin_lens_equation_both_focal_signs() { + for &f in &[200.0f64, -200.0, 144.0, -97.0] { + for &d_o in &[100.0f64, 250.0, 400.0, 600.0] { + if (d_o - f).abs() < TINY { + continue; + } + let (d_i, m) = geom::conjugates(f, d_o).unwrap(); + // 1/f = 1/d_o + 1/d_i + let lhs = 1.0 / f; + let rhs = 1.0 / d_o + 1.0 / d_i; + assert!( + (lhs - rhs).abs() / lhs.abs() < 1e-9, + "f={f} do={d_o} di={d_i}" + ); + assert!((m - (-d_i / d_o)).abs() < 1e-12); + // Converging with object beyond f gives a real, inverted image. + if f > 0.0 && d_o > f { + assert!(d_i > 0.0 && m < 0.0); + } + // Diverging always gives a virtual, upright image. + if f < 0.0 { + assert!(d_i < 0.0 && m > 0.0); + } + } + } + // Object at the focal plane: no finite image. + assert!(geom::conjugates(150.0, 150.0).is_none()); +} + +#[test] +fn principal_rays_form_real_and_virtual_images_on_the_correct_side() { + for side in [-1.0, 1.0] { + for (f, d) in [(0.2, 0.35), (0.2, 0.12), (-0.2, 0.35)] { + let height = 0.1; + let (image_distance, magnification) = geom::conjugates(f, d).unwrap(); + let image = V::new(side * image_distance, magnification * height); + let rays = diagram::principal_rays(f, d, height, side, Some(image.y)); + for ray in rays.iter().flatten() { + assert!(ray.outgoing.x * side > 0.0); + let to_image = image - ray.hit; + assert!(to_image.dot(ray.outgoing.perp()).abs() < TINY); + assert_eq!(to_image.dot(ray.outgoing).signum(), image_distance.signum()); + } + let [parallel, vertex, focal] = rays.map(Option::unwrap); + let focus = V::new(side * f, 0.0); + assert!((focus - parallel.hit).dot(parallel.outgoing.perp()).abs() < TINY); + let tip = V::new(-d, height); + if side > 0.0 { + assert!((vertex.hit - tip).unit().dot(vertex.outgoing) > 1.0 - TINY); + } else { + let reflected = geom::reflect((vertex.hit - tip).unit(), V::new(-1.0, 0.0)); + assert!((reflected - vertex.outgoing).length() < TINY); + } + let incident_focus = V::new(-f, 0.0); + assert!( + (incident_focus - tip) + .dot((focal.hit - tip).unit().perp()) + .abs() + < TINY + ); + assert_eq!(focal.outgoing, V::new(side, 0.0)); + } + + let [a, b, c] = diagram::principal_rays(0.2, 0.2, 0.1, side, None); + assert_eq!(a.unwrap().outgoing, b.unwrap().outgoing); + assert!(c.is_none()); + } +} + +#[test] +fn critical_angle_value_is_the_textbook_one() { + let deg = geom::critical_angle(1.5, 1.0).unwrap().to_degrees(); + // asin(1/1.5) = 41.81... degrees. + assert!((deg - 41.8103).abs() < 1e-3); + let water = geom::critical_angle(1.33, 1.0).unwrap().to_degrees(); + assert!((water - 48.75).abs() < 0.05); +} + +#[test] +fn snell_and_critical_angle_labels_are_explicit() { + // Refraction air -> glass at 45 deg transmits at asin(sin 45 / 1.5). + let refr = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("refraction".into())), + ("angle_deg", ParamValue::Number(45.0)), + ])); + let t = texts(&refr); + assert!(t.contains(&"θ₂ = 28.1°"), "{t:?}"); + assert!(t.contains(&"n₁ sin θ₁ = n₂ sin θ₂")); + // Media are labelled by role: n₁ incident, n₂ transmitting. + assert!(t.contains(&"n₁ = 1.00"), "{t:?}"); + assert!(t.contains(&"n₂ = 1.50"), "{t:?}"); + + // Glass -> air past the critical angle: no θ₂, only total internal + // reflection. + let past_critical = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("refraction".into())), + ("angle_deg", ParamValue::Number(60.0)), + ("index_1", ParamValue::Number(1.5)), + ("index", ParamValue::Number(1.0)), + ])); + let t = texts(&past_critical); + assert!(t.contains(&"Total internal reflection"), "{t:?}"); + assert!(!t.iter().any(|s| s.contains("θ₂"))); + + // The tir sweep states the ratio that defines the critical angle, and its + // n₁ is the incident (denser) slab, matching the refraction convention. + let tir = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("tir".into())), + ("progress", ParamValue::Number(1.0)), + ("angle_deg", ParamValue::Number(45.0)), + ("index_1", ParamValue::Number(1.0)), + ("index", ParamValue::Number(1.5)), + ])); + let t = texts(&tir); + assert!( + t.iter() + .any(|s| s.contains("sin θc = n₂/n₁") && s.contains("41.8")), + "{t:?}" + ); + assert!(t.contains(&"n₁ = 1.50"), "{t:?}"); + assert!(t.contains(&"n₂ = 1.00"), "{t:?}"); + assert!(t.contains(&"θ₁ = 45.0°"), "{t:?}"); +} + +#[test] +fn critical_angle_equation_stays_clear_of_the_ray_sweep() { + for step in 0..=100 { + let rendered = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("tir".into())), + ("angle_deg", ParamValue::Number(89.0)), + ("progress", ParamValue::Number(f64::from(step) / 100.0)), + ])); + let Some(equation) = rendered.elements.iter().find_map(|element| match element { + DrawCommand::TextRun(text) if text.text.starts_with("sin θc") => Some(text), + _ => None, + }) else { + // The label fades in as the incident ray approaches the interface. + assert!(step < 28); + continue; + }; + // Allow room for the centred equation's glyphs and padding. + let right = 640.0 + equation.x + 6.5 * equation.font_size; + let bottom = equation.y + 2.0 * equation.font_size; + for element in &rendered.elements { + let (path, color) = match element { + DrawCommand::StrokePath((path, style)) => (path, &style.color), + DrawCommand::FillPath((path, color)) => (path, color), + _ => continue, + }; + if (color.r, color.g, color.b) != (255, 205, 66) { + continue; + } + let mut points = path.iter().filter_map(|verb| match verb { + PathVerb::MoveTo(point) | PathVerb::LineTo(point) => Some(point), + _ => None, + }); + assert!( + points.clone().all(|p| p.x > right + 2.0) || points.all(|p| p.y > bottom + 2.0), + "ray enters the critical equation area at progress {step}%" + ); + } + } +} + +#[test] +fn mirror_curvature_maps_to_signed_focal_with_radius_floor() { + let u = 720.0; + // Concave (>= 0) focal is positive, convex negative, both R/2. + assert!((mirror_focal(30.0, u) - 0.15 * u).abs() < 1e-9); + assert!((mirror_focal(-30.0, u) + 0.15 * u).abs() < 1e-9); + // Radii below the 10% floor use the floored radius; zero is concave. + assert!((mirror_focal(5.0, u) - 0.05 * u).abs() < 1e-9); + assert!((mirror_focal(-5.0, u) + 0.05 * u).abs() < 1e-9); + assert!(mirror_focal(0.0, u) > 0.0); + assert!((mirror_focal(50.0, u) - 0.25 * u).abs() < 1e-9); + assert!((mirror_focal(-50.0, u) + 0.25 * u).abs() < 1e-9); +} + +#[test] +fn near_focus_images_scale_into_finite_on_canvas_coordinates() { + let size = Size { + width: 1280, + height: 720, + }; + let center = size.width as f32 / 2.0; + for (setup, focal_distance) in [("mirror", 15.0), ("lens-diagram", 20.0)] { + for (gap, height, expected) in [ + (-0.5, 30.0, "Virtual image"), + (-0.00001, 15.0, "Virtual image"), + (0.00001, 15.0, "Real image"), + (0.5, 15.0, "Real image"), + ] { + let distance = focal_distance + gap; + let rendered = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice(setup.into())), + ("object_distance", ParamValue::Number(distance)), + ("object_height", ParamValue::Number(height)), + ])); + assert_finite_and_on_canvas(&rendered, size); + let labels = texts(&rendered); + assert!( + labels.contains(&expected), + "{setup} at {distance}: {labels:?}" + ); + // The third principal ray leaves the element parallel to the axis. + assert!( + rendered.elements.iter().any(|element| matches!( + element, + DrawCommand::StrokePath((path, _)) + if matches!(path.as_slice(), + [PathVerb::MoveTo(_), PathVerb::LineTo(hit), PathVerb::LineTo(end)] + if hit.x == center && hit.y == end.y + && if setup == "mirror" { end.x < hit.x } else { end.x > hit.x }) + )), + "{setup} at {distance}: missing third ray" + ); + } + } +} + +#[test] +fn dispersion_index_and_spectrum_are_sane() { + // 550 nm is the calibration point. + assert!((crate::spectrum::index_at(1.5, 550.0) - 1.5).abs() < 1e-12); + // Shorter wavelength => larger index (blue bends more than red). + assert!(crate::spectrum::index_at(1.5, 400.0) > crate::spectrum::index_at(1.5, 700.0)); + for w in 1..=5 { + let samples = crate::spectrum::sample_wavelengths(w * 8); + assert_eq!(samples.first().unwrap().round() as i64, 400); + assert_eq!(samples.last().unwrap().round() as i64, 700); + // Monotone index across the samples. + for pair in samples.windows(2) { + assert!( + crate::spectrum::index_at(1.5, pair[0]) >= crate::spectrum::index_at(1.5, pair[1]) + ); + } + } + // Spectral colours are distinct and ordered violet -> red. + let (vr, _vg, vb) = crate::spectrum::wavelength_rgb(410.0); + let (rr, _rg, rb) = crate::spectrum::wavelength_rgb(680.0); + assert!(vb > rb && vr < rr); + assert!(crate::spectrum::wavelength_rgb(550.0).1 > 0); +} + +#[test] +fn dispersion_vanishes_at_index_one_and_scales_with_n_minus_one() { + // An index of 1 is vacuum: no dispersion at any wavelength. + for nm in [400.0, 450.0, 550.0, 620.0, 700.0] { + assert!( + (crate::spectrum::index_at(1.0, nm) - 1.0).abs() < 1e-12, + "{nm}" + ); + } + // The Cauchy coefficient is calibrated BK7-like at n = 1.5 + // (B = 0.004 µm²): n(400) - n(700) = 0.004 · (1/0.16 - 1/0.49). + let spread = + |base: f64| crate::spectrum::index_at(base, 400.0) - crate::spectrum::index_at(base, 700.0); + assert!((spread(1.5) - 0.004 * (1.0 / 0.16 - 1.0 / 0.49)).abs() < 1e-12); + // Weaker media disperse proportionally less, stronger ones more. + assert!(spread(1.2) > 0.0 && spread(1.2) < spread(1.5)); + assert!(spread(1.9) > spread(1.5)); + // The calibration point stays exact for every base. + for base in [1.0, 1.2, 1.5, 1.9, 2.5] { + assert!((crate::spectrum::index_at(base, 550.0) - base).abs() < 1e-12); + } +} + +#[test] +fn prism_spectrum_bends_violet_more_than_red() { + use crate::trace::{trace, Surface, MAX_SEGMENTS}; + let ([top, left, right], entry, incident) = diagram::prism_beam(1.0, 45.0_f64.to_radians()); + let surfaces = [ + Surface { a: top, b: left }, + Surface { a: left, b: right }, + Surface { a: right, b: top }, + ]; + assert!(((top - left).length() - (right - left).length()).abs() < TINY); + let source = entry - incident; + let wavelengths = crate::spectrum::sample_wavelengths(64); + let budget = MAX_SEGMENTS / wavelengths.len(); + let mut deviation = f64::NEG_INFINITY; + let mut segments = 0; + for wavelength in wavelengths { + let n = crate::spectrum::index_at(1.5, wavelength); + let ray = trace(source, incident, &surfaces, 1.0, n, budget); + assert_eq!(ray, trace(source, incident, &surfaces, 1.0, n, budget)); + assert!(!ray.inside); + assert_eq!(ray.hits.len(), 2); + assert!((ray.hits[0] - entry).length() < TINY); + assert!((ray.hits[1] - right).dot((top - right).unit().perp()).abs() < TINY); + let exit = ray.onward.unwrap(); + assert!(exit.x > 0.0 && exit.y < 0.0); + let angle = exit.y.atan2(exit.x); + assert!( + angle > deviation, + "shorter wavelengths must deviate farther down" + ); + deviation = angle; + segments += ray.hits.len() + 1; + } + assert!(segments <= MAX_SEGMENTS); +} + +#[test] +fn prism_trace_budget_stops_at_boundary_during_internal_reflection() { + use crate::trace::{trace, Surface}; + let ([top, left, right], entry, incident) = diagram::prism_beam(1.0, 5.0_f64.to_radians()); + let surfaces = [ + Surface { a: top, b: left }, + Surface { a: left, b: right }, + Surface { a: right, b: top }, + ]; + let source = entry - incident; + let limited = trace(source, incident, &surfaces, 1.0, 1.5, 3); + assert_eq!(limited.hits.len(), 2); + assert!(limited.inside && limited.onward.is_none()); + let full = trace(source, incident, &surfaces, 1.0, 1.5, 9); + assert!(full.hits.len() > limited.hits.len()); + let bounce = (full.hits[2] - full.hits[1]).unit(); + let before = (full.hits[1] - full.hits[0]).unit(); + let normal = (top - right).unit().perp(); + assert!((bounce - geom::reflect(before, normal)).length() < TINY); +} + +#[test] +fn prism_corner_stops_at_the_last_defined_surface() { + use crate::trace::{trace, Surface}; + let ([top, left, right], entry, incident) = diagram::prism_beam(1.0, 0.0); + let surfaces = [ + Surface { a: top, b: left }, + Surface { a: left, b: right }, + Surface { a: right, b: top }, + ]; + let ray = trace(entry - incident, incident, &surfaces, 1.0, 1.5, 9); + assert_eq!(ray.hits.len(), 2); + assert!((ray.hits[1] - right).length() < TINY); + assert!(ray.onward.is_none()); +} + +#[test] +fn ray_geometry_primitives() { + let orig = V::new(0.0, 0.0); + let dir = V::new(1.0, 0.0); + // Segment crossing. + let t = orig + .ray_segment_hit(dir, V::new(5.0, -2.0), V::new(5.0, 2.0)) + .unwrap(); + assert!((t - 5.0).abs() < 1e-12); + // Segment behind the ray origin: no hit. + assert!(orig + .ray_segment_hit(dir, V::new(-5.0, -2.0), V::new(-5.0, 2.0)) + .is_none()); + // Parallel segment: no hit. + assert!(orig + .ray_segment_hit(dir, V::new(5.0, 2.0), V::new(9.0, 2.0)) + .is_none()); + // Line intersection. + let p = geom::lines_intersection( + V::new(0.0, 0.0), + V::new(10.0, 10.0), + V::new(0.0, 10.0), + V::new(10.0, 0.0), + ) + .unwrap(); + assert!((p.x - 5.0).abs() < 1e-12 && (p.y - 5.0).abs() < 1e-12); + assert!(geom::lines_intersection( + V::new(0.0, 0.0), + V::new(1.0, 0.0), + V::new(0.0, 1.0), + V::new(1.0, 1.0) + ) + .is_none()); +} + +#[test] +fn partial_polyline_covers_exact_fractions() { + let line = [V::new(0.0, 0.0), V::new(10.0, 0.0), V::new(10.0, 10.0)]; + assert!(geom::partial_polyline(&line, 0.0).is_empty()); + assert_eq!(geom::partial_polyline(&line, 1.0), line.to_vec()); + let half = geom::partial_polyline(&line, 0.5); + let half_len = geom::polyline_length(&half); + assert!( + (half_len - 10.0).abs() < 1e-12, + "half of 20 is 10, got {half_len}" + ); + let quarter = geom::partial_polyline(&line, 0.25); + assert!((quarter.last().unwrap().x - 5.0).abs() < 1e-12); + // Monotone in t. + let mut last = 0.0; + for i in 1..=10 { + let len = geom::polyline_length(&geom::partial_polyline(&line, i as f64 / 10.0)); + assert!(len >= last - TINY); + last = len; + } +} + +#[test] +fn formats_are_stable_and_ascii() { + assert_eq!(geom::fmt(41.8103, 1), "41.8"); + assert_eq!(geom::fmt(-0.004, 2), "0.00"); // negative zero cleans up + assert_eq!(geom::fmt(1.5, 2), "1.50"); + assert!(geom::fmt(12.345, 2).is_ascii()); +} + +#[test] +fn all_setups_render_and_stay_bounded() { + for setup in SETUPS { + let scene = scene(¶ms(&[("setup", ParamValue::EnumChoice(setup.into()))])); + assert!( + !scene.elements.is_empty(), + "{setup} must draw with default parameters" + ); + assert!(scene.elements.len() <= MAX_ELEMENTS); + } +} + +#[test] +fn rendering_is_deterministic_and_progress_drives_rays() { + let a = scene(¶ms(&[( + "setup", + ParamValue::EnumChoice("dispersion".into()), + )])); + let b = scene(¶ms(&[( + "setup", + ParamValue::EnumChoice("dispersion".into()), + )])); + assert!( + format!("{a:?}") == format!("{b:?}"), + "repeat render differs" + ); + let mut frames = Vec::new(); + for p in [0.0, 0.25, 0.5, 0.75, 1.0] { + frames.push(scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("lens-diagram".into())), + ("progress", ParamValue::Number(p)), + ]))); + } + assert!(format!("{:?}", frames[0]) != format!("{:?}", frames[2])); + assert!(format!("{:?}", frames[2]) != format!("{:?}", frames[4])); + // Growth is monotone: a later progress frame is never a prefix-truncation + // of an earlier one's ray work. Simply check all frames differ. + for i in 1..frames.len() { + assert!(format!("{:?}", frames[i - 1]) != format!("{:?}", frames[i])); + } +} + +#[test] +fn toggles_change_the_scene() { + let with = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("refraction".into())), + ("show_labels", ParamValue::Bool(true)), + ])); + let without = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("refraction".into())), + ("show_labels", ParamValue::Bool(false)), + ])); + assert!(format!("{with:?}") != format!("{without:?}")); + let colored = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("dispersion".into())), + ("spectrum", ParamValue::Bool(true)), + ])); + let plain = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("dispersion".into())), + ("spectrum", ParamValue::Bool(false)), + ])); + assert!(format!("{colored:?}") != format!("{plain:?}")); +} + +#[test] +fn invalid_and_extreme_inputs_fail_cleanly() { + assert!(render( + &[ParamEntry { + id: "setup".into(), + value: ParamValue::EnumChoice("holodeck".into()), + }], + Size { + width: 100, + height: 100 + }, + ) + .is_err()); + assert!(render( + &[], + Size { + width: 0, + height: 100 + }, + ) + .is_err()); + assert!(render( + &[ParamEntry { + id: "progress".into(), + value: ParamValue::Number(f64::NAN), + }], + Size { + width: 100, + height: 100 + }, + ) + .is_err()); + // Extreme but valid parameters still render (clamped, finite). + let extreme = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("mirror".into())), + ("curvature", ParamValue::Number(-50.0)), + ("object_distance", ParamValue::Number(90.0)), + ("object_height", ParamValue::Number(30.0)), + ("angle_deg", ParamValue::Number(89.0)), + ])); + assert!(!extreme.elements.is_empty()); + let near_focus = scene(¶ms(&[ + ("setup", ParamValue::EnumChoice("lens-diagram".into())), + ("focal_length", ParamValue::Number(20.0)), + ("object_distance", ParamValue::Number(20.0)), // exactly at f + ])); + assert!(!near_focus.elements.is_empty()); +} diff --git a/community/optics/src/trace.rs b/community/optics/src/trace.rs new file mode 100644 index 0000000..4953bf3 --- /dev/null +++ b/community/optics/src/trace.rs @@ -0,0 +1,86 @@ +//! Nearest-hit tracing through a convex prism or a slab with parallel faces. +//! At each boundary, transmission switches media and TIR keeps the ray in +//! the current medium. The caller assigns each ray a share of the scene budget. + +use crate::geom::{self, V}; + +pub const MAX_DEPTH: usize = 8; +pub const MAX_SEGMENTS: usize = 256; + +pub struct Surface { + pub a: V, + pub b: V, +} + +#[derive(Debug, PartialEq)] +pub struct Trace { + pub hits: Vec, + /// Direction in the exterior after the last hit, or the current direction + /// if no further face was reached inside the visible region. + pub onward: Option, + pub inside: bool, +} + +pub fn trace( + origin: V, + direction: V, + surfaces: &[Surface], + outside_index: f64, + inside_index: f64, + segment_budget: usize, +) -> Trace { + let mut pos = origin; + let mut dir = direction; + let mut inside = false; + let mut hits = Vec::new(); + // Reserve room for the final segment off the element. + for _ in 0..segment_budget.saturating_sub(1).min(MAX_DEPTH) { + let hits_ahead = surfaces.iter().filter_map(move |surface| { + let t = pos.ray_segment_hit(dir, surface.a, surface.b)?; + Some((t, surface)) + }); + let nearest = hits_ahead.clone().min_by(|(a, _), (b, _)| a.total_cmp(b)); + let Some((t, surface)) = nearest else { + return Trace { + hits, + onward: Some(dir), + inside, + }; + }; + pos = pos + dir * t; + hits.push(pos); + // At a shared vertex there is no unique surface normal. + if hits_ahead + .filter(|(other, _)| (t - other).abs() <= 1e-9 * t.max(1.0)) + .count() + > 1 + { + break; + } + let normal = (surface.b - surface.a).unit().perp(); + let (from, to) = if inside { + (inside_index, outside_index) + } else { + (outside_index, inside_index) + }; + if let Some(transmitted) = geom::refract(dir, normal, from, to) { + dir = transmitted; + inside = !inside; + } else { + dir = geom::reflect(dir, normal); + } + if !inside { + return Trace { + hits, + onward: Some(dir), + inside, + }; + } + } + // An unfinished internal path stops at its last actual interaction. + Trace { + hits, + onward: None, + inside, + } +} diff --git a/community/optics/wit/plugin.wit b/community/optics/wit/plugin.wit new file mode 100644 index 0000000..b6820d9 --- /dev/null +++ b/community/optics/wit/plugin.wit @@ -0,0 +1,582 @@ +package animathio:plugin@1.1.0; + +/// Shared data types for vector graphics, parameter schemas and plugin manifests. +interface types { + /// 2D dimensions in integer pixels. + record size { + width: u32, + height: u32, + } + + /// Finite 2D coordinates: x right, y down. Scene.coordinate-space selects units. + record point { + x: f32, + y: f32, + } + + /// Straight-alpha 8-bit RGBA color. + record color { + r: u8, + g: u8, + b: u8, + a: u8, + } + + /// Path segment command. + variant path-verb { + move-to(point), + line-to(point), + quad-to(tuple), + cubic-to(tuple), + close, + } + + /// Sequence of path commands forming one or more contours. + type path = list; + + /// Line cap style at path endpoints. + enum stroke-cap { + butt, + round, + square, + } + + /// Line join style at path vertices. + enum stroke-join { + miter, + round, + bevel, + } + + /// Outline styling parameters. + record stroke-style { + width: f32, + color: color, + cap: stroke-cap, + join: stroke-join, + } + + /// Horizontal alignment in the available canvas width. + enum text-alignment { left, center, right } + + /// Text run layout element. + record text-element { + align: text-alignment, + text: string, + font-size: f32, + x: f32, + y: f32, + color: color, + } + + /// Vector drawing command. + variant draw-command { + fill-path(tuple), + stroke-path(tuple), + text-run(text-element), + } + + /// canvas: pixels on the requested render canvas. normalized: local unit square, + /// with x scaled by width and y by height. Strokes are outlined in local + /// units then transformed with the paths (nonuniform scaling is allowed). + /// Normalized text-run font-size is a fraction of canvas height; x/y are + /// offsets from the centered text block. Values outside 0..1 are allowed. + enum coordinate-space { canvas, normalized } + + /// Evaluated vector scene composed of ordered draw commands. + record scene { + coordinate-space: coordinate-space, + elements: list, + } + + /// Axis-aligned bounding box in canvas coordinates. + record bbox { + min-x: f32, + min-y: f32, + max-x: f32, + max-y: f32, + } + + /// Result of host-side math typesetting. + record typeset-result { + paths: list, + bbox: bbox, + } + + /// Input language for host-side math typesetting. + enum math-mode { + latex, + typst, + } + + /// Finite inclusive range; min <= default <= max and step > 0 (UI hint). + record number-range { + min: f64, + max: f64, + default: f64, + step: f64, + } + + /// Color parameter declaration. + record color-param { + default: color, + } + + /// Text string parameter declaration. + record string-param { + default: string, + } + + /// Multiple-choice enum parameter declaration. + record enum-param { + options: list, + default: string, + } + + /// Boolean toggle parameter declaration. + record bool-param { + default: bool, + } + + /// 2D point parameter declaration. + record point-param { + default: point, + } + + /// Asset reference parameter declaration. + record asset-ref-param { + media-type: string, + default-asset: option, + } + + /// Supported parameter types. + variant param-kind { + %number(number-range), + %color(color-param), + %string(string-param), + enum-choice(enum-param), + %bool(bool-param), + %point(point-param), + asset-ref(asset-ref-param), + } + + /// Stable id, fallback human label and typed schema. Labels are not identifiers. + /// Translation keys and units may be supplied in manifest.metadata. + record param-spec { + id: string, + label: string, + kind: param-kind, + } + + /// Concrete value assigned to a parameter at evaluation time. + variant param-value { + %number(f64), + %color(color), + %string(string), + enum-choice(string), + %bool(bool), + %point(point), + asset-ref(string), + } + + /// Key-value parameter entry. + record param-entry { + id: string, + value: param-value, + } + + /// Map of parameter values passed to plugin invocations. + type param-map = list; + + /// Open classification: clip-source, effect, audio-effect, animation-preset + /// (1.1) or importer (1.1). The legacy animation kind has no execution world. + /// Unknown strings are metadata, never permission to invoke an unknown world. + type plugin-kind = string; + + /// Optional, namespaced advisory metadata. Unknown keys must be ignored. + /// Keys are unique; values are UTF-8, never executable content. Reserved + /// conventions: label-key, description-key, param..unit, + /// param..label-key and param..option..label-key; + /// prefix with effect.. for effect descriptors. No localization service + /// is implied: plain labels/messages remain mandatory fallbacks. + type metadata = list>; + + /// Extensible error code plus fallback diagnostic text and advisory details. + /// Known codes: invalid-input, limit-exceeded, service-failed, plugin-error. + /// Unknown codes are displayed using message; callers must not parse messages. + record diagnostic { + code: string, + message: string, + metadata: metadata, + } + + /// Plugin metadata and parameter schema. + record manifest { + name: string, + version: string, + description: string, + kinds: list, + metadata: metadata, + params: list, + } +} + +/// Host-provided services imported by plugins. +interface host { + use types.{path, math-mode, typeset-result, diagnostic}; + + /// Text shaping via host font engine. Size is pixels; positive and finite. + /// Returns glyph outline paths or an explicit diagnostic. + shape-text: func(text: string, font-size: f32) -> result, diagnostic>; + + /// Typeset math via the host typesetting engine. Returns glyph and rule + /// outline paths plus a tight bounding box. + typeset-math: func(source: string, mode: math-mode, font-size: f32) -> result; + + /// Extract double-quoted d attributes from SVG path elements, or accept raw + /// SVG path data. This is not a complete SVG renderer: transforms, styles, + /// other primitives and external resources are not interpreted. Empty input + /// succeeds with no paths; unsupported/non-path input returns a diagnostic. + svg-to-paths: func(svg-xml: string) -> result, diagnostic>; + + /// Hard limits configured for this host, as unique key/value pairs. + /// Stable keys: ticks-per-second, max-memory-bytes, max-table-elements, + /// fuel-per-call, epoch-interval-ms, epoch-deadline-ticks, max-effect-pixels, + /// effect-memory-bytes, effect-fuel-per-pixel, effect-epoch-deadline-ticks, + /// max-audio-block-frames, max-audio-state-bytes, audio-memory-bytes, + /// audio-fuel-per-sample, audio-epoch-deadline-ticks, max-audio-channels, + /// max-audio-sample-rate, max-shape-text-chars, max-shape-text-verbs, + /// max-svg-input-bytes, max-svg-verbs, max-typeset-verbs, + /// max-typeset-source-bytes, max-typeset-font-size-px, typeset-timeout-ms, + /// max-log-message-bytes, max-log-entries, max-effects-per-plugin (added in 1.0.x); since 1.1 also max-import-source-bytes, + /// import-memory-bytes, import-fuel-per-byte, import-epoch-deadline-ticks, + /// max-import-output-bytes, max-import-commands, max-sibling-file-bytes, + /// max-sibling-total-bytes, max-sibling-files, max-preset-keys. + /// Keys and units are specified in docs/plugins.md; unknown keys are ignored. + /// This reports policy, not remaining fuel or memory. Budgets reset per call. + limits: func() -> list>; + + /// Host logging for diagnostic and debug output. + log: func(message: string); +} + +/// Pixel-filter effects, added in API 0.2.1. +/// +/// A frame effect receives one straight-alpha sRGB RGBA8 frame and returns a +/// frame of the same size. The host enforces size, fuel, wall-clock and memory +/// limits on every call; see `SandboxLimits` in `plugin-host`. +interface frame-effects { + use types.{size, param-map, param-spec, diagnostic}; + + /// One filter offered by an effect plugin. + record effect-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`), stored in projects. + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Numeric parameters with range, default and step. Only `number` kinds are + /// supported; effect parameters are keyframeable numbers. + params: list, + } + + /// List the filters this plugin provides. + list-effects: func() -> list; + + /// Apply filter `effect` to `pixels`: `size.width * size.height * 4` bytes of + /// row-major straight-alpha sRGB RGBA8. Must return exactly the same number + /// of bytes. `time-ticks` is the clip-local source time. The call is a pure + /// function of its arguments. Returns a diagnostic on invalid input. + apply-frame: func(effect: string, pixels: list, size: size, params: param-map, time-ticks: s64) -> result, diagnostic>; +} + +/// Audio effects, added in API 0.2.2. +/// +/// An audio effect receives one block of interleaved f32 PCM and returns a block of +/// the same size. The host splits longer signals into contiguous blocks and carries an +/// opaque `state` blob from each call to the next, so filters, envelope followers and +/// other stateful processors work across block boundaries without the plugin keeping any +/// memory between calls. The host enforces block size, state size, fuel, wall-clock and +/// memory limits on every call; see `SandboxLimits` in `plugin-host`. +interface audio-effects { + use types.{param-map, param-spec, diagnostic}; + + /// One audio filter offered by an audio-effect plugin. + record audio-effect-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`), stored in projects. + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Numeric parameters with range, default and step; keyframeable on clip chains. + /// Only `number` kinds are supported. + params: list, + } + + /// A block of interleaved 32-bit float PCM. + record audio-block { + /// Frames per second (1..=768000). + sample-rate: u32, + /// Interleaved channel count (1..=32). + channels: u16, + /// Time of the first frame in the chain's own timeline, in ticks: clip-local for a + /// clip chain, project time for a track chain. + start-ticks: s64, + /// `frames * channels` finite samples, frame-major interleaving. Unclipped; + /// values may exceed 1.0. Preserve channel order (stereo is left, right). + /// No channel-layout negotiation or planar format is implied. + samples: list, + } + + /// Result of processing one block. + record block-output { + /// Exactly as many samples as the input block. + samples: list, + /// State to hand back with the next contiguous block, or none for stateless filters. + state: option>, + } + + /// List the audio filters this plugin provides. + list-audio-effects: func() -> list; + + /// Process one block with filter `effect`. `state` is `none` for the first block of a + /// signal; an empty blob is equivalent to none. Otherwise it is exactly the + /// nonempty blob the previous call returned. The call is a pure + /// function of its arguments. Returns a diagnostic on invalid input. + process-block: func(effect: string, block: audio-block, params: param-map, state: option>) -> result; +} + +/// Animation presets, added in API 1.1.0. +/// +/// A preset plugin turns a preset choice into ordinary keyframe curves. The host +/// converts the curves into one `Command::Batch` of keyframe edits, so rendering never +/// calls the plugin and undo restores the previous keyframes exactly. +interface animation-presets { + use types.{param-map, param-spec, diagnostic}; + + /// Where a preset sits in a clip's lifetime. The host places the window: + /// entrance at the clip start, exit at the clip end, emphasis centred on the clip. + enum preset-role { + entrance, + exit, + emphasis, + } + + /// One preset offered by an animation-preset plugin. + record preset-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`). + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Window placement. + role: preset-role, + /// Clip kinds the preset applies to; empty means every visual clip. Kind ids: + /// `video`, `image`, `vector` and `plugin:`. + applies-to: list, + /// Default window length in ticks (positive). + default-duration-ticks: s64, + /// Preset options: number, enum-choice or bool kinds only. + params: list, + } + + /// The clip a preset is generated for. + record clip-info { + /// Clip kind id, as in `applies-to`. + kind: string, + /// Visible clip length in ticks (positive). + duration-ticks: s64, + /// Length of one project frame in ticks (positive); a sampling hint. + frame-ticks: s64, + /// Current value of every animatable numeric target at the window's rest + /// point: the end of an entrance window, the start of an exit or emphasis + /// window. Keys are the curve target ids below. + rest: list>, + } + + /// Interpolation toward the next key, matching core keyframes. + enum curve-interpolation { + hold, + linear, + ease-in-out, + } + + /// One keyframe. `time-ticks` is relative to the window start, 0..=window. + record curve-key { + time-ticks: s64, + value: f64, + interpolation: curve-interpolation, + } + + /// Keyframes for one target: `opacity`, `x`, `y`, `scale-x`, `scale-y`, + /// `rotation` (radians) or `param:` for a numeric clip parameter. + record curve { + target: string, + keys: list, + } + + /// List the presets this plugin provides. + list-presets: func() -> list; + + /// Generate the curves for `preset` over a window of `window-ticks` (positive, + /// at most the clip duration). Pure in its arguments. Returns a diagnostic on + /// invalid input, e.g. a preset that does not apply to the clip kind. + generate: func(preset: string, clip: clip-info, window-ticks: s64, params: param-map) -> result, diagnostic>; +} + +/// Bounded reads of files next to an imported source, added in API 1.1.0. +/// Only importer components import this interface. +interface import-files { + use types.{diagnostic}; + + /// Read a file relative to the directory the host granted for this import. + /// `relative-path` uses `/` separators; absolute paths, `..` components and + /// paths that resolve (through symlinks) outside the directory are refused. + /// Per-file, total-byte and file-count caps apply per call; without a granted + /// directory every read fails with `invalid-input`. + read-sibling: func(relative-path: string) -> result, diagnostic>; +} + +/// Project importers, added in API 1.1.0. +/// +/// An importer turns source bytes into a versioned command document that the host +/// validates and replays onto a fresh project, plus content-addressed asset bytes. +interface importer { + use types.{param-map, param-spec, diagnostic}; + + /// One import format offered by an importer plugin. + record importer-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`). + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Lower-case file extensions without the dot, e.g. `py`. + extensions: list, + /// Import options: string, number, enum-choice or bool kinds only. + params: list, + } + + /// The source being imported. + record import-source { + /// File name hint without directories (may be empty). + file-name: string, + /// Raw source bytes. + bytes: list, + } + + /// One asset referenced by the command document. + record imported-asset { + /// Lower-case hex BLAKE3 hash of `bytes`; the host recomputes it. + id: string, + /// Human-readable filename hint. + name: string, + /// Declared media type; decoders still probe the bytes. + media-type: string, + bytes: list, + } + + /// Non-fatal message severity. + enum message-severity { + info, + warning, + } + + /// One non-fatal observation; line and column are one-based, 0 when unknown. + record import-message { + severity: message-severity, + line: u32, + column: u32, + message: string, + snippet: string, + } + + /// A successful import. + record import-output { + /// UTF-8 JSON `{"version": 1, "commands": [...]}`: AniMathIO core commands + /// in their control-protocol serialization, replayed in order on an empty + /// project. Every command is validated; any failure rejects the import. + commands: string, + assets: list, + messages: list, + } + + /// List the formats this plugin imports. + list-importers: func() -> list; + + /// Import `source` with format `importer`. Pure apart from `read-sibling`. + run-import: func(importer: string, source: import-source, params: param-map) -> result; +} + +/// World for animation-preset plugins (`kinds = ["animation-preset"]`), API 1.1.0. +world animation-preset-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The presets themselves. + export animation-presets; +} + +/// World for importer plugins (`kinds = ["importer"]`), API 1.1.0. +world importer-plugin { + import host; + import import-files; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The import formats themselves. + export importer; +} + +/// World for audio-effect plugins (`kinds = ["audio-effect"]`): describe plus audio filters. +world audio-effect-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The audio filters themselves. + export audio-effects; +} + +/// World for effect plugins (`kinds = ["effect"]`): describe plus pixel filters. +/// Components for this world need no clip-source or animation exports. +world effect-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The pixel filters themselves. + export frame-effects; +} + +/// Pure vector generators. Frame and audio effects use their own worlds. +world source-plugin { + import host; + + use types.{manifest, scene, param-map, size, diagnostic}; + + /// Describe the plugin, its kinds and its parameter schema. + export describe: func() -> manifest; + + /// Render a vector scene, pure in its arguments. time-ticks is clip-local source + /// time in integer flicks (705600000 ticks/second). size is the render canvas. + /// An empty scene is valid; invalid geometry or traps fail the call. + export render-clip: func(params: param-map, time-ticks: s64, size: size) -> result; +}