Merge pull request #3934 from dotCooCoo/fix/kurbo-linear-cubic-zero-tangent

kurbo: carry 0.13.1 in vendor/ with a stroke fix for zero tangents
This commit is contained in:
BFlat authored and GitHub committed 2026-11-29 00:25:53 +07:00
commit 7f52db114e
59 files changed
+21204 -4

No files matched your search

Generated
-2
View File
@@ -8420,8 +8420,6 @@ dependencies = [
[[package]]
name = "kurbo"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
dependencies = [
"arrayvec",
"euclid",
+2 -1
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/*"]
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu"]
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu", "vendor/kurbo"]
[workspace.package]
version = "0.1.0"
@@ -325,6 +325,7 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
linesweeper = { path = "vendor/linesweeper" }
vello_common = { path = "vendor/vello_common" }
vello_cpu = { path = "vendor/vello_cpu" }
kurbo = { path = "vendor/kurbo" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
+8
View File
@@ -308,6 +308,14 @@ as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
changes and the files left out.
kurbo
kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR
Apache-2.0, is stored in vendor/kurbo with its upstream license files and local patches, to
src/stroke.rs. Its source files carry "Copyright <year> the Kurbo Authors" lines (2018 to 2026),
and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/kurbo/README.craft.md and
vendor/kurbo/SOURCE.json for provenance and the local patches.
Platform lifecycle source provenance
The optional crates/platform services adapt the preserved local platform candidate
+2 -1
View File
@@ -7,7 +7,7 @@ test_root=$(mktemp -d "${TMPDIR:-/tmp}/craft-pdf-backends.XXXXXX")
trap 'rm -rf "$test_root"' EXIT
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$root/target}"
patches=()
for backend in hayro hayro-interpret hayro-syntax hayro-jbig2 hayro-cmap hayro-postscript vello_common vello_cpu; do
for backend in hayro hayro-interpret hayro-syntax hayro-jbig2 hayro-cmap hayro-postscript vello_common vello_cpu kurbo; do
cp -R "$root/vendor/$backend" "$test_root/$backend"
patches+=(--config "patch.crates-io.$backend.path=\"$test_root/$backend\"")
done
@@ -25,6 +25,7 @@ cargo test --manifest-path "$test_root/linesweeper/Cargo.toml" --locked --test p
cargo test --manifest-path "$test_root/linesweeper/Cargo.toml" --locked --test paperjs load_errors_are_reported
cargo test --manifest-path "$test_root/linesweeper/Cargo.toml" --locked --lib --features generators generators::
cargo test --manifest-path "$test_root/linesweeper/Cargo.toml" --locked --doc
cargo test --manifest-path "$test_root/kurbo/Cargo.toml" --locked --all-features
cargo test --manifest-path "$test_root/linesweeper/Cargo.toml" --locked --example visualize_op
cargo test --manifest-path "$test_root/linesweeper/Cargo.toml" --locked --example curve_metrics --features metrics
cargo check --manifest-path "$test_root/linesweeper/Cargo.toml" --locked --all-targets --all-features
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "838b69ef35f3381cefc007d86aa8364f5a6dc673"
},
"path_in_vcs": "kurbo"
}
Generated Vendored
+705
View File
@@ -0,0 +1,705 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
[[package]]
name = "anes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "arrayvec"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
[[package]]
name = "autocfg"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "bumpalo"
version = "3.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "ciborium"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
dependencies = [
"ciborium-io",
"ciborium-ll",
"serde",
]
[[package]]
name = "ciborium-io"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
[[package]]
name = "ciborium-ll"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
dependencies = [
"ciborium-io",
"half",
]
[[package]]
name = "clap"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
dependencies = [
"clap_builder",
]
[[package]]
name = "clap_builder"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
dependencies = [
"anstyle",
"clap_lex",
]
[[package]]
name = "clap_lex"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "criterion"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928"
dependencies = [
"anes",
"cast",
"ciborium",
"clap",
"criterion-plot",
"itertools",
"num-traits",
"oorandom",
"plotters",
"regex",
"serde",
"serde_json",
"tinytemplate",
"walkdir",
]
[[package]]
name = "criterion-plot"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338"
dependencies = [
"cast",
"itertools",
]
[[package]]
name = "crunchy"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "dyn-clone"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
[[package]]
name = "either"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
name = "euclid"
version = "0.22.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
dependencies = [
"num-traits",
]
[[package]]
name = "futures-core"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
[[package]]
name = "futures-task"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]
name = "futures-util"
version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "getrandom"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi",
"wasip2",
"wasm-bindgen",
]
[[package]]
name = "half"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
dependencies = [
"cfg-if",
"crunchy",
"zerocopy",
]
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "js-sys"
version = "0.3.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08"
dependencies = [
"cfg-if",
"futures-util",
"once_cell",
"wasm-bindgen",
]
[[package]]
name = "kurbo"
version = "0.13.1"
dependencies = [
"arrayvec",
"criterion",
"euclid",
"getrandom",
"libm",
"mint",
"polycool",
"rand",
"schemars",
"serde",
"smallvec",
]
[[package]]
name = "libc"
version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "libm"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
[[package]]
name = "memchr"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "mint"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e53debba6bda7a793e5f99b8dacf19e626084f525f7829104ba9898f367d85ff"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
"libm",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "oorandom"
version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "plotters"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747"
dependencies = [
"num-traits",
"plotters-backend",
"plotters-svg",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "plotters-backend"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a"
[[package]]
name = "plotters-svg"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670"
dependencies = [
"plotters-backend",
]
[[package]]
name = "polycool"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"
dependencies = [
"arrayvec",
"libm",
]
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "rand"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
dependencies = [
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom",
]
[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]]
name = "rustversion"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "schemars"
version = "0.8.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615"
dependencies = [
"dyn-clone",
"schemars_derive",
"serde",
"serde_json",
"smallvec",
]
[[package]]
name = "schemars_derive"
version = "0.8.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d"
dependencies = [
"proc-macro2",
"quote",
"serde_derive_internals",
"syn",
]
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_derive_internals"
version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
dependencies = [
"serde",
]
[[package]]
name = "syn"
version = "2.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tinytemplate"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "wasip2"
version = "1.0.3+wasi-0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "wasm-bindgen"
version = "0.2.121"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.121"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.121"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.121"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441"
dependencies = [
"unicode-ident",
]
[[package]]
name = "web-sys"
version = "0.3.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]
name = "zerocopy"
version = "0.8.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
+230
View File
@@ -0,0 +1,230 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.85"
name = "kurbo"
version = "0.13.1"
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "A 2D curves library"
readme = "README.md"
keywords = [
"graphics",
"curve",
"curves",
"bezier",
"geometry",
]
categories = ["graphics"]
license = "Apache-2.0 OR MIT"
repository = "https://github.com/linebender/kurbo"
resolver = "2"
[package.metadata.docs.rs]
all-features = true
default-target = "x86_64-unknown-linux-gnu"
targets = []
[features]
default = ["std"]
euclid = ["dep:euclid"]
libm = [
"dep:libm",
"polycool/libm",
"euclid?/libm",
]
mint = ["dep:mint"]
schemars = [
"schemars/smallvec",
"dep:schemars",
]
serde = [
"smallvec/serde",
"dep:serde",
]
std = [
"polycool/std",
"euclid?/std",
]
[lib]
name = "kurbo"
path = "src/lib.rs"
[[example]]
name = "arclen_accuracy"
path = "examples/arclen_accuracy.rs"
[[example]]
name = "circle"
path = "examples/circle.rs"
[[example]]
name = "cubic_arclen"
path = "examples/cubic_arclen.rs"
[[example]]
name = "ellipse"
path = "examples/ellipse.rs"
[[example]]
name = "fit_poly"
path = "examples/fit_poly.rs"
[[example]]
name = "quad_intersect"
path = "examples/quad_intersect.rs"
[[example]]
name = "simplify"
path = "examples/simplify.rs"
[[example]]
name = "stroke"
path = "examples/stroke.rs"
[[bench]]
name = "cubic"
path = "benches/cubic.rs"
harness = false
[[bench]]
name = "cubic_arclen"
path = "benches/cubic_arclen.rs"
harness = false
[[bench]]
name = "nearest"
path = "benches/nearest.rs"
harness = false
[[bench]]
name = "quad_arclen"
path = "benches/quad_arclen.rs"
harness = false
[[bench]]
name = "quartic"
path = "benches/quartic.rs"
harness = false
[[bench]]
name = "rect_expand"
path = "benches/rect_expand.rs"
harness = false
[dependencies.arrayvec]
version = "0.7.6"
default-features = false
[dependencies.euclid]
version = "0.22"
optional = true
default-features = false
[dependencies.libm]
version = "0.2.16"
optional = true
[dependencies.mint]
version = "0.5.9"
optional = true
[dependencies.polycool]
version = "0.4.0"
default-features = false
[dependencies.schemars]
version = "0.8.22"
optional = true
[dependencies.serde]
version = "1.0.228"
features = [
"alloc",
"derive",
]
optional = true
default-features = false
[dependencies.smallvec]
version = "1.15.1"
features = ["const_new"]
[dev-dependencies.criterion]
version = "0.7.0"
features = [
"plotters",
"cargo_bench_support",
]
default-features = false
[dev-dependencies.rand]
version = "0.9.4"
[target.wasm32-unknown-unknown.dev-dependencies.getrandom]
version = "0.3.4"
features = ["wasm_js"]
[lints.clippy]
allow_attributes_without_reason = "warn"
cargo_common_metadata = "warn"
cast_possible_truncation = "warn"
cast_possible_wrap = "warn"
collection_is_never_read = "warn"
dbg_macro = "warn"
debug_assert_with_mut_call = "warn"
default_trait_access = "warn"
doc_markdown = "warn"
fn_to_numeric_cast_any = "warn"
infinite_loop = "warn"
large_stack_arrays = "warn"
mismatching_type_param_order = "warn"
missing_assert_message = "warn"
missing_fields_in_debug = "warn"
negative_feature_names = "warn"
redundant_feature_names = "warn"
same_functions_in_if_condition = "warn"
semicolon_if_nothing_returned = "warn"
should_panic_without_expect = "warn"
todo = "warn"
too_many_arguments = "allow"
unseparated_literal_suffix = "warn"
use_self = "warn"
wildcard_dependencies = "warn"
[lints.rust]
elided_lifetimes_in_paths = "warn"
keyword_idents_2024 = "forbid"
missing_debug_implementations = "warn"
missing_docs = "warn"
non_ascii_idents = "forbid"
non_local_definitions = "forbid"
trivial_numeric_casts = "warn"
unnameable_types = "warn"
unreachable_pub = "warn"
unsafe_code = "forbid"
unsafe_op_in_unsafe_fn = "forbid"
unused_import_braces = "warn"
unused_lifetimes = "warn"
unused_macro_rules = "warn"
unused_qualifications = "warn"
[lints.rust.unexpected_cfgs]
level = "warn"
priority = 0
check-cfg = ["cfg(nightly)"]
+81
View File
@@ -0,0 +1,81 @@
[package]
name = "kurbo"
version.workspace = true
license.workspace = true
edition.workspace = true
description = "A 2D curves library"
keywords = ["graphics", "curve", "curves", "bezier", "geometry"]
categories = ["graphics"]
repository.workspace = true
rust-version.workspace = true
[package.metadata.docs.rs]
all-features = true
# There are no platform specific docs.
default-target = "x86_64-unknown-linux-gnu"
targets = []
[features]
default = ["std"]
# Get floating point functions from the standard library (likely using your target's libc)
std = ["polycool/std", "euclid?/std"]
# Use floating point implementations from libm
libm = ["dep:libm", "polycool/libm", "euclid?/libm"]
# Enable `From`/`Into` conversion of Kurbo and [mint] types, enabling interoperability
# with other graphics libraries
mint = ["dep:mint"]
# Enable `From`/`Into` conversion of Kurbo and euclid types
euclid = ["dep:euclid"]
# Implement `serde::Deserialize` and `serde::Serialize` on various types
serde = ["smallvec/serde", "dep:serde"]
# Add best-effort support for using Kurbo types in JSON schemas using schemars
schemars = ["schemars/smallvec", "dep:schemars"]
[dependencies]
arrayvec = { workspace = true }
euclid = { workspace = true, optional = true }
libm = { workspace = true, optional = true }
mint = { workspace = true, optional = true }
polycool = { workspace = true }
schemars = { workspace = true, optional = true }
serde = { workspace = true, optional = true, features = ["alloc", "derive"] }
smallvec = { workspace = true, features = ["const_new"] }
[dev-dependencies]
# This is used for research but not really needed; maybe refactor.
rand = { workspace = true }
# wasm doesn't support rayon, so disable criterion's rayon support. (In
# principle we could make it target-dependent.)
criterion = { workspace = true, features = ["plotters", "cargo_bench_support"] }
[target.wasm32-unknown-unknown.dev-dependencies]
# We have a transitive dependency on getrandom and it does not automatically
# support wasm32-unknown-unknown. We need to enable the wasm_js feature.
getrandom = { version = "0.3.4", features = ["wasm_js"] }
[lints]
workspace = true
[[bench]]
name = "cubic"
harness = false
[[bench]]
name = "cubic_arclen"
harness = false
[[bench]]
name = "quad_arclen"
harness = false
[[bench]]
name = "quartic"
harness = false
[[bench]]
name = "nearest"
harness = false
[[bench]]
name = "rect_expand"
harness = false
+202
View File
@@ -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.
+25
View File
@@ -0,0 +1,25 @@
Copyright (c) 2018 Raph Levien
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+55
View File
@@ -0,0 +1,55 @@
# Local kurbo 0.13.1 copy
This is the crates.io kurbo 0.13.1 package (MIT OR Apache-2.0) with the local patches listed below.
`.cargo_vcs_info.json` names the commit it was packaged from,
`838b69ef35f3381cefc007d86aa8364f5a6dc673`, the `v0.13.1` tag of
[linebender/kurbo](https://github.com/linebender/kurbo/tree/838b69ef35f3381cefc007d86aa8364f5a6dc673/kurbo).
The patched file is `src/stroke.rs`.
Every file here except this one, `SOURCE.json` and the patched file is byte for byte the file in the
`.crate` archive. `SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`)
and, for every file kept, the hash in the package (`source_sha256`) and the hash here (`sha256`).
`local_patches` describes each local change. No file of the package is left out.
## Local changes
| File | Change |
|---|---|
| `src/stroke.rs` | `StrokeCtx::do_linear` skips a cusp, or the end point, whose tangent from the point before it is exactly zero, instead of passing the tangent to `do_join` and `do_line`, which divide by its length. After rounding, a collinear cubic that runs back and forth can put two cusps at the same point, or a cusp on the end point, and the whole outline then held NaN coordinates. The `linear_cubic_with_coincident_cusps` test strokes one cubic of each kind with every join, two widths and two tolerances. Code comments label the change `Craft patch (zero tangent)`. |
| `src/stroke.rs` | The stroker skips a quadratic or cubic whose start or end tangent is zero, as it skips a zero-length line. `PathSeg::tangents` falls back to the chord when the control arms are shorter than 1e-6, and a curve that ends where it starts has a zero chord, so such a closed loop gave NaN coordinates in the outline. A quadratic is stroked as the cubic it raises to, whose control arms are 2/3 as long, so the quadratic's own tangents are passed on to `do_cubic` and `do_linear`. The `tiny_closed_loops` test strokes loops with arms of 1e-7, 1.25e-6 and 1e-5, on their own and after a line. Code comments label the change `Craft patch (zero tangent)`. |
Every change here updates this table and `SOURCE.json` in the same commit.
## Using it
The directory is excluded from the workspace. With the root manifest's `[patch.crates-io]` entry,
every crate here that depends on kurbo 0.13 builds against this copy. Cargo ignores a dependency's
patches, so a consuming workspace adds its own entry:
```toml
[patch.crates-io]
kurbo = { git = "https://github.com/storytold/craft-libs", rev = "<rev>" }
```
The entry applies to kurbo 0.13 only. A dependency on another kurbo version, such as 0.11, still
resolves to crates.io.
## Tests
`scripts/test-pdf-backends.sh` runs the package's unit and doc tests with every feature, and builds
its `hayro` and `hayro-interpret` tests against this copy. The workspace's own tests also build
against it through the patch entry. No workflow runs clippy on this copy. Run the tests and the
builds without `std` and for Wasm from this directory:
```sh
cargo test --locked --all-features
cargo check --locked --no-default-features --features libm
cargo test --locked --all-features --target wasm32-unknown-unknown --no-run
```
The package's tests need the `std` feature. Clippy 1.100.0 with `-D warnings` reports two lints in
the package as published, `needless_late_init` in `src/common.rs` and `useless_borrows_in_formatting`
in a test in `src/cubicbez.rs`; the copy keeps that code unchanged.
Cargo writes to `target/` in this directory, which the root `.gitignore` excludes.
+94
View File
@@ -0,0 +1,94 @@
<div align="center">
# Kurbo
**A Rust 2D curves library**
[![Linebender Zulip, #kurbo channel](https://img.shields.io/badge/Linebender-%23kurbo-blue?logo=Zulip)](https://xi.zulipchat.com/#narrow/channel/260979-kurbo)
[![dependency status](https://deps.rs/repo/github/linebender/kurbo/status.svg)](https://deps.rs/repo/github/linebender/kurbo)
[![Apache 2.0 or MIT license.](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](#license)
[![Build status](https://github.com/linebender/kurbo/workflows/CI/badge.svg)](https://github.com/linebender/kurbo/actions)
[![Crates.io](https://img.shields.io/crates/v/kurbo.svg)](https://crates.io/crates/kurbo)
[![Docs](https://docs.rs/kurbo/badge.svg)](https://docs.rs/kurbo)
</div>
The Kurbo library contains data structures and algorithms for curves and vector paths.
It is probably most appropriate for creative tools, but is general enough it might be useful for other applications.
The name "kurbo" is Esperanto for "curve".
There is a focus on accuracy and good performance in high-accuracy conditions.
Thus, the library might be useful in engineering and science contexts as well, as opposed to visual arts where rough approximations are often sufficient.
Many approximate functions come with an accuracy parameter, and analytical solutions are used where they are practical.
An example is area calculation, which is done using Green's theorem.
The library is still in fairly early development stages.
There are traits intended to be useful for general curves (not just Béziers), but these will probably be reorganized.
## Minimum supported Rust Version (MSRV)
This version of Kurbo has been verified to compile with **Rust 1.85** and later.
Future versions of Kurbo might increase the Rust version requirement.
It will not be treated as a breaking change and as such can even happen with small patch releases.
<details>
<summary>Click here if compiling fails.</summary>
As time has passed, some of Kurbo's dependencies could have released versions with a higher Rust requirement.
If you encounter a compilation issue due to a dependency and don't want to upgrade your Rust toolchain, then you could downgrade the dependency.
```sh
# Use the problematic dependency's name and version
cargo update -p package_name --precise 0.1.1
```
</details>
## Similar crates
Here we mention a few other curves libraries and touch on some of the decisions made differently here.
* [lyon_geom] has a lot of very good vector algorithms. It's most focused on rendering.
* [flo_curves] has good Bézier primitives, and seems tuned for animation. It's generic on the coordinate type, while we use `f64` for everything.
* [vek] has both 2D and 3D Béziers among other things, and is tuned for game engines.
Some code has been copied from lyon_geom with adaptation, thus the author of lyon_geom, Nicolas Silva, is credited in the [AUTHORS] file.
## More info
To learn more about Bézier curves, [A Primer on Bézier Curves] by Pomax is indispensable.
## Community
[![Linebender Zulip](https://img.shields.io/badge/Linebender-%23kurbo-blue?logo=Zulip)](https://xi.zulipchat.com/#narrow/channel/260979-kurbo)
Discussion of Kurbo development happens in the [Linebender Zulip](https://xi.zulipchat.com/), specifically the [#kurbo channel](https://xi.zulipchat.com/#narrow/channel/260979-kurbo).
All public content can be read without logging in.
## License
Licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
at your option.
## Contribution
Contributions are welcome by pull request. The [Rust code of conduct] applies.
Please feel free to add your name to the [AUTHORS] file in any substantive pull request.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions.
[Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct
[lyon_geom]: https://crates.io/crates/lyon_geom
[flo_curves]: https://crates.io/crates/flo_curves
[vek]: https://crates.io/crates/vek
[A Primer on Bézier Curves]: https://pomax.github.io/bezierinfo/
[AUTHORS]: ./AUTHORS
[CHANGELOG.md]: ./CHANGELOG.md
+70
View File
@@ -0,0 +1,70 @@
{
"crate": "kurbo",
"source_repository": "https://crates.io/api/v1/crates/kurbo/0.13.1/download",
"source_revision": "0.13.1",
"source_directory": "kurbo-0.13.1",
"source_archive_sha256": "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2",
"upstream_repository": "https://github.com/linebender/kurbo",
"upstream_revision": "838b69ef35f3381cefc007d86aa8364f5a6dc673",
"upstream_directory": "kurbo",
"local_patches": [
"In `src/stroke.rs`, `StrokeCtx::do_linear` skips a cusp, or the end point, whose tangent from the point before it is exactly zero, instead of passing the tangent to `do_join` and `do_line`, which divide by its length, so a collinear cubic whose cusps round onto the point before them or onto its end point no longer gives NaN coordinates. The test `stroke::tests::linear_cubic_with_coincident_cusps` covers it.",
"In `src/stroke.rs`, the stroker skips a quadratic or cubic whose start or end tangent from `PathSeg::tangents` is zero, as it skips a zero-length line, so a closed loop with control arms shorter than 1e-6 no longer gives NaN coordinates; a quadratic's own tangents are passed on to `do_cubic` and `do_linear`, since the cubic it raises to has control arms 2/3 as long. The test `stroke::tests::tiny_closed_loops` covers it."
],
"files": [
{ "path": ".cargo_vcs_info.json", "source_sha256": "4bfe3d4ab606efdb8e558db546ae666decc53fa3caa34865b4f66ffa67449a66", "source_git_blob": null, "sha256": "4bfe3d4ab606efdb8e558db546ae666decc53fa3caa34865b4f66ffa67449a66" },
{ "path": "Cargo.lock", "source_sha256": "1f13e8fcd58e548bb2130320c3ed5addb20ff658722d3f20b697c2a6a0b27e90", "source_git_blob": null, "sha256": "1f13e8fcd58e548bb2130320c3ed5addb20ff658722d3f20b697c2a6a0b27e90" },
{ "path": "Cargo.toml", "source_sha256": "3c5b41c42b588b750fbca3109b48438288586c2b22fdda571ea0fc188b6e08b0", "source_git_blob": null, "sha256": "3c5b41c42b588b750fbca3109b48438288586c2b22fdda571ea0fc188b6e08b0" },
{ "path": "Cargo.toml.orig", "source_sha256": "20e9fc1c17fd24b20c7eba09b657f999cc503999b18051dcdf7770e581fab175", "source_git_blob": null, "sha256": "20e9fc1c17fd24b20c7eba09b657f999cc503999b18051dcdf7770e581fab175" },
{ "path": "LICENSE-APACHE", "source_sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", "source_git_blob": null, "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" },
{ "path": "LICENSE-MIT", "source_sha256": "23c23145f6eac25c28cdcc03d38506a5712a9a8cffb5bd5301457f6173ea696e", "source_git_blob": null, "sha256": "23c23145f6eac25c28cdcc03d38506a5712a9a8cffb5bd5301457f6173ea696e" },
{ "path": "README.md", "source_sha256": "d731f0edd82b188d9156cfbd909a1fdce6dd7424299b5d9ab540135d20693aab", "source_git_blob": null, "sha256": "d731f0edd82b188d9156cfbd909a1fdce6dd7424299b5d9ab540135d20693aab" },
{ "path": "benches/cubic.rs", "source_sha256": "753d2822c69a8684032a3b4a5f40e3b03ea4b4553cd8aba39fe6afd159711ab9", "source_git_blob": null, "sha256": "753d2822c69a8684032a3b4a5f40e3b03ea4b4553cd8aba39fe6afd159711ab9" },
{ "path": "benches/cubic_arclen.rs", "source_sha256": "93ad92e94f421ef9b7ee60ed3b59909a59554ade76a18279ccacf8bfcd715477", "source_git_blob": null, "sha256": "93ad92e94f421ef9b7ee60ed3b59909a59554ade76a18279ccacf8bfcd715477" },
{ "path": "benches/nearest.rs", "source_sha256": "8cbf5ead45bce5ea79d1234f72fae704042162a934228b3af9611cf0932ef5fd", "source_git_blob": null, "sha256": "8cbf5ead45bce5ea79d1234f72fae704042162a934228b3af9611cf0932ef5fd" },
{ "path": "benches/quad_arclen.rs", "source_sha256": "f447a066c32703cbbba14bed66f419841cca1cb83e01ca7511e6f09a5d115e20", "source_git_blob": null, "sha256": "f447a066c32703cbbba14bed66f419841cca1cb83e01ca7511e6f09a5d115e20" },
{ "path": "benches/quartic.rs", "source_sha256": "3535c44734c559992b3f62077e5d933300777e248251b883b1451457280df1f3", "source_git_blob": null, "sha256": "3535c44734c559992b3f62077e5d933300777e248251b883b1451457280df1f3" },
{ "path": "benches/rect_expand.rs", "source_sha256": "496b987a239680b61b2d65b0ab91cbfab55c807cc1831476bcb08129c092f8de", "source_git_blob": null, "sha256": "496b987a239680b61b2d65b0ab91cbfab55c807cc1831476bcb08129c092f8de" },
{ "path": "examples/arclen_accuracy.rs", "source_sha256": "7bf354d4d34b42e915e082774d74177209b2997b09ee6972a38cb32dfaf385b2", "source_git_blob": null, "sha256": "7bf354d4d34b42e915e082774d74177209b2997b09ee6972a38cb32dfaf385b2" },
{ "path": "examples/circle.rs", "source_sha256": "1416fe74c7a82b15b1d2ee4166d09a75cf8cc9ac6744dddc7df338881258ded3", "source_git_blob": null, "sha256": "1416fe74c7a82b15b1d2ee4166d09a75cf8cc9ac6744dddc7df338881258ded3" },
{ "path": "examples/cubic_arclen.rs", "source_sha256": "467bcf52b26e3480ad05dddbd06374ce219df54b7dc1fa7fb96367eed41e1d5b", "source_git_blob": null, "sha256": "467bcf52b26e3480ad05dddbd06374ce219df54b7dc1fa7fb96367eed41e1d5b" },
{ "path": "examples/ellipse.rs", "source_sha256": "22db083067328d2d4f80a2be1ba1cf7e5478950ecde99142563a4cd9fa6dfaca", "source_git_blob": null, "sha256": "22db083067328d2d4f80a2be1ba1cf7e5478950ecde99142563a4cd9fa6dfaca" },
{ "path": "examples/fit_poly.rs", "source_sha256": "ed1d8adaf2e0adcee445cfd4fd06a110f064455ef382354ec2a99d3450442654", "source_git_blob": null, "sha256": "ed1d8adaf2e0adcee445cfd4fd06a110f064455ef382354ec2a99d3450442654" },
{ "path": "examples/quad_intersect.rs", "source_sha256": "56becf3a522316e1c54eaae7d2d75365fa275bbfc17bb2bf6884d63bf887d88a", "source_git_blob": null, "sha256": "56becf3a522316e1c54eaae7d2d75365fa275bbfc17bb2bf6884d63bf887d88a" },
{ "path": "examples/simplify.rs", "source_sha256": "7bd3fdcfd60fe9094b9f5da51be4a70061f3df760a62a0ae62e7e8c77f649558", "source_git_blob": null, "sha256": "7bd3fdcfd60fe9094b9f5da51be4a70061f3df760a62a0ae62e7e8c77f649558" },
{ "path": "examples/stroke.rs", "source_sha256": "f055edc18fc05c55c2a3f9ad2e3caa6b997e2d9cd7c5781959d752182afe1b90", "source_git_blob": null, "sha256": "f055edc18fc05c55c2a3f9ad2e3caa6b997e2d9cd7c5781959d752182afe1b90" },
{ "path": "src/affine.rs", "source_sha256": "7288c89bb5ce16acd7d1b046f189df5855cfafa0454d667fc7b0dc4454fa2663", "source_git_blob": null, "sha256": "7288c89bb5ce16acd7d1b046f189df5855cfafa0454d667fc7b0dc4454fa2663" },
{ "path": "src/arc.rs", "source_sha256": "f1479f3e54c7e4717424920f128ebfda59ea2984c08b43291411072072eb1475", "source_git_blob": null, "sha256": "f1479f3e54c7e4717424920f128ebfda59ea2984c08b43291411072072eb1475" },
{ "path": "src/axis.rs", "source_sha256": "6ccf1f4cca904fa43f54d9d71a6511927fdab171a8d00382ab311cd2776ef781", "source_git_blob": null, "sha256": "6ccf1f4cca904fa43f54d9d71a6511927fdab171a8d00382ab311cd2776ef781" },
{ "path": "src/bezpath.rs", "source_sha256": "6d9d5769715dfc4c10f90c1de500fca7a2ca35c0d673d2e05d7ddd615a987be4", "source_git_blob": null, "sha256": "6d9d5769715dfc4c10f90c1de500fca7a2ca35c0d673d2e05d7ddd615a987be4" },
{ "path": "src/circle.rs", "source_sha256": "434d23a89e13ad22be300c383cdf027e41a9ccfbd8a3f9152c1e97a5ad330491", "source_git_blob": null, "sha256": "434d23a89e13ad22be300c383cdf027e41a9ccfbd8a3f9152c1e97a5ad330491" },
{ "path": "src/common.rs", "source_sha256": "5d32994b9832dc34738a0d34464d9b2435398404bfd576c838584c301359d062", "source_git_blob": null, "sha256": "5d32994b9832dc34738a0d34464d9b2435398404bfd576c838584c301359d062" },
{ "path": "src/cubicbez.rs", "source_sha256": "de793f84444c55467a4669de64b4a06209f97540362c2da1fe0ad2b2367f5b80", "source_git_blob": null, "sha256": "de793f84444c55467a4669de64b4a06209f97540362c2da1fe0ad2b2367f5b80" },
{ "path": "src/ellipse.rs", "source_sha256": "991e9830a32643d2aa5c34c57330323e65f3b15231c80b086eb715b0665fc41d", "source_git_blob": null, "sha256": "991e9830a32643d2aa5c34c57330323e65f3b15231c80b086eb715b0665fc41d" },
{ "path": "src/expand.rs", "source_sha256": "f0ef21c91790097498bfacd2cc624f6ac86b32bc2600aa78c57583e46c5d0ae6", "source_git_blob": null, "sha256": "f0ef21c91790097498bfacd2cc624f6ac86b32bc2600aa78c57583e46c5d0ae6" },
{ "path": "src/fit.rs", "source_sha256": "3d7dace4a4452ce6a5eff3186a48f8dc0d0d625029feae78c24017fb5b68695b", "source_git_blob": null, "sha256": "3d7dace4a4452ce6a5eff3186a48f8dc0d0d625029feae78c24017fb5b68695b" },
{ "path": "src/insets.rs", "source_sha256": "cf6019c2ab0783ede641ef61677b60d4c2cf4f721317024a0944e8c66373dc98", "source_git_blob": null, "sha256": "cf6019c2ab0783ede641ef61677b60d4c2cf4f721317024a0944e8c66373dc98" },
{ "path": "src/interop_euclid.rs", "source_sha256": "bc94da5023b455df685b74cd942d569e1ee5025191c64ff4217f068d845b9418", "source_git_blob": null, "sha256": "bc94da5023b455df685b74cd942d569e1ee5025191c64ff4217f068d845b9418" },
{ "path": "src/lib.rs", "source_sha256": "f513dc1a758bc061cc2a177fa98a1d566003d6c83e36d3befbc9bbea2e4349e7", "source_git_blob": null, "sha256": "f513dc1a758bc061cc2a177fa98a1d566003d6c83e36d3befbc9bbea2e4349e7" },
{ "path": "src/line.rs", "source_sha256": "66fba2df6d9653aa03adfda457a5059a7cbdd1ae29fa2c2db4ba5aefb1d4db28", "source_git_blob": null, "sha256": "66fba2df6d9653aa03adfda457a5059a7cbdd1ae29fa2c2db4ba5aefb1d4db28" },
{ "path": "src/mindist.rs", "source_sha256": "3f6e98e5cc25395e042bcd3138abd237176034cbddb13d48a11b66f581d724e4", "source_git_blob": null, "sha256": "3f6e98e5cc25395e042bcd3138abd237176034cbddb13d48a11b66f581d724e4" },
{ "path": "src/moments.rs", "source_sha256": "decf10b9116aacab2bab47c8b331a6a5e3ba16b3c63527710289cedc5df930a0", "source_git_blob": null, "sha256": "decf10b9116aacab2bab47c8b331a6a5e3ba16b3c63527710289cedc5df930a0" },
{ "path": "src/offset.rs", "source_sha256": "8999fdb31334a6c08c260f2ae360aba3b091652e26454b735ea985c99a545cd9", "source_git_blob": null, "sha256": "8999fdb31334a6c08c260f2ae360aba3b091652e26454b735ea985c99a545cd9" },
{ "path": "src/param_curve.rs", "source_sha256": "5cac1495643a9cb5f4af7ea618265a9deb87e7f82ee9628fdb46c49fd970a553", "source_git_blob": null, "sha256": "5cac1495643a9cb5f4af7ea618265a9deb87e7f82ee9628fdb46c49fd970a553" },
{ "path": "src/point.rs", "source_sha256": "4311047b9497b4fbd38022eb62ebaa9771c05e55e1bafb9431f2243949515ca7", "source_git_blob": null, "sha256": "4311047b9497b4fbd38022eb62ebaa9771c05e55e1bafb9431f2243949515ca7" },
{ "path": "src/quadbez.rs", "source_sha256": "37ab1037750d32eed6b3664b250a8c14c78419a1567e790695c0e46544263bbd", "source_git_blob": null, "sha256": "37ab1037750d32eed6b3664b250a8c14c78419a1567e790695c0e46544263bbd" },
{ "path": "src/quadspline.rs", "source_sha256": "cfa129dd52d23a7852be3a1103e8022cc792cb2bd481440d3ebc1221a635e28d", "source_git_blob": null, "sha256": "cfa129dd52d23a7852be3a1103e8022cc792cb2bd481440d3ebc1221a635e28d" },
{ "path": "src/rect.rs", "source_sha256": "20c0bca0e79ab1b69321bf5d7e2db618cb4582bb29f47854faa5979a38a9ff2a", "source_git_blob": null, "sha256": "20c0bca0e79ab1b69321bf5d7e2db618cb4582bb29f47854faa5979a38a9ff2a" },
{ "path": "src/rounded_rect.rs", "source_sha256": "495d08f409456a97cd8c228f84624383922c4ef01e4d2edf624a40765a12b3c4", "source_git_blob": null, "sha256": "495d08f409456a97cd8c228f84624383922c4ef01e4d2edf624a40765a12b3c4" },
{ "path": "src/rounded_rect_radii.rs", "source_sha256": "ac42ee920ff31c6b5524ea9ae22e9da8ad2a8d17572e9ade1c369d827b8004d7", "source_git_blob": null, "sha256": "ac42ee920ff31c6b5524ea9ae22e9da8ad2a8d17572e9ade1c369d827b8004d7" },
{ "path": "src/shape.rs", "source_sha256": "226a32a1996d298e9587cc921b7cc8644ca6e04b2c740732e0a63ab00d3351ae", "source_git_blob": null, "sha256": "226a32a1996d298e9587cc921b7cc8644ca6e04b2c740732e0a63ab00d3351ae" },
{ "path": "src/simplify.rs", "source_sha256": "771fc68a2dd0a00d994906176641bcb17c9351b3d1205e037a78a5893b51a684", "source_git_blob": null, "sha256": "771fc68a2dd0a00d994906176641bcb17c9351b3d1205e037a78a5893b51a684" },
{ "path": "src/size.rs", "source_sha256": "645a1f7ba1528b1b10e5881d53019eac428e556c1d9bdea8d3f42ce351c00950", "source_git_blob": null, "sha256": "645a1f7ba1528b1b10e5881d53019eac428e556c1d9bdea8d3f42ce351c00950" },
{ "path": "src/stroke.rs", "source_sha256": "9ae69c57571d653a34ded745e176869ef587e4ff5c3dcb1607a398df7e029498", "source_git_blob": null, "sha256": "18f6f59a8935516f42c8790cda61f6e0993c33dc0d9db8fbe1b6b3bb4c6a6cf0" },
{ "path": "src/svg.rs", "source_sha256": "b403a258614b3e287c3e5210b0745814f08acda92e95696bdddbf50e341fa3be", "source_git_blob": null, "sha256": "b403a258614b3e287c3e5210b0745814f08acda92e95696bdddbf50e341fa3be" },
{ "path": "src/translate_scale.rs", "source_sha256": "8b82eb5f46744cb9a044263e200d79d797270616320337e4230356942ab85f1a", "source_git_blob": null, "sha256": "8b82eb5f46744cb9a044263e200d79d797270616320337e4230356942ab85f1a" },
{ "path": "src/triangle.rs", "source_sha256": "27a6cddb109ae36ef55c470261c689d085502ab72a47f3a32ca22e771df7b03e", "source_git_blob": null, "sha256": "27a6cddb109ae36ef55c470261c689d085502ab72a47f3a32ca22e771df7b03e" },
{ "path": "src/vec2.rs", "source_sha256": "05b37bf834417a040012fef380aa9eb10925324ea1a07fba3328839a56c9a060", "source_git_blob": null, "sha256": "05b37bf834417a040012fef380aa9eb10925324ea1a07fba3328839a56c9a060" }
],
"omitted_files": []
}
+25
View File
@@ -0,0 +1,25 @@
// Copyright 2022 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Benchmarks of the cubic equation solver.
#![allow(missing_docs, reason = "criterion emits undocumented functions")]
use criterion::{Criterion, criterion_group, criterion_main};
use std::hint::black_box;
use kurbo::common::solve_cubic;
fn bench_cubic(cc: &mut Criterion) {
let (x1, x2, x3) = (1.0, 2.0, 3.0);
let a = -(x1 + x2 + x3);
let b = x1 * x2 + x1 * x3 + x2 * x3;
let c = -x1 * x2 * x3;
cc.bench_function("cubic roots", |bb| {
bb.iter(|| solve_cubic(black_box(c), black_box(b), black_box(a), 1.0));
});
}
criterion_group!(benches, bench_cubic);
criterion_main!(benches);
+36
View File
@@ -0,0 +1,36 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Benchmarks of cubic arclength approaches.
#![allow(missing_docs, reason = "criterion emits undocumented functions")]
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use std::hint::black_box;
use kurbo::{CubicBez, ParamCurveArclen};
fn bench_cubic_arclen(cc: &mut Criterion) {
{
let mut group = cc.benchmark_group("cubic_arclen");
for accuracy in [1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9] {
group.bench_with_input(
BenchmarkId::from_parameter(accuracy),
&accuracy,
|b, &accuracy| {
let c =
CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0), (1.0, 1.0));
b.iter(|| black_box(c).arclen(accuracy));
},
);
}
}
cc.bench_function("cubic_arclen degenerate", |b| {
let c = CubicBez::new((0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0));
b.iter(|| black_box(c).arclen(1e-6));
});
}
criterion_group!(benches, bench_cubic_arclen);
criterion_main!(benches);
+53
View File
@@ -0,0 +1,53 @@
// Copyright 2022 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Benchmarks of the quartic equation solver.
#![allow(missing_docs, reason = "criterion emits undocumented functions")]
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use std::hint::black_box;
use kurbo::{CubicBez, ParamCurveNearest as _, Point, QuadBez};
fn bench_nearest_quadratic(cc: &mut Criterion) {
let q = QuadBez {
p0: (-1.0, -1.0).into(),
p1: (0.0, 2.0).into(),
p2: (1.0, -1.0).into(),
};
let p = Point::new(0.0, 0.0);
for acc in [1e-3, 1e-6, 1e-12] {
cc.bench_with_input(
BenchmarkId::new("quadratic nearest point", acc),
&acc,
|bb, acc| {
bb.iter(|| black_box(q).nearest(black_box(p), *acc));
},
);
}
}
fn bench_nearest_cubic(cc: &mut Criterion) {
let c = CubicBez {
p0: (-1.0, -1.0).into(),
p1: (0.0, 2.0).into(),
p2: (1.0, -1.0).into(),
p3: (2.0, 2.0).into(),
};
let p = Point::new(0.0, 0.0);
for acc in [1e-3, 1e-6, 1e-12] {
cc.bench_with_input(
BenchmarkId::new("cubic nearest point", acc),
&acc,
|bb, acc| {
bb.iter(|| black_box(c).nearest(black_box(p), *acc));
},
);
}
}
criterion_group!(benches, bench_nearest_quadratic, bench_nearest_cubic);
criterion_main!(benches);
+170
View File
@@ -0,0 +1,170 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Benchmarks of quadratic arclength approaches.
#![allow(missing_docs, reason = "criterion emits undocumented functions")]
// TODO: organize so there's less cut'n'paste from arclen_accuracy example.
use criterion::{Criterion, criterion_group, criterion_main};
use std::hint::black_box;
use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv, QuadBez};
// Based on http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/
fn quad_arclen_analytical(q: QuadBez) -> f64 {
let d2 = q.p0.to_vec2() - 2.0 * q.p1.to_vec2() + q.p2.to_vec2();
let a = d2.hypot2();
let d1 = q.p1 - q.p0;
let b = 2.0 * d2.dot(d1);
let c = d1.hypot2();
let sabc = (a + b + c).sqrt();
let a2 = a.powf(-0.5);
let a32 = a2.powi(3);
let c2 = 2.0 * c.sqrt();
let ba = b * a2;
sabc + 0.25
* (a2 * a2 * b * (2.0 * sabc - c2)
+ a32 * (4.0 * c * a - b * b) * (((2.0 * a + b) * a2 + 2.0 * sabc) / (ba + c2)).ln())
}
/// Calculate arclength using Gauss-Legendre quadrature using formula from Behdad
/// in <https://github.com/Pomax/BezierInfo-2/issues/77>
fn gauss_arclen_3(q: QuadBez) -> f64 {
let v0 = (-0.492943519233745 * q.p0.to_vec2()
+ 0.430331482911935 * q.p1.to_vec2()
+ 0.0626120363218102 * q.p2.to_vec2())
.hypot();
let v1 = ((q.p2 - q.p0) * 0.4444444444444444).hypot();
let v2 = (-0.0626120363218102 * q.p0.to_vec2() - 0.430331482911935 * q.p1.to_vec2()
+ 0.492943519233745 * q.p2.to_vec2())
.hypot();
v0 + v1 + v2
}
fn awesome_quad_arclen3(q: QuadBez, accuracy: f64, depth: usize) -> f64 {
let pm = q.p0.midpoint(q.p2);
let d1 = q.p1 - pm;
let d = q.p2 - q.p0;
let dhypot2 = d.hypot2();
let x = 2.0 * d.dot(d1) / dhypot2;
let y = 2.0 * d.cross(d1) / dhypot2;
let lc = (q.p2 - q.p0).hypot();
let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot();
let est_err = 0.06 * (lp - lc) * (x * x + y * y).powf(2.0);
if est_err < accuracy || depth == 16 {
gauss_arclen_3(q)
} else {
let (q0, q1) = q.subdivide();
awesome_quad_arclen3(q0, accuracy * 0.5, depth + 1)
+ awesome_quad_arclen3(q1, accuracy * 0.5, depth + 1)
}
}
/// Another implementation, using weights from
/// <https://pomax.github.io/bezierinfo/legendre-gauss.html>
fn gauss_arclen_n(q: QuadBez, coeffs: &[(f64, f64)]) -> f64 {
let d = q.deriv();
coeffs
.iter()
.map(|(wi, xi)| wi * d.eval(0.5 * (xi + 1.0)).to_vec2().hypot())
.sum::<f64>()
* 0.5
}
fn gauss_arclen_7(q: QuadBez) -> f64 {
gauss_arclen_n(
q,
&[
(0.4179591836734694, 0.0000000000000000),
(0.3818300505051189, 0.4058451513773972),
(0.3818300505051189, -0.4058451513773972),
(0.2797053914892766, -0.7415311855993945),
(0.2797053914892766, 0.7415311855993945),
(0.1294849661688697, -0.9491079123427585),
(0.1294849661688697, 0.9491079123427585),
],
)
}
fn gauss_arclen_24(q: QuadBez) -> f64 {
gauss_arclen_n(
q,
&[
(0.1279381953467522, -0.0640568928626056),
(0.1279381953467522, 0.0640568928626056),
(0.1258374563468283, -0.1911188674736163),
(0.1258374563468283, 0.1911188674736163),
(0.1216704729278034, -0.3150426796961634),
(0.1216704729278034, 0.3150426796961634),
(0.1155056680537256, -0.4337935076260451),
(0.1155056680537256, 0.4337935076260451),
(0.1074442701159656, -0.5454214713888396),
(0.1074442701159656, 0.5454214713888396),
(0.0976186521041139, -0.6480936519369755),
(0.0976186521041139, 0.6480936519369755),
(0.0861901615319533, -0.7401241915785544),
(0.0861901615319533, 0.7401241915785544),
(0.0733464814110803, -0.820001985973903),
(0.0733464814110803, 0.820001985973903),
(0.0592985849154368, -0.8864155270044011),
(0.0592985849154368, 0.8864155270044011),
(0.0442774388174198, -0.9382745520027328),
(0.0442774388174198, 0.9382745520027328),
(0.0285313886289337, -0.9747285559713095),
(0.0285313886289337, 0.9747285559713095),
(0.0123412297999872, -0.9951872199970213),
(0.0123412297999872, 0.9951872199970213),
],
)
}
fn awesome_quad_arclen7(q: QuadBez, accuracy: f64, depth: usize) -> f64 {
let pm = q.p0.midpoint(q.p2);
let d1 = q.p1 - pm;
let d = q.p2 - q.p0;
let dhypot2 = d.hypot2();
let x = 2.0 * d.dot(d1) / dhypot2;
let y = 2.0 * d.cross(d1) / dhypot2;
let lc = dhypot2.sqrt();
let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot();
let est_err = 2.5e-2 * (lp - lc) * (x * x + y * y).powf(8.0).tanh();
if est_err < accuracy || depth == 16 {
gauss_arclen_7(q)
} else {
let (q0, q1) = q.subdivide();
awesome_quad_arclen7(q0, accuracy * 0.5, depth + 1)
+ awesome_quad_arclen7(q1, accuracy * 0.5, depth + 1)
}
}
const ACCURACY: f64 = 1e-6;
fn bench_quad_arclen(cc: &mut Criterion) {
let q = QuadBez::new((0.0, 0.0), (1.0, 0.0), (1.0, 1.0));
cc.bench_function("quad_arclen_analytical", |b| {
b.iter(|| quad_arclen_analytical(black_box(q)));
});
cc.bench_function("quad_arclen", |b| b.iter(|| black_box(q).arclen(ACCURACY)));
cc.bench_function("quad_arclen_gauss3", |b| {
b.iter(|| awesome_quad_arclen3(black_box(q), ACCURACY, 0));
});
cc.bench_function("quad_arclen_gauss7", |b| {
b.iter(|| awesome_quad_arclen7(black_box(q), ACCURACY, 0));
});
cc.bench_function("quad_arclen_gauss3_one", |b| {
b.iter(|| gauss_arclen_3(black_box(q)));
});
cc.bench_function("quad_arclen_gauss7_one", |b| {
b.iter(|| gauss_arclen_7(black_box(q)));
});
cc.bench_function("quad_arclen_gauss24_one", |b| {
b.iter(|| gauss_arclen_24(black_box(q)));
});
}
criterion_group!(benches, bench_quad_arclen);
criterion_main!(benches);
+26
View File
@@ -0,0 +1,26 @@
// Copyright 2022 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Benchmarks of the quartic equation solver.
#![allow(missing_docs, reason = "criterion emits undocumented functions")]
use criterion::{Criterion, criterion_group, criterion_main};
use std::hint::black_box;
use kurbo::common::solve_quartic;
fn bench_quartic(cc: &mut Criterion) {
let (x1, x2, x3, x4) = (1.0, 2.0, 3.0, 4.0);
let a = -(x1 + x2 + x3 + x4);
let b = x1 * (x2 + x3) + x2 * (x3 + x4) + x4 * (x1 + x3);
let c = -x1 * x2 * (x3 + x4) - x3 * x4 * (x1 + x2);
let d = x1 * x2 * x3 * x4;
cc.bench_function("quartic roots", |bb| {
bb.iter(|| solve_quartic(black_box(d), black_box(c), black_box(b), black_box(a), 1.0));
});
}
criterion_group!(benches, bench_quartic);
criterion_main!(benches);
+56
View File
@@ -0,0 +1,56 @@
// Copyright 2020 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Benchmarks of rect expansion.
#![allow(missing_docs, reason = "criterion emits undocumented functions")]
use criterion::{Criterion, criterion_group, criterion_main};
use std::hint::black_box;
use kurbo::Rect;
// In positive space
static RECT_POS: Rect = Rect::new(3.3, 3.6, 5.6, 4.1);
// In both positive and negative space
static RECT_PAN: Rect = Rect::new(-3.3, -3.6, 5.6, 4.1);
// In negative space
static RECT_NEG: Rect = Rect::new(-5.6, -4.1, -3.3, -3.6);
// In positive space reverse
static RECT_POR: Rect = Rect::new(5.6, 4.1, 3.3, 3.6);
// In both positive and negative space reverse
static RECT_PNR: Rect = Rect::new(5.6, 4.1, -3.3, -3.6);
// In negative space reverse
static RECT_NER: Rect = Rect::new(-3.3, -3.6, -5.6, -4.1);
// In positive space mixed
static RECT_POM: Rect = Rect::new(3.3, 4.1, 5.6, 3.6);
// In both positive and negative space mixed
static RECT_PNM: Rect = Rect::new(-3.3, 4.1, 5.6, -3.6);
// In negative space mixed
static RECT_NEM: Rect = Rect::new(-5.6, -3.6, -3.3, -4.1);
#[inline]
fn expand(rects: &[Rect; 9]) {
black_box(rects[0].expand());
black_box(rects[1].expand());
black_box(rects[2].expand());
black_box(rects[3].expand());
black_box(rects[4].expand());
black_box(rects[5].expand());
black_box(rects[6].expand());
black_box(rects[7].expand());
black_box(rects[8].expand());
}
fn bench_expand(c: &mut Criterion) {
// Creating the array here to prevent the compiler from optimizing all of it to NOP.
let rects: [Rect; 9] = [
RECT_POS, RECT_PAN, RECT_NEG, RECT_POR, RECT_PNR, RECT_NER, RECT_POM, RECT_PNM, RECT_NEM,
];
c.bench_function("expand", |b| b.iter(|| expand(&rects)));
}
criterion_group!(benches, bench_expand);
criterion_main!(benches);
+248
View File
@@ -0,0 +1,248 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A test program to plot the error of arclength approximation.
#![allow(unused, reason = "a bunch of experiments in the code")]
// TODO: make more functionality accessible from command line rather than uncommenting.
use std::env;
use std::time::{Duration, Instant};
use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv, QuadBez};
use kurbo::common::{GAUSS_LEGENDRE_COEFFS_5, GAUSS_LEGENDRE_COEFFS_7, GAUSS_LEGENDRE_COEFFS_24};
/// Calculate arclength using Gauss-Legendre quadrature using formula from Behdad
/// in <https://github.com/Pomax/BezierInfo-2/issues/77>
fn gauss_arclen_3(q: QuadBez) -> f64 {
let v0 = (-0.492943519233745 * q.p0.to_vec2()
+ 0.430331482911935 * q.p1.to_vec2()
+ 0.0626120363218102 * q.p2.to_vec2())
.hypot();
let v1 = ((q.p2 - q.p0) * 0.4444444444444444).hypot();
let v2 = (-0.0626120363218102 * q.p0.to_vec2() - 0.430331482911935 * q.p1.to_vec2()
+ 0.492943519233745 * q.p2.to_vec2())
.hypot();
v0 + v1 + v2
}
fn awesome_quad_arclen(q: QuadBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 {
let pm = q.p0.midpoint(q.p2);
let d1 = q.p1 - pm;
let d = q.p2 - q.p0;
let dhypot2 = d.hypot2();
let x = 2.0 * d.dot(d1) / dhypot2;
let y = 2.0 * d.cross(d1) / dhypot2;
let lc = (q.p2 - q.p0).hypot();
let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot();
let est_err = 0.06 * (lp - lc) * (x * x + y * y).powf(2.0);
if est_err < accuracy || depth == 16 {
*count += 1;
gauss_arclen_3(q)
} else {
let (q0, q1) = q.subdivide();
awesome_quad_arclen(q0, accuracy * 0.5, depth + 1, count)
+ awesome_quad_arclen(q1, accuracy * 0.5, depth + 1, count)
}
}
const MAX_DEPTH: usize = 16;
fn gravesen_rec(q: &QuadBez, l0: f64, accuracy: f64, depth: usize, count: &mut usize) -> f64 {
let (q0, q1) = q.subdivide();
let l0_q0 = calc_l0(q0);
let l0_q1 = calc_l0(q1);
let l1 = l0_q0 + l0_q1;
let error = (l0 - l1) * (1.0 / 15.0);
if error.abs() < accuracy || depth == MAX_DEPTH {
*count += 1;
l1 - error
} else {
gravesen_rec(&q0, l0_q0, accuracy * 0.5, depth + 1, count)
+ gravesen_rec(&q1, l0_q1, accuracy * 0.5, depth + 1, count)
}
}
fn gauss_arclen_5(q: QuadBez) -> f64 {
q.gauss_arclen(GAUSS_LEGENDRE_COEFFS_5)
}
fn gauss_arclen_7(q: QuadBez) -> f64 {
q.gauss_arclen(GAUSS_LEGENDRE_COEFFS_7)
}
fn gauss_arclen_24(q: QuadBez) -> f64 {
q.gauss_arclen(GAUSS_LEGENDRE_COEFFS_24)
}
fn awesome_quad_arclen7(q: QuadBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 {
let pm = q.p0.midpoint(q.p2);
let d1 = q.p1 - pm;
let d = q.p2 - q.p0;
let dhypot2 = d.hypot2();
let x = 2.0 * d.dot(d1) / dhypot2;
let y = 2.0 * d.cross(d1) / dhypot2;
let lc = (q.p2 - q.p0).hypot();
let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot();
let est_err = 2.5e-2 * (lp - lc) * (x * x + y * y).powf(8.0).tanh();
// Increase depth, so we can be an accurate baseline for comparison.
if est_err < accuracy || depth == 22 {
*count += 1;
gauss_arclen_7(q)
} else {
let (q0, q1) = q.subdivide();
awesome_quad_arclen7(q0, accuracy * 0.5, depth + 1, count)
+ awesome_quad_arclen7(q1, accuracy * 0.5, depth + 1, count)
}
}
fn awesome_quad_arclen24(q: QuadBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 {
let pm = q.p0.midpoint(q.p2);
let d1 = q.p1 - pm;
let d = q.p2 - q.p0;
let dhypot2 = d.hypot2();
let x = 2.0 * d.dot(d1) / dhypot2;
let y = 2.0 * d.cross(d1) / dhypot2;
let lc = (q.p2 - q.p0).hypot();
let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot();
// This isn't quite right near (1.1, 0)
let est_err = 1.0 * (lp - lc) * (0.5 * x * x + 0.1 * y * y).powf(16.0).tanh();
if est_err < accuracy || depth == 16 {
*count += 1;
gauss_arclen_24(q)
} else {
let (q0, q1) = q.subdivide();
awesome_quad_arclen24(q0, accuracy * 0.5, depth + 1, count)
+ awesome_quad_arclen24(q1, accuracy * 0.5, depth + 1, count)
}
}
// Based on http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/
fn quad_arclen_analytical(q: QuadBez) -> f64 {
let d2 = q.p0.to_vec2() - 2.0 * q.p1.to_vec2() + q.p2.to_vec2();
let a = d2.hypot2();
let d1 = q.p1 - q.p0;
let c = d1.hypot2();
if a < 5e-4 * c {
return gauss_arclen_3(q);
}
let b = 2.0 * d2.dot(d1);
let sabc = (a + b + c).sqrt();
let a2 = a.powf(-0.5);
let a32 = a2.powi(3);
let c2 = 2.0 * c.sqrt();
let ba_c2 = b * a2 + c2;
let v0 = 0.25 * a2 * a2 * b * (2.0 * sabc - c2) + sabc;
// TODO: justify and fine-tune this exact constant.
if ba_c2 < 1e-13 {
// This case happens for Béziers with a sharp kink.
v0
} else {
v0 + 0.25 * a32 * (4.0 * c * a - b * b) * (((2.0 * a + b) * a2 + 2.0 * sabc) / ba_c2).ln()
}
}
/// Calculate the L0 metric from "Adaptive subdivision and the length and
/// energy of Bézier curves" by Jens Gravesen.
fn calc_l0(q: QuadBez) -> f64 {
let lc = (q.p2 - q.p0).hypot();
let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot();
(2.0 / 3.0) * lc + (1.0 / 3.0) * lp
}
fn with_subdiv(q: QuadBez, f: &dyn Fn(QuadBez) -> f64, depth: usize) -> f64 {
if depth == 0 {
f(q)
} else {
let (q0, q1) = q.subdivide();
with_subdiv(q0, f, depth - 1) + with_subdiv(q1, f, depth - 1)
}
}
fn duration_to_time(d: Duration) -> f64 {
1e-9 * (d.subsec_nanos() as f64) + (d.as_secs() as f64)
}
fn run_simple() {
let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0));
let true_len = q.arclen(1e-13);
for i in 0..20 {
let n = 1 << i;
let start_time = Instant::now();
let mut est = 0.0;
let mut last = q.start();
let dt = (n as f64).recip();
for j in 0..n {
let t = ((j + 1) as f64) * dt;
let p = q.eval(t);
est += (p - last).hypot();
last = p;
}
let elapsed = duration_to_time(start_time.elapsed());
let err = true_len - est;
if i > 0 {
println!("{elapsed} {err}");
}
}
}
/// Generate map data suitable for plotting in Gnuplot.
fn main() {
let mut n_subdiv = 0;
let mut func: &dyn Fn(QuadBez) -> f64 = &gauss_arclen_3;
for arg in env::args().skip(1) {
if arg == "gauss3" {
func = &gauss_arclen_3;
} else if arg == "gauss5" {
func = &gauss_arclen_5;
} else if arg == "gauss7" {
func = &gauss_arclen_7;
} else if arg == "gauss24" {
func = &gauss_arclen_24;
} else if arg == "l0" {
func = &calc_l0;
} else if arg == "simple" {
run_simple();
return;
} else if let Ok(n) = arg.parse() {
n_subdiv = n;
} else {
println!("usage: arclen_accuracy [func] n_subdiv");
std::process::exit(1);
}
}
let n = 400;
let accuracy = 1e-6;
for i in 0..=n {
let x = 2.0 * (i as f64) * (n as f64).recip();
for j in 0..=n {
let y = 2.0 * (j as f64) * (n as f64).recip();
let q = QuadBez::new((-1.0, 0.0), (x, y), (1.0, 0.0));
let mut count = 0;
let accurate_arclen = awesome_quad_arclen7(q, 1e-15, 0, &mut count);
//count = 0;
let start_time = Instant::now();
//let est = awesome_quad_arclen7(q, accuracy, 0, &mut count);
let est = quad_arclen_analytical(q);
let elapsed = start_time.elapsed();
//let est = gravesen_rec(&q, calc_l0(q), accuracy, 0, &mut count);
//let est = with_subdiv(q, func, n_subdiv);
let error = est - accurate_arclen;
println!("{} {} {}", x, y, (error.abs() + 1e-18).log10());
//println!("{} {} {}", x, y, count);
//println!("{} {} {}", x, y, elapsed.subsec_nanos());
//let accurate_arclen = with_subdiv(q, &gauss_arclen_5, 8);
//let error = est - accurate_arclen;
/*
let lc = (q.p2 - q.p0).hypot();
let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot();
let est_err = 1.0 * (lp - lc) * (0.5 * x * x + 0.1 * y * y).powf(16.0).tanh();
println!("{} {} {}", x, y, (est_err/error.abs() + 1e-15).log10());
*/
}
println!();
}
}
+27
View File
@@ -0,0 +1,27 @@
// Copyright 2019 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Example of circle
#[cfg(feature = "std")]
fn main() {
use kurbo::{Circle, Shape};
let circle = Circle::new((400.0, 400.0), 380.0);
println!("<!DOCTYPE html>");
println!("<html>");
println!("<body>");
println!("<svg height=\"800\" width=\"800\">");
let black_path = circle.to_path(1e-3).to_svg();
println!(" <path d=\"{black_path}\" stroke=\"black\" fill=\"none\" />");
let red_path = circle.to_path(1.0).to_svg();
println!(" <path d=\"{red_path}\" stroke=\"red\" fill=\"none\" />");
println!("</svg>");
println!("</body>");
println!("</html>");
}
#[cfg(not(feature = "std"))]
fn main() {
println!("This example requires the standard library");
}
+256
View File
@@ -0,0 +1,256 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Research testbed for arclengths of cubic Bézier segments.
#![allow(unused, reason = "a bunch of experiments in the code")]
use kurbo::common::{GAUSS_LEGENDRE_COEFFS_7, GAUSS_LEGENDRE_COEFFS_9, GAUSS_LEGENDRE_COEFFS_11};
use kurbo::{
CubicBez, ParamCurve, ParamCurveArclen, ParamCurveCurvature, ParamCurveDeriv, Point, Vec2,
};
/// Calculate arclength using Gauss-Legendre quadrature using formula from Behdad
/// in <https://github.com/Pomax/BezierInfo-2/issues/77>
fn gauss_arclen_5(c: CubicBez) -> f64 {
let v0 = (c.p1 - c.p0).hypot() * 0.15;
let v1 = (-0.558983582205757 * c.p0.to_vec2()
+ 0.325650248872424 * c.p1.to_vec2()
+ 0.208983582205757 * c.p2.to_vec2()
+ 0.024349751127576 * c.p3.to_vec2())
.hypot();
let v2 = (c.p3 - c.p0 + (c.p2 - c.p1)).hypot() * 0.26666666666666666;
let v3 = (-0.024349751127576 * c.p0.to_vec2()
- 0.208983582205757 * c.p1.to_vec2()
- 0.325650248872424 * c.p2.to_vec2()
+ 0.558983582205757 * c.p3.to_vec2())
.hypot();
let v4 = (c.p3 - c.p2).hypot() * 0.15;
v0 + v1 + v2 + v3 + v4
}
fn gauss_arclen_7<C: ParamCurveDeriv>(c: C) -> f64 {
c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_7)
}
fn est_gauss5_error(c: CubicBez) -> f64 {
let lc = (c.p3 - c.p0).hypot();
let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot();
let d2 = c.deriv().deriv();
let d3 = d2.deriv();
let lmi = 2.0 / (lp + lc);
7e-8 * (d3.eval(0.5).to_vec2().hypot() * lmi + 5.0 * d2.eval(0.5).to_vec2().hypot() * lmi)
.powi(5)
* lp
}
fn gauss_errnorm_n<C: ParamCurveDeriv>(c: C, coeffs: &[(f64, f64)]) -> f64
where
C::DerivResult: ParamCurveDeriv,
{
let d = c.deriv().deriv();
coeffs
.iter()
.map(|(wi, xi)| wi * d.eval(0.5 * (xi + 1.0)).to_vec2().hypot2())
.sum::<f64>()
}
// Squared L2 norm of the second derivative of the cubic.
fn cubic_errnorm(c: CubicBez) -> f64 {
let d = c.deriv().deriv();
let dd = d.end() - d.start();
d.start().to_vec2().hypot2() + d.start().to_vec2().dot(dd) + dd.hypot2() * (1.0 / 3.0)
}
fn est_gauss7_error(c: CubicBez) -> f64 {
let lc = (c.p3 - c.p0).hypot();
let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot();
8e-9 * (2.0 * cubic_errnorm(c) / lc.powi(2)).powi(6) * lp
}
fn gauss_arclen_9<C: ParamCurveDeriv>(c: C) -> f64 {
c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_9)
}
fn gauss_arclen_11<C: ParamCurveDeriv>(c: C) -> f64 {
c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_11)
}
fn est_gauss9_error(c: CubicBez) -> f64 {
let lc = (c.p3 - c.p0).hypot();
let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot();
1e-10 * (2.0 * cubic_errnorm(c) / lc.powi(2)).powi(8) * lp
}
fn est_gauss11_error(c: CubicBez) -> f64 {
let lc = (c.p3 - c.p0).hypot();
let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot();
1e-12 * (2.0 * cubic_errnorm(c) / lc.powi(2)).powi(11) * lp
}
// A new approach based on integrating local error.
fn est_gauss11_error_2(c: CubicBez) -> f64 {
let d = c.deriv();
let d2 = d.deriv();
GAUSS_LEGENDRE_COEFFS_11
.iter()
.map(|(wi, xi)| {
wi * {
let t = 0.5 * (xi + 1.0);
let v = d.eval(t).to_vec2().hypot();
let a2 = d2.eval(t).to_vec2().hypot2();
a2.powi(3) / v.powi(5)
}
})
.sum::<f64>()
}
#[expect(
clippy::neg_cmp_op_on_partial_ord,
reason = "probably IEEE semantics nuance"
)]
fn est_max_curvature(c: CubicBez) -> f64 {
let n = 100;
let mut max = 0.0;
for i in 0..=n {
let t = (i as f64) * (n as f64).recip();
let k = c.curvature(t).abs();
if !(k < max) {
max = k;
}
}
max
}
fn est_min_deriv_norm2(c: CubicBez) -> f64 {
let d = c.deriv();
let n = 100;
let mut min = d.eval(1.0).to_vec2().hypot2();
for i in 0..n {
let t = (i as f64) * (n as f64).recip();
min = min.min(d.eval(t).to_vec2().hypot2());
}
min
}
fn est_gauss11_error_3(c: CubicBez) -> f64 {
let lc = (c.p3 - c.p0).hypot();
let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot();
let pc_err = (lp - lc) * 0.02;
let ks = est_max_curvature(c) * lp;
let est = ks.powi(3) * lp * 8e-9;
if est < pc_err { est } else { pc_err }
}
fn est_gauss9_error_3(c: CubicBez) -> f64 {
let lc = (c.p3 - c.p0).hypot();
let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot();
let pc_err = (lp - lc) * 0.02;
let ks = est_max_curvature(c) * lp;
let est = ks.powi(3) * lp * 5e-8;
if est < pc_err { est } else { pc_err }
}
// A new approach based on integrating local error; the cost of evaluating the
// error metric is likely to dominate unless the accuracy buys a lot of subdivisions.
fn est_gauss9_error_2(c: CubicBez) -> f64 {
let d = c.deriv();
let d2 = d.deriv();
let p = 10;
GAUSS_LEGENDRE_COEFFS_9
.iter()
.map(|(wi, xi)| {
wi * {
let t = 0.5 * (xi + 1.0);
let v = d.eval(t).to_vec2().hypot();
let a = d2.eval(t).to_vec2().hypot();
(1.0e-1 * a / v).tanh().powi(p) * v
}
})
.sum::<f64>()
* 3.0
}
fn my_arclen(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 {
if depth == 16 || est_gauss5_error(c) < accuracy {
*count += 1;
gauss_arclen_5(c)
} else {
let (c0, c1) = c.subdivide();
my_arclen(c0, accuracy * 0.5, depth + 1, count)
+ my_arclen(c1, accuracy * 0.5, depth + 1, count)
}
}
fn my_arclen7(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 {
if depth == 16 || est_gauss7_error(c) < accuracy {
*count += 1;
gauss_arclen_7(c)
} else {
let (c0, c1) = c.subdivide();
my_arclen7(c0, accuracy * 0.5, depth + 1, count)
+ my_arclen7(c1, accuracy * 0.5, depth + 1, count)
}
}
// Should make this generic instead of copy+paste, but we need only one when we're done.
fn my_arclen9(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 {
if depth == 16 || est_gauss9_error(c) < accuracy {
*count += 1;
gauss_arclen_9(c)
} else {
let (c0, c1) = c.subdivide();
my_arclen9(c0, accuracy * 0.5, depth + 1, count)
+ my_arclen9(c1, accuracy * 0.5, depth + 1, count)
}
}
// This doesn't help; we can't really get a more accurate error bound, so all this
// does is overkill the accuracy.
fn my_arclen11(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 {
if depth == 16 || est_gauss9_error(c) < accuracy {
*count += 1;
gauss_arclen_11(c)
} else {
let (c0, c1) = c.subdivide();
my_arclen11(c0, accuracy * 0.5, depth + 1, count)
+ my_arclen11(c1, accuracy * 0.5, depth + 1, count)
}
}
fn randpt() -> Point {
Point::new(rand::random(), rand::random())
}
fn randbez() -> CubicBez {
CubicBez::new(randpt(), randpt(), randpt(), randpt())
}
fn main() {
let accuracy = 1e-4;
for _ in 0..10_000 {
let c = randbez();
let t: f64 = rand::random();
let c = c.subsegment(0.0..t);
//let accurate_arclen = c.arclen(1e-12);
let mut count = 0;
let accurate_arclen = my_arclen9(c, 1e-15, 0, &mut count);
let est = gauss_arclen_9(c);
let est_err = est_gauss9_error_3(c);
let err = (accurate_arclen - est).abs();
println!("{est_err} {err}");
/*
let mut count = 0;
let est = my_arclen9(c, accuracy, 0, &mut count);
let err = (accurate_arclen - est).abs();
println!("{err} {count}");
*/
}
}
+28
View File
@@ -0,0 +1,28 @@
// Copyright 2020 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Example of ellipse
#[cfg(feature = "std")]
fn main() {
use kurbo::{Ellipse, Shape};
use std::f64::consts::PI;
let ellipse = Ellipse::new((400.0, 400.0), (200.0, 100.0), 0.25 * PI);
println!("<!DOCTYPE html>");
println!("<html>");
println!("<body>");
println!("<svg height=\"800\" width=\"800\" style=\"background-color: #999\">");
let black_path = ellipse.to_path(1e-3).to_svg();
println!(" <path d=\"{black_path}\" stroke=\"black\" fill=\"none\" />");
let red_path = ellipse.to_path(1.0).to_svg();
println!(" <path d=\"{red_path}\" stroke=\"red\" fill=\"none\" />");
println!("</svg>");
println!("</body>");
println!("</html>");
}
#[cfg(not(feature = "std"))]
fn main() {
println!("This example requires the standard library");
}
+76
View File
@@ -0,0 +1,76 @@
// Copyright 2022 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A test case for the cubic Bézier path simplifier, generating a very
//! efficient and accurate SVG file to plot a quartic polynomial. This
//! file was used to generate the image for the Wikipedia article on
//! quartic polynomials.
use std::{io::Write, ops::Range};
use kurbo::{BezPath, CurveFitSample, ParamCurveFit, PathEl, Point, Vec2};
struct MyPoly;
fn eval_mypoly(x: f64) -> f64 {
(x + 4.) * (x + 1.) * (x - 1.) * (x - 3.) / 14. + 0.5
}
fn eval_mypoly_deriv(x: f64) -> f64 {
(((4. * x + 3.) * x - 26.) * x - 1.) / 14.
}
impl ParamCurveFit for MyPoly {
fn sample_pt_deriv(&self, t: f64) -> (Point, Vec2) {
const S: f64 = 336.;
let x = 37. + t * S;
let math_x = (x - 220.) / 40.;
let y = -eval_mypoly(math_x) * 40. + 260.;
let dx = S;
let dy = -dx * eval_mypoly_deriv(math_x);
(Point::new(x, y), Vec2::new(dx, dy))
}
fn sample_pt_tangent(&self, t: f64, _: f64) -> CurveFitSample {
let (p, tangent) = self.sample_pt_deriv(t);
CurveFitSample { p, tangent }
}
fn break_cusp(&self, _: Range<f64>) -> Option<f64> {
None
}
}
fn to_svg_economical(path: &BezPath) -> String {
let mut buffer = Vec::new();
write_to(path, &mut buffer).unwrap();
String::from_utf8(buffer).unwrap()
}
/// Write the SVG representation of this path to the provided buffer.
fn write_to<W: Write>(path: &BezPath, mut writer: W) -> std::io::Result<()> {
for el in path.elements() {
match *el {
PathEl::MoveTo(p) => write!(writer, "M{:.2} {:.2}", p.x, p.y)?,
PathEl::LineTo(p) => write!(writer, "L{} {}", p.x, p.y)?,
PathEl::QuadTo(p1, p2) => write!(writer, "Q{} {} {} {}", p1.x, p1.y, p2.x, p2.y)?,
PathEl::CurveTo(p1, p2, p3) => write!(
writer,
"C{:.2} {:.2} {:.2} {:.2} {:.2} {:.2}",
p1.x, p1.y, p2.x, p2.y, p3.x, p3.y
)?,
PathEl::ClosePath => write!(writer, "Z")?,
}
}
Ok(())
}
fn main() {
println!("<svg width='800' height='600' xmlns='http://www.w3.org/2000/svg'>");
let path = kurbo::fit_to_bezpath_opt(&MyPoly, 0.1);
println!(
" <path d='{}' stroke='#008' fill='none' stroke-width='2.0'/>",
to_svg_economical(&path)
);
println!("</svg>");
}
+92
View File
@@ -0,0 +1,92 @@
// Copyright 2022 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Test case that demonstrates quadratic/quadratic intersection using
//! new quartic solver.
use arrayvec::ArrayVec;
use kurbo::{ParamCurve, Point, QuadBez, Shape, common::solve_quartic};
use rand::Rng;
fn rand_point() -> Point {
let mut rng = rand::rng();
Point::new(rng.random_range(0.0..500.0), rng.random_range(0.0..500.0))
}
fn rand_quad() -> QuadBez {
QuadBez::new(rand_point(), rand_point(), rand_point())
}
struct ImplicitQuad {
x2: f64,
xy: f64,
y2: f64,
x: f64,
y: f64,
c: f64,
}
impl ImplicitQuad {
fn from_quad(q: QuadBez) -> Self {
let Point { x: ax, y: ay } = q.p0;
let Point { x: bx, y: by } = q.p1;
let Point { x: cx, y: cy } = q.p2;
let (u0, u1, u2) = (by - cy, cx - bx, bx * cy - by * cx);
let (v0, v1, v2) = (cy - ay, ax - cx, cx * ay - cy * ax);
let (w0, w1, w2) = (ay - by, bx - ax, ax * by - ay * bx);
Self {
x2: 4. * u0 * w0 - v0 * v0,
xy: 4. * (u0 * w1 + u1 * w0) - 2. * v0 * v1,
y2: 4. * u1 * w1 - v1 * v1,
x: 4. * (u0 * w2 + u2 * w0) - 2. * v0 * v2,
y: 4. * (u1 * w2 + u2 * w1) - 2. * v1 * v2,
c: 4. * u2 * w2 - v2 * v2,
}
}
fn eval(&self, x: f64, y: f64) -> f64 {
self.x2 * x * x + self.xy * x * y + self.y2 * y * y + self.x * x + self.y * y + self.c
}
}
fn intersect_quads(q0: QuadBez, q1: QuadBez) -> ArrayVec<f64, 4> {
let iq = ImplicitQuad::from_quad(q0);
let c = q1.p0.to_vec2();
let b = (q1.p1 - q1.p0) * 2.0;
let a = c - q1.p1.to_vec2() * 2.0 + q1.p2.to_vec2();
let c0 = iq.eval(c.x, c.y);
let c1 = iq.x * b.x
+ iq.y * b.y
+ 2. * iq.x2 * (b.x * c.x)
+ 2. * iq.y2 * (b.y * c.y)
+ iq.xy * (b.x * c.y + b.y * c.x);
let c2 = iq.x * a.x
+ iq.y * a.y
+ iq.x2 * (2. * a.x * c.x + b.x * b.x)
+ iq.xy * (a.x * c.y + b.x * b.y + a.y * c.x)
+ iq.y2 * (2. * a.y * c.y + b.y * b.y);
let c3 = iq.x2 * 2. * a.x * b.x + iq.xy * (a.x * b.y + b.x * a.y) + iq.y2 * 2. * a.y * b.y;
let c4 = iq.x2 * a.x * a.x + iq.xy * a.x * a.y + iq.y2 * a.y * a.y;
let ts = solve_quartic(c0, c1, c2, c3, c4);
println!("ts: {ts:?}");
ts
}
fn main() {
let q0 = rand_quad();
let q1 = rand_quad();
println!(
" <path d='{}' stroke='#000' fill='none' />",
q0.to_path(1e-9).to_svg()
);
println!(
" <path d='{}' stroke='#008' fill='none' />",
q1.to_path(1e-9).to_svg()
);
for t in intersect_quads(q0, q1) {
if (0.0..=1.0).contains(&t) {
let p = q1.eval(t);
println!(" <circle cx='{}' cy='{}' r='3' />", p.x, p.y);
}
}
}
+52
View File
@@ -0,0 +1,52 @@
// Copyright 2022 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Test case showing simplification of a Bézier path. In this case, the
//! source path is a simple mathematical function, but it should work for
//! more general cases as well.
use kurbo::{BezPath, Point};
fn plot_fn(f: &dyn Fn(f64) -> f64, d: &dyn Fn(f64) -> f64, xa: f64, xb: f64, n: usize) -> BezPath {
let width = 800.;
let dx = (xb - xa) / n as f64;
let xs = width / (xb - xa);
let ys = 250.;
let y_origin = 300.;
let plot = |x, y| Point::new((x - xa) * xs, y_origin - y * ys);
let mut x0 = xa;
let mut y0 = f(xa);
let mut d0 = d(xa);
let mut path = BezPath::new();
path.move_to(plot(x0, y0));
for i in 0..n {
let x3 = xa + dx * (i + 1) as f64;
let y3 = f(x3);
let d3 = d(x3);
let x1 = x0 + (1. / 3.) * dx;
let x2 = x3 - (1. / 3.) * dx;
let y1 = y0 + d0 * (1. / 3.) * dx;
let y2 = y3 - d3 * (1. / 3.) * dx;
path.curve_to(plot(x1, y1), plot(x2, y2), plot(x3, y3));
x0 = x3;
y0 = y3;
d0 = d3;
}
path
}
fn main() {
println!("<svg width='800' height='600' xmlns='http://www.w3.org/2000/svg'>");
let path = plot_fn(&|x| x.sin(), &|x| x.cos(), -8., 8., 20);
println!(
" <path d='{}' stroke='#8c8' fill='none' stroke-width='5'/>",
path.to_svg()
);
let simpl = kurbo::simplify::SimplifyBezPath::new(path);
let simplified_path = kurbo::fit_to_bezpath_opt(&simpl, 0.1);
println!(
" <path d='{}' stroke='#000' fill='none' stroke-width='1'/>",
simplified_path.to_svg()
);
println!("</svg>");
}
+183
View File
@@ -0,0 +1,183 @@
// Copyright 2025 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Stroke example.
//!
//! This example has been lightly adapted from Vello, which in turn has
//! been adapted from the Skia "tricky stroke" test.
use kurbo::{Affine, BezPath, Cap, Join, Rect, Shape, Stroke, StrokeOpts, stroke};
fn tricky_strokes() {
const CELL_SIZE: f64 = 200.;
const STROKE_WIDTH: f64 = 30.;
const NUM_COLS: usize = 5;
fn stroke_bounds(pts: &[(f64, f64); 4]) -> Rect {
use kurbo::CubicBez;
CubicBez::new(pts[0], pts[1], pts[2], pts[3])
.bounding_box()
.inflate(STROKE_WIDTH, STROKE_WIDTH)
}
fn map_rect_to_rect(src: &Rect, dst: &Rect) -> (Affine, f64) {
let (scale, x_larger) = {
let sx = dst.width() / src.width();
let sy = dst.height() / src.height();
(sx.min(sy), sx > sy)
};
let tx = dst.x0 - src.x0 * scale;
let ty = dst.y0 - src.y0 * scale;
let (tx, ty) = if x_larger {
(tx + 0.5 * (dst.width() - src.width() * scale), ty)
} else {
(tx, ty + 0.5 * (dst.height() - src.height() * scale))
};
(Affine::new([scale, 0.0, 0.0, scale, tx, ty]), scale)
}
let tricky_cubics = [
[(122., 737.), (348., 553.), (403., 761.), (400., 760.)],
[(244., 520.), (244., 518.), (1141., 634.), (394., 688.)],
[(550., 194.), (138., 130.), (1035., 246.), (288., 300.)],
[(226., 733.), (556., 779.), (-43., 471.), (348., 683.)],
[(268., 204.), (492., 304.), (352., 23.), (433., 412.)],
[(172., 480.), (396., 580.), (256., 299.), (338., 677.)],
[(731., 340.), (318., 252.), (1026., -64.), (367., 265.)],
[(475., 708.), (62., 620.), (770., 304.), (220., 659.)],
[(0., 0.), (128., 128.), (128., 0.), (0., 128.)], // Perfect cusp
[(0., 0.01), (128., 127.999), (128., 0.01), (0., 127.99)], // Near-cusp
[(0., -0.01), (128., 128.001), (128., -0.01), (0., 128.001)], // Near-cusp
[(0., 0.), (0., -10.), (0., -10.), (0., 10.)], // Flat line with 180
[(10., 0.), (0., 0.), (20., 0.), (10., 0.)], // Flat line with 2 180s
[(39., -39.), (40., -40.), (40., -40.), (0., 0.)], // Flat diagonal with 180
[(40., 40.), (0., 0.), (200., 200.), (0., 0.)], // Diag w/ an internal 180
[(0., 0.), (1e-2, 0.), (-1e-2, 0.), (0., 0.)], // Circle
// Flat line with no turns:
[
(400.75, 100.05),
(400.75, 100.05),
(100.05, 300.95),
(100.05, 300.95),
],
[(0.5, 0.), (0., 0.), (20., 0.), (10., 0.)], // Flat line with 2 180s
[(10., 0.), (0., 0.), (10., 0.), (10., 0.)], // Flat line with a 180
];
// Flat conic with a cusp: (1,1) (2,1) (1,1), weight: 1
let flat_quad = [
// moveTo(1., 1.),
[(2., 1.), (1., 1.)],
];
// Flat conic with a cusp: (1,1) (100,1) (25,1), weight: 0.3
let flat_conic_as_quads = [
// moveTo(1., 1.),
[(2.232486, 1.000000), (3.471740, 1.000000)],
[(4.710995, 1.000000), (5.949262, 1.000000)],
[(7.187530, 1.000000), (8.417061, 1.000000)],
[(9.646591, 1.000000), (10.859690, 1.000000)],
[(12.072789, 1.000000), (13.261865, 1.000000)],
[(14.450940, 1.000000), (15.608549, 1.000000)],
[(16.766161, 1.000000), (17.885059, 1.000000)],
[(19.003958, 1.000000), (20.077141, 1.000000)],
[(21.150328, 1.000000), (22.171083, 1.000000)],
[(23.191839, 1.000000), (24.153776, 1.000000)],
[(25.115715, 1.000000), (26.012812, 1.000000)],
[(26.909912, 1.000000), (27.736557, 1.000000)],
[(28.563202, 1.000000), (29.314220, 1.000000)],
[(30.065239, 1.000000), (30.735928, 1.000000)],
[(31.406620, 1.000000), (31.992788, 1.000000)],
[(32.578957, 1.000000), (33.076927, 1.000000)],
[(33.574905, 1.000000), (33.981567, 1.000000)],
[(34.388233, 1.000000), (34.701038, 1.000000)],
[(35.013851, 1.000000), (35.230850, 1.000000)],
[(35.447845, 1.000000), (35.567669, 1.000000)],
[(35.687500, 1.000000), (35.709404, 1.000000)],
[(35.731312, 1.000000), (35.655155, 1.000000)],
[(35.579006, 1.000000), (35.405273, 1.000000)],
[(35.231541, 1.000000), (34.961311, 1.000000)],
[(34.691086, 1.000000), (34.326057, 1.000000)],
[(33.961029, 1.000000), (33.503479, 1.000000)],
[(33.045937, 1.000000), (32.498734, 1.000000)],
[(31.951530, 1.000000), (31.318098, 1.000000)],
[(30.684669, 1.000000), (29.968971, 1.000000)],
[(29.253277, 1.000000), (28.459791, 1.000000)],
[(27.666309, 1.000000), (26.800005, 1.000000)],
[(25.933704, 1.000000), (25.000000, 1.000000)],
];
// Flat conic with a cusp: (1,1) (100,1) (25,1), weight: 1.5
let bigger_flat_conic_as_quads = [
// moveTo(1., 1.),
[(8.979845, 1.000000), (15.795975, 1.000000)],
[(22.612104, 1.000000), (28.363287, 1.000000)],
[(34.114471, 1.000000), (38.884045, 1.000000)],
[(43.653618, 1.000000), (47.510696, 1.000000)],
[(51.367767, 1.000000), (54.368233, 1.000000)],
[(57.368698, 1.000000), (59.556030, 1.000000)],
[(61.743366, 1.000000), (63.149269, 1.000000)],
[(64.555168, 1.000000), (65.200005, 1.000000)],
[(65.844841, 1.000000), (65.737961, 1.000000)],
[(65.631073, 1.000000), (64.770912, 1.000000)],
[(63.910763, 1.000000), (62.284878, 1.000000)],
[(60.658997, 1.000000), (58.243816, 1.000000)],
[(55.828640, 1.000000), (52.589172, 1.000000)],
[(49.349705, 1.000000), (45.239006, 1.000000)],
[(41.128315, 1.000000), (36.086826, 1.000000)],
[(31.045338, 1.000000), (25.000000, 1.000000)],
];
let mut idx = 0;
let tolerance = 0.25;
for cubic in &tricky_cubics {
let x = (idx % NUM_COLS) as f64 * CELL_SIZE;
let y = (idx / NUM_COLS) as f64 * CELL_SIZE;
let cell = Rect::new(x, y, x + CELL_SIZE, y + CELL_SIZE);
let bounds = stroke_bounds(cubic);
let (t, s) = map_rect_to_rect(&bounds, &cell);
let style = Stroke::new(STROKE_WIDTH / s)
.with_caps(Cap::Butt)
.with_join(Join::Miter);
let mut path = BezPath::new();
path.move_to(cubic[0]);
path.curve_to(cubic[1], cubic[2], cubic[3]);
let stroked = stroke(path, &style, &StrokeOpts::default(), tolerance);
println!(
" <path d='{}' stroke='#000' fill='#aec' stroke-width='1'/>",
(t * stroked).to_svg()
);
idx += 1;
}
let flat_curves = [
flat_quad.as_slice(),
flat_conic_as_quads.as_slice(),
bigger_flat_conic_as_quads.as_slice(),
];
for quads in flat_curves.iter() {
let mut path = BezPath::new();
path.move_to((1., 1.));
for quad in quads.iter() {
path.quad_to(quad[0], quad[1]);
}
let x = (idx % NUM_COLS) as f64 * CELL_SIZE;
let y = (idx / NUM_COLS) as f64 * CELL_SIZE;
let cell = Rect::new(x, y, x + CELL_SIZE, y + CELL_SIZE);
let bounds = path.bounding_box().inflate(STROKE_WIDTH, STROKE_WIDTH);
let (t, s) = map_rect_to_rect(&bounds, &cell);
let style = Stroke::new(STROKE_WIDTH / s)
.with_caps(Cap::Butt)
.with_join(Join::Miter);
let stroked = stroke(path, &style, &StrokeOpts::default(), tolerance);
println!(
" <path d='{}' stroke='#000' fill='#aec' stroke-width='1'/>",
(t * stroked).to_svg()
);
idx += 1;
}
}
fn main() {
println!("<svg width='1000' height='1000' xmlns='http://www.w3.org/2000/svg'>");
tricky_strokes();
println!("</svg>");
}
+865
View File
@@ -0,0 +1,865 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Affine transforms.
use core::ops::{Mul, MulAssign};
use crate::{Point, Rect, Vec2};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A 2D affine transform.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Affine([f64; 6]);
impl Affine {
/// The identity transform.
pub const IDENTITY: Affine = Affine::scale(1.0);
/// A transform that is flipped on the y-axis. Useful for converting between
/// y-up and y-down spaces.
pub const FLIP_Y: Affine = Affine::new([1.0, 0., 0., -1.0, 0., 0.]);
/// A transform that is flipped on the x-axis.
pub const FLIP_X: Affine = Affine::new([-1.0, 0., 0., 1.0, 0., 0.]);
/// Construct an affine transform from coefficients.
///
/// If the coefficients are `(a, b, c, d, e, f)`, then the resulting
/// transformation represents this augmented matrix:
///
/// ```text
/// | a c e |
/// | b d f |
/// | 0 0 1 |
/// ```
///
/// Note that this convention is transposed from PostScript and
/// Direct2D, but is consistent with the
/// [Wikipedia](https://en.wikipedia.org/wiki/Affine_transformation)
/// formulation of affine transformation as augmented matrix. The
/// idea is that `(A * B) * v == A * (B * v)`, where `*` is the
/// [`Mul`] trait.
#[inline(always)]
pub const fn new(c: [f64; 6]) -> Affine {
Affine(c)
}
/// An affine transform representing uniform scaling.
#[inline(always)]
pub const fn scale(s: f64) -> Affine {
Affine([s, 0.0, 0.0, s, 0.0, 0.0])
}
/// An affine transform representing non-uniform scaling
/// with different scale values for x and y
#[inline(always)]
pub const fn scale_non_uniform(s_x: f64, s_y: f64) -> Affine {
Affine([s_x, 0.0, 0.0, s_y, 0.0, 0.0])
}
/// An affine transform representing a scale of `scale` about `center`.
///
/// Useful for a view transform that zooms at a specific point,
/// while keeping that point fixed in the result space.
///
/// See [`Affine::scale()`] for more info.
#[inline]
pub fn scale_about(s: f64, center: impl Into<Point>) -> Affine {
let center = center.into().to_vec2();
Self::translate(-center)
.then_scale(s)
.then_translate(center)
}
/// An affine transform representing rotation.
///
/// The convention for rotation is that a positive angle rotates a
/// positive X direction into positive Y. Thus, in a Y-down coordinate
/// system (as is common for graphics), it is a clockwise rotation, and
/// in Y-up (traditional for math), it is anti-clockwise.
///
/// The angle, `th`, is expressed in radians.
#[inline]
pub fn rotate(th: f64) -> Affine {
let (s, c) = th.sin_cos();
Affine([c, s, -s, c, 0.0, 0.0])
}
/// An affine transform representing a rotation of `th` radians about `center`.
///
/// See [`Affine::rotate()`] for more info.
#[inline]
pub fn rotate_about(th: f64, center: impl Into<Point>) -> Affine {
let center = center.into().to_vec2();
Self::translate(-center)
.then_rotate(th)
.then_translate(center)
}
/// An affine transform representing translation.
#[inline(always)]
pub fn translate<V: Into<Vec2>>(p: V) -> Affine {
let p = p.into();
Affine([1.0, 0.0, 0.0, 1.0, p.x, p.y])
}
/// An affine transformation representing a skew.
///
/// The `skew_x` and `skew_y` parameters represent skew factors for the
/// horizontal and vertical directions, respectively.
///
/// This is commonly used to generate a faux oblique transform for
/// font rendering. In this case, you can slant the glyph 20 degrees
/// clockwise in the horizontal direction (assuming a Y-up coordinate
/// system):
///
/// ```
/// let oblique_transform = kurbo::Affine::skew(20f64.to_radians().tan(), 0.0);
/// ```
#[inline(always)]
pub const fn skew(skew_x: f64, skew_y: f64) -> Affine {
Affine([1.0, skew_y, skew_x, 1.0, 0.0, 0.0])
}
/// Create an affine transform that represents reflection about the line `point + direction * t, t in (-infty, infty)`
///
/// # Examples
///
/// ```
/// # use kurbo::{Point, Vec2, Affine};
/// # fn assert_near(p0: Point, p1: Point) {
/// # assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}");
/// # }
/// let point = Point::new(1., 0.);
/// let vec = Vec2::new(1., 1.);
/// let map = Affine::reflect(point, vec);
/// assert_near(map * Point::new(1., 0.), Point::new(1., 0.));
/// assert_near(map * Point::new(2., 1.), Point::new(2., 1.));
/// assert_near(map * Point::new(2., 2.), Point::new(3., 1.));
/// ```
#[inline]
#[must_use]
pub fn reflect(point: impl Into<Point>, direction: impl Into<Vec2>) -> Self {
let point = point.into();
let direction = direction.into();
let n = Vec2 {
x: direction.y,
y: -direction.x,
}
.normalize();
// Compute Householder reflection matrix
let x2 = n.x * n.x;
let xy = n.x * n.y;
let y2 = n.y * n.y;
// Here we also add in the post translation, because it doesn't require any further calc.
let aff = Affine::new([
1. - 2. * x2,
-2. * xy,
-2. * xy,
1. - 2. * y2,
point.x,
point.y,
]);
aff.pre_translate(-point.to_vec2())
}
/// A [rotation] by `th` followed by `self`.
///
/// Equivalent to `self * Affine::rotate(th)`
///
/// [rotation]: Affine::rotate
#[inline]
#[must_use]
pub fn pre_rotate(self, th: f64) -> Self {
self * Affine::rotate(th)
}
/// A [rotation] by `th` about `center` followed by `self`.
///
/// Equivalent to `self * Affine::rotate_about(th, center)`
///
/// [rotation]: Affine::rotate_about
#[inline]
#[must_use]
pub fn pre_rotate_about(self, th: f64, center: impl Into<Point>) -> Self {
self * Affine::rotate_about(th, center)
}
/// A [scale] by `scale` followed by `self`.
///
/// Equivalent to `self * Affine::scale(scale)`
///
/// [scale]: Affine::scale
#[inline]
#[must_use]
pub fn pre_scale(self, scale: f64) -> Self {
self * Affine::scale(scale)
}
/// A [scale] by `(scale_x, scale_y)` followed by `self`.
///
/// Equivalent to `self * Affine::scale_non_uniform(scale_x, scale_y)`
///
/// [scale]: Affine::scale_non_uniform
#[inline]
#[must_use]
pub fn pre_scale_non_uniform(self, scale_x: f64, scale_y: f64) -> Self {
self * Affine::scale_non_uniform(scale_x, scale_y)
}
/// A [translation] of `trans` followed by `self`.
///
/// Equivalent to `self * Affine::translate(trans)`
///
/// [translation]: Affine::translate
#[inline]
#[must_use]
pub fn pre_translate(self, trans: Vec2) -> Self {
self * Affine::translate(trans)
}
/// A [skew] of `(skew_x, skew_y)` followed by `self`.
///
/// Equivalent to `self * Affine::skew(skew_x, skew_y)`
///
/// [skew]: Affine::skew
#[inline]
#[must_use]
pub fn pre_skew(self, skew_x: f64, skew_y: f64) -> Self {
self * Affine::skew(skew_x, skew_y)
}
/// A [reflection] about the line through `point` in `direction` followed by `self`.
///
/// Equivalent to `self * Affine::reflect(point, direction)`
///
/// [reflection]: Affine::reflect
#[inline]
#[must_use]
pub fn pre_reflect(self, point: impl Into<Point>, direction: impl Into<Vec2>) -> Self {
self * Affine::reflect(point, direction)
}
/// `self` followed by a [rotation] of `th`.
///
/// Equivalent to `Affine::rotate(th) * self`
///
/// [rotation]: Affine::rotate
#[inline]
#[must_use]
pub fn then_rotate(self, th: f64) -> Self {
Affine::rotate(th) * self
}
/// `self` followed by a [rotation] of `th` about `center`.
///
/// Equivalent to `Affine::rotate_about(th, center) * self`
///
/// [rotation]: Affine::rotate_about
#[inline]
#[must_use]
pub fn then_rotate_about(self, th: f64, center: impl Into<Point>) -> Self {
Affine::rotate_about(th, center) * self
}
/// `self` followed by a [scale] of `scale`.
///
/// Equivalent to `Affine::scale(scale) * self`
///
/// [scale]: Affine::scale
#[inline]
#[must_use]
pub fn then_scale(self, scale: f64) -> Self {
Affine::scale(scale) * self
}
/// `self` followed by a [scale] of `(scale_x, scale_y)`.
///
/// Equivalent to `Affine::scale_non_uniform(scale_x, scale_y) * self`
///
/// [scale]: Affine::scale_non_uniform
#[inline]
#[must_use]
pub fn then_scale_non_uniform(self, scale_x: f64, scale_y: f64) -> Self {
Affine::scale_non_uniform(scale_x, scale_y) * self
}
/// `self` followed by a [scale] of `scale` about `center`.
///
/// Equivalent to `Affine::scale_about(scale) * self`
///
/// [scale]: Affine::scale_about
#[inline]
#[must_use]
pub fn then_scale_about(self, scale: f64, center: impl Into<Point>) -> Self {
Affine::scale_about(scale, center) * self
}
/// `self` followed by a [skew] of `(skew_x, skew_y)`.
///
/// Equivalent to `Affine::skew(skew_x, skew_y) * self`
///
/// [skew]: Affine::skew
#[inline]
#[must_use]
pub fn then_skew(self, skew_x: f64, skew_y: f64) -> Self {
Affine::skew(skew_x, skew_y) * self
}
/// `self` followed by a [reflection] about the line through `point` in `direction`.
///
/// Equivalent to `Affine::reflect(point, direction) * self`
///
/// [reflection]: Affine::reflect
#[inline]
#[must_use]
pub fn then_reflect(self, point: impl Into<Point>, direction: impl Into<Vec2>) -> Self {
Affine::reflect(point, direction) * self
}
/// `self` followed by a translation of `trans`.
///
/// Equivalent to `Affine::translate(trans) * self`
///
/// [translation]: Affine::translate
#[inline]
#[must_use]
pub const fn then_translate(mut self, trans: Vec2) -> Self {
self.0[4] += trans.x;
self.0[5] += trans.y;
self
}
/// Creates an affine transformation that takes the unit square to the given rectangle.
///
/// Useful when you want to draw into the unit square but have your output fill any rectangle.
/// In this case push the `Affine` onto the transform stack.
pub const fn map_unit_square(rect: Rect) -> Affine {
Affine([rect.width(), 0., 0., rect.height(), rect.x0, rect.y0])
}
/// Get the coefficients of the transform.
#[inline(always)]
pub const fn as_coeffs(self) -> [f64; 6] {
self.0
}
/// Compute the determinant of this transform.
///
/// # Geometric interpretation
///
/// Consider a region transformed by this affine. The transformed region's area is the area of
/// the original region scaled by the absolute value of the determinant. A negative determinant
/// indicates orientation reversal.
#[inline]
pub const fn determinant(self) -> f64 {
self.0[0] * self.0[3] - self.0[1] * self.0[2]
}
/// Compute the square of the nuclear norm of this transform.
///
/// This is the square of the [Schatten p-norm][schatten] with `p=1`, also known as the "trace norm."
///
/// Returns the squared norm for efficiency; take the square root as necessary.
///
/// # Geometric interpretation
///
/// Consider a unit circle transformed by this affine. The nuclear norm is the sum of the
/// resulting ellipse's radii (semi axes). That sum multiplied by π is a first-order
/// approximation of the ellipse's perimeter.
///
/// [schatten]: <https://en.wikipedia.org/w/index.php?title=Matrix_norm&oldid=1348997593#Schatten_norms>
#[inline]
pub const fn nuclear_norm_squared(self) -> f64 {
self.frobenius_norm_squared() + 2. * self.determinant().abs()
}
/// Compute the square of the Frobenius norm of this transform.
///
/// This is the square of the [Schatten p-norm][schatten] with `p=2`.
///
/// Returns the squared norm for efficiency; take the square root as necessary.
///
/// # Geometric interpretation
///
/// Consider a unit circle transformed by this affine. The squared Frobenius norm is twice the
/// mean squared radius of the resulting ellipse. Alternatively, it is equal to the squared
/// distance from the ellipse's center to a corner of the rectangle spanned by the ellipse's
/// axes.
///
/// [schatten]: <https://en.wikipedia.org/w/index.php?title=Matrix_norm&oldid=1348997593#Schatten_norms>
#[inline]
pub const fn frobenius_norm_squared(self) -> f64 {
let [a, b, c, d, _, _] = self.as_coeffs();
a * a + b * b + c * c + d * d
}
/// Compute the spectral norm of this transform.
///
/// This is the [Schatten p-norm][schatten] with `p=∞`.
///
/// # Geometric interpretation
///
/// Consider a unit circle transformed by this affine. The spectral norm is the major radius
/// (semi-major axis) of the Ellipse.
///
/// [schatten]: <https://en.wikipedia.org/w/index.php?title=Matrix_norm&oldid=1348997593#Schatten_norms>
#[inline]
pub fn spectral_norm(self) -> f64 {
// Note a different calculation, returning the `_squared` form like our nuclear and
// Frobenius norms, could be `0.5 (frob^2 + sqrt(frob^4 - 4 det^2))`. In terms of operations
// it's a wash: one fewer sqrt if the user actually wants the squared form, but it uses more
// muls. More importantly, that form has worse numeric conditioning.
self.svd().0.x
}
/// Compute the inverse transform.
///
/// Produces NaN values when the determinant is zero.
pub const fn inverse(self) -> Affine {
let inv_det = self.determinant().recip();
Affine([
inv_det * self.0[3],
-inv_det * self.0[1],
-inv_det * self.0[2],
inv_det * self.0[0],
inv_det * (self.0[2] * self.0[5] - self.0[3] * self.0[4]),
inv_det * (self.0[1] * self.0[4] - self.0[0] * self.0[5]),
])
}
/// Compute the bounding box of a transformed rectangle.
///
/// Returns the minimal `Rect` that encloses the given `Rect` after affine transformation.
/// If the transform is axis-aligned, then this bounding box is "tight", in other words the
/// returned `Rect` is the transformed rectangle.
///
/// The returned rectangle always has non-negative width and height.
pub fn transform_rect_bbox(self, rect: Rect) -> Rect {
let p00 = self * Point::new(rect.x0, rect.y0);
let p01 = self * Point::new(rect.x0, rect.y1);
let p10 = self * Point::new(rect.x1, rect.y0);
let p11 = self * Point::new(rect.x1, rect.y1);
Rect::from_points(p00, p01).union(Rect::from_points(p10, p11))
}
/// Is this map [finite]?
///
/// [finite]: f64::is_finite
#[inline]
pub const fn is_finite(&self) -> bool {
self.0[0].is_finite()
&& self.0[1].is_finite()
&& self.0[2].is_finite()
&& self.0[3].is_finite()
&& self.0[4].is_finite()
&& self.0[5].is_finite()
}
/// Is this map [NaN]?
///
/// [NaN]: f64::is_nan
#[inline]
pub const fn is_nan(&self) -> bool {
self.0[0].is_nan()
|| self.0[1].is_nan()
|| self.0[2].is_nan()
|| self.0[3].is_nan()
|| self.0[4].is_nan()
|| self.0[5].is_nan()
}
/// Compute the singular value decomposition of the linear transformation (ignoring the
/// translation).
///
/// All non-degenerate linear transformations can be represented as
///
/// 1. a rotation about the origin.
/// 2. a scaling along the x and y axes
/// 3. another rotation about the origin
///
/// composed together. Decomposing a 2x2 matrix in this way is called a "singular value
/// decomposition" and is written `U Σ V^T`, where U and V^T are orthogonal (rotations) and Σ
/// is a diagonal matrix (a scaling).
///
/// Since currently this function is used to calculate ellipse radii and rotation from an
/// affine map on the unit circle, we don't calculate V^T, since a rotation of the unit (or
/// any) circle about its center always results in the same circle. This is the reason that an
/// ellipse mapped using an affine map is always an ellipse.
///
/// Will return NaNs if the matrix (or equivalently the linear map) is non-finite.
///
/// The first part of the returned tuple is the scaling, the second part is the angle of
/// rotation (in radians). The scaling along the x-axis is guaranteed to be greater than or
/// equal to the scaling along the y-axis.
//
// Note: though this does quite some computation, we are often interested only in specific
// components of the result. Hence this is marked `#[inline(always)]`, to give the compiler a
// good chance at eliminating dead code.
#[inline(always)]
pub(crate) fn svd(self) -> (Vec2, f64) {
let [a, b, c, d, _, _] = self.0;
let a2 = a * a;
let b2 = b * b;
let c2 = c * c;
let d2 = d * d;
let ab = a * b;
let cd = c * d;
let angle = 0.5 * (2.0 * (ab + cd)).atan2(a2 - b2 + c2 - d2);
// Given matrix A = [ a c ]
// [ b d ]
//
// The two singular values σ1, σ2 of A are the square roots of the two eigen values λ1, λ2
// of M = A^T A. The common formula for 2x2 eigenvalues requires evaluating a square root,
// but we'd like to compute the singular values of the matrix without nested square roots.
//
// M = A^T A = [ aa+cc ab+cd ]
// [ ab+cd bb+dd ]
//
// We have
// λ = 1/2 (tr(M) ± sqrt(tr(M)^2 - 4 det(M))).
//
// Note det(M) = det(A^T A) = det(A)^2.
// => 2λ = tr(M) ± sqrt(tr(M)^2 - 4 det(A)^2)
// => 2λ = tr(M) ± sqrt[(a^2+b^2+c^2+d^2)^2 - 4 (ad-bc)^2]
// By factorizing the inner term,
// => 2λ = tr(M) ± sqrt[((a+d)^2 + (b-c)^2) ((a-d)^2 + (b+c)^2)]
// => 2λ = tr(M) ± sqrt[(a+d)^2 + (b-c)^2] sqrt[(a-d)^2 + (b+c)^2]
//
// Define S1 = sqrt[(a+d)^2 + (b-c)^2]
// S2 = sqrt[(a-d)^2 + (b+c)^2].
//
// => 2λ = tr(M) ± S1 S2
// => 2λ = 1/2 (S1^2 + S2^2) ± S1 S2
// => λ = 1/4 (S1^2 + S2^2 ± 2 S1 S2)
// => λ = 1/4 (S1 ± S2)^2
//
// Note we're interested in
// σ = sqrt(λ).
//
// => σ1 = 1/2 (S1 + S2)
// and similarly σ2 = 1/2 |S1 - S2|
let s1 = ((a + d).powi(2) + (b - c).powi(2)).sqrt();
let s2 = ((a - d).powi(2) + (b + c).powi(2)).sqrt();
(
Vec2 {
x: 0.5 * (s1 + s2),
y: 0.5 * (s1 - s2).abs(),
},
angle,
)
}
/// Returns the translation part of this affine map (`(self.0[4], self.0[5])`).
#[inline(always)]
pub const fn translation(self) -> Vec2 {
Vec2 {
x: self.0[4],
y: self.0[5],
}
}
/// Replaces the translation portion of this affine map
///
/// The translation can be seen as being applied after the linear part of the map.
#[must_use]
#[inline(always)]
pub const fn with_translation(mut self, trans: Vec2) -> Affine {
self.0[4] = trans.x;
self.0[5] = trans.y;
self
}
}
impl Default for Affine {
#[inline(always)]
fn default() -> Affine {
Affine::IDENTITY
}
}
impl Mul<Point> for Affine {
type Output = Point;
#[inline]
fn mul(self, other: Point) -> Point {
Point::new(
self.0[0] * other.x + self.0[2] * other.y + self.0[4],
self.0[1] * other.x + self.0[3] * other.y + self.0[5],
)
}
}
impl Mul for Affine {
type Output = Affine;
#[inline]
fn mul(self, other: Affine) -> Affine {
Affine([
self.0[0] * other.0[0] + self.0[2] * other.0[1],
self.0[1] * other.0[0] + self.0[3] * other.0[1],
self.0[0] * other.0[2] + self.0[2] * other.0[3],
self.0[1] * other.0[2] + self.0[3] * other.0[3],
self.0[0] * other.0[4] + self.0[2] * other.0[5] + self.0[4],
self.0[1] * other.0[4] + self.0[3] * other.0[5] + self.0[5],
])
}
}
impl MulAssign for Affine {
#[inline]
fn mul_assign(&mut self, other: Affine) {
*self = self.mul(other);
}
}
impl Mul<Affine> for f64 {
type Output = Affine;
#[inline]
fn mul(self, other: Affine) -> Affine {
Affine([
self * other.0[0],
self * other.0[1],
self * other.0[2],
self * other.0[3],
self * other.0[4],
self * other.0[5],
])
}
}
// Conversions to and from mint
#[cfg(feature = "mint")]
impl From<Affine> for mint::ColumnMatrix2x3<f64> {
#[inline(always)]
fn from(a: Affine) -> mint::ColumnMatrix2x3<f64> {
mint::ColumnMatrix2x3 {
x: mint::Vector2 {
x: a.0[0],
y: a.0[1],
},
y: mint::Vector2 {
x: a.0[2],
y: a.0[3],
},
z: mint::Vector2 {
x: a.0[4],
y: a.0[5],
},
}
}
}
#[cfg(feature = "mint")]
impl From<mint::ColumnMatrix2x3<f64>> for Affine {
#[inline(always)]
fn from(m: mint::ColumnMatrix2x3<f64>) -> Affine {
Affine([m.x.x, m.x.y, m.y.x, m.y.y, m.z.x, m.z.y])
}
}
#[cfg(test)]
mod tests {
use crate::{Affine, Point, Vec2};
use std::f64::consts::PI;
fn assert_near(p0: Point, p1: Point) {
assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}");
}
fn affine_assert_near(a0: Affine, a1: Affine) {
for i in 0..6 {
assert!((a0.0[i] - a1.0[i]).abs() < 1e-9, "{a0:?} != {a1:?}");
}
}
#[test]
fn affine_basic() {
let p = Point::new(3.0, 4.0);
assert_near(Affine::default() * p, p);
assert_near(Affine::scale(2.0) * p, Point::new(6.0, 8.0));
assert_near(Affine::rotate(0.0) * p, p);
assert_near(Affine::rotate(PI / 2.0) * p, Point::new(-4.0, 3.0));
assert_near(Affine::translate((5.0, 6.0)) * p, Point::new(8.0, 10.0));
assert_near(Affine::skew(0.0, 0.0) * p, p);
assert_near(Affine::skew(2.0, 4.0) * p, Point::new(11.0, 16.0));
}
#[test]
fn affine_mul() {
let a1 = Affine::new([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
let a2 = Affine::new([0.1, 1.2, 2.3, 3.4, 4.5, 5.6]);
let px = Point::new(1.0, 0.0);
let py = Point::new(0.0, 1.0);
let pxy = Point::new(1.0, 1.0);
assert_near(a1 * (a2 * px), (a1 * a2) * px);
assert_near(a1 * (a2 * py), (a1 * a2) * py);
assert_near(a1 * (a2 * pxy), (a1 * a2) * pxy);
}
#[test]
fn affine_inv() {
let a = Affine::new([0.1, 1.2, 2.3, 3.4, 4.5, 5.6]);
let a_inv = a.inverse();
let px = Point::new(1.0, 0.0);
let py = Point::new(0.0, 1.0);
let pxy = Point::new(1.0, 1.0);
assert_near(a * (a_inv * px), px);
assert_near(a * (a_inv * py), py);
assert_near(a * (a_inv * pxy), pxy);
assert_near(a_inv * (a * px), px);
assert_near(a_inv * (a * py), py);
assert_near(a_inv * (a * pxy), pxy);
}
#[test]
fn reflection() {
affine_assert_near(
Affine::reflect(Point::ZERO, (1., 0.)),
Affine::new([1., 0., 0., -1., 0., 0.]),
);
affine_assert_near(
Affine::reflect(Point::ZERO, (0., 1.)),
Affine::new([-1., 0., 0., 1., 0., 0.]),
);
// y = x
affine_assert_near(
Affine::reflect(Point::ZERO, (1., 1.)),
Affine::new([0., 1., 1., 0., 0., 0.]),
);
// no translate
let point = Point::new(0., 0.);
let vec = Vec2::new(1., 1.);
let map = Affine::reflect(point, vec);
assert_near(map * Point::new(0., 0.), Point::new(0., 0.));
assert_near(map * Point::new(1., 1.), Point::new(1., 1.));
assert_near(map * Point::new(1., 2.), Point::new(2., 1.));
// with translate
let point = Point::new(1., 0.);
let vec = Vec2::new(1., 1.);
let map = Affine::reflect(point, vec);
assert_near(map * Point::new(1., 0.), Point::new(1., 0.));
assert_near(map * Point::new(2., 1.), Point::new(2., 1.));
assert_near(map * Point::new(2., 2.), Point::new(3., 1.));
}
#[test]
fn svd() {
let a = Affine::new([1., 2., 3., 4., 5., 6.]);
let a_no_translate = a.with_translation(Vec2::ZERO);
// translation should have no effect
let (scale, rotation) = a.svd();
let (scale_no_translate, rotation_no_translate) = a_no_translate.svd();
assert_near(scale.to_point(), scale_no_translate.to_point());
assert!((rotation - rotation_no_translate).abs() <= 1e-9);
assert_near(
scale.to_point(),
Point::new(5.4649857042190427, 0.36596619062625782),
);
assert!((rotation - 0.95691013360780001).abs() <= 1e-9);
// singular affine
let a = Affine::new([0., 0., 0., 0., 5., 6.]);
assert_eq!(a.determinant(), 0.);
let (scale, rotation) = a.svd();
assert_eq!(scale, Vec2::new(0., 0.));
assert_eq!(rotation, 0.);
}
#[test]
fn svd_singular_values() {
// Test a few known singular values.
let mat = |a, b, c, d| Affine::new([a, b, c, d, 0., 0.]);
let s = mat(1., 0., 0., 1.).svd().0;
assert_near(s.to_point(), Point::new(1., 1.));
let s = mat(1., 0., 0., -1.).svd().0;
assert_near(s.to_point(), Point::new(1., 1.));
let s = mat(1., 1., 1., 1.).svd().0;
assert_near(s.to_point(), Point::new(2., 0.));
let s = mat(1., 1., 1., 1.).svd().0;
assert_near(s.to_point(), Point::new(2., 0.));
let s = mat(0., 0., 1., 0.).svd().0;
assert_near(s.to_point(), Point::new(1., 0.));
// The singular values are the scaling of the affine map. So let's test that.
let s = Affine::scale_non_uniform(4., 8.)
.then_rotate_about(42_f64.to_radians(), (-2., 50.))
.svd()
.0;
assert_near(s.to_point(), Point::new(8., 4.));
// Correctly handles negative scaling (singular values are necessarily non-negative).
let s = Affine::scale_non_uniform(-20., 3.).svd().0;
assert_near(s.to_point(), Point::new(20., 3.));
let s = Affine::scale_non_uniform(-20., -3.).svd().0;
assert_near(s.to_point(), Point::new(20., 3.));
let s = Affine::scale_non_uniform(20., -3.).svd().0;
assert_near(s.to_point(), Point::new(20., 3.));
// One more property: given a full-rank transform, the product of its singular values
// should be equal to its absolute determinant.
let m = mat(10., 9., -2.5, 3.3333);
let s = m.svd().0;
let prod = s.x * s.y;
let det = m.determinant().abs();
assert!(
(prod - det) < 1e-9,
"The product of the singular values {s:?} ({prod}) should be equal to the absolute determinant {det}.",
);
}
#[test]
fn rotate_about_composition() {
let theta = core::f64::consts::FRAC_PI_2;
let center = Point::new(-1., 0.);
let translation = Vec2::new(0., 1.);
let probe = Point::ORIGIN;
let rotate_about = Affine::rotate_about(theta, center);
let translate = Affine::translate(translation);
// Establish baselines with raw matrix composition
// (also a sanity check to ensure the order of ops matters for this contrived test)
let rotate_then_translate = translate * rotate_about;
let translate_then_rotate = rotate_about * translate;
assert_near(rotate_then_translate * probe, Point::new(-1., 2.));
assert_near(translate_then_rotate * probe, Point::new(-2., 1.));
// Check .then_* semantics
affine_assert_near(
rotate_about.then_translate(translation),
rotate_then_translate,
);
affine_assert_near(
translate.then_rotate_about(theta, center),
translate_then_rotate,
);
// Check .pre_rotate_about semantics
affine_assert_near(
translate.pre_rotate_about(theta, center),
rotate_then_translate,
);
}
}
+341
View File
@@ -0,0 +1,341 @@
// Copyright 2019 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! An ellipse arc.
use crate::{Affine, Ellipse, ParamCurve, PathEl, Point, Rect, Shape, Vec2};
use core::{
f64::consts::{FRAC_PI_2, PI},
iter,
ops::{Mul, Range},
};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A single elliptical arc segment.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Arc {
/// The arc's centre point.
pub center: Point,
/// The arc's radii, where the vector's x-component is the radius in the
/// positive x direction after applying `x_rotation`.
pub radii: Vec2,
/// The start angle in radians.
pub start_angle: f64,
/// The angle between the start and end of the arc, in radians.
pub sweep_angle: f64,
/// How much the arc is rotated, in radians.
pub x_rotation: f64,
}
impl Arc {
/// Create a new `Arc`.
#[inline(always)]
pub fn new(
center: impl Into<Point>,
radii: impl Into<Vec2>,
start_angle: f64,
sweep_angle: f64,
x_rotation: f64,
) -> Self {
Self {
center: center.into(),
radii: radii.into(),
start_angle,
sweep_angle,
x_rotation,
}
}
/// Returns a copy of this `Arc` in the opposite direction.
///
/// The new `Arc` will sweep towards the original `Arc`s
/// start angle.
#[must_use]
#[inline]
pub fn reversed(&self) -> Arc {
Self {
center: self.center,
radii: self.radii,
start_angle: self.start_angle + self.sweep_angle,
sweep_angle: -self.sweep_angle,
x_rotation: self.x_rotation,
}
}
#[inline]
fn angle_at(&self, t: f64) -> f64 {
self.start_angle + self.sweep_angle * t
}
/// Create an iterator generating Bezier path elements.
///
/// The generated elements can be appended to an existing bezier path.
pub fn append_iter(&self, tolerance: f64) -> ArcAppendIter {
let sign = self.sweep_angle.signum();
let scaled_err = self.radii.x.max(self.radii.y) / tolerance;
// Number of subdivisions per ellipse based on error tolerance.
// Note: this may slightly underestimate the error for quadrants.
let n_err = (1.1163 * scaled_err).powf(1.0 / 6.0).max(3.999_999);
let n = (n_err * self.sweep_angle.abs() * (1.0 / (2.0 * PI))).ceil();
let angle_step = self.sweep_angle / n;
let n = n as usize;
let arm_len = (4.0 / 3.0) * (0.25 * angle_step).abs().tan() * sign;
let angle0 = self.start_angle;
let p0 = sample_ellipse(self.radii, self.x_rotation, angle0);
ArcAppendIter {
idx: 0,
center: self.center,
radii: self.radii,
x_rotation: self.x_rotation,
n,
arm_len,
angle_step,
p0,
angle0,
}
}
/// Converts an `Arc` into a series of cubic bezier segments.
///
/// The closure `p` will be invoked with the control points for each segment.
pub fn to_cubic_beziers<P>(self, tolerance: f64, mut p: P)
where
P: FnMut(Point, Point, Point),
{
let mut path = self.append_iter(tolerance);
while let Some(PathEl::CurveTo(p1, p2, p3)) = path.next() {
p(p1, p2, p3);
}
}
}
#[doc(hidden)]
pub struct ArcAppendIter {
idx: usize,
center: Point,
radii: Vec2,
x_rotation: f64,
n: usize,
arm_len: f64,
angle_step: f64,
p0: Vec2,
angle0: f64,
}
impl Iterator for ArcAppendIter {
type Item = PathEl;
fn next(&mut self) -> Option<Self::Item> {
if self.idx >= self.n {
return None;
}
let angle1 = self.angle0 + self.angle_step;
let p0 = self.p0;
let p1 = p0
+ self.arm_len * sample_ellipse(self.radii, self.x_rotation, self.angle0 + FRAC_PI_2);
let p3 = sample_ellipse(self.radii, self.x_rotation, angle1);
let p2 =
p3 - self.arm_len * sample_ellipse(self.radii, self.x_rotation, angle1 + FRAC_PI_2);
self.angle0 = angle1;
self.p0 = p3;
self.idx += 1;
Some(PathEl::CurveTo(
self.center + p1,
self.center + p2,
self.center + p3,
))
}
}
/// Take the ellipse radii, how the radii are rotated, and the sweep angle, and return a point on
/// the ellipse.
fn sample_ellipse(radii: Vec2, x_rotation: f64, angle: f64) -> Vec2 {
let (angle_sin, angle_cos) = angle.sin_cos();
let u = radii.x * angle_cos;
let v = radii.y * angle_sin;
rotate_pt(Vec2::new(u, v), x_rotation)
}
/// Rotate `pt` about the origin by `angle` radians.
fn rotate_pt(pt: Vec2, angle: f64) -> Vec2 {
let (angle_sin, angle_cos) = angle.sin_cos();
Vec2::new(
pt.x * angle_cos - pt.y * angle_sin,
pt.x * angle_sin + pt.y * angle_cos,
)
}
impl ParamCurve for Arc {
fn eval(&self, t: f64) -> Point {
self.center + sample_ellipse(self.radii, self.x_rotation, self.angle_at(t))
}
fn subsegment(&self, range: Range<f64>) -> Self {
Self {
center: self.center,
radii: self.radii,
start_angle: self.angle_at(range.start),
sweep_angle: self.sweep_angle * (range.end - range.start),
x_rotation: self.x_rotation,
}
}
}
impl Shape for Arc {
type PathElementsIter<'iter> = iter::Chain<iter::Once<PathEl>, ArcAppendIter>;
fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_> {
iter::once(PathEl::MoveTo(self.start())).chain(self.append_iter(tolerance))
}
/// Note: shape isn't closed so area is not well defined.
#[inline]
fn area(&self) -> f64 {
let Vec2 { x, y } = self.radii;
PI * x * y
}
/// The perimeter of the arc.
///
/// For now we just approximate by using the bezier curve representation.
#[inline]
fn perimeter(&self, accuracy: f64) -> f64 {
self.path_segments(0.1).perimeter(accuracy)
}
/// Note: shape isn't closed, so a point's winding number is not well defined.
#[inline]
fn winding(&self, pt: Point) -> i32 {
self.path_segments(0.1).winding(pt)
}
#[inline]
fn bounding_box(&self) -> Rect {
self.path_segments(0.1).bounding_box()
}
}
impl Mul<Arc> for Affine {
type Output = Arc;
fn mul(self, arc: Arc) -> Self::Output {
let ellipse = self * Ellipse::new(arc.center, arc.radii, arc.x_rotation);
let center = ellipse.center();
let (radii, rotation) = ellipse.radii_and_rotation();
Arc {
center,
radii,
x_rotation: rotation,
start_angle: arc.start_angle,
sweep_angle: arc.sweep_angle,
}
}
}
#[cfg(test)]
mod tests {
use core::f64::consts::{FRAC_PI_4, FRAC_PI_6};
use crate::ParamCurve;
use super::*;
fn assert_point_near(actual: Point, expected: Point) {
let epsilon = 1e-12;
assert!(
actual.distance(expected) <= epsilon,
"expected {expected:?}, got {actual:?}"
);
}
fn assert_subsegment_matches(arc: Arc, range: Range<f64>) {
let subsegment = arc.subsegment(range.clone());
for t in [0.0, 0.25, 0.5, 1.0] {
let expected_t = range.start + (range.end - range.start) * t;
assert_point_near(subsegment.eval(t), arc.eval(expected_t));
}
assert_point_near(subsegment.start(), arc.eval(range.start));
assert_point_near(subsegment.end(), arc.eval(range.end));
}
#[test]
fn reversed_arc() {
let a = Arc::new((0., 0.), (1., 0.), 0., PI, 0.);
let f = a.reversed();
// Most fields should be unchanged:
assert_eq!(a.center, f.center);
assert_eq!(a.radii, f.radii);
assert_eq!(a.x_rotation, f.x_rotation);
// Sweep angle should be in reverse
assert_eq!(a.sweep_angle, -f.sweep_angle);
// Reversing it again should result in the original arc
assert_eq!(a, f.reversed());
}
#[test]
fn eval_endpoints_and_midpoint() {
let arc = Arc::new((3.0, -2.0), (4.0, 1.5), FRAC_PI_6, PI, 0.0);
assert_point_near(arc.eval(0.0), arc.start());
assert_point_near(arc.eval(1.0), arc.end());
assert_point_near(
arc.eval(0.5),
arc.center + sample_ellipse(arc.radii, arc.x_rotation, arc.angle_at(0.5)),
);
}
#[test]
fn eval_rotated_ellipse() {
let arc = Arc::new((5.0, 7.0), (3.0, 2.0), FRAC_PI_6, PI / 3.0, FRAC_PI_4);
assert_point_near(
arc.start(),
arc.center + sample_ellipse(arc.radii, arc.x_rotation, arc.start_angle),
);
assert_point_near(
arc.end(),
arc.center
+ sample_ellipse(arc.radii, arc.x_rotation, arc.start_angle + arc.sweep_angle),
);
}
#[test]
fn eval_reversed_arc() {
let arc = Arc::new((2.0, 3.0), (4.0, 1.0), FRAC_PI_6, PI / 2.0, FRAC_PI_4);
let reversed = arc.reversed();
assert_point_near(reversed.start(), arc.end());
assert_point_near(reversed.end(), arc.start());
assert_point_near(reversed.eval(0.5), arc.eval(0.5));
}
#[test]
fn subsegment_matches_original() {
let arc = Arc::new((1.0, -4.0), (3.0, 2.0), -FRAC_PI_4, PI, FRAC_PI_6);
assert_subsegment_matches(arc, 0.2..0.7);
}
#[test]
fn subsegment_negative_sweep_matches_original() {
let arc = Arc::new((1.0, 2.0), (5.0, 3.0), PI, -0.75 * PI, FRAC_PI_6);
assert_subsegment_matches(arc, 0.1..0.8);
}
#[test]
fn subsegment_tiny_sweep_matches_original() {
let arc = Arc::new((0.0, 0.0), (2.0, 1.0), 1.0, 1e-9, FRAC_PI_4);
assert_subsegment_matches(arc, 0.25..0.75);
}
}
+72
View File
@@ -0,0 +1,72 @@
// Copyright 2025 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
use crate::{Point, Size, Vec2};
/// An axis in the plane.
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub enum Axis {
/// The x axis.
Horizontal,
/// The y axis.
Vertical,
}
impl Axis {
/// Get the axis perpendicular to this one.
#[inline]
pub const fn cross(self) -> Self {
match self {
Self::Horizontal => Self::Vertical,
Self::Vertical => Self::Horizontal,
}
}
/// Create a new [`Point`] by arranging the given magnitudes.
///
/// The axis value is the one matching the axis (e.g. `y` for [`Self::Vertical`]).
/// The cross value is the other one.
#[inline]
pub const fn pack_point(self, axis_value: f64, cross_value: f64) -> Point {
match self {
Self::Horizontal => Point::new(axis_value, cross_value),
Self::Vertical => Point::new(cross_value, axis_value),
}
}
/// Create a new [`Size`] by arranging the given magnitudes.
///
/// The axis value is the one matching the axis (e.g. `height` for [`Self::Vertical`]).
/// The cross value is the other one.
#[inline]
pub const fn pack_size(self, axis_value: f64, cross_value: f64) -> Size {
match self {
Self::Horizontal => Size::new(axis_value, cross_value),
Self::Vertical => Size::new(cross_value, axis_value),
}
}
/// Create a new [`Vec2`] by arranging the given magnitudes.
///
/// The axis value is the one matching the axis (e.g. `y` for [`Self::Vertical`]).
/// The cross value is the other one.
#[inline]
pub const fn pack_vec2(self, axis_value: f64, cross_value: f64) -> Vec2 {
match self {
Self::Horizontal => Vec2::new(axis_value, cross_value),
Self::Vertical => Vec2::new(cross_value, axis_value),
}
}
/// Create a new `(x, y)` pair by arranging the given magnitudes.
///
/// The axis value is the one matching the axis (e.g. `y` for [`Self::Vertical`]).
/// The cross value is the other one.
#[inline]
pub const fn pack_xy(self, axis_value: f64, cross_value: f64) -> (f64, f64) {
match self {
Self::Horizontal => (axis_value, cross_value),
Self::Vertical => (cross_value, axis_value),
}
}
}
+2311
View File
File diff suppressed because it is too large. Load diff
+428
View File
@@ -0,0 +1,428 @@
// Copyright 2019 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Implementation of circle shape.
use core::{
f64::consts::{FRAC_PI_2, PI},
iter,
ops::{Add, Mul, Sub},
};
use crate::{Affine, Arc, ArcAppendIter, Ellipse, PathEl, Point, Rect, Shape, Vec2};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A circle.
#[derive(Clone, Copy, Default, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Circle {
/// The center.
pub center: Point,
/// The radius.
pub radius: f64,
}
impl Circle {
/// A new circle from center and radius.
#[inline(always)]
pub fn new(center: impl Into<Point>, radius: f64) -> Circle {
Circle {
center: center.into(),
radius,
}
}
/// Create a [`CircleSegment`] by cutting out parts of this circle.
#[inline(always)]
pub fn segment(self, inner_radius: f64, start_angle: f64, sweep_angle: f64) -> CircleSegment {
CircleSegment {
center: self.center,
outer_radius: self.radius,
inner_radius,
start_angle,
sweep_angle,
}
}
/// Is this circle [finite]?
///
/// [finite]: f64::is_finite
#[inline]
pub fn is_finite(&self) -> bool {
self.center.is_finite() && self.radius.is_finite()
}
/// Is this circle [NaN]?
///
/// [NaN]: f64::is_nan
#[inline]
pub fn is_nan(&self) -> bool {
self.center.is_nan() || self.radius.is_nan()
}
}
impl Add<Vec2> for Circle {
type Output = Circle;
#[inline]
fn add(self, v: Vec2) -> Circle {
Circle {
center: self.center + v,
radius: self.radius,
}
}
}
impl Sub<Vec2> for Circle {
type Output = Circle;
#[inline]
fn sub(self, v: Vec2) -> Circle {
Circle {
center: self.center - v,
radius: self.radius,
}
}
}
impl Mul<Circle> for Affine {
type Output = Ellipse;
fn mul(self, other: Circle) -> Self::Output {
self * Ellipse::from(other)
}
}
#[doc(hidden)]
pub struct CirclePathIter {
circle: Circle,
delta_th: f64,
arm_len: f64,
ix: usize,
n: usize,
}
impl Shape for Circle {
type PathElementsIter<'iter> = CirclePathIter;
fn path_elements(&self, tolerance: f64) -> CirclePathIter {
let scaled_err = self.radius.abs() / tolerance;
let (n, arm_len) = if scaled_err < 1.0 / 1.9608e-4 {
// Solution from http://spencermortensen.com/articles/bezier-circle/
(4, 0.551915024494)
} else {
// This is empirically determined to fall within error tolerance.
let n = (1.1163 * scaled_err).powf(1.0 / 6.0).ceil() as usize;
// Note: this isn't minimum error, but it is simple and we can easily
// estimate the error.
let arm_len = (4.0 / 3.0) * (FRAC_PI_2 / (n as f64)).tan();
(n, arm_len)
};
CirclePathIter {
circle: *self,
delta_th: 2.0 * PI / (n as f64),
arm_len,
ix: 0,
n,
}
}
#[inline]
fn area(&self) -> f64 {
PI * self.radius.powi(2)
}
#[inline]
fn perimeter(&self, _accuracy: f64) -> f64 {
(2.0 * PI * self.radius).abs()
}
fn winding(&self, pt: Point) -> i32 {
if (pt - self.center).hypot2() < self.radius.powi(2) {
1
} else {
0
}
}
#[inline]
fn bounding_box(&self) -> Rect {
let r = self.radius.abs();
let (x, y) = self.center.into();
Rect::new(x - r, y - r, x + r, y + r)
}
#[inline(always)]
fn as_circle(&self) -> Option<Circle> {
Some(*self)
}
}
impl Iterator for CirclePathIter {
type Item = PathEl;
fn next(&mut self) -> Option<PathEl> {
let a = self.arm_len;
let r = self.circle.radius;
let (x, y) = self.circle.center.into();
let ix = self.ix;
self.ix += 1;
if ix == 0 {
Some(PathEl::MoveTo(Point::new(x + r, y)))
} else if ix <= self.n {
let th1 = self.delta_th * (ix as f64);
let th0 = th1 - self.delta_th;
let (s0, c0) = th0.sin_cos();
let (s1, c1) = if ix == self.n {
(0.0, 1.0)
} else {
th1.sin_cos()
};
Some(PathEl::CurveTo(
Point::new(x + r * (c0 - a * s0), y + r * (s0 + a * c0)),
Point::new(x + r * (c1 + a * s1), y + r * (s1 - a * c1)),
Point::new(x + r * c1, y + r * s1),
))
} else if ix == self.n + 1 {
Some(PathEl::ClosePath)
} else {
None
}
}
}
/// A segment of a circle.
///
/// If `inner_radius > 0`, then the shape will be a doughnut segment.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CircleSegment {
/// The center.
pub center: Point,
/// The outer radius.
pub outer_radius: f64,
/// The inner radius.
pub inner_radius: f64,
/// The angle to start drawing the segment (in radians).
pub start_angle: f64,
/// The arc length of the segment (in radians).
pub sweep_angle: f64,
}
impl CircleSegment {
/// Create a `CircleSegment` out of its constituent parts.
#[inline(always)]
pub fn new(
center: impl Into<Point>,
outer_radius: f64,
inner_radius: f64,
start_angle: f64,
sweep_angle: f64,
) -> Self {
CircleSegment {
center: center.into(),
outer_radius,
inner_radius,
start_angle,
sweep_angle,
}
}
/// Return an arc representing the outer radius.
#[must_use]
#[inline(always)]
pub fn outer_arc(&self) -> Arc {
Arc {
center: self.center,
radii: Vec2::new(self.outer_radius, self.outer_radius),
start_angle: self.start_angle,
sweep_angle: self.sweep_angle,
x_rotation: 0.0,
}
}
/// Return an arc representing the inner radius.
///
/// This is [reversed] from the outer arc, so that it is in the
/// same direction as the arc that would be drawn (as the path
/// elements for this circle segment produce a closed path).
///
/// [reversed]: Arc::reversed
#[must_use]
#[inline]
pub fn inner_arc(&self) -> Arc {
Arc {
center: self.center,
radii: Vec2::new(self.inner_radius, self.inner_radius),
start_angle: self.start_angle + self.sweep_angle,
sweep_angle: -self.sweep_angle,
x_rotation: 0.0,
}
}
/// Is this circle segment [finite]?
///
/// [finite]: f64::is_finite
#[inline]
pub const fn is_finite(&self) -> bool {
self.center.is_finite()
&& self.outer_radius.is_finite()
&& self.inner_radius.is_finite()
&& self.start_angle.is_finite()
&& self.sweep_angle.is_finite()
}
/// Is this circle segment [NaN]?
///
/// [NaN]: f64::is_nan
#[inline]
pub const fn is_nan(&self) -> bool {
self.center.is_nan()
|| self.outer_radius.is_nan()
|| self.inner_radius.is_nan()
|| self.start_angle.is_nan()
|| self.sweep_angle.is_nan()
}
}
impl Add<Vec2> for CircleSegment {
type Output = CircleSegment;
#[inline]
fn add(self, v: Vec2) -> Self {
Self {
center: self.center + v,
..self
}
}
}
impl Sub<Vec2> for CircleSegment {
type Output = CircleSegment;
#[inline]
fn sub(self, v: Vec2) -> Self {
Self {
center: self.center - v,
..self
}
}
}
type CircleSegmentPathIter = iter::Chain<
iter::Chain<
iter::Chain<iter::Chain<iter::Once<PathEl>, iter::Once<PathEl>>, ArcAppendIter>,
iter::Once<PathEl>,
>,
ArcAppendIter,
>;
impl Shape for CircleSegment {
type PathElementsIter<'iter> = CircleSegmentPathIter;
fn path_elements(&self, tolerance: f64) -> CircleSegmentPathIter {
iter::once(PathEl::MoveTo(point_on_circle(
self.center,
self.inner_radius,
self.start_angle,
)))
// First radius
.chain(iter::once(PathEl::LineTo(point_on_circle(
self.center,
self.outer_radius,
self.start_angle,
))))
// outer arc
.chain(self.outer_arc().append_iter(tolerance))
// second radius
.chain(iter::once(PathEl::LineTo(point_on_circle(
self.center,
self.inner_radius,
self.start_angle + self.sweep_angle,
))))
// inner arc
.chain(self.inner_arc().append_iter(tolerance))
}
#[inline]
fn area(&self) -> f64 {
0.5 * (self.outer_radius.powi(2) - self.inner_radius.powi(2)).abs() * self.sweep_angle
}
#[inline]
fn perimeter(&self, _accuracy: f64) -> f64 {
2.0 * (self.outer_radius - self.inner_radius).abs()
+ self.sweep_angle * (self.inner_radius + self.outer_radius)
}
fn winding(&self, pt: Point) -> i32 {
let angle = (pt - self.center).atan2();
if angle < self.start_angle || angle > self.start_angle + self.sweep_angle {
return 0;
}
let dist2 = (pt - self.center).hypot2();
if (dist2 < self.outer_radius.powi(2) && dist2 > self.inner_radius.powi(2)) ||
// case where outer_radius < inner_radius
(dist2 < self.inner_radius.powi(2) && dist2 > self.outer_radius.powi(2))
{
1
} else {
0
}
}
#[inline]
fn bounding_box(&self) -> Rect {
// todo this is currently not tight
let r = self.inner_radius.max(self.outer_radius);
let (x, y) = self.center.into();
Rect::new(x - r, y - r, x + r, y + r)
}
}
#[inline]
fn point_on_circle(center: Point, radius: f64, angle: f64) -> Point {
let (angle_sin, angle_cos) = angle.sin_cos();
center
+ Vec2 {
x: angle_cos * radius,
y: angle_sin * radius,
}
}
#[cfg(test)]
mod tests {
use crate::{Circle, Point, Shape};
use std::f64::consts::PI;
fn assert_approx_eq(x: f64, y: f64) {
// Note: we might want to be more rigorous in testing the accuracy
// of the conversion into Béziers. But this seems good enough.
assert!((x - y).abs() < 1e-7, "{x} != {y}");
}
#[test]
fn area_sign() {
let center = Point::new(5.0, 5.0);
let c = Circle::new(center, 5.0);
assert_approx_eq(c.area(), 25.0 * PI);
assert_eq!(c.winding(center), 1);
let p = c.to_path(1e-9);
assert_approx_eq(c.area(), p.area());
assert_eq!(c.winding(center), p.winding(center));
let c_neg_radius = Circle::new(center, -5.0);
assert_approx_eq(c_neg_radius.area(), 25.0 * PI);
assert_eq!(c_neg_radius.winding(center), 1);
let p_neg_radius = c_neg_radius.to_path(1e-9);
assert_approx_eq(c_neg_radius.area(), p_neg_radius.area());
assert_eq!(c_neg_radius.winding(center), p_neg_radius.winding(center));
}
}
+1121
View File
File diff suppressed because it is too large. Load diff
+1257
View File
File diff suppressed because it is too large. Load diff
+554
View File
@@ -0,0 +1,554 @@
// Copyright 2020 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Implementation of ellipse shape.
use core::f64::consts::PI;
use core::{
iter,
ops::{Add, Mul, Sub},
};
use crate::{Affine, Arc, ArcAppendIter, Circle, PathEl, Point, Rect, Shape, Size, Vec2};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// An ellipse.
#[derive(Clone, Copy, Default, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Ellipse {
/// All ellipses can be represented as an affine map of the unit circle,
/// centred at (0, 0). Therefore we can store the ellipse as an affine map,
/// with the implication that it be applied to the unit circle to recover the
/// actual shape.
inner: Affine,
}
impl Ellipse {
/// Create A new ellipse with a given center, radii, and rotation.
///
/// The returned ellipse will be the result of taking a circle, stretching
/// it by the `radii` along the x and y axes, then rotating it from the
/// x axis by `rotation` radians, before finally translating the center
/// to `center`.
///
/// Rotation is clockwise in a y-down coordinate system. For more on
/// rotation, see [`Affine::rotate`].
#[inline]
pub fn new(center: impl Into<Point>, radii: impl Into<Vec2>, x_rotation: f64) -> Ellipse {
let Point { x: cx, y: cy } = center.into();
let Vec2 { x: rx, y: ry } = radii.into();
Ellipse::private_new(Vec2 { x: cx, y: cy }, rx, ry, x_rotation)
}
/// Returns the largest ellipse that can be bounded by this [`Rect`].
///
/// This uses the absolute width and height of the rectangle.
///
/// This ellipse is always axis-aligned; to apply rotation you can call
/// [`with_rotation`] with the result.
///
/// [`with_rotation`]: Ellipse::with_rotation
#[inline]
pub fn from_rect(rect: Rect) -> Self {
let center = rect.center().to_vec2();
let Size { width, height } = rect.size() / 2.0;
Ellipse::private_new(center, width, height, 0.0)
}
/// Create an ellipse from an affine transformation of the unit circle.
#[inline(always)]
pub const fn from_affine(affine: Affine) -> Self {
Ellipse { inner: affine }
}
/// Create a new `Ellipse` centered on the provided point.
#[inline]
#[must_use]
pub fn with_center(self, new_center: impl Into<Point>) -> Ellipse {
let Point { x: cx, y: cy } = new_center.into();
Ellipse {
inner: self.inner.with_translation(Vec2 { x: cx, y: cy }),
}
}
/// Create a new `Ellipse` with the provided radii.
#[inline]
#[must_use]
pub fn with_radii(self, new_radii: Vec2) -> Ellipse {
let rotation = self.inner.svd().1;
let translation = self.inner.translation();
Ellipse::private_new(translation, new_radii.x, new_radii.y, rotation)
}
/// Create a new `Ellipse`, with the rotation replaced by `rotation`
/// radians.
///
/// The rotation is clockwise, for a y-down coordinate system. For more
/// on rotation, See [`Affine::rotate`].
#[inline]
#[must_use]
pub fn with_rotation(self, rotation: f64) -> Ellipse {
let scale = self.inner.svd().0;
let translation = self.inner.translation();
Ellipse::private_new(translation, scale.x, scale.y, rotation)
}
/// This gives us an internal method without any type conversions.
#[inline]
fn private_new(center: Vec2, scale_x: f64, scale_y: f64, x_rotation: f64) -> Ellipse {
// Since the circle is symmetric about the x and y axes, using absolute values for the
// radii results in the same ellipse. For simplicity we make this change here.
Ellipse {
inner: Affine::translate(center)
* Affine::rotate(x_rotation)
* Affine::scale_non_uniform(scale_x.abs(), scale_y.abs()),
}
}
// Getters and setters.
/// Returns the center of this ellipse.
#[inline(always)]
pub fn center(&self) -> Point {
self.inner.translation().to_point()
}
/// Returns the two radii of this ellipse.
///
/// The first number is the horizontal radius and the second is the vertical
/// radius, before rotation.
///
/// If you are only interested in the value of the greatest or smallest radius of this ellipse,
/// consider using [`Ellipse::major_radius`] or [`Ellipse::minor_radius`] instead.
#[inline]
pub fn radii(&self) -> Vec2 {
self.inner.svd().0
}
/// Returns the major radius of this ellipse.
///
/// This metric is also known as the semi-major axis.
#[inline]
pub fn major_radius(&self) -> f64 {
self.inner.svd().0.x
}
/// Returns the minor radius of this ellipse.
///
/// This metric is also known as the semi-minor axis.
#[inline]
pub fn minor_radius(&self) -> f64 {
self.inner.svd().0.y
}
/// The ellipse's rotation, in radians.
///
/// This allows all possible ellipses to be drawn by always starting with
/// an ellipse with the two radii on the x and y axes.
#[inline]
pub fn rotation(&self) -> f64 {
self.inner.svd().1
}
/// Returns the radii and the rotation of this ellipse.
///
/// Equivalent to `(self.radii(), self.rotation())` but more efficient.
#[inline]
pub fn radii_and_rotation(&self) -> (Vec2, f64) {
self.inner.svd()
}
/// Is this ellipse [finite]?
///
/// [finite]: f64::is_finite
#[inline]
pub const fn is_finite(&self) -> bool {
self.inner.is_finite()
}
/// Is this ellipse [NaN]?
///
/// [NaN]: f64::is_nan
#[inline]
pub const fn is_nan(&self) -> bool {
self.inner.is_nan()
}
}
impl Add<Vec2> for Ellipse {
type Output = Ellipse;
/// In this context adding a `Vec2` applies the corresponding translation to the ellipse.
#[inline]
#[allow(clippy::suspicious_arithmetic_impl)]
fn add(self, v: Vec2) -> Ellipse {
Ellipse {
inner: Affine::translate(v) * self.inner,
}
}
}
impl Sub<Vec2> for Ellipse {
type Output = Ellipse;
/// In this context subtracting a `Vec2` applies the corresponding translation to the ellipse.
#[inline]
fn sub(self, v: Vec2) -> Ellipse {
Ellipse {
inner: Affine::translate(-v) * self.inner,
}
}
}
impl Mul<Ellipse> for Affine {
type Output = Ellipse;
#[inline]
fn mul(self, other: Ellipse) -> Self::Output {
Ellipse {
inner: self * other.inner,
}
}
}
impl From<Circle> for Ellipse {
#[inline]
fn from(circle: Circle) -> Self {
Ellipse::new(circle.center, Vec2::splat(circle.radius), 0.0)
}
}
impl Shape for Ellipse {
type PathElementsIter<'iter> = iter::Chain<iter::Once<PathEl>, ArcAppendIter>;
fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_> {
let (radii, x_rotation) = self.inner.svd();
Arc {
center: self.center(),
radii,
start_angle: 0.0,
sweep_angle: 2.0 * PI,
x_rotation,
}
.path_elements(tolerance)
}
/// The area of the ellipse.
///
/// This is always positive if the result is finite.
///
/// If non-finite, this will be [`f64::INFINITY`] or [`f64::NAN`] depending on whether the
/// inner affine's [determinant](Affine::determinant) is [`f64::INFINITY`] (either positive or
/// negative) or [`f64::NAN`].
#[inline]
fn area(&self) -> f64 {
// `Ellipse` is represented as a unit circle transformed by `Affine`. The transformed area
// of a region is `area * |det(affine)|`, see
// <https://en.wikipedia.org/w/index.php?title=Determinant&oldid=1344268205#Geometric_meaning>.
//
// A unit circle has area `PI`. Therefore, the area of this ellipse is PI multiplied by the
// affine's determinant.
PI * self.inner.determinant().abs()
}
/// Approximate the ellipse perimeter.
///
/// This uses a numerical approximation. The absolute error between the calculated perimeter
/// and the true perimeter is bounded by `accuracy` (modulo floating point rounding errors).
///
/// For circular ellipses (equal horizontal and vertical radii), the calculated perimeter is
/// exact.
#[inline]
fn perimeter(&self, accuracy: f64) -> f64 {
let radii = self.radii();
// Note: the radii are calculated from an inner affine map (`self.inner`), and may be NaN.
// Currently, constructing an ellipse with infinite radii will produce an ellipse whose
// calculated radii are NaN.
if !radii.is_finite() {
return f64::NAN;
}
// Check for the trivial case where the ellipse has one of its radii equal to 0, i.e.,
// where it describes a line, as the numerical method used breaks down with this extreme.
if radii.x == 0. || radii.y == 0. {
return 4. * f64::max(radii.x, radii.y);
}
// Evaluate an approximation based on a truncated infinite series. If it returns a good
// enough value, we do not need to iterate.
if kummer_elliptic_perimeter_range(radii) <= accuracy {
return kummer_elliptic_perimeter(radii);
}
agm_elliptic_perimeter(accuracy, radii)
}
#[inline]
fn winding(&self, pt: Point) -> i32 {
// Strategy here is to apply the inverse map to the point and see if it is in the unit
// circle.
let inv = self.inner.inverse();
if (inv * pt).to_vec2().hypot2() < 1.0 {
1
} else {
0
}
}
// Compute a tight bounding box of the ellipse.
//
// See https://www.iquilezles.org/www/articles/ellipses/ellipses.htm. We can get the two
// radius vectors by applying the affine map to the two impulses (1, 0) and (0, 1) which gives
// (a, b) and (c, d) if the affine map is
//
// a | c | e
// -----------
// b | d | f
//
// We can then use the method in the link with the translation to get the bounding box.
#[inline]
fn bounding_box(&self) -> Rect {
let aff = self.inner.as_coeffs();
let a2 = aff[0] * aff[0];
let b2 = aff[1] * aff[1];
let c2 = aff[2] * aff[2];
let d2 = aff[3] * aff[3];
let cx = aff[4];
let cy = aff[5];
let range_x = (a2 + c2).sqrt();
let range_y = (b2 + d2).sqrt();
Rect {
x0: cx - range_x,
y0: cy - range_y,
x1: cx + range_x,
y1: cy + range_y,
}
}
}
/// Calculates circumference C of an ellipse with radii (x, y) as the infinite series
///
/// C = pi (x+y) * ∑ binom(1/2, n)^2 * h^n from n = 0 to inf
/// with h = (x - y)^2 / (x + y)^2
/// and binom(.,.) the binomial coefficient
///
/// as described by Kummer ("Über die Hypergeometrische Reihe", 1837) and rediscovered by
/// Linderholm and Segal ("An Overlooked Series for the Elliptic Perimeter", 1995).
///
/// The series converges very quickly for ellipses with only moderate eccentricity (`h` not close
/// to 1).
///
/// The series is truncated to the sixth power, meaning a lower bound on the true value is
/// returned. Adding the value of [`kummer_elliptic_perimeter_range`] to the value returned by this
/// function calculates an upper bound on the true value.
#[inline]
fn kummer_elliptic_perimeter(radii: Vec2) -> f64 {
let Vec2 { x, y } = radii;
let h = ((x - y) / (x + y)).powi(2);
let h2 = h * h;
let h3 = h2 * h;
let h4 = h3 * h;
let h5 = h4 * h;
let h6 = h5 * h;
let lower = PI
+ h * (PI / 4.)
+ h2 * (PI / 64.)
+ h3 * (PI / 256.)
+ h4 * (PI * 25. / 16384.)
+ h5 * (PI * 49. / 65536.)
+ h6 * (PI * 441. / 1048576.);
(x + y) * lower
}
/// This calculates the error range of [`kummer_elliptic_perimeter`]. That function returns a lower
/// bound on the true value, and though we do not know what the remainder of the infinite series
/// sums to, we can calculate an upper bound:
///
/// ∑ binom(1/2, n)^2 for n = 0 to inf
/// = 1 + (1 / 2!!)^2 + (1!! / 4!!)^2 + (3!! / 6!!)^2 + (5!! / 8!!)^2 + ..
/// = 4 / pi
/// with !! the double factorial
/// (equation 274 in "Summation of Series", L. B. W. Jolley, 1961).
///
/// This means the remainder of the infinite series for C, assuming the series was truncated to the
/// mth term and h = 1, sums to
/// 4 / pi - ∑ binom(1/2, n)^2 for n = 0 to m-1
///
/// As 0 ≤ h ≤ 1, this is an upper bound.
#[inline]
fn kummer_elliptic_perimeter_range(radii: Vec2) -> f64 {
let Vec2 { x, y } = radii;
let h = ((x - y) / (x + y)).powi(2);
const BINOM_SQUARED_REMAINDER: f64 = 0.00101416479131503;
// = 4. / PI - (1. + 1. / 4. + 1. / 64. + 1. / 256. + 25. / 16384. + 49. / 65536. + 441. / 1048576.)
PI * BINOM_SQUARED_REMAINDER * h.powi(7) * (x + y)
}
/// Calculates circumference C of an ellipse with radii (x, y) using the arithmetic-geometric mean,
/// as described in equation 19.8.6 of
/// <https://web.archive.org/web/20240926233336/https://dlmf.nist.gov/19.8#i>.
fn agm_elliptic_perimeter(accuracy: f64, radii: Vec2) -> f64 {
let Vec2 { x, y } = if radii.x >= radii.y {
radii
} else {
Vec2::new(radii.y, radii.x)
};
let accuracy = accuracy / (2. * PI * x);
let mut sum = 1.;
let mut a = 1.;
let mut g = y / x;
let mut c = (1. - g.powi(2)).sqrt();
let mut mul = 0.5;
loop {
let c2 = c.powi(2);
// term = 2^(n-1) c_n^2
let term = mul * c2;
sum -= term;
// We have c_(n+1) ≤ 1/2 c_n
// (for a derivation, see e.g. section 2.1 of "Elliptic integrals, the
// arithmetic-geometric mean and the Brent-Salamin algorithm for π" by G.J.O. Jameson:
// <https://web.archive.org/web/20241002140956/https://www.maths.lancs.ac.uk/jameson/ellagm.pdf>)
//
// Therefore
// ∑ 2^(i-1) c_i^2 from i = 1 ≤ ∑ 2^(i-1) ((1/2)^i c_0)^2 from i = 1
// = ∑ 2^-(i+1) c_0^2 from i = 1
// = 1/2 c_0^2
//
// or, for arbitrary starting point i = n+1:
// ∑ 2^(i-1) c_i^2 from i = n+1 ≤ ∑ 2^(i-1) ((1/2)^(i-n) c_n)^2 from i = n+1
// = ∑ 2^(2n - i - 1) c_n^2 from i = n+1
// = 2^(2n) ∑ 2^(-(i+1)) c_n^2 from i = n+1
// = 2^(2n) 2^(-(n+1)) c_n^2
// = 2^(n-1) c_n^2
//
// Therefore, the remainder of the series sums to less than or equal to 2^(n-1) c_n^2,
// which is exactly the value of the nth term.
//
// Furthermore, a_m ≥ g_n, and g_n ≤ 1, for all m, n.
if term <= accuracy * g {
// `sum` currently overestimates the true value - subtract the upper bound of the
// remaining series. We will then underestimate the true value, but by no more than
// `accuracy`.
sum -= term;
break;
}
mul *= 2.;
// This is equal to c_next = c^2 / (4 * a_next)
c = (a - g) / 2.;
let a_next = (a + g) / 2.;
g = (a * g).sqrt();
a = a_next;
}
2. * PI * x / a * sum
}
#[cfg(test)]
mod tests {
use crate::{Circle, Ellipse, Point, Shape};
use std::f64::consts::PI;
fn assert_approx_eq(x: f64, y: f64) {
// Note: we might want to be more rigorous in testing the accuracy
// of the conversion into Béziers. But this seems good enough.
assert!((x - y).abs() < 1e-7, "{x} != {y}");
}
#[test]
fn circular_perimeter() {
for radius in [1.0, 0., 1.5, PI, 10.0, -1.0, 1_234_567_890.1] {
let circle = Circle::new((0., 0.), radius);
let ellipse = Ellipse::new((0., 0.), (radius, radius), 0.);
let circle_p = circle.perimeter(0.);
let ellipse_p = ellipse.perimeter(0.1);
// We expect the results to be identical, modulo potential roundoff errors. Compare
// with a very small relative epsilon.
let epsilon = f64::EPSILON * 8. * circle_p.max(ellipse_p);
assert!(
(circle_p - ellipse_p).abs() <= epsilon,
"Expected circular ellipse radius {ellipse_p} to be equal to circle radius {circle_p} for radius {radius}"
);
}
}
#[test]
fn compare_perimeter_with_bez() {
const EPSILON: f64 = 0.000_002;
for radii in [
(0.5, 1.),
(2., 1.),
(0.000_000_1, 1.),
(0., 1.),
(1., 0.),
(-0.5, 1.),
(-0.000_000_1, -1.),
] {
let ellipse = Ellipse::new((0., 0.), radii, 0.);
let ellipse_p = ellipse.perimeter(0.000_001);
let bez_p = ellipse.path_segments(0.000_000_25).perimeter(0.000_000_25);
assert!(
(ellipse_p - bez_p).abs() < EPSILON,
"Numerically approximated ellipse perimeter ({ellipse_p}) does not match bezier segment perimeter length ({bez_p}) for radii {radii:?}"
);
}
}
#[test]
fn known_perimeter() {
const ACCURACY: f64 = 0.000_000_000_001;
for (radii, perimeter) in [
((0.5, 1.), 4.844_224_110_273_838),
((0.001, 1.), 4.000_015_588_104_688),
] {
let ellipse = Ellipse::new((0., 0.), radii, 0.);
let ellipse_p = ellipse.perimeter(ACCURACY);
assert!(
(ellipse_p - perimeter).abs() <= ACCURACY,
"Numerically approximated ellipse perimeter ({ellipse_p}) does not match known perimeter ({perimeter}) radii {radii:?}"
);
}
}
#[test]
fn area_sign() {
let center = Point::new(5.0, 5.0);
let e = Ellipse::new(center, (5.0, 5.0), 1.0);
assert_approx_eq(e.area(), 25.0 * PI);
let e = Ellipse::new(center, (5.0, 10.0), 1.0);
assert_approx_eq(e.area(), 50.0 * PI);
assert_eq!(e.winding(center), 1);
let p = e.to_path(1e-9);
assert_approx_eq(e.area(), p.area());
assert_eq!(e.winding(center), p.winding(center));
let e_neg_radius = Ellipse::new(center, (-5.0, 10.0), 1.0);
assert_approx_eq(e_neg_radius.area(), 50.0 * PI);
assert_eq!(e_neg_radius.winding(center), 1);
let p_neg_radius = e_neg_radius.to_path(1e-9);
assert_approx_eq(e_neg_radius.area(), p_neg_radius.area());
assert_eq!(e_neg_radius.winding(center), p_neg_radius.winding(center));
}
}
+604
View File
@@ -0,0 +1,604 @@
// Copyright 2026 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
use crate::{
Affine, Arc, BezPath, CubicBez, Join, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Point,
QuadBez, Shape, Vec2, bezpath::close_subpaths, segments,
};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A diagonal matrix, suitable for representing anisotropic scaling.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Diagonal2 {
/// The horizontal expansion factor.
pub xx: f64,
/// The vertical expansion factor.
pub yy: f64,
}
struct ExpandCtx {
expand: Diagonal2,
join: Join,
miter_limit: f64,
tolerance: f64,
result: BezPath,
first_n: Option<Vec2>,
first_tan: Vec2,
last_pt: Point,
last_n: Option<Vec2>,
last_tan: Vec2,
}
struct CubicCtx {
q: QuadBez,
utan0: Vec2,
utan1: Vec2,
}
struct TwoPointSample {
a_n: f64,
b_n: f64,
c_n: f64,
}
impl Diagonal2 {
/// Create a diagonal matrix.
pub const fn new(xx: f64, yy: f64) -> Self {
Self { xx, yy }
}
/// Matrix inverse.
///
/// Will of course produce infinities if a component is zero.
pub const fn inv(self) -> Self {
Diagonal2::new(1.0 / self.xx, 1.0 / self.yy)
}
/// Absolute value of transform components.
pub const fn abs(self) -> Self {
Self::new(self.xx.abs(), self.yy.abs())
}
/// Scale a normal vector.
///
/// This is mathematically equivalent to `self * (self * n).normalize()`
/// for positive transforms, but handles zeros and gets the sign correct
/// when negative.
///
/// Note that `n` need not be unit length.
pub fn scale_normal(self, n: Vec2) -> Vec2 {
let z = self * n;
let z_hypot2 = z.hypot2();
if z_hypot2 == 0.0 {
Vec2::ZERO
} else {
let inv_scale = 1.0 / z_hypot2.sqrt();
self.abs() * z * inv_scale
}
}
}
impl core::ops::Neg for Diagonal2 {
type Output = Self;
fn neg(self) -> Self {
Diagonal2::new(-self.xx, -self.yy)
}
}
impl core::ops::Mul<Vec2> for Diagonal2 {
type Output = Vec2;
fn mul(self, rhs: Vec2) -> Vec2 {
Vec2::new(self.xx * rhs.x, self.yy * rhs.y)
}
}
impl core::ops::Mul<Point> for Diagonal2 {
type Output = Point;
fn mul(self, rhs: Point) -> Point {
Point::new(self.xx * rhs.x, self.yy * rhs.y)
}
}
// Note: a bunch more ops on `Diagonal2` could be implemented, but for now we'll stick to what we need.
/// Expand a path.
///
/// Expands a filled path by the expansion, which allows separate x and y factors. The
/// path (and the result) is interpreted according to the nonzero winding rule. Both
/// factors should be positive. A negative expansion will shrink the path but is also
/// likely to leave intersection artifacts at corners.
///
/// The direction of the expansion is based on the signed area of the overall path.
/// This should give expected results most of the time, but there are exceptions. For a
/// figure-eight path, one lobe will be expanded and the other shrunk. Similarly if
/// there are two disjoint subpaths with opposite winding.
///
/// The tolerance is mostly for joins and robustness; it is not used to guide
/// subdivision. Rather, each Bézier segment in the input generally results in one
/// cubic Bézier in the output. Thus, it is not expected to work well when the
/// expansion factor is large compared with the radius of curvature on the input.
pub fn expand_path(
path: impl Shape,
mut expand: Diagonal2,
join: Join,
miter_limit: f64,
tolerance: f64,
) -> BezPath {
if segments(close_subpaths(path.path_elements(tolerance))).area() >= 0.0 {
expand = -expand;
}
expand_path_signed(path, expand, join, miter_limit, tolerance)
}
/// Expand a path when the sign is known.
///
/// Applies the expansion based on the path orientation, so that expansion happens
/// with positive `expand` values on subpaths with negative area, or vice versa. This
/// is backwards from the intuitive sign convention, but results from the choice of
/// convention for the offset primitives.
pub fn expand_path_signed(
path: impl Shape,
expand: Diagonal2,
join: Join,
miter_limit: f64,
tolerance: f64,
) -> BezPath {
let result = BezPath::new();
let mut ctx = ExpandCtx {
expand,
join,
miter_limit,
tolerance,
result,
first_n: None,
first_tan: Vec2::default(),
last_pt: Point::default(),
last_n: None,
last_tan: Vec2::default(),
};
let mut first_pt = Point::default();
for el in path.path_elements(tolerance) {
match el {
PathEl::MoveTo(point) => {
ctx.do_close_path(first_pt);
first_pt = point;
ctx.last_pt = point;
}
PathEl::LineTo(p1) => ctx.do_line(p1),
PathEl::QuadTo(p1, p2) => ctx.do_quad(p1, p2),
PathEl::CurveTo(p1, p2, p3) => ctx.do_cubic(p1, p2, p3),
PathEl::ClosePath => ctx.do_close_path(first_pt),
}
}
// Treat all subpaths as closed; close if left open in input.
ctx.do_close_path(first_pt);
ctx.result
}
impl ExpandCtx {
/// Helper function to determine if a distance is within tolerance.
fn in_tolerance(&self, v: Vec2) -> bool {
v.hypot2() < self.tolerance * self.tolerance
}
/// Process a line segment. Includes initial join.
fn do_line(&mut self, p1: Point) {
if p1 == self.last_pt {
return;
}
let tan = p1 - self.last_pt;
let n = self.expand.scale_normal(tan.turn_90());
self.do_join(n, tan, true);
let out_p1 = p1 + n;
self.result.line_to(out_p1);
self.last_n = Some(n);
self.last_tan = tan;
self.last_pt = p1;
}
/// Process a quadratic Bézier segment. Includes initial join.
fn do_quad(&mut self, p1: Point, p2: Point) {
let q0 = p1 - self.last_pt;
let q1 = p2 - p1;
if self.in_tolerance(q0) || self.in_tolerance(q1) {
self.do_line(p2);
return;
}
let einv = self.expand.inv();
let utan0 = (einv * q0).normalize();
let utan1 = (einv * q1).normalize();
let det = utan1.cross(utan0);
if det.abs() < 1e-10 {
self.do_line(p2);
return;
}
let utanm = (einv * (p2 - self.last_pt)).normalize();
let n0 = self.expand.abs() * utan0.turn_90();
let n1 = self.expand.abs() * utan1.turn_90();
let mid_chord = self.last_pt.midpoint(p2);
let m = mid_chord.midpoint(p1) + self.expand.abs() * utanm.turn_90();
let out_p0 = self.last_pt + n0;
let out_p3 = p2 + n1;
let rhs = einv * (m - out_p0.midpoint(out_p3));
let idet = (8. / 3.) / det;
let a = (utan1.cross(rhs) * idet).max(0.0);
let b = (utan0.cross(rhs) * idet).max(0.0);
self.do_join(n0, q0, false);
let out_p1 = out_p0 + self.expand * (a * utan0);
let out_p2 = out_p3 - self.expand * (b * utan1);
self.result.curve_to(out_p1, out_p2, out_p3);
self.last_n = Some(n1);
self.last_tan = q1;
self.last_pt = p2;
}
/// Process a cubic segment. Includes initial join.
fn do_cubic(&mut self, p1: Point, p2: Point, p3: Point) {
let einv = self.expand.inv();
let c = CubicBez::new(einv * self.last_pt, einv * p1, einv * p2, einv * p3);
let (tan0, tan1) = PathSeg::Cubic(c).tangents();
let utan0 = tan0.normalize();
let utan1 = tan1.normalize();
let q = c.deriv();
let p1xp0 = q.p1.to_vec2().cross(q.p0.to_vec2());
let p2xp1 = q.p2.to_vec2().cross(q.p1.to_vec2());
let cx = CubicCtx { q, utan0, utan1 };
// First we try one-point, but only if there isn't one inflection point.
let mut soln = if p1xp0 * p2xp1 >= 0.0 {
try_one_point(&cx)
} else {
None
};
if soln.is_none() {
// We try two-point linear if we don't have a one-point solution. A
// more sophisticated approach would be to evaluate error and pick a
// minimum, but that would be more complexity and take time. This is
// very likely good enough for the purpose.
soln = two_point_linear(&cx);
}
if let Some((a, b)) = soln {
let n0 = self.expand.abs() * utan0.turn_90();
let n1 = self.expand.abs() * utan1.turn_90();
self.do_join(n0, self.expand * utan0, false);
let out_p3 = p3 + n1;
// TODO: clamp to correct direction
let out_p1 = p1 + n0 + self.expand.abs() * (a * utan0);
let out_p2 = p2 + n1 + self.expand.abs() * (b * utan1);
self.result.curve_to(out_p1, out_p2, out_p3);
self.last_n = Some(n1);
self.last_tan = self.expand * utan1;
self.last_pt = p3;
} else {
self.do_line(p3);
}
}
/// Do a join.
///
/// The `tan` parameter is a vector tangent to the start of the new segment.
/// The `n` parameter is the normal vector (turned tangent) scaled by the expansion.
fn do_join(&mut self, n: Vec2, tan: Vec2, is_line: bool) {
// TODO: other join types etc
if let Some(last_n) = self.last_n {
let p = self.last_pt + n;
if !self.in_tolerance(n - last_n) {
if self.join != Join::Bevel {
let cross = self.last_tan.cross(tan);
if cross * self.expand.xx < 0.0 {
match self.join {
Join::Bevel => unreachable!(),
Join::Miter => {
let dot = self.last_tan.dot(tan);
let hypot = cross.hypot(dot);
if 2.0 * hypot < (hypot + dot) * self.miter_limit * self.miter_limit
{
let h = (n - last_n).cross(tan) / self.last_tan.cross(tan);
let miter_pt = self.last_pt + last_n + h * self.last_tan;
// A cheap optimization to reduce line segments with joins to lines
if let Some(PathEl::LineTo(p)) =
self.result.elements_mut().last_mut()
{
*p = miter_pt;
} else {
self.result.line_to(miter_pt);
}
if is_line {
return;
}
}
}
Join::Round => {
// Cheaper inverse; everything is normalized so we don't care about uniform scaling.
let einv = Diagonal2::new(self.expand.yy, self.expand.xx);
let last_tann = einv * self.last_tan;
let tann = einv * tan;
let crossn = (last_tann).cross(tann);
let dotn = (last_tann).dot(tann);
let angle = crossn.atan2(dotn).abs();
let nt = self.expand * tann.normalize();
let a = Affine::new([
n.x,
n.y,
nt.x,
nt.y,
self.last_pt.x,
self.last_pt.y,
]);
let arc: Arc =
Arc::new(Point::ORIGIN, (1.0, 1.0), -angle, angle, 0.0);
let tolerance = self.tolerance / einv.xx.abs().max(einv.yy.abs());
arc.to_cubic_beziers(tolerance, |p1, p2, p3| {
self.result.curve_to(a * p1, a * p2, a * p3);
});
return;
}
}
}
}
// Bevel case
self.result.line_to(p);
}
} else {
self.result.move_to(self.last_pt + n);
self.first_n = Some(n);
self.first_tan = tan;
}
}
/// Close an open subpath if there is one; no-op if already closed.
fn do_close_path(&mut self, first_pt: Point) {
if let Some(first_n) = self.first_n.take() {
// could do this test inside do_line for all lines, but it already checks for 0-length
if first_pt.distance_squared(self.last_pt) > self.tolerance * self.tolerance {
self.do_line(first_pt);
}
self.do_join(first_n, self.first_tan, true);
self.result.close_path();
}
self.last_n = None;
}
}
// Note: here is our own copy of sophisticated cubic Bézier offset logic. We have
// the ability to apply anisotropic expansion, but not cusp detection or subdivision,
// and I've also stripped out all the error evaluation. At some point, we want to
// redo stroking, and there may be an opportunity to share code.
/// Try to compute one-point shape control for a cubic.
///
/// Result is (a, b) parameters.
fn try_one_point(cx: &CubicCtx) -> Option<(f64, f64)> {
// TODO: possibly reduce duplication with quadratic case.
let tan = cx.q.eval(0.5).to_vec2();
let tan_hypot2 = tan.hypot2();
if tan_hypot2 < 1e-12 {
return None;
}
let utan = tan / tan_hypot2.sqrt();
let z = (utan - 0.5 * (cx.utan0 + cx.utan1)).turn_90();
let cross = cx.utan0.cross(cx.utan1);
if cross.abs() < 1e-12 {
return None;
}
let idet = (8. / 3.) / cross;
let a = z.cross(cx.utan1) * idet;
let b = cx.utan0.cross(z) * idet;
//let delta_tan = 0.75 * (b * cx.utan1 - a * cx.utan0) + 1.5 * (cx.utan1 - cx.utan0).turn_90();
//let angle_err = delta_tan.cross(utan);
//let err_est = 0.16 * angle_err.abs();
Some((a, b))
}
fn two_point_linear(cx: &CubicCtx) -> Option<(f64, f64)> {
const T0: f64 = 0.35;
let s = [T0, 1.0 - T0].map(|t| {
let utan = cx.q.eval(t).to_vec2().normalize();
let n = utan.turn_90();
let utan0_n = cx.utan0.dot(n);
let utan1_n = cx.utan1.dot(n);
let utan0xn = cx.utan0.dot(utan);
let utan1xn = cx.utan1.dot(utan);
let mt = 1.0 - t;
let b0 = mt * mt * mt;
let b1 = 3.0 * mt * t * mt;
let b2 = 3.0 * mt * t * t;
let b3 = t * t * t;
let a_n = b1 * utan0_n;
let b_n = b2 * utan1_n;
let c_n = (b0 + b1) * utan0xn + (b2 + b3) * utan1xn - 1.0;
TwoPointSample { a_n, b_n, c_n }
});
let det = s[0].a_n * s[1].b_n - s[1].a_n * s[0].b_n;
// Consider both near-zero and NaN determinants to be failures.
if det.abs().partial_cmp(&1e-12) != Some(core::cmp::Ordering::Greater) {
return None;
}
let idet = -1.0 / det;
let a = idet * (s[0].c_n * s[1].b_n - s[1].c_n * s[0].b_n);
let b = idet * (s[0].a_n * s[1].c_n - s[1].a_n * s[0].c_n);
Some((a, b))
}
#[cfg(test)]
mod tests {
use std::f64::consts::PI;
use crate::{
Affine, BezPath, Circle, Diagonal2, Join, ParamCurveMoments, PathEl, Point, Rect, Shape,
Size, Vec2, expand_path,
};
#[test]
fn expand_circle_basic() {
const CENTER: Point = Point::new(100., 100.);
const RADIUS: f64 = 10.0;
let circle = Circle::new(CENTER, RADIUS);
let expected_area = PI * RADIUS.powi(2);
let expected_perimeter = 2.0 * PI * RADIUS;
assert!((circle.area() - expected_area).abs() < 1e-9);
assert!((circle.perimeter(1e-12) - expected_perimeter).abs() < 1e-9);
const R_DELTA: f64 = 2.0;
const EXPAND: Diagonal2 = Diagonal2::new(R_DELTA, R_DELTA);
let expanded = expand_path(circle, EXPAND, Join::Bevel, 4.0, 1e-3);
let expected_area_expanded = PI * (RADIUS + R_DELTA).powi(2);
let expected_perimeter_expanded = 2.0 * PI * (RADIUS + R_DELTA);
assert!((expanded.area() - expected_area_expanded).abs() < 4e-2);
assert!((expanded.perimeter(1e-12) - expected_perimeter_expanded).abs() < 3e-3);
let mirror = Affine::reflect(CENTER, Vec2::new(0.0, 1.0));
// We have to convert to a path here as the circle type doesn't support negative area.
let circle_mirror = mirror * circle.to_path(1e-3);
let expanded_mirror = expand_path(circle_mirror, EXPAND, Join::Bevel, 4.0, 1e-3);
assert!((-expanded_mirror.area() - expected_area_expanded).abs() < 4e-2);
assert!((expanded_mirror.perimeter(1e-12) - expected_perimeter_expanded).abs() < 3e-3);
}
#[test]
fn expand_ellipse_anisotropic() {
const CENTER: Point = Point::new(100., 100.);
const RADIUS: f64 = 10.0;
let circle = Circle::new(CENTER, RADIUS);
const STRETCH: f64 = 2.717;
let ellipse = Affine::scale_non_uniform(STRETCH, 1.0) * circle;
let expected_area = PI * RADIUS.powi(2) * STRETCH;
assert!((ellipse.area() - expected_area).abs() < 1e-9);
const R_DELTA: f64 = 2.0;
const EXPAND: Diagonal2 = Diagonal2::new(R_DELTA * STRETCH, R_DELTA);
let expanded = expand_path(ellipse, EXPAND, Join::Bevel, 4.0, 1e-3);
let expected_area_expanded = PI * (RADIUS + R_DELTA).powi(2) * STRETCH;
assert!((expanded.area() - expected_area_expanded).abs() < 4e-2);
}
#[test]
fn expand_rect() {
const CENTER: Point = Point::new(100., 100.);
const SIZE: Size = Size::new(30., 20.);
let rect = Rect::from_center_size(CENTER, SIZE);
assert!((rect.area() - SIZE.area()).abs() < 1e-9);
const EXPAND: Diagonal2 = Diagonal2::new(10.0, 10.0);
let mitered = expand_path(rect, EXPAND, Join::Miter, 4.0, 1e-3);
let expected_area_mitered =
(SIZE.width + 2.0 * EXPAND.xx) * (SIZE.height + 2.0 * EXPAND.yy);
assert!((mitered.area() - expected_area_mitered).abs() < 1e-9);
let beveled = expand_path(rect, EXPAND, Join::Bevel, 4.0, 1e-3);
let expected_area_beveled = expected_area_mitered - 2.0 * EXPAND.xx * EXPAND.yy;
assert!((beveled.area() - expected_area_beveled).abs() < 1e-9);
let rounded = expand_path(rect, EXPAND, Join::Round, 4.0, 0.1);
let expected_area_rounded = expected_area_mitered - (4.0 - PI) * EXPAND.xx * EXPAND.yy;
assert!((rounded.area() - expected_area_rounded).abs() < 1e-1);
}
#[test]
fn expand_rounding_tolerance() {
const CENTER: Point = Point::new(100., 100.);
const SIZE: Size = Size::new(30., 20.);
let rect = Rect::from_center_size(CENTER, SIZE);
const EXPAND: Diagonal2 = Diagonal2::new(10.0, 10.0);
let expected_area_mitered =
(SIZE.width + 2.0 * EXPAND.xx) * (SIZE.height + 2.0 * EXPAND.yy);
let expected_area_rounded = expected_area_mitered - (4.0 - PI) * EXPAND.xx * EXPAND.yy;
let rounded = expand_path(rect, EXPAND, Join::Round, 4.0, 1e-3);
assert!((rounded.area() - expected_area_rounded).abs() < 2e-3);
// Validate that a lower tolerance increases accuracy.
let rounded_fine = expand_path(rect, EXPAND, Join::Round, 4.0, 1e-6);
assert!((rounded_fine.area() - expected_area_rounded).abs() < 3e-5);
}
#[test]
fn expand_glyph_shape() {
// WARNING: this test is fragile. If there is optimization to simplify inner joins by
// computing intersections, the measurements change. A properly written test would
// compare the result after path intersection, or alternatively probe for zero/nonzero
// winding number for a collection of sample points. But at least it is sensitive to
// regressions.
// Roboto "e" glyph
let path = BezPath::from_svg(
"M10.359375,-0.359375 Q6.484375,-0.359375 4.0625,2.1875 Q1.640625,4.734375 1.640625,8.984375 \
L1.640625,9.578125 Q1.640625,12.40625 2.71875,14.625 Q3.796875,16.859375 5.734375,18.109375 \
Q7.6875,19.375 9.953125,19.375 Q13.65625,19.375 15.703125,16.921875 Q17.765625,14.484375 17.765625,9.9375 \
L17.765625,8.578125 L4.890625,8.578125 Q4.953125,5.765625 6.53125,4.03125 Q8.109375,2.296875 10.53125,2.296875 \
Q12.25,2.296875 13.4375,3 Q14.640625,3.703125 15.546875,4.875 L17.53125,3.328125 Q15.140625,-0.359375 10.359375,-0.359375 Z \
M9.953125,16.703125 Q7.984375,16.703125 6.640625,15.265625 Q5.3125,13.828125 5,11.25 L14.515625,11.25 L14.515625,11.5 \
Q14.375,13.96875 13.171875,15.328125 Q11.984375,16.703125 9.953125,16.703125 Z",
)
.unwrap();
const EXPAND: Diagonal2 = Diagonal2::new(1.5, 1.0);
let expanded = expand_path(&path, EXPAND, Join::Round, 4.0, 0.1);
//println!("{}", expanded.to_svg());
// The outline has been visually verified, these are measurements taken from known-good.
const EXPECTED_AREA: f64 = -291.3217958410297;
const EXPECTED_PERIMETER: f64 = 120.89147879578239;
const EXPECTED_MOMENT_X: f64 = -2788.568539588466;
const EXPECTED_MOMENT_Y: f64 = -2801.3818805722685;
const EXPECTED_MOMENT_XX: f64 = -34280.940819978576;
const EXPECTED_MOMENT_XY: f64 = -26971.281063345254;
const EXPECTED_MOMENT_YY: f64 = -36722.298990246876;
assert!((expanded.area() - EXPECTED_AREA).abs() < 1e-3);
assert!((expanded.perimeter(1e-9) - EXPECTED_PERIMETER).abs() < 1e-3);
let moments = expanded.moments();
assert!((moments.moment_x - EXPECTED_MOMENT_X).abs() < 1e-3);
assert!((moments.moment_y - EXPECTED_MOMENT_Y).abs() < 1e-3);
assert!((moments.moment_xx - EXPECTED_MOMENT_XX).abs() < 1e-3);
assert!((moments.moment_xy - EXPECTED_MOMENT_XY).abs() < 1e-3);
assert!((moments.moment_yy - EXPECTED_MOMENT_YY).abs() < 1e-3);
}
#[test]
fn assert_expand_subpath_closed() {
let mut path = BezPath::new();
path.move_to((0.0, 0.0));
path.line_to((100.0, 0.0));
path.line_to((100.0, 100.0));
path.line_to((0.0, 100.0));
let expanded = expand_path(path, Diagonal2::new(10.0, 10.0), Join::Miter, 4.0, 1e-3);
assert_eq!(expanded.elements().last(), Some(&PathEl::ClosePath));
}
#[test]
fn expand_degenerate_input() {
let path = BezPath::from_svg("M0,0 C0,0 0,0 0,0 Z").unwrap();
let expanded = expand_path(path, Diagonal2::new(10.0, 10.0), Join::Miter, 4.0, 1e-3);
assert!(expanded.is_empty());
}
#[test]
fn expand_degenerate_ghost() {
let mut path = BezPath::new();
path.extend(Rect::new(0.0, 0.0, 10.0, 10.0).path_elements(1e-3));
let expected = expand_path(&path, Diagonal2::new(1.0, 1.0), Join::Miter, 4.0, 1e-3);
path.move_to((20.0, 20.0));
path.close_path();
let actual = expand_path(&path, Diagonal2::new(1.0, 1.0), Join::Miter, 4.0, 1e-3);
assert_eq!(actual, expected);
}
#[test]
fn expand_open_subpath_uses_implicit_close_for_area_sign() {
let mut open = BezPath::new();
open.move_to((100.0, 100.0));
open.line_to((110.0, 100.0));
open.line_to((100.0, 110.0));
let mut closed = open.clone();
closed.close_path();
let expand = Diagonal2::new(1.0, 1.0);
let open_expanded = expand_path(open, expand, Join::Miter, 4.0, 1e-3);
let closed_expanded = expand_path(closed, expand, Join::Miter, 4.0, 1e-3);
assert_eq!(open_expanded, closed_expanded);
}
}
+719
View File
@@ -0,0 +1,719 @@
// Copyright 2022 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! An implementation of cubic Bézier curve fitting based on a quartic
//! solver making signed area and moment match the source curve.
use core::ops::Range;
use alloc::vec::Vec;
use arrayvec::ArrayVec;
use crate::{
Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2,
common::{
GAUSS_LEGENDRE_COEFFS_16, factor_quartic_inner, solve_cubic, solve_itp_fallible,
solve_quadratic,
},
};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// The source curve for curve fitting.
///
/// This trait is a general representation of curves to be used as input to a curve
/// fitting process. It can represent source curves with cusps and corners, though
/// if the corners are known in advance, it may be better to run curve fitting on
/// subcurves bounded by the corners.
///
/// The trait primarily works by sampling the source curve and computing the position
/// and derivative at each sample. Those derivatives are then used for multiple
/// sub-tasks, including ensuring G1 continuity at subdivision points, computing the
/// area and moment of the curve for curve fitting, and casting rays for evaluation
/// of a distance metric to test accuracy.
///
/// A major motivation is computation of offset curves, which often have cusps, but
/// the presence and location of those cusps is not generally known. It is also
/// intended for conversion between curve types (for example, piecewise Euler spiral
/// or NURBS), and distortion effects such as perspective transform.
///
/// Note general similarities to [`ParamCurve`] but also important differences.
/// Instead of separate [`eval`] and evaluation of derivative, have a single
/// [`sample_pt_deriv`] method which can be more efficient and also handles cusps more
/// robustly. Also there is no method for subsegment, as that is not needed and
/// would be annoying to implement.
///
/// [`ParamCurve`]: crate::ParamCurve
/// [`eval`]: crate::ParamCurve::eval
/// [`sample_pt_deriv`]: ParamCurveFit::sample_pt_deriv
pub trait ParamCurveFit {
/// Evaluate the curve and its tangent at parameter `t`.
///
/// For a regular curve (one not containing a cusp or corner), the
/// derivative is a good choice for the tangent vector and the `sign`
/// parameter can be ignored. Otherwise, the `sign` parameter selects which
/// side of the discontinuity the tangent will be sampled from.
///
/// Generally `t` is in the range [0..1].
fn sample_pt_tangent(&self, t: f64, sign: f64) -> CurveFitSample;
/// Evaluate the point and derivative at parameter `t`.
///
/// In curves with cusps, the derivative can go to zero.
fn sample_pt_deriv(&self, t: f64) -> (Point, Vec2);
/// Compute moment integrals.
///
/// This method computes the integrals of y dx, x y dx, and y^2 dx over the
/// length of this curve. From these integrals it is fairly straightforward
/// to derive the moments needed for curve fitting.
///
/// A default implementation is provided which does quadrature integration
/// with Green's theorem, in terms of samples evaluated with
/// [`sample_pt_deriv`].
///
/// [`sample_pt_deriv`]: ParamCurveFit::sample_pt_deriv
fn moment_integrals(&self, range: Range<f64>) -> (f64, f64, f64) {
let t0 = 0.5 * (range.start + range.end);
let dt = 0.5 * (range.end - range.start);
let (a, x, y) = GAUSS_LEGENDRE_COEFFS_16
.iter()
.map(|(wi, xi)| {
let t = t0 + xi * dt;
let (p, d) = self.sample_pt_deriv(t);
let a = wi * d.x * p.y;
let x = p.x * a;
let y = p.y * a;
(a, x, y)
})
.fold((0.0, 0.0, 0.0), |(a0, x0, y0), (a1, x1, y1)| {
(a0 + a1, x0 + x1, y0 + y1)
});
(a * dt, x * dt, y * dt)
}
/// Find a cusp or corner within the given range.
///
/// If the range contains a corner or cusp, return it. If there is more
/// than one such discontinuity, any can be reported, as the function will
/// be called repeatedly after subdivision of the range.
///
/// Do not report cusps at the endpoints of the range, as this may cause
/// potentially infinite subdivision. In particular, when a cusp is reported
/// and this method is called on a subdivided range bounded by the reported
/// cusp, then the subsequent call should not report a cusp there.
///
/// The definition of what exactly constitutes a cusp is somewhat loose.
/// If a cusp is missed, then the curve fitting algorithm will attempt to
/// fit the curve with a smooth curve, which is generally not a disaster
/// will usually result in more subdivision. Conversely, it might be useful
/// to report near-cusps, specifically points of curvature maxima where the
/// curvature is large but still mathematically finite.
fn break_cusp(&self, range: Range<f64>) -> Option<f64>;
}
/// A sample point of a curve for fitting.
pub struct CurveFitSample {
/// A point on the curve at the sample location.
pub p: Point,
/// A vector tangent to the curve at the sample location.
pub tangent: Vec2,
}
impl CurveFitSample {
/// Intersect a ray orthogonal to the tangent with the given cubic.
///
/// Returns a vector of `t` values on the cubic.
fn intersect(&self, c: CubicBez) -> ArrayVec<f64, 3> {
let p1 = 3.0 * (c.p1 - c.p0);
let p2 = 3.0 * c.p2.to_vec2() - 6.0 * c.p1.to_vec2() + 3.0 * c.p0.to_vec2();
let p3 = (c.p3 - c.p0) - 3.0 * (c.p2 - c.p1);
let c0 = (c.p0 - self.p).dot(self.tangent);
let c1 = p1.dot(self.tangent);
let c2 = p2.dot(self.tangent);
let c3 = p3.dot(self.tangent);
solve_cubic(c0, c1, c2, c3)
.into_iter()
.filter(|t| (0.0..=1.0).contains(t))
.collect()
}
}
/// Generate a Bézier path that fits the source curve.
///
/// This function is still experimental and the signature might change; it's possible
/// it might become a method on the [`ParamCurveFit`] trait.
///
/// This function recursively subdivides the curve in half by the parameter when the
/// accuracy is not met. That gives a reasonably optimized result but not necessarily
/// the minimum number of segments.
///
/// In general, the resulting Bézier path should have a Fréchet distance less than
/// the provided `accuracy` parameter. However, this is not a rigorous guarantee, as
/// the error metric is computed approximately.
///
/// This function is intended for use when the source curve is piecewise continuous,
/// with the discontinuities reported by the cusp method. In applications (such as
/// stroke expansion) where this property may not hold, it is up to the client to
/// detect and handle such cases. Even so, best effort is made to avoid infinite
/// subdivision.
///
/// When a higher degree of optimization is desired (at considerably more runtime cost),
/// consider [`fit_to_bezpath_opt`] instead.
pub fn fit_to_bezpath(source: &impl ParamCurveFit, accuracy: f64) -> BezPath {
let mut path = BezPath::new();
fit_to_bezpath_rec(source, 0.0..1.0, accuracy, &mut path);
path
}
// Discussion question: possibly should take endpoint samples, to avoid
// duplication of that work.
fn fit_to_bezpath_rec(
source: &impl ParamCurveFit,
range: Range<f64>,
accuracy: f64,
path: &mut BezPath,
) {
let start = range.start;
let end = range.end;
let start_p = source.sample_pt_tangent(range.start, 1.0).p;
let end_p = source.sample_pt_tangent(range.end, -1.0).p;
if start_p.distance_squared(end_p) <= accuracy * accuracy {
if let Some((c, _)) = try_fit_line(source, accuracy, range, start_p, end_p) {
if path.is_empty() {
path.move_to(c.p0);
}
path.curve_to(c.p1, c.p2, c.p3);
return;
}
}
let t = if let Some(t) = source.break_cusp(start..end) {
t
} else if let Some((c, _)) = fit_to_cubic(source, start..end, accuracy) {
if path.is_empty() {
path.move_to(c.p0);
}
path.curve_to(c.p1, c.p2, c.p3);
return;
} else {
// A smarter approach is possible than midpoint subdivision, but would be
// a significant increase in complexity.
0.5 * (start + end)
};
if t == start || t == end {
// infinite recursion, just draw a line
let p1 = start_p.lerp(end_p, 1.0 / 3.0);
let p2 = end_p.lerp(start_p, 1.0 / 3.0);
if path.is_empty() {
path.move_to(start_p);
}
path.curve_to(p1, p2, end_p);
return;
}
fit_to_bezpath_rec(source, start..t, accuracy, path);
fit_to_bezpath_rec(source, t..end, accuracy, path);
}
const N_SAMPLE: usize = 20;
/// An acceleration structure for estimating curve distance
struct CurveDist {
samples: ArrayVec<CurveFitSample, N_SAMPLE>,
arcparams: ArrayVec<f64, N_SAMPLE>,
range: Range<f64>,
/// A "spicy" curve is one with potentially extreme curvature variation,
/// so use arc length measurement for better accuracy.
spicy: bool,
}
impl CurveDist {
fn from_curve(source: &impl ParamCurveFit, range: Range<f64>) -> Self {
let step = (range.end - range.start) * (1.0 / (N_SAMPLE + 1) as f64);
let mut last_tan = None;
let mut spicy = false;
const SPICY_THRESH: f64 = 0.2;
let mut samples = ArrayVec::new();
for i in 0..N_SAMPLE + 2 {
let sample = source.sample_pt_tangent(range.start + i as f64 * step, 1.0);
if let Some(last_tan) = last_tan {
let cross = sample.tangent.cross(last_tan);
let dot = sample.tangent.dot(last_tan);
if cross.abs() > SPICY_THRESH * dot.abs() {
spicy = true;
}
}
last_tan = Some(sample.tangent);
if i > 0 && i < N_SAMPLE + 1 {
samples.push(sample);
}
}
CurveDist {
samples,
arcparams: ArrayVec::default(),
range,
spicy,
}
}
fn compute_arc_params(&mut self, source: &impl ParamCurveFit) {
const N_SUBSAMPLE: usize = 10;
let (start, end) = (self.range.start, self.range.end);
let dt = (end - start) * (1.0 / ((N_SAMPLE + 1) * N_SUBSAMPLE) as f64);
let mut arclen = 0.0;
for i in 0..N_SAMPLE + 1 {
for j in 0..N_SUBSAMPLE {
let t = start + dt * ((i * N_SUBSAMPLE + j) as f64 + 0.5);
let (_, deriv) = source.sample_pt_deriv(t);
arclen += deriv.hypot();
}
if i < N_SAMPLE {
self.arcparams.push(arclen);
}
}
let arclen_inv = arclen.recip();
for x in &mut self.arcparams {
*x *= arclen_inv;
}
}
/// Evaluate distance based on arc length parametrization
fn eval_arc(&self, c: CubicBez, acc2: f64) -> Option<f64> {
// TODO: this could perhaps be tuned.
const EPS: f64 = 1e-9;
let c_arclen = c.arclen(EPS);
let mut max_err2 = 0.0;
for (sample, s) in self.samples.iter().zip(&self.arcparams) {
let t = c.inv_arclen(c_arclen * s, EPS);
let err = sample.p.distance_squared(c.eval(t));
max_err2 = err.max(max_err2);
if max_err2 > acc2 {
return None;
}
}
Some(max_err2)
}
/// Evaluate distance to a cubic approximation.
///
/// If distance exceeds stated accuracy, can return `None`. Note that
/// `acc2` is the square of the target.
///
/// Returns the square of the error, which is intended to be a good
/// approximation of the Fréchet distance.
fn eval_ray(&self, c: CubicBez, acc2: f64) -> Option<f64> {
let mut max_err2 = 0.0;
for sample in &self.samples {
let mut best = acc2 + 1.0;
for t in sample.intersect(c) {
let err = sample.p.distance_squared(c.eval(t));
best = best.min(err);
}
max_err2 = best.max(max_err2);
if max_err2 > acc2 {
return None;
}
}
Some(max_err2)
}
fn eval_dist(&mut self, source: &impl ParamCurveFit, c: CubicBez, acc2: f64) -> Option<f64> {
// Always compute cheaper distance, hoping for early-out.
let ray_dist = self.eval_ray(c, acc2)?;
if !self.spicy {
return Some(ray_dist);
}
if self.arcparams.is_empty() {
self.compute_arc_params(source);
}
self.eval_arc(c, acc2)
}
}
/// As described in [Simplifying Bézier paths], strictly optimizing for
/// Fréchet distance can create bumps. The problem is curves with long
/// control arms (distance from the control point to the corresponding
/// endpoint). We mitigate that by applying a penalty as a multiplier to
/// the measured error (approximate Fréchet distance). This is ReLU-like,
/// with a value of 1.0 below the elbow, and a given slope above it. The
/// values here have been determined empirically to give good results.
///
/// [Simplifying Bézier paths]:
/// https://raphlinus.github.io/curves/2023/04/18/bezpath-simplify.html
const D_PENALTY_ELBOW: f64 = 0.65;
const D_PENALTY_SLOPE: f64 = 2.0;
/// Try fitting a line.
///
/// This is especially useful for very short chords, in which the standard
/// cubic fit is not numerically stable. The tangents are not considered, so
/// it's useful in cusp and near-cusp situations where the tangents are not
/// reliable, as well.
///
/// Returns the line raised to a cubic and the error, if within tolerance.
fn try_fit_line(
source: &impl ParamCurveFit,
accuracy: f64,
range: Range<f64>,
start: Point,
end: Point,
) -> Option<(CubicBez, f64)> {
let acc2 = accuracy * accuracy;
let chord_l = Line::new(start, end);
const SHORT_N: usize = 7;
let mut max_err2 = 0.0;
let dt = (range.end - range.start) / (SHORT_N + 1) as f64;
for i in 0..SHORT_N {
let t = range.start + (i + 1) as f64 * dt;
let p = source.sample_pt_deriv(t).0;
let err2 = chord_l.nearest(p, accuracy).distance_sq;
if err2 > acc2 {
// Not in tolerance; likely subdivision will help.
return None;
}
max_err2 = err2.max(max_err2);
}
let p1 = start.lerp(end, 1.0 / 3.0);
let p2 = end.lerp(start, 1.0 / 3.0);
let c = CubicBez::new(start, p1, p2, end);
Some((c, max_err2))
}
/// Fit a single cubic to a range of the source curve.
///
/// Returns the cubic segment and the square of the error.
/// Discussion question: should this be a method on the trait instead?
pub fn fit_to_cubic(
source: &impl ParamCurveFit,
range: Range<f64>,
accuracy: f64,
) -> Option<(CubicBez, f64)> {
let start = source.sample_pt_tangent(range.start, 1.0);
let end = source.sample_pt_tangent(range.end, -1.0);
let d = end.p - start.p;
let chord2 = d.hypot2();
let acc2 = accuracy * accuracy;
if chord2 <= acc2 {
// Special case very short chords; try to fit a line.
return try_fit_line(source, accuracy, range, start.p, end.p);
}
let th = d.atan2();
fn mod_2pi(th: f64) -> f64 {
let th_scaled = th * core::f64::consts::FRAC_1_PI * 0.5;
core::f64::consts::PI * 2.0 * (th_scaled - th_scaled.round())
}
let th0 = mod_2pi(start.tangent.atan2() - th);
let th1 = mod_2pi(th - end.tangent.atan2());
let (mut area, mut x, mut y) = source.moment_integrals(range.clone());
let (x0, y0) = (start.p.x, start.p.y);
let (dx, dy) = (d.x, d.y);
// Subtract off area of chord
area -= dx * (y0 + 0.5 * dy);
// `area` is signed area of closed curve segment.
// This quantity is invariant to translation and rotation.
// Subtract off moment of chord
let dy_3 = dy * (1. / 3.);
x -= dx * (x0 * y0 + 0.5 * (x0 * dy + y0 * dx) + dy_3 * dx);
y -= dx * (y0 * y0 + y0 * dy + dy_3 * dy);
// Translate start point to origin; convert raw integrals to moments.
x -= x0 * area;
y = 0.5 * y - y0 * area;
// Rotate into place (this also scales up by chordlength for efficiency).
let moment = d.x * x + d.y * y;
// `moment` is the chordlength times the x moment of the curve translated
// so its start point is on the origin, and rotated so its end point is on the
// x axis.
let chord2_inv = chord2.recip();
let unit_area = area * chord2_inv;
let mx = moment * chord2_inv.powi(2);
// `unit_area` is signed area scaled to unit chord; `mx` is scaled x moment
let chord = chord2.sqrt();
let aff = Affine::translate(start.p.to_vec2()) * Affine::rotate(th) * Affine::scale(chord);
let mut curve_dist = CurveDist::from_curve(source, range);
let mut best_c = None;
let mut best_err2 = None;
for (cand, d0, d1) in cubic_fit(th0, th1, unit_area, mx) {
let c = aff * cand;
if let Some(err2) = curve_dist.eval_dist(source, c, acc2) {
fn scale_f(d: f64) -> f64 {
1.0 + (d - D_PENALTY_ELBOW).max(0.0) * D_PENALTY_SLOPE
}
let scale = scale_f(d0).max(scale_f(d1)).powi(2);
let err2 = err2 * scale;
if err2 < acc2 && best_err2.map(|best| err2 < best).unwrap_or(true) {
best_c = Some(c);
best_err2 = Some(err2);
}
}
}
match (best_c, best_err2) {
(Some(c), Some(err2)) => Some((c, err2)),
_ => None,
}
}
/// Returns curves matching area and moment, given unit chord.
fn cubic_fit(th0: f64, th1: f64, area: f64, mx: f64) -> ArrayVec<(CubicBez, f64, f64), 4> {
// Note: maybe we want to take unit vectors instead of angle? Shouldn't
// matter much either way though.
let (s0, c0) = th0.sin_cos();
let (s1, c1) = th1.sin_cos();
let a4 = -9.
* c0
* (((2. * s1 * c1 * c0 + s0 * (2. * c1 * c1 - 1.)) * c0 - 2. * s1 * c1) * c0
- c1 * c1 * s0);
let a3 = 12.
* ((((c1 * (30. * area * c1 - s1) - 15. * area) * c0 + 2. * s0
- c1 * s0 * (c1 + 30. * area * s1))
* c0
+ c1 * (s1 - 15. * area * c1))
* c0
- s0 * c1 * c1);
let a2 = 12.
* ((((70. * mx + 15. * area) * s1 * s1 + c1 * (9. * s1 - 70. * c1 * mx - 5. * c1 * area))
* c0
- 5. * s0 * s1 * (3. * s1 - 4. * c1 * (7. * mx + area)))
* c0
- c1 * (9. * s1 - 70. * c1 * mx - 5. * c1 * area));
let a1 = 16.
* (((12. * s0 - 5. * c0 * (42. * mx - 17. * area)) * s1
- 70. * c1 * (3. * mx - area) * s0
- 75. * c0 * c1 * area * area)
* s1
- 75. * c1 * c1 * area * area * s0);
let a0 = 80. * s1 * (42. * s1 * mx - 25. * area * (s1 - c1 * area));
// TODO: "roots" is not a good name for this variable, as it also contains
// the real part of complex conjugate pairs.
let mut roots = ArrayVec::<f64, 4>::new();
const EPS: f64 = 1e-12;
if a4.abs() > EPS {
let a = a3 / a4;
let b = a2 / a4;
let c = a1 / a4;
let d = a0 / a4;
if let Some(quads) = factor_quartic_inner(a, b, c, d, false) {
for (qc1, qc0) in quads {
let qroots = solve_quadratic(qc0, qc1, 1.0);
if qroots.is_empty() {
// Real part of pair of complex roots
roots.push(-0.5 * qc1);
} else {
roots.extend(qroots);
}
}
}
} else if a3.abs() > EPS {
roots.extend(solve_cubic(a0, a1, a2, a3));
} else if a2.abs() > EPS || a1.abs() > EPS || a0.abs() > EPS {
roots.extend(solve_quadratic(a0, a1, a2));
} else {
return [(
CubicBez::new((0.0, 0.0), (1. / 3., 0.0), (2. / 3., 0.0), (1., 0.0)),
1f64 / 3.,
1f64 / 3.,
)]
.into_iter()
.collect();
}
let s01 = s0 * c1 + s1 * c0;
roots
.iter()
.filter_map(|&d0| {
let (d0, d1) = if d0 > 0.0 {
let d1 = (d0 * s0 - area * (10. / 3.)) / (0.5 * d0 * s01 - s1);
if d1 > 0.0 { (d0, d1) } else { (s1 / s01, 0.0) }
} else {
(0.0, s0 / s01)
};
// We could implement a maximum d value here.
if d0 >= 0.0 && d1 >= 0.0 {
Some((
CubicBez::new(
(0.0, 0.0),
(d0 * c0, d0 * s0),
(1.0 - d1 * c1, d1 * s1),
(1.0, 0.0),
),
d0,
d1,
))
} else {
None
}
})
.collect()
}
/// Generate a highly optimized Bézier path that fits the source curve.
///
/// This function is still experimental and the signature might change; it's possible
/// it might become a method on the [`ParamCurveFit`] trait.
///
/// This function is considerably slower than [`fit_to_bezpath`], as it computes
/// optimal subdivision points. Its result is expected to be very close to the optimum
/// possible Bézier path for the source curve, in that it has a minimal number of curve
/// segments, and a minimal error over all paths with that number of segments.
///
/// See [`fit_to_bezpath`] for an explanation of the `accuracy` parameter.
pub fn fit_to_bezpath_opt(source: &impl ParamCurveFit, accuracy: f64) -> BezPath {
let mut cusps = Vec::new();
let mut path = BezPath::new();
let mut t0 = 0.0;
loop {
let t1 = cusps.last().copied().unwrap_or(1.0);
match fit_to_bezpath_opt_inner(source, accuracy, t0..t1, &mut path) {
Some(t) => cusps.push(t),
None => match cusps.pop() {
Some(t) => t0 = t,
None => break,
},
}
}
path
}
/// Fit a range without cusps.
///
/// On Ok return, range has been added to the path. On Err return, report a cusp (and don't
/// mutate path).
fn fit_to_bezpath_opt_inner(
source: &impl ParamCurveFit,
accuracy: f64,
range: Range<f64>,
path: &mut BezPath,
) -> Option<f64> {
if let Some(t) = source.break_cusp(range.clone()) {
return Some(t);
}
let err;
if let Some((c, err2)) = fit_to_cubic(source, range.clone(), accuracy) {
err = err2.sqrt();
if err < accuracy {
if range.start == 0.0 {
path.move_to(c.p0);
}
path.curve_to(c.p1, c.p2, c.p3);
return None;
}
} else {
err = 2.0 * accuracy;
}
let (mut t0, t1) = (range.start, range.end);
let mut n = 0;
let last_err;
loop {
n += 1;
match fit_opt_segment(source, accuracy, t0..t1) {
FitResult::ParamVal(t) => t0 = t,
FitResult::SegmentError(err) => {
last_err = err;
break;
}
FitResult::CuspFound(t) => return Some(t),
}
}
t0 = range.start;
const EPS: f64 = 1e-9;
let f = |x| fit_opt_err_delta(source, x, accuracy, t0..t1, n);
let k1 = 0.2 / accuracy;
let ya = -err;
let yb = accuracy - last_err;
let (_, x) = match solve_itp_fallible(f, 0.0, accuracy, EPS, 1, k1, ya, yb) {
Ok(x) => x,
Err(t) => return Some(t),
};
//println!("got fit with n={}, err={}", n, x);
let path_len = path.elements().len();
for i in 0..n {
let t1 = if i < n - 1 {
match fit_opt_segment(source, x, t0..range.end) {
FitResult::ParamVal(t1) => t1,
FitResult::SegmentError(_) => range.end,
FitResult::CuspFound(t) => {
path.truncate(path_len);
return Some(t);
}
}
} else {
range.end
};
let (c, _) = fit_to_cubic(source, t0..t1, accuracy).unwrap();
if i == 0 && range.start == 0.0 {
path.move_to(c.p0);
}
path.curve_to(c.p1, c.p2, c.p3);
t0 = t1;
if t0 == range.end {
// This is unlikely but could happen when not monotonic.
break;
}
}
None
}
fn measure_one_seg(source: &impl ParamCurveFit, range: Range<f64>, limit: f64) -> Option<f64> {
fit_to_cubic(source, range, limit).map(|(_, err2)| err2.sqrt())
}
enum FitResult {
/// The parameter (`t`) value that meets the desired accuracy.
ParamVal(f64),
/// Error of the measured segment.
SegmentError(f64),
/// The parameter value where a cusp was found.
CuspFound(f64),
}
fn fit_opt_segment(source: &impl ParamCurveFit, accuracy: f64, range: Range<f64>) -> FitResult {
if let Some(t) = source.break_cusp(range.clone()) {
return FitResult::CuspFound(t);
}
let missing_err = accuracy * 2.0;
let err = measure_one_seg(source, range.clone(), accuracy).unwrap_or(missing_err);
if err <= accuracy {
return FitResult::SegmentError(err);
}
let (t0, t1) = (range.start, range.end);
let f = |x| {
if let Some(t) = source.break_cusp(range.clone()) {
return Err(t);
}
let err = measure_one_seg(source, t0..x, accuracy).unwrap_or(missing_err);
Ok(err - accuracy)
};
const EPS: f64 = 1e-9;
let k1 = 2.0 / (t1 - t0);
match solve_itp_fallible(f, t0, t1, EPS, 1, k1, -accuracy, err - accuracy) {
Ok((t1, _)) => FitResult::ParamVal(t1),
Err(t) => FitResult::CuspFound(t),
}
}
// Ok result is delta error (accuracy - error of last seg).
// Err result is a cusp.
fn fit_opt_err_delta(
source: &impl ParamCurveFit,
accuracy: f64,
limit: f64,
range: Range<f64>,
n: usize,
) -> Result<f64, f64> {
let (mut t0, t1) = (range.start, range.end);
for _ in 0..n - 1 {
t0 = match fit_opt_segment(source, accuracy, t0..t1) {
FitResult::ParamVal(t0) => t0,
// In this case, n - 1 will work, which of course means the error is highly
// non-monotonic. We should probably harvest that solution.
FitResult::SegmentError(_) => return Ok(accuracy),
FitResult::CuspFound(t) => return Err(t),
}
}
let err = measure_one_seg(source, t0..t1, limit).unwrap_or(accuracy * 2.0);
Ok(accuracy - err)
}
+404
View File
@@ -0,0 +1,404 @@
// Copyright 2019 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A description of the distances between the edges of two rectangles.
use core::ops::{Add, Div, Mul, Neg, Sub};
use crate::{Rect, Size};
/// Insets from the edges of a rectangle.
///
///
/// The inset value for each edge can be thought of as a delta computed from
/// the center of the rect to that edge. For instance, with an inset of `2.0` on
/// the x-axis, a rectangle with the origin `(0.0, 0.0)` with that inset added
/// will have the new origin at `(-2.0, 0.0)`.
///
/// Put alternatively, a positive inset represents increased distance from center,
/// and a negative inset represents decreased distance from center.
///
/// # Examples
///
/// Positive insets added to a [`Rect`] produce a larger [`Rect`]:
/// ```
/// # use kurbo::{Insets, Rect};
/// let rect = Rect::from_origin_size((0., 0.,), (10., 10.,));
/// let insets = Insets::uniform_xy(3., 0.,);
///
/// let inset_rect = rect + insets;
/// assert_eq!(inset_rect.width(), 16.0, "10.0 + 3.0 × 2");
/// assert_eq!(inset_rect.x0, -3.0);
/// ```
///
/// Negative insets added to a [`Rect`] produce a smaller [`Rect`]:
///
/// ```
/// # use kurbo::{Insets, Rect};
/// let rect = Rect::from_origin_size((0., 0.,), (10., 10.,));
/// let insets = Insets::uniform_xy(-3., 0.,);
///
/// let inset_rect = rect + insets;
/// assert_eq!(inset_rect.width(), 4.0, "10.0 - 3.0 × 2");
/// assert_eq!(inset_rect.x0, 3.0);
/// ```
///
/// [`Insets`] operate on the absolute rectangle [`Rect::abs`], and so ignore
/// existing negative widths and heights.
///
/// ```
/// # use kurbo::{Insets, Rect};
/// let rect = Rect::new(7., 11., 0., 0.,);
/// let insets = Insets::uniform_xy(0., 1.,);
///
/// assert_eq!(rect.width(), -7.0);
///
/// let inset_rect = rect + insets;
/// assert_eq!(inset_rect.width(), 7.0);
/// assert_eq!(inset_rect.x0, 0.0);
/// assert_eq!(inset_rect.height(), 13.0);
/// ```
///
/// The width and height of an inset operation can still be negative if the
/// [`Insets`]' dimensions are greater than the dimensions of the original [`Rect`].
///
/// ```
/// # use kurbo::{Insets, Rect};
/// let rect = Rect::new(0., 0., 3., 5.);
/// let insets = Insets::uniform_xy(0., 7.,);
///
/// let inset_rect = rect - insets;
/// assert_eq!(inset_rect.height(), -9., "5 - 7 × 2")
/// ```
///
/// `Rect - Rect = Insets`:
///
///
/// ```
/// # use kurbo::{Insets, Rect};
/// let rect = Rect::new(0., 0., 5., 11.);
/// let insets = Insets::uniform_xy(1., 7.,);
///
/// let inset_rect = rect + insets;
/// let insets2 = inset_rect - rect;
///
/// assert_eq!(insets2.x0, insets.x0);
/// assert_eq!(insets2.y1, insets.y1);
/// assert_eq!(insets2.x_value(), insets.x_value());
/// assert_eq!(insets2.y_value(), insets.y_value());
/// ```
#[derive(Clone, Copy, Default, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Insets {
/// The minimum x coordinate (left edge).
pub x0: f64,
/// The minimum y coordinate (top edge in y-down spaces).
pub y0: f64,
/// The maximum x coordinate (right edge).
pub x1: f64,
/// The maximum y coordinate (bottom edge in y-down spaces).
pub y1: f64,
}
impl Insets {
/// Zeroed insets.
pub const ZERO: Insets = Insets::uniform(0.);
/// New uniform insets.
#[inline(always)]
pub const fn uniform(d: f64) -> Insets {
Insets {
x0: d,
y0: d,
x1: d,
y1: d,
}
}
/// New insets with uniform values along each axis.
#[inline(always)]
pub const fn uniform_xy(x: f64, y: f64) -> Insets {
Insets {
x0: x,
y0: y,
x1: x,
y1: y,
}
}
/// New insets. The ordering of the arguments is "left, top, right, bottom",
/// assuming a y-down coordinate space.
#[inline(always)]
pub const fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Insets {
Insets { x0, y0, x1, y1 }
}
/// The total delta on the x-axis represented by these insets.
///
/// # Examples
///
/// ```
/// use kurbo::Insets;
///
/// let insets = Insets::uniform_xy(3., 8.);
/// assert_eq!(insets.x_value(), 6.);
///
/// let insets = Insets::new(5., 0., -12., 0.,);
/// assert_eq!(insets.x_value(), -7.);
/// ```
#[inline]
pub const fn x_value(self) -> f64 {
self.x0 + self.x1
}
/// The total delta on the y-axis represented by these insets.
///
/// # Examples
///
/// ```
/// use kurbo::Insets;
///
/// let insets = Insets::uniform_xy(3., 7.);
/// assert_eq!(insets.y_value(), 14.);
///
/// let insets = Insets::new(5., 10., -12., 4.,);
/// assert_eq!(insets.y_value(), 14.);
/// ```
#[inline]
pub const fn y_value(self) -> f64 {
self.y0 + self.y1
}
/// Returns the total delta represented by these insets as a [`Size`].
///
/// This is equivalent to creating a [`Size`] from the values returned by
/// [`x_value`] and [`y_value`].
///
/// This function may return a size with negative values.
///
/// # Examples
///
/// ```
/// use kurbo::{Insets, Size};
///
/// let insets = Insets::new(11.1, -43.3, 3.333, -0.0);
/// assert_eq!(insets.size(), Size::new(insets.x_value(), insets.y_value()));
/// ```
///
/// [`x_value`]: Insets::x_value
/// [`y_value`]: Insets::y_value
pub const fn size(self) -> Size {
Size::new(self.x_value(), self.y_value())
}
/// Return `true` iff all values are nonnegative.
pub const fn are_nonnegative(self) -> bool {
let Insets { x0, y0, x1, y1 } = self;
x0 >= 0.0 && y0 >= 0.0 && x1 >= 0.0 && y1 >= 0.0
}
/// Return new `Insets` with all negative values replaced with `0.0`.
///
/// This is provided as a convenience for applications where negative insets
/// are not meaningful.
///
/// # Examples
///
/// ```
/// use kurbo::Insets;
///
/// let insets = Insets::new(-10., 3., -0.2, 4.);
/// let nonnegative = insets.nonnegative();
/// assert_eq!(nonnegative.x_value(), 0.0);
/// assert_eq!(nonnegative.y_value(), 7.0);
/// ```
pub const fn nonnegative(self) -> Insets {
let Insets { x0, y0, x1, y1 } = self;
Insets {
x0: x0.max(0.0),
y0: y0.max(0.0),
x1: x1.max(0.0),
y1: y1.max(0.0),
}
}
/// Are these insets finite?
#[inline]
pub const fn is_finite(&self) -> bool {
self.x0.is_finite() && self.y0.is_finite() && self.x1.is_finite() && self.y1.is_finite()
}
/// Are these insets NaN?
#[inline]
pub const fn is_nan(&self) -> bool {
self.x0.is_nan() || self.y0.is_nan() || self.x1.is_nan() || self.y1.is_nan()
}
/// Returns the component-wise minimum of `self` and `other`.
///
/// # Examples
///
/// ```
/// use kurbo::Insets;
///
/// let this = Insets::new(1., 2., 3., 4.);
/// let other = Insets::new(4., 3., 2., 1.);
///
/// assert_eq!(this.min(other), Insets::new(1., 2., 2., 1.));
/// ```
pub const fn min(self, other: Insets) -> Self {
Self {
x0: self.x0.min(other.x0),
x1: self.x1.min(other.x1),
y0: self.y0.min(other.y0),
y1: self.y1.min(other.y1),
}
}
/// Returns the component-wise maximum of `self` and `other`.
///
/// # Examples
///
/// ```
/// use kurbo::Insets;
///
/// let this = Insets::new(1., 2., 3., 4.);
/// let other = Insets::new(4., 3., 2., 1.);
///
/// assert_eq!(this.max(other), Insets::new(4., 3., 3., 4.));
/// ```
pub const fn max(self, other: Insets) -> Self {
Self {
x0: self.x0.max(other.x0),
x1: self.x1.max(other.x1),
y0: self.y0.max(other.y0),
y1: self.y1.max(other.y1),
}
}
}
impl Neg for Insets {
type Output = Insets;
#[inline]
fn neg(self) -> Insets {
Insets::new(-self.x0, -self.y0, -self.x1, -self.y1)
}
}
impl Add<Insets> for Insets {
type Output = Insets;
fn add(self, other: Insets) -> Self::Output {
Insets {
x0: self.x0 + other.x0,
x1: self.x1 + other.x1,
y0: self.y0 + other.y0,
y1: self.y1 + other.y1,
}
}
}
impl Sub<Insets> for Insets {
type Output = Insets;
fn sub(self, other: Insets) -> Self::Output {
Insets {
x0: self.x0 - other.x0,
x1: self.x1 - other.x1,
y0: self.y0 - other.y0,
y1: self.y1 - other.y1,
}
}
}
impl Add<Rect> for Insets {
type Output = Rect;
#[inline]
#[allow(clippy::suspicious_arithmetic_impl)]
fn add(self, other: Rect) -> Rect {
let other = other.abs();
Rect::new(
other.x0 - self.x0,
other.y0 - self.y0,
other.x1 + self.x1,
other.y1 + self.y1,
)
}
}
impl Add<Insets> for Rect {
type Output = Rect;
#[inline]
fn add(self, other: Insets) -> Rect {
other + self
}
}
impl Sub<Rect> for Insets {
type Output = Rect;
#[inline]
fn sub(self, other: Rect) -> Rect {
other + -self
}
}
impl Mul<f64> for Insets {
type Output = Insets;
fn mul(self, rhs: f64) -> Self::Output {
Self {
x0: self.x0 * rhs,
y0: self.y0 * rhs,
x1: self.x1 * rhs,
y1: self.y1 * rhs,
}
}
}
impl Div<f64> for Insets {
type Output = Insets;
fn div(self, rhs: f64) -> Self::Output {
Self {
x0: self.x0 / rhs,
y0: self.y0 / rhs,
x1: self.x1 / rhs,
y1: self.y1 / rhs,
}
}
}
impl Sub<Insets> for Rect {
type Output = Rect;
#[inline]
fn sub(self, other: Insets) -> Rect {
other - self
}
}
impl From<f64> for Insets {
#[inline(always)]
fn from(src: f64) -> Insets {
Insets::uniform(src)
}
}
impl From<(f64, f64)> for Insets {
#[inline(always)]
fn from(src: (f64, f64)) -> Insets {
Insets::uniform_xy(src.0, src.1)
}
}
impl From<(f64, f64, f64, f64)> for Insets {
#[inline(always)]
fn from(src: (f64, f64, f64, f64)) -> Insets {
Insets::new(src.0, src.1, src.2, src.3)
}
}
+91
View File
@@ -0,0 +1,91 @@
// Copyright 2025 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
use euclid::UnknownUnit;
impl From<euclid::Vector2D<f64, UnknownUnit>> for crate::Vec2 {
#[inline(always)]
fn from(value: euclid::Vector2D<f64, UnknownUnit>) -> Self {
Self::new(value.x, value.y)
}
}
impl From<crate::Vec2> for euclid::Vector2D<f64, UnknownUnit> {
#[inline(always)]
fn from(value: crate::Vec2) -> Self {
Self::new(value.x, value.y)
}
}
impl From<euclid::Point2D<f64, UnknownUnit>> for crate::Point {
#[inline(always)]
fn from(value: euclid::Point2D<f64, UnknownUnit>) -> Self {
Self::new(value.x, value.y)
}
}
impl From<crate::Point> for euclid::Point2D<f64, UnknownUnit> {
#[inline(always)]
fn from(value: crate::Point) -> Self {
Self::new(value.x, value.y)
}
}
impl From<euclid::Size2D<f64, UnknownUnit>> for crate::Size {
#[inline(always)]
fn from(value: euclid::Size2D<f64, UnknownUnit>) -> Self {
Self::new(value.width, value.height)
}
}
impl From<crate::Size> for euclid::Size2D<f64, UnknownUnit> {
#[inline(always)]
fn from(value: crate::Size) -> Self {
Self::new(value.width, value.height)
}
}
impl From<euclid::Rect<f64, UnknownUnit>> for crate::Rect {
#[inline]
fn from(value: euclid::Rect<f64, UnknownUnit>) -> Self {
Self::from_origin_size(value.origin, value.size)
}
}
impl From<crate::Rect> for euclid::Rect<f64, UnknownUnit> {
#[inline]
fn from(value: crate::Rect) -> Self {
Self::new(value.origin().into(), value.size().into())
}
}
impl From<euclid::Box2D<f64, UnknownUnit>> for crate::Rect {
#[inline]
fn from(value: euclid::Box2D<f64, UnknownUnit>) -> Self {
Self::from_points(value.min, value.max)
}
}
impl From<crate::Rect> for euclid::Box2D<f64, UnknownUnit> {
#[inline]
fn from(value: crate::Rect) -> Self {
Self::new(
euclid::Point2D::new(value.min_x(), value.min_y()),
euclid::Point2D::new(value.max_x(), value.max_y()),
)
}
}
impl From<euclid::Transform2D<f64, UnknownUnit, UnknownUnit>> for crate::Affine {
#[inline(always)]
fn from(t: euclid::Transform2D<f64, UnknownUnit, UnknownUnit>) -> Self {
Self::new(t.to_array())
}
}
impl From<crate::Affine> for euclid::Transform2D<f64, UnknownUnit, UnknownUnit> {
#[inline(always)]
fn from(a: crate::Affine) -> Self {
Self::from_array(a.as_coeffs())
}
}
+189
View File
@@ -0,0 +1,189 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! 2D geometry, with a focus on curves.
//!
//! The kurbo library contains data structures and algorithms for curves and
//! vector paths. It was designed to serve the needs of 2D graphics applications,
//! but it is intended to be general enough to be useful for other applications.
//! It can be used as "vocabulary types" for representing curves and paths, and
//! also contains a number of computational geometry methods.
//!
//! # Examples
//!
//! Basic UI-style geometry:
//! ```
//! use kurbo::{Insets, Point, Rect, Size, Vec2};
//!
//! let pt = Point::new(10.0, 10.0);
//! let vector = Vec2::new(5.0, -5.0);
//! let pt2 = pt + vector;
//! assert_eq!(pt2, Point::new(15.0, 5.0));
//!
//! let rect = Rect::from_points(pt, pt2);
//! assert_eq!(rect, Rect::from_origin_size((10.0, 5.0), (5.0, 5.0)));
//!
//! let insets = Insets::uniform(1.0);
//! let inset_rect = rect - insets;
//! assert_eq!(inset_rect.size(), Size::new(3.0, 3.0));
//! ```
//!
//! Finding the closest position on a [`Shape`]'s perimeter to a [`Point`]:
//!
//! ```
//! use kurbo::{Circle, ParamCurve, ParamCurveNearest, Point, Shape};
//!
//! const DESIRED_ACCURACY: f64 = 0.1;
//!
//! /// Given a shape and a point, returns the closest position on the shape's
//! /// perimeter, or `None` if the shape is malformed.
//! fn closest_perimeter_point(shape: impl Shape, pt: Point) -> Option<Point> {
//! let mut best: Option<(Point, f64)> = None;
//! for segment in shape.path_segments(DESIRED_ACCURACY) {
//! let nearest = segment.nearest(pt, DESIRED_ACCURACY);
//! if best.map(|(_, best_d)| nearest.distance_sq < best_d).unwrap_or(true) {
//! best = Some((segment.eval(nearest.t), nearest.distance_sq))
//! }
//! }
//! best.map(|(point, _)| point)
//! }
//!
//! let circle = Circle::new((5.0, 5.0), 5.0);
//! let hit_point = Point::new(5.0, -2.0);
//! let expectation = Point::new(5.0, 0.0);
//! let hit = closest_perimeter_point(circle, hit_point).unwrap();
//! assert!(hit.distance(expectation) <= DESIRED_ACCURACY);
//! ```
//!
//! # Feature Flags
//!
//! The following crate [feature flags](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features) are available:
//!
//! - `std` (enabled by default): Get floating point functions from the standard library
//! (likely using your target's libc).
//! - `libm`: Use floating point implementations from [libm][].
//! This is useful for `no_std` environments.
//! However, note that the `libm` crate is not as efficient as the standard library.
//! - `mint`: Enable `From`/`Into` conversion of Kurbo and [mint][] types, enabling interoperability
//! with other graphics libraries.
//! - `euclid`: Enable `From`/`Into` conversion of Kurbo and [euclid][] types.
//! Note that if you're using both Kurbo and euclid at the same time, you *must*
//! also enable one of euclid's `std` or `libm` features.
//! - `serde`: Implement `serde::Deserialize` and `serde::Serialize` on various types.
//! - `schemars`: Add best-effort support for using Kurbo types in JSON schemas using [schemars][].
//!
//! At least one of `std` and `libm` is required; `std` overrides `libm`.
//! Note that Kurbo does require that an allocator is available (i.e. it uses [alloc]).
// LINEBENDER LINT SET - lib.rs - v4
// See https://linebender.org/wiki/canonical-lints/
// These lints shouldn't apply to examples or tests.
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
// These lints shouldn't apply to examples.
#![warn(clippy::print_stdout, clippy::print_stderr)]
// Targeting e.g. 32-bit means structs containing usize can give false positives for 64-bit.
#![cfg_attr(target_pointer_width = "64", warn(clippy::trivially_copy_pass_by_ref))]
// END LINEBENDER LINT SET
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
#![allow(
clippy::unreadable_literal,
clippy::many_single_char_names,
clippy::excessive_precision,
clippy::bool_to_int_with_if
)]
// The following lints are part of the Linebender standard set,
// but resolving them has been deferred for now.
// Feel free to send a PR that solves one or more of these.
#![allow(
missing_debug_implementations,
elided_lifetimes_in_paths,
trivial_numeric_casts,
unnameable_types,
clippy::use_self,
clippy::cast_possible_truncation,
clippy::missing_assert_message,
clippy::unseparated_literal_suffix,
clippy::duplicated_attributes,
clippy::allow_attributes_without_reason
)]
#[cfg(not(any(feature = "std", feature = "libm")))]
compile_error!("kurbo requires either the `std` or `libm` feature");
// Suppress the unused_crate_dependencies lint when both std and libm are specified.
#[cfg(all(feature = "std", feature = "libm"))]
use libm as _;
extern crate alloc;
mod affine;
mod arc;
mod axis;
mod bezpath;
mod circle;
pub mod common;
mod cubicbez;
mod ellipse;
mod expand;
mod fit;
mod insets;
mod line;
mod mindist;
mod moments;
pub mod offset;
mod param_curve;
mod point;
mod quadbez;
mod quadspline;
mod rect;
mod rounded_rect;
mod rounded_rect_radii;
mod shape;
pub mod simplify;
mod size;
mod stroke;
mod svg;
mod translate_scale;
mod triangle;
mod vec2;
#[cfg(feature = "euclid")]
mod interop_euclid;
pub use crate::affine::Affine;
pub use crate::arc::{Arc, ArcAppendIter};
pub use crate::axis::Axis;
pub use crate::bezpath::{
BezPath, LineIntersection, MinDistance, PathEl, PathSeg, PathSegIter, Segments, flatten,
segments,
};
pub use crate::circle::{Circle, CirclePathIter, CircleSegment};
pub use crate::cubicbez::{CubicBez, CubicBezIter, CuspType, cubics_to_quadratic_splines};
pub use crate::ellipse::Ellipse;
pub use crate::expand::{Diagonal2, expand_path, expand_path_signed};
pub use crate::fit::{
CurveFitSample, ParamCurveFit, fit_to_bezpath, fit_to_bezpath_opt, fit_to_cubic,
};
pub use crate::insets::Insets;
pub use crate::line::{ConstPoint, Line, LinePathIter};
pub use crate::moments::{Moments, ParamCurveMoments};
pub use crate::param_curve::{
DEFAULT_ACCURACY, MAX_EXTREMA, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea,
ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest,
};
pub use crate::point::Point;
pub use crate::quadbez::{QuadBez, QuadBezIter};
pub use crate::quadspline::QuadSpline;
pub use crate::rect::{Rect, RectPathIter};
pub use crate::rounded_rect::{RoundedRect, RoundedRectPathIter};
pub use crate::rounded_rect_radii::RoundedRectRadii;
pub use crate::shape::Shape;
pub use crate::size::Size;
pub use crate::stroke::{
Cap, Dashes, Join, Stroke, StrokeCtx, StrokeOptLevel, StrokeOpts, dash, stroke, stroke_with,
};
pub use crate::svg::{SvgArc, SvgParseError};
pub use crate::translate_scale::TranslateScale;
pub use crate::triangle::{Triangle, TrianglePathIter};
pub use crate::vec2::Vec2;
+448
View File
@@ -0,0 +1,448 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Lines.
use core::ops::{Add, Mul, Range, Sub};
use arrayvec::ArrayVec;
use crate::{
Affine, DEFAULT_ACCURACY, MAX_EXTREMA, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea,
ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point,
Rect, Shape, Vec2,
};
/// A single line.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Line {
/// The line's start point.
pub p0: Point,
/// The line's end point.
pub p1: Point,
}
impl Line {
/// Create a new line.
#[inline(always)]
pub fn new(p0: impl Into<Point>, p1: impl Into<Point>) -> Line {
Line {
p0: p0.into(),
p1: p1.into(),
}
}
/// Returns a copy of this `Line` with the end points swapped so that it
/// points in the opposite direction.
#[must_use]
#[inline(always)]
pub const fn reversed(&self) -> Line {
Self {
p0: self.p1,
p1: self.p0,
}
}
/// The length of the line.
#[inline]
pub fn length(self) -> f64 {
self.arclen(DEFAULT_ACCURACY)
}
/// The midpoint of the line.
///
/// This is the same as calling [`Point::midpoint`] with
/// the endpoints of this line.
#[must_use]
#[inline]
pub fn midpoint(&self) -> Point {
self.p0.midpoint(self.p1)
}
/// Computes the point where two lines, if extended to infinity, would cross.
pub fn crossing_point(self, other: Line) -> Option<Point> {
let ab = self.p1 - self.p0;
let cd = other.p1 - other.p0;
let pcd = ab.cross(cd);
if pcd == 0.0 {
return None;
}
let h = ab.cross(self.p0 - other.p0) / pcd;
Some(other.p0 + cd * h)
}
/// Is this line `finite`?
///
/// [finite]: f64::is_finite
#[inline]
pub const fn is_finite(self) -> bool {
self.p0.is_finite() && self.p1.is_finite()
}
/// Is this line `NaN`?
///
/// [NaN]: f64::is_nan
#[inline]
pub const fn is_nan(self) -> bool {
self.p0.is_nan() || self.p1.is_nan()
}
}
impl From<(Point, Point)> for Line {
#[inline(always)]
fn from((from, to): (Point, Point)) -> Self {
Line::new(from, to)
}
}
impl From<(Point, Vec2)> for Line {
#[inline(always)]
fn from((origin, displacement): (Point, Vec2)) -> Self {
Line::new(origin, origin + displacement)
}
}
impl ParamCurve for Line {
#[inline]
fn eval(&self, t: f64) -> Point {
self.p0.lerp(self.p1, t)
}
#[inline]
fn subsegment(&self, range: Range<f64>) -> Line {
Line {
p0: self.eval(range.start),
p1: self.eval(range.end),
}
}
#[inline(always)]
fn start(&self) -> Point {
self.p0
}
#[inline(always)]
fn end(&self) -> Point {
self.p1
}
}
impl ParamCurveDeriv for Line {
type DerivResult = ConstPoint;
#[inline]
fn deriv(&self) -> ConstPoint {
ConstPoint((self.p1 - self.p0).to_point())
}
}
impl ParamCurveArclen for Line {
#[inline]
fn arclen(&self, _accuracy: f64) -> f64 {
(self.p1 - self.p0).hypot()
}
#[inline]
fn inv_arclen(&self, arclen: f64, _accuracy: f64) -> f64 {
arclen / (self.p1 - self.p0).hypot()
}
}
impl ParamCurveArea for Line {
#[inline]
fn signed_area(&self) -> f64 {
self.p0.to_vec2().cross(self.p1.to_vec2()) * 0.5
}
}
impl ParamCurveNearest for Line {
#[inline]
fn nearest(&self, p: Point, _accuracy: f64) -> Nearest {
let d = self.p1 - self.p0;
let v = p - self.p0;
// Calculate projection parameter `t` of the point onto the line segment s(t), with
// s(t) = (1-t) * p0 + t * p1.
//
// Note when the segment has 0 length, this will be positive or negative infinity or NaN;
// see the clamping below.
let t = d.dot(v) / d.hypot2();
// Clamp the parameter to be on the line segment. This clamps negative infinity and NaN to
// `0.`, and positive infinity to `1.`.
#[expect(
clippy::manual_clamp,
reason = "`clamp` uses slightly more instructions than chained `max` and `min` on x86 and aarch64"
)]
let t = { t.max(0.).min(1.) };
// Calculate ||p - s(t)||^2.
let distance_sq = (v - t * d).hypot2();
Nearest { distance_sq, t }
}
}
impl ParamCurveCurvature for Line {
#[inline(always)]
fn curvature(&self, _t: f64) -> f64 {
0.0
}
}
impl ParamCurveExtrema for Line {
#[inline]
fn extrema(&self) -> ArrayVec<f64, MAX_EXTREMA> {
ArrayVec::new()
}
}
/// A trivial "curve" that is just a constant.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ConstPoint(Point);
impl ConstPoint {
/// Is this point [finite]?
///
/// [finite]: f64::is_finite
#[inline]
pub const fn is_finite(self) -> bool {
self.0.is_finite()
}
/// Is this point [NaN]?
///
/// [NaN]: f64::is_nan
#[inline]
pub const fn is_nan(self) -> bool {
self.0.is_nan()
}
}
impl ParamCurve for ConstPoint {
#[inline(always)]
fn eval(&self, _t: f64) -> Point {
self.0
}
#[inline(always)]
fn subsegment(&self, _range: Range<f64>) -> ConstPoint {
*self
}
}
impl ParamCurveDeriv for ConstPoint {
type DerivResult = ConstPoint;
#[inline(always)]
fn deriv(&self) -> ConstPoint {
ConstPoint(Point::new(0.0, 0.0))
}
}
impl ParamCurveArclen for ConstPoint {
#[inline(always)]
fn arclen(&self, _accuracy: f64) -> f64 {
0.0
}
#[inline(always)]
fn inv_arclen(&self, _arclen: f64, _accuracy: f64) -> f64 {
0.0
}
}
impl Mul<Line> for Affine {
type Output = Line;
#[inline]
fn mul(self, other: Line) -> Line {
Line {
p0: self * other.p0,
p1: self * other.p1,
}
}
}
impl Add<Vec2> for Line {
type Output = Line;
#[inline]
fn add(self, v: Vec2) -> Line {
Line::new(self.p0 + v, self.p1 + v)
}
}
impl Sub<Vec2> for Line {
type Output = Line;
#[inline]
fn sub(self, v: Vec2) -> Line {
Line::new(self.p0 - v, self.p1 - v)
}
}
/// An iterator yielding the path for a single line.
#[doc(hidden)]
pub struct LinePathIter {
line: Line,
ix: usize,
}
impl Shape for Line {
type PathElementsIter<'iter> = LinePathIter;
#[inline]
fn path_elements(&self, _tolerance: f64) -> LinePathIter {
LinePathIter { line: *self, ix: 0 }
}
/// Returning zero here is consistent with the contract (area is
/// only meaningful for closed shapes), but an argument can be made
/// that the contract should be tightened to include the Green's
/// theorem contribution.
#[inline(always)]
fn area(&self) -> f64 {
0.0
}
#[inline]
fn perimeter(&self, _accuracy: f64) -> f64 {
(self.p1 - self.p0).hypot()
}
/// Same consideration as `area`.
#[inline(always)]
fn winding(&self, _pt: Point) -> i32 {
0
}
#[inline(always)]
fn bounding_box(&self) -> Rect {
Rect::from_points(self.p0, self.p1)
}
#[inline(always)]
fn as_line(&self) -> Option<Line> {
Some(*self)
}
}
impl Iterator for LinePathIter {
type Item = PathEl;
fn next(&mut self) -> Option<PathEl> {
self.ix += 1;
match self.ix {
1 => Some(PathEl::MoveTo(self.line.p0)),
2 => Some(PathEl::LineTo(self.line.p1)),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use crate::{Line, ParamCurveArclen, Point};
#[test]
fn line_reversed() {
let l = Line::new((0.0, 0.0), (1.0, 1.0));
let f = l.reversed();
assert_eq!(l.p0, f.p1);
assert_eq!(l.p1, f.p0);
// Reversing it again should result in the original line
assert_eq!(l, f.reversed());
}
#[test]
fn line_arclen() {
let l = Line::new((0.0, 0.0), (1.0, 1.0));
let true_len = 2.0f64.sqrt();
let epsilon = 1e-9;
assert!(l.arclen(epsilon) - true_len < epsilon);
let t = l.inv_arclen(true_len / 3.0, epsilon);
assert!((t - 1.0 / 3.0).abs() < epsilon);
}
#[test]
fn line_midpoint() {
let l = Line::new((0.0, 0.0), (2.0, 4.0));
assert_eq!(l.midpoint(), Point::new(1.0, 2.0));
}
#[test]
fn line_is_finite() {
assert!(
(Line {
p0: Point { x: 0., y: 0. },
p1: Point { x: 1., y: 1. }
})
.is_finite()
);
assert!(
!(Line {
p0: Point { x: 0., y: 0. },
p1: Point {
x: f64::INFINITY,
y: 1.
}
})
.is_finite()
);
assert!(
!(Line {
p0: Point { x: 0., y: 0. },
p1: Point {
x: 0.,
y: f64::INFINITY
}
})
.is_finite()
);
}
#[test]
fn line_nearest() {
use crate::{ParamCurve, ParamCurveNearest};
const EPSILON: f64 = 1e-9;
let line = Line::new((-4., 0.), (2., 1.));
// Projects onto the line segment end point.
let point = Point::new(4., 0.);
let nearest = line.nearest(point, 0.);
assert_eq!(nearest.t, 1.);
assert!((nearest.distance_sq - line.p1.distance_squared(point)).abs() < EPSILON);
// Projects onto the line segment start point.
let point = Point::new(0., -50.);
let nearest = line.nearest(point, 0.);
assert_eq!(nearest.t, 0.);
assert!((nearest.distance_sq - line.p0.distance_squared(point)).abs() < EPSILON);
// Projects onto the line segment proper (not just onto one of its extrema).
let point = Point::new(-1., 0.5);
let nearest = line.nearest(point, 0.);
assert!(nearest.t > 0. && nearest.t < 1.);
// Ensure evaluating and calculating distance manually has the same result.
assert!(
(line.eval(nearest.t).distance_squared(point) - nearest.distance_sq).abs() < EPSILON
);
// Test minimality while avoiding reimplementing projection in this test by checking that
// moving to a slightly different point on the segment increases the distance.
assert!(line.eval(nearest.t * 0.95).distance_squared(point) > nearest.distance_sq);
assert!(line.eval(nearest.t * 1.05).distance_squared(point) > nearest.distance_sq);
}
}
+359
View File
@@ -0,0 +1,359 @@
// Copyright 2021 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Minimum distance between two Bézier curves
//!
//! This implements the algorithm in "Computing the minimum distance between
//! two Bézier curves", Chen et al., *Journal of Computational and Applied
//! Mathematics* 229(2009), 294-301
use crate::Vec2;
use core::cmp::Ordering;
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// Given the control points of n- and m-dimensional Bézier curves in `bez1` and `bez2`
/// respectively, calculate the minimum distance between the two curves.
///
/// This should work for arbitrary Bézier curves up to and including degree 255, but only lines,
/// quadratics and cubics are tested.
///
/// Returns a tuple of the distance, the path time `t1` of the closest point on the first Bézier,
/// and the path time `t2` of the closest point on the second Bézier.
///
/// # Panics
///
/// This panics if more than 256 control points are given in `bez1` or `bez2`, i.e., if either
/// Bézier is of degree greater than 255.
pub(crate) fn min_dist_param(
bez1: &[Vec2],
bez2: &[Vec2],
u: (f64, f64),
v: (f64, f64),
epsilon: f64,
best_alpha: Option<f64>,
) -> (f64, f64, f64) {
assert!(!bez1.is_empty() && !bez2.is_empty());
let n = u8::try_from(bez1.len() - 1).expect("At most 256 control points");
let m = u8::try_from(bez2.len() - 1).expect("At most 256 control points");
let (umin, umax) = u;
let (vmin, vmax) = v;
let umid = (umin + umax) / 2.0;
let vmid = (vmin + vmax) / 2.0;
let svalues: [(f64, f64, f64); 4] = [
(S(umin, vmin, bez1, bez2), umin, vmin),
(S(umin, vmax, bez1, bez2), umin, vmax),
(S(umax, vmin, bez1, bez2), umax, vmin),
(S(umax, vmax, bez1, bez2), umax, vmax),
];
let alpha: f64 = svalues.iter().map(|(a, _, _)| *a).reduce(f64::min).unwrap();
if let Some(best) = best_alpha {
if alpha > best {
return (alpha, umid, vmid);
}
}
if (umax - umin).abs() < epsilon || (vmax - vmin).abs() < epsilon {
return (alpha, umid, vmid);
}
// Property one: D(r>k) > alpha
let mut is_outside = true;
let mut min_drk = None;
let mut min_ij = None;
for r in 0..(2 * n) {
for k in 0..(2 * m) {
let d_rk = D_rk(r, k, bez1, bez2);
if d_rk < alpha {
is_outside = false;
}
if min_drk.is_none() || Some(d_rk) < min_drk {
min_drk = Some(d_rk);
min_ij = Some((r, k));
}
}
}
if is_outside {
return (alpha, umid, vmid);
}
// Property two: boundary check
let mut at_boundary0on_bez1 = true;
let mut at_boundary1on_bez1 = true;
let mut at_boundary0on_bez2 = true;
let mut at_boundary1on_bez2 = true;
for i in 0..2 * n {
for j in 0..2 * m {
let dij = D_rk(i, j, bez1, bez2);
let dkj = D_rk(0, j, bez1, bez2);
if dij < dkj {
at_boundary0on_bez1 = false;
}
let dkj = D_rk(2 * n, j, bez1, bez2);
if dij < dkj {
at_boundary1on_bez1 = false;
}
let dkj = D_rk(i, 0, bez1, bez2);
if dij < dkj {
at_boundary0on_bez2 = false;
}
let dkj = D_rk(i, 2 * m, bez1, bez2);
if dij < dkj {
at_boundary1on_bez2 = false;
}
}
}
if at_boundary0on_bez1 && at_boundary0on_bez2 {
return svalues[0];
}
if at_boundary0on_bez1 && at_boundary1on_bez2 {
return svalues[1];
}
if at_boundary1on_bez1 && at_boundary0on_bez2 {
return svalues[2];
}
if at_boundary1on_bez1 && at_boundary1on_bez2 {
return svalues[3];
}
let (min_i, min_j) = min_ij.unwrap();
let new_umid = umin + (umax - umin) * (min_i as f64 / (2 * n) as f64);
let new_vmid = vmin + (vmax - vmin) * (min_j as f64 / (2 * m) as f64);
// Subdivide
let results = [
min_dist_param(
bez1,
bez2,
(umin, new_umid),
(vmin, new_vmid),
epsilon,
Some(alpha),
),
min_dist_param(
bez1,
bez2,
(umin, new_umid),
(new_vmid, vmax),
epsilon,
Some(alpha),
),
min_dist_param(
bez1,
bez2,
(new_umid, umax),
(vmin, new_vmid),
epsilon,
Some(alpha),
),
min_dist_param(
bez1,
bez2,
(new_umid, umax),
(new_vmid, vmax),
epsilon,
Some(alpha),
),
];
*results
.iter()
.min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Less))
.unwrap()
}
// $ S(u,v)=\sum_{r=0}^{2n} \sum _{k=0}^{2m} D_{r,k} B_{2n}^r(u) B_{2m}^k(v) $
#[allow(non_snake_case)]
fn S(u: f64, v: f64, bez1: &[Vec2], bez2: &[Vec2]) -> f64 {
#[expect(
clippy::cast_possible_truncation,
reason = "By the checks in `min_dist_param` we know `bez1.len()` and `bez2.len()` are less than or equal to 256"
)]
let (n, m) = { ((bez1.len() - 1) as u8, (bez2.len() - 1) as u8) };
let mut summand = 0.0;
for r in 0..=2 * n {
for k in 0..=2 * m {
summand +=
D_rk(r, k, bez1, bez2) * basis_function(2 * n, r, u) * basis_function(2 * m, k, v);
}
}
summand
}
// $ C_{r,k} = ( \sum_{i=\theta}^\upsilon P_i C_n^i C_n^{r-i} / C_{2n}^r ) \cdot (\sum_{j=\sigma}^\varsigma Q_j C_m^j C_m^{k-j} / C_{2m}^k ) $
#[allow(non_snake_case)]
fn C_rk(r: u8, k: u8, bez1: &[Vec2], bez2: &[Vec2]) -> f64 {
#[expect(
clippy::cast_possible_truncation,
reason = "By the checks in `min_dist_param` we know `bez1.len()` and `bez2.len()` are less than or equal to 256"
)]
let (n, m) = { ((bez1.len() - 1) as u8, (bez2.len() - 1) as u8) };
let upsilon = r.min(n);
let theta = r - n.min(r);
let mut left: Vec2 = Vec2::ZERO;
for i in theta..upsilon + 1 {
let item = bez1[usize::from(i)];
left += item * (choose(n, i) * choose(n, r - i)) as f64 / (choose(2 * n, r) as f64);
}
let varsigma = k.min(m);
let sigma = k - m.min(k);
let mut right: Vec2 = Vec2::ZERO;
for j in sigma..varsigma + 1 {
let item = bez2[usize::from(j)];
right += item * (choose(m, j) * choose(m, k - j)) as f64 / (choose(2 * m, k) as f64);
}
left.dot(right)
}
// $ A_r=\sum _{i=\theta} ^\upsilon (P_i \cdot P_{r-i}) C_n^i C_n^{r-i} / C_{2n}^r $
// ($ B_k $ is just the same as $ A_r $ but for the other curve.)
#[allow(non_snake_case)]
fn A_r(r: u8, p: &[Vec2]) -> f64 {
#[expect(
clippy::cast_possible_truncation,
reason = "By the checks in `min_dist_param` we know `p.len()` is less than or equal to 256"
)]
let n = (p.len() - 1) as u8;
let upsilon = r.min(n);
let theta = r - n.min(r);
(theta..=upsilon)
.map(|i| {
let dot = p[usize::from(i)].dot(p[usize::from(r - i)]); // These are bounds checked by the sum limits
let factor = (choose(n, i) * choose(n, r - i)) as f64 / (choose(2 * n, r) as f64);
dot * factor
})
.sum()
}
#[allow(non_snake_case)]
fn D_rk(r: u8, k: u8, bez1: &[Vec2], bez2: &[Vec2]) -> f64 {
// In the paper, B_k is used for the second factor, but it's the same thing
A_r(r, bez1) + A_r(k, bez2) - 2.0 * C_rk(r, k, bez1, bez2)
}
// Bézier basis function
fn basis_function(n: u8, i: u8, u: f64) -> f64 {
choose(n, i) as f64 * (1.0 - u).powi((n - i) as i32) * u.powi(i as i32)
}
// Binomial co-efficient, but returning zeros for values outside of domain
fn choose(n: u8, k: u8) -> u32 {
let mut n = n as u32;
let k = k as u32;
if k > n {
return 0;
}
let mut p = 1;
for i in 1..=(n - k) {
p *= n;
p /= i;
n -= 1;
}
p
}
#[cfg(test)]
mod tests {
use crate::mindist::A_r;
use crate::mindist::{D_rk, choose};
use crate::param_curve::ParamCurve;
use crate::{CubicBez, Line, PathSeg, Vec2};
#[test]
fn test_choose() {
assert_eq!(choose(6, 0), 1);
assert_eq!(choose(6, 1), 6);
assert_eq!(choose(6, 2), 15);
}
#[test]
fn test_d_rk() {
let bez1 = vec![
Vec2::new(129.0, 139.0),
Vec2::new(190.0, 139.0),
Vec2::new(201.0, 364.0),
Vec2::new(90.0, 364.0),
];
let bez2 = vec![
Vec2::new(309.0, 159.0),
Vec2::new(178.0, 159.0),
Vec2::new(215.0, 408.0),
Vec2::new(309.0, 408.0),
];
let b = A_r(1, &bez2);
assert!((b - 80283.0).abs() < 0.005, "B_1(Q)={b:?}");
let d = D_rk(0, 1, &bez1, &bez2);
assert!((d - 9220.0).abs() < 0.005, "D={d:?}");
}
#[test]
fn test_mindist() {
let bez1 = PathSeg::Cubic(CubicBez::new(
(129.0, 139.0),
(190.0, 139.0),
(201.0, 364.0),
(90.0, 364.0),
));
let bez2 = PathSeg::Cubic(CubicBez::new(
(309.0, 159.0),
(178.0, 159.0),
(215.0, 408.0),
(309.0, 408.0),
));
let mindist = bez1.min_dist(bez2, 0.001);
assert!((mindist.distance - 50.9966).abs() < 0.5);
}
#[test]
fn test_overflow() {
let bez1 = PathSeg::Cubic(CubicBez::new(
(232.0, 126.0),
(134.0, 126.0),
(139.0, 232.0),
(141.0, 301.0),
));
let bez2 = PathSeg::Line(Line::new((359.0, 416.0), (367.0, 755.0)));
let mindist = bez1.min_dist(bez2, 0.001);
assert!((mindist.distance - 246.4731222669117).abs() < 0.5);
}
#[test]
fn test_out_of_order() {
let bez1 = PathSeg::Cubic(CubicBez::new(
(287.0, 182.0),
(346.0, 277.0),
(356.0, 299.0),
(359.0, 416.0),
));
let bez2 = PathSeg::Line(Line::new((141.0, 301.0), (152.0, 709.0)));
let mindist1 = bez1.min_dist(bez2, 0.5);
let mindist2 = bez2.min_dist(bez1, 0.5);
assert!((mindist1.distance - mindist2.distance).abs() < 0.5);
}
#[test]
fn test_line_curve() {
let line = PathSeg::Line(Line::new((929.0, 335.0), (911.0, 340.0)));
let line_as_bez = PathSeg::Cubic(CubicBez::new(
line.eval(0.0),
line.eval(1.0 / 3.0),
line.eval(2.0 / 3.0),
line.eval(1.0),
));
let bez2 = PathSeg::Cubic(CubicBez::new(
(1052.0, 401.0),
(1048.0, 305.0),
(1046.0, 216.0),
(1054.0, 146.0),
));
let mindist_as_bez = line_as_bez.min_dist(bez2, 0.5);
let mindist_as_line = line.min_dist(bez2, 0.5);
assert!((mindist_as_line.distance - mindist_as_bez.distance).abs() < 0.5);
}
}
+594
View File
@@ -0,0 +1,594 @@
// Copyright 2025 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
use crate::{PathEl, Point};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A collect of moment integrals for a path, used for computing
/// shape properties like area, centroid, and inertia.
///
/// The moments are computed using Green's theorem, which relates the
/// integrals of a function over a closed curve to the integrals of its
/// partial derivatives over the region enclosed by the curve.
#[derive(Debug, Default, Copy, Clone)]
pub struct Moments {
/// The first moment of area about the x-axis.
pub moment_x: f64,
/// The first moment of area about the y-axis.
pub moment_y: f64,
/// The second moment of area about the x-axis (also known as the
/// area moment of inertia about the x-axis).
pub moment_xx: f64,
/// The second moment of area about the xy-axis (also known as the
/// product of inertia).
pub moment_xy: f64,
/// The second moment of area about the y-axis (also known as the
/// area moment of inertia about the y-axis).
pub moment_yy: f64,
}
impl core::ops::Add<Self> for Moments {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self {
moment_x: self.moment_x + rhs.moment_x,
moment_y: self.moment_y + rhs.moment_y,
moment_xx: self.moment_xx + rhs.moment_xx,
moment_xy: self.moment_xy + rhs.moment_xy,
moment_yy: self.moment_yy + rhs.moment_yy,
}
}
}
impl Moments {
// The code below is derived from fontTools's fontTools.pens.momentsPen, which is in turn generated
// by running sympy on the Green's theorem integral expressions.
fn handle_line(&mut self, p0: Point, p1: Point) {
let (x0, y0) = (p0.x, p0.y);
let (x1, y1) = (p1.x, p1.y);
let r0 = x1 * y0;
let r1 = x1 * y1;
let r2 = x1.powi(2);
let r3 = r2 * y1;
let r4 = y0 - y1;
let r5 = r4 * x0;
let r6 = x0.powi(2);
let r7 = 2.0 * y0;
let r8 = y0.powi(2);
let r9 = y1.powi(2);
let r10 = x1.powi(3);
let r11 = y0.powi(3);
let r12 = y1.powi(3);
self.moment_x += -r2 * y0 / 6.0 - r3 / 3.0 - r5 * x1 / 6.0 + r6 * (r7 + y1) / 6.0;
self.moment_y +=
-r0 * y1 / 6.0 - r8 * x1 / 6.0 - r9 * x1 / 6.0 + x0 * (r8 + r9 + y0 * y1) / 6.0;
self.moment_xx += -r10 * y0 / 12.0 - r10 * y1 / 4.0 - r2 * r5 / 12.0 - r4 * r6 * x1 / 12.0
+ x0.powi(3) * (3.0 * y0 + y1) / 12.0;
self.moment_xy += -r2 * r8 / 24.0 - r2 * r9 / 8.0 - r3 * r7 / 24.0
+ r6 * (r7 * y1 + 3.0 * r8 + r9) / 24.0
- x0 * x1 * (r8 - r9) / 12.0;
self.moment_yy += -r0 * r9 / 12.0 - r1 * r8 / 12.0 - r11 * x1 / 12.0 - r12 * x1 / 12.0
+ x0 * (r11 + r12 + r8 * y1 + r9 * y0) / 12.0;
}
fn handle_quad(&mut self, p0: Point, p1: Point, p2: Point) {
let (x0, y0) = (p0.x, p0.y);
let x1 = p1.x;
let y1 = p1.y;
let x2 = p2.x;
let y2 = p2.y;
let r0 = 2.0 * y1;
let r1 = r0 * x2;
let r2 = x2 * y2;
let r3 = 3.0 * r2;
let r4 = 2.0 * x1;
let r5 = 3.0 * y0;
let r6 = x1.powi(2);
let r7 = x2.powi(2);
let r8 = 4.0 * y1;
let r9 = 10.0 * y2;
let r10 = 2.0 * y2;
let r11 = r4 * x2;
let r12 = x0.powi(2);
let r13 = 10.0 * y0;
let r14 = r4 * y2;
let r15 = x2 * y0;
let r16 = 4.0 * x1;
let r17 = r0 * x1 + r2;
let r18 = r2 * r8;
let r19 = y1.powi(2);
let r20 = 2.0 * r19;
let r21 = y2.powi(2);
let r22 = r21 * x2;
let r23 = 5.0 * r22;
let r24 = y0.powi(2);
let r25 = y0 * y2;
let r26 = 5.0 * r24;
let r27 = x1.powi(3);
let r28 = x2.powi(3);
let r29 = 30.0 * y1;
let r30 = 6.0 * y1;
let r31 = 10.0 * r7 * x1;
let r32 = 5.0 * y2;
let r33 = 12.0 * r6;
let r34 = 30.0 * x1;
let r35 = x1 * y1;
let r36 = r3 + 20.0 * r35;
let r37 = 12.0 * x1;
let r38 = 20.0 * r6;
let r39 = 8.0 * r6 * y1;
let r40 = r32 * r7;
let r41 = 60.0 * y1;
let r42 = 20.0 * r19;
let r43 = 4.0 * r19;
let r44 = 15.0 * r21;
let r45 = 12.0 * x2;
let r46 = 12.0 * y2;
let r47 = 6.0 * x1;
let r48 = 8.0 * r19 * x1 + r23;
let r49 = 8.0 * y1.powi(3);
let r50 = y2.powi(3);
let r51 = y0.powi(3);
let r52 = 10.0 * y1;
let r53 = 12.0 * y1;
self.moment_x += -r11 * (-r10 + y1) / 30.0 + r12 * (r13 + r8 + y2) / 30.0 + r6 * y2 / 15.0
- r7 * r8 / 30.0
- r7 * r9 / 30.0
+ x0 * (r14 - r15 - r16 * y0 + r17) / 30.0
- y0 * (r11 + 2.0 * r6 + r7) / 30.0;
self.moment_y += -r18 / 30.0 - r20 * x2 / 30.0 - r23 / 30.0 - r24 * (r16 + x2) / 30.0
+ x0 * (r0 * y2 + r20 + r21 + r25 + r26 + r8 * y0) / 30.0
+ x1 * y2 * (r10 + y1) / 15.0
- y0 * (r1 + r17) / 30.0;
self.moment_xx += r12 * (r1 - 5.0 * r15 - r34 * y0 + r36 + r9 * x1) / 420.0
+ 2.0 * r27 * y2 / 105.0
- r28 * r29 / 420.0
- r28 * y2 / 4.0
- r31 * (r0 - 3.0 * y2) / 420.0
- r6 * x2 * (r0 - r32) / 105.0
+ x0.powi(3) * (r30 + 21.0 * y0 + y2) / 84.0
- x0 * (r0 * r7 + r15 * r37 - r2 * r37 - r33 * y2 + r38 * y0 - r39 - r40 + r5 * r7)
/ 420.0
- y0 * (8.0 * r27 + 5.0 * r28 + r31 + r33 * x2) / 420.0;
self.moment_xy += r12 * (r13 * y2 + 3.0 * r21 + 105.0 * r24 + r41 * y0 + r42 + r46 * y1)
/ 840.0
- r16 * x2 * (r43 - r44) / 840.0
- r21 * r7 / 8.0
- r24 * (r38 + r45 * x1 + 3.0 * r7) / 840.0
- r41 * r7 * y2 / 840.0
- r42 * r7 / 840.0
+ r6 * y2 * (r32 + r8) / 210.0
+ x0 * (-r15 * r8 + r16 * r25 + r18 + r21 * r47 - r24 * r34 - r26 * x2
+ r35 * r46
+ r48)
/ 420.0
- y0 * (r16 * r2 + r30 * r7 + r35 * r45 + r39 + r40) / 420.0;
self.moment_yy += -r2 * r42 / 420.0
- r22 * r29 / 420.0
- r24 * (r14 + r36 + r52 * x2) / 420.0
- r49 * x2 / 420.0
- r50 * x2 / 12.0
- r51 * (r47 + x2) / 84.0
+ x0 * (r19 * r46
+ r21 * r5
+ r21 * r52
+ r24 * r29
+ r25 * r53
+ r26 * y2
+ r42 * y0
+ r49
+ 5.0 * r50
+ 35.0 * r51)
/ 420.0
+ x1 * y2 * (r43 + r44 + r9 * y1) / 210.0
- y0 * (r19 * r45 + r2 * r53 - r21 * r4 + r48) / 420.0;
}
fn handle_cubic(&mut self, p0: Point, p1: Point, p2: Point, p3: Point) {
let x0 = p0.x;
let y0 = p0.y;
let x1 = p1.x;
let y1 = p1.y;
let x2 = p2.x;
let y2 = p2.y;
let x3 = p3.x;
let y3 = p3.y;
let r0 = 6.0 * y2;
let r1 = r0 * x3;
let r2 = 10.0 * y3;
let r3 = r2 * x3;
let r4 = 3.0 * y1;
let r5 = 6.0 * x1;
let r6 = 3.0 * x2;
let r7 = 6.0 * y1;
let r8 = 3.0 * y2;
let r9 = x2.powi(2);
let r10 = 45.0 * r9;
let r11 = r10 * y3;
let r12 = x3.powi(2);
let r13 = r12 * y2;
let r14 = r12 * y3;
let r15 = 7.0 * y3;
let r16 = 15.0 * x3;
let r17 = r16 * x2;
let r18 = x1.powi(2);
let r19 = 9.0 * r18;
let r20 = x0.powi(2);
let r21 = 21.0 * y1;
let r22 = 9.0 * r9;
let r23 = r7 * x3;
let r24 = 9.0 * y2;
let r25 = r24 * x2 + r3;
let r26 = 9.0 * x2;
let r27 = x2 * y3;
let r28 = -r26 * y1 + 15.0 * r27;
let r29 = 3.0 * x1;
let r30 = 45.0 * x1;
let r31 = 12.0 * x3;
let r32 = 45.0 * r18;
let r33 = 5.0 * r12;
let r34 = r8 * x3;
let r35 = 105.0 * y0;
let r36 = 30.0 * y0;
let r37 = r36 * x2;
let r38 = 5.0 * x3;
let r39 = 15.0 * y3;
let r40 = 5.0 * y3;
let r41 = r40 * x3;
let r42 = x2 * y2;
let r43 = 18.0 * r42;
let r44 = 45.0 * y1;
let r45 = r41 + r43 + r44 * x1;
let r46 = y2 * y3;
let r47 = r46 * x3;
let r48 = y2.powi(2);
let r49 = 45.0 * r48;
let r50 = r49 * x3;
let r51 = y3.powi(2);
let r52 = r51 * x3;
let r53 = y1.powi(2);
let r54 = 9.0 * r53;
let r55 = y0.powi(2);
let r56 = 21.0 * x1;
let r57 = 6.0 * x2;
let r58 = r16 * y2;
let r59 = r39 * y2;
let r60 = 9.0 * r48;
let r61 = r6 * y3;
let r62 = 3.0 * y3;
let r63 = r36 * y2;
let r64 = y1 * y3;
let r65 = 45.0 * r53;
let r66 = 5.0 * r51;
let r67 = x2.powi(3);
let r68 = x3.powi(3);
let r69 = 630.0 * y2;
let r70 = 126.0 * x3;
let r71 = x1.powi(3);
let r72 = 126.0 * x2;
let r73 = 63.0 * r9;
let r74 = r73 * x3;
let r75 = r15 * x3 + 15.0 * r42;
let r76 = 630.0 * x1;
let r77 = 14.0 * x3;
let r78 = 21.0 * r27;
let r79 = 42.0 * x1;
let r80 = 42.0 * x2;
let r81 = x1 * y2;
let r82 = 63.0 * r42;
let r83 = x1 * y1;
let r84 = r41 + r82 + 378.0 * r83;
let r85 = x2 * x3;
let r86 = r85 * y1;
let r87 = r27 * x3;
let r88 = 27.0 * r9;
let r89 = r88 * y2;
let r90 = 42.0 * r14;
let r91 = 90.0 * x1;
let r92 = 189.0 * r18;
let r93 = 378.0 * r18;
let r94 = r12 * y1;
let r95 = 252.0 * x1 * x2;
let r96 = r79 * x3;
let r97 = 30.0 * r85;
let r98 = r83 * x3;
let r99 = 30.0 * x3;
let r100 = 42.0 * x3;
let r101 = r42 * x1;
let r102 = r10 * y2 + 14.0 * r14 + 126.0 * r18 * y1 + r81 * r99;
let r103 = 378.0 * r48;
let r104 = 18.0 * y1;
let r105 = r104 * y2;
let r106 = y0 * y1;
let r107 = 252.0 * y2;
let r108 = r107 * y0;
let r109 = y0 * y3;
let r110 = 42.0 * r64;
let r111 = 378.0 * r53;
let r112 = 63.0 * r48;
let r113 = 27.0 * x2;
let r114 = r27 * y2;
let r115 = r113 * r48 + 42.0 * r52;
let r116 = x3 * y3;
let r117 = 54.0 * r42;
let r118 = r51 * x1;
let r119 = r51 * x2;
let r120 = r48 * x1;
let r121 = 21.0 * x3;
let r122 = r64 * x1;
let r123 = r81 * y3;
let r124 = 30.0 * r27 * y1 + r49 * x2 + 14.0 * r52 + 126.0 * r53 * x1;
let r125 = y2.powi(3);
let r126 = y3.powi(3);
let r127 = y1.powi(3);
let r128 = y0.powi(3);
let r129 = r51 * y2;
let r130 = r112 * y3 + r21 * r51;
let r131 = 189.0 * r53;
let r132 = 90.0 * y2;
self.moment_x += r11 / 840.0 - r13 / 8.0 - r14 / 3.0 - r17 * (-r15 + r8) / 840.0
+ r19 * (r8 + 2.0 * y3) / 840.0
+ r20 * (r0 + r21 + 56.0 * y0 + y3) / 168.0
+ r29 * (-r23 + r25 + r28) / 840.0
- r4 * (10.0 * r12 + r17 + r22) / 840.0
+ x0 * (12.0 * r27 + r30 * y2 + r34 - r35 * x1 - r37 - r38 * y0 + r39 * x1 - r4 * x3
+ r45)
/ 840.0
- y0 * (r17 + r30 * x2 + r31 * x1 + r32 + r33 + 18.0 * r9) / 840.0;
self.moment_y += -r4 * (r25 + r58) / 840.0
- r47 / 8.0
- r50 / 840.0
- r52 / 6.0
- r54 * (r6 + 2.0 * x3) / 840.0
- r55 * (r56 + r57 + x3) / 168.0
+ x0 * (r35 * y1
+ r40 * y0
+ r44 * y2
+ 18.0 * r48
+ 140.0 * r55
+ r59
+ r63
+ 12.0 * r64
+ r65
+ r66)
/ 840.0
+ x1 * (r24 * y1 + 10.0 * r51 + r59 + r60 + r7 * y3) / 280.0
+ x2 * y3 * (r15 + r8) / 56.0
- y0 * (r16 * y1 + r31 * y2 + r44 * x2 + r45 + r61 - r62 * x1) / 840.0;
self.moment_xx += -r12 * r72 * (-r40 + r8) / 9240.0
+ 3.0 * r18 * (r28 + r34 - r38 * y1 + r75) / 3080.0
+ r20
* (r24 * x3 - r72 * y0 - r76 * y0 - r77 * y0
+ r78
+ r79 * y3
+ r80 * y1
+ 210.0 * r81
+ r84)
/ 9240.0
- r29
* (r12 * r21 + 14.0 * r13 + r44 * r9 - r73 * y3 + 54.0 * r86
- 84.0 * r87
- r89
- r90)
/ 9240.0
- r4 * (70.0 * r12 * x2 + 27.0 * r67 + 42.0 * r68 + r74) / 9240.0
+ 3.0 * r67 * y3 / 220.0
- r68 * r69 / 9240.0
- r68 * y3 / 4.0
- r70 * r9 * (-r62 + y2) / 9240.0
+ 3.0 * r71 * (r24 + r40) / 3080.0
+ x0.powi(3) * (r24 + r44 + 165.0 * y0 + y3) / 660.0
+ x0 * (r100 * r27 + 162.0 * r101 + r102 + r11 + 63.0 * r18 * y3 + r27 * r91
- r33 * y0
- r37 * x3
+ r43 * x3
- r73 * y0
- r88 * y1
+ r92 * y2
- r93 * y0
- 9.0 * r94
- r95 * y0
- r96 * y0
- r97 * y1
- 18.0 * r98
+ r99 * x1 * y3)
/ 9240.0
- y0 * (r12 * r56
+ r12 * r80
+ r32 * x3
+ 45.0 * r67
+ 14.0 * r68
+ 126.0 * r71
+ r74
+ r85 * r91
+ 135.0 * r9 * x1
+ r92 * x2)
/ 9240.0;
self.moment_xy += -r103 * r12 / 18480.0 - r12 * r51 / 8.0 - 3.0 * r14 * y2 / 44.0
+ 3.0 * r18 * (r105 + r2 * y1 + 18.0 * r46 + 15.0 * r48 + 7.0 * r51) / 6160.0
+ r20
* (1260.0 * r106
+ r107 * y1
+ r108
+ 28.0 * r109
+ r110
+ r111
+ r112
+ 30.0 * r46
+ 2310.0 * r55
+ r66)
/ 18480.0
- r54 * (7.0 * r12 + 18.0 * r85 + 15.0 * r9) / 18480.0
- r55 * (r33 + r73 + r93 + r95 + r96 + r97) / 18480.0
- r7 * (42.0 * r13 + r82 * x3 + 28.0 * r87 + r89 + r90) / 18480.0
- 3.0 * r85 * (r48 - r66) / 220.0
+ 3.0 * r9 * y3 * (r62 + 2.0 * y2) / 440.0
+ x0 * (-r1 * y0 - 84.0 * r106 * x2
+ r109 * r56
+ 54.0 * r114
+ r117 * y1
+ 15.0 * r118
+ 21.0 * r119
+ 81.0 * r120
+ r121 * r46
+ 54.0 * r122
+ 60.0 * r123
+ r124
- r21 * x3 * y0
+ r23 * y3
- r54 * x3
- r55 * r72
- r55 * r76
- r55 * r77
+ r57 * y0 * y3
+ r60 * x3
+ 84.0 * r81 * y0
+ 189.0 * r81 * y1)
/ 9240.0
+ x1 * (r104 * r27 - r105 * x3 - r113 * r53 + 63.0 * r114 + r115 - r16 * r53
+ 28.0 * r47
+ r51 * r80)
/ 3080.0
- y0 * (54.0 * r101 + r102 + r116 * r5 + r117 * x3 + 21.0 * r13 - r19 * y3
+ r22 * y3
+ r78 * x3
+ 189.0 * r83 * x2
+ 60.0 * r86
+ 81.0 * r9 * y1
+ 15.0 * r94
+ 54.0 * r98)
/ 9240.0;
self.moment_yy += -r103 * r116 / 9240.0
- r125 * r70 / 9240.0
- r126 * x3 / 12.0
- 3.0 * r127 * (r26 + r38) / 3080.0
- r128 * (r26 + r30 + x3) / 660.0
- r4 * (r112 * x3 + r115 - 14.0 * r119 + 84.0 * r47) / 9240.0
- r52 * r69 / 9240.0
- r54 * (r58 + r61 + r75) / 9240.0
- r55 * (r100 * y1 + r121 * y2 + r26 * y3 + r79 * y2 + r84 + 210.0 * x2 * y1) / 9240.0
+ x0 * (r108 * y1
+ r110 * y0
+ r111 * y0
+ r112 * y0
+ 45.0 * r125
+ 14.0 * r126
+ 126.0 * r127
+ 770.0 * r128
+ 42.0 * r129
+ r130
+ r131 * y2
+ r132 * r64
+ 135.0 * r48 * y1
+ 630.0 * r55 * y1
+ 126.0 * r55 * y2
+ 14.0 * r55 * y3
+ r63 * y3
+ r65 * y3
+ r66 * y0)
/ 9240.0
+ x1 * (27.0 * r125
+ 42.0 * r126
+ 70.0 * r129
+ r130
+ r39 * r53
+ r44 * r48
+ 27.0 * r53 * y2
+ 54.0 * r64 * y2)
/ 3080.0
+ 3.0 * x2 * y3 * (r48 + r66 + r8 * y3) / 220.0
- y0 * (r100 * r46 + 18.0 * r114
- 9.0 * r118
- 27.0 * r120
- 18.0 * r122
- 30.0 * r123
+ r124
+ r131 * x2
+ r132 * x3 * y1
+ 162.0 * r42 * y1
+ r50
+ 63.0 * r53 * x3
+ r64 * r99)
/ 9240.0;
}
}
/// A trait for types that can provide moment integrals for a path using Green's theorem.
pub trait ParamCurveMoments<'a> {
/// Returns the moment integrals for the path using Green's theorem.
fn moments(&'a self) -> Moments;
}
impl<'a, T: 'a> ParamCurveMoments<'a> for T
where
&'a T: IntoIterator<Item = PathEl>,
{
fn moments(&'a self) -> Moments {
let mut moments = Moments::default();
let mut start_pt: Point = Point::ZERO;
let mut cur: Point = Point::ZERO;
for el in self {
match el {
PathEl::MoveTo(p) => {
start_pt = p;
cur = p;
}
PathEl::LineTo(p) => {
moments.handle_line(cur, p);
cur = p;
}
PathEl::QuadTo(p0, p1) => {
moments.handle_quad(cur, p0, p1);
cur = p1;
}
PathEl::CurveTo(p1, p2, p3) => {
moments.handle_cubic(cur, p1, p2, p3);
cur = p3;
}
PathEl::ClosePath => {
if cur != start_pt {
moments.handle_line(cur, start_pt);
cur = start_pt;
}
}
}
}
moments
}
}
#[cfg(test)]
mod tests {
use crate::BezPath;
use super::*;
macro_rules! assert_approx_eq {
($x: expr, $y: expr) => {
assert!(($x - $y).abs() < 1e-8, "{} != {}", $x, $y);
};
}
#[test]
fn test_moments() {
let path = BezPath::from_vec(vec![
PathEl::MoveTo(Point::new(0.0, 0.0)),
PathEl::LineTo(Point::new(1.0, 0.0)),
PathEl::LineTo(Point::new(1.0, 1.0)),
PathEl::LineTo(Point::new(0.0, 1.0)),
PathEl::ClosePath,
]);
let moments = path.moments();
assert_approx_eq!(moments.moment_x, 0.5);
assert_approx_eq!(moments.moment_y, 0.5);
assert_approx_eq!(moments.moment_xx, 0.3333333333333333);
assert_approx_eq!(moments.moment_xy, 0.25);
assert_approx_eq!(moments.moment_yy, 0.3333333333333333);
}
}
+668
View File
@@ -0,0 +1,668 @@
// Copyright 2022 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Computation of offset curves of cubic Béziers.
//!
//! The main algorithm in this module is a new technique designed for robustness
//! and speed. The details are involved; hopefully there will be a paper.
use arrayvec::ArrayVec;
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
use crate::{
BezPath, CubicBez, ParamCurve, ParamCurveDeriv, PathSeg, Point, QuadBez, Vec2,
common::{solve_itp, solve_quadratic},
};
/// State used for computing an offset curve of a single cubic.
struct CubicOffset {
/// The cubic being offset. This has been regularized.
c: CubicBez,
/// The derivative of `c`.
q: QuadBez,
/// The offset distance (same as the argument).
d: f64,
/// `c0 + c1 t + c2 t^2` is the cross product of second and first
/// derivatives of the underlying cubic, multiplied by the offset.
/// This is used for computing cusps on the offset curve.
///
/// Note that given a curve `c(t)`, its signed curvature is
/// `c''(t) x c'(t) / ||c'(t)||^3`. See also [`Self::cusp_sign`].
c0: f64,
c1: f64,
c2: f64,
/// The tolerance (same as the argument).
tolerance: f64,
}
// We never let cusp values have an absolute value smaller than
// this. When a cusp is found, determine its sign and use this value.
const CUSP_EPSILON: f64 = 1e-12;
/// Number of points for least-squares fit and error evaluation.
///
/// This value is a tradeoff between accuracy and performance. The main risk in it
/// being to small is under-sampling the error and thus letting excessive error
/// slip through. That said, the "arc drawing" approach is designed to be robust
/// and not generate approximate results with narrow error peaks, even in near-cusp
/// "J" shape curves.
const N_LSE: usize = 8;
/// The proportion of transverse error that is blended in the least-squares logic.
const BLEND: f64 = 1e-3;
/// Maximum recursion depth.
///
/// Recursion is bounded to this depth, so the total number of subdivisions will
/// not exceed two to this power.
///
/// This is primarily a "belt and suspenders" robustness guard. In normal operation,
/// the recursion bound should never be reached, as accuracy improves very quickly
/// on subdivision. For unreasonably large coordinate values or small tolerances, it
/// is possible, and in those cases the result will be out of tolerance.
///
/// Perhaps should be configurable.
const MAX_DEPTH: usize = 8;
/// State local to a subdivision
struct OffsetRec {
t0: f64,
t1: f64,
// unit tangent at t0
utan0: Vec2,
// unit tangent at t1
utan1: Vec2,
cusp0: f64,
cusp1: f64,
/// Recursion depth
depth: usize,
}
/// Result of error evaluation
struct ErrEval {
/// Maximum detected error
err_squared: f64,
/// Unit normals sampled uniformly across approximation
unorms: [Vec2; N_LSE],
/// Difference between point on source curve and normal from approximation.
err_vecs: [Vec2; N_LSE],
}
/// Result of subdivision
struct SubdivisionPoint {
/// Source curve t value at subdivision point
t: f64,
/// Unit tangent at subdivision point
utan: Vec2,
}
/// Compute an approximate offset curve.
///
/// The parallel curve of `c` offset by `d` is written to the `result` path.
///
/// There is a fair amount of attention to robustness, but this method is not suitable
/// for degenerate cubics with entirely co-linear control points. Those cases should be
/// handled before calling this function, by replacing them with linear segments.
pub fn offset_cubic(c: CubicBez, d: f64, tolerance: f64, result: &mut BezPath) {
result.truncate(0);
// A tuning parameter for regularization. A value too large may distort the curve,
// while a value too small may fail to generate smooth curves. This is a somewhat
// arbitrary value, and should be revisited.
const DIM_TUNE: f64 = 0.25;
// We use regularization to perturb the curve to avoid *interior* zero-derivative
// cusps. There is robustness logic in place to handle zero derivatives at the
// endpoints.
//
// As a performance note, it might be a good idea to move regularization and
// tangent determination to the caller, as those computations are the same for both
// signs of `d`.
let c_regularized = c.regularize_cusp(tolerance * DIM_TUNE);
let co = CubicOffset::new(c_regularized, d, tolerance);
let (tan0, tan1) = PathSeg::Cubic(c).tangents();
let utan0 = tan0.normalize();
let utan1 = tan1.normalize();
let cusp0 = co.endpoint_cusp(co.q.p0, co.c0);
let cusp1 = co.endpoint_cusp(co.q.p2, co.c0 + co.c1 + co.c2);
result.move_to(c.p0 + d * utan0.turn_90());
let rec = OffsetRec::new(0., 1., utan0, utan1, cusp0, cusp1, 0);
co.offset_rec(&rec, result);
}
impl CubicOffset {
/// Create a new curve from Bézier segment and offset.
fn new(c: CubicBez, d: f64, tolerance: f64) -> Self {
let q = c.deriv();
let d2 = 2.0 * d;
let p1xp0 = q.p1.to_vec2().cross(q.p0.to_vec2());
let p2xp0 = q.p2.to_vec2().cross(q.p0.to_vec2());
let p2xp1 = q.p2.to_vec2().cross(q.p1.to_vec2());
CubicOffset {
c,
q,
d,
c0: d2 * p1xp0,
c1: d2 * (p2xp0 - 2.0 * p1xp0),
c2: d2 * (p2xp1 - p2xp0 + p1xp0),
tolerance,
}
}
/// Compute curvature of the source curve times offset plus 1.
///
/// This quantity is called "cusp" because cusps appear in the offset curve
/// where this value crosses zero. This is based on the geometric property
/// that the offset curve has a cusp when the radius of curvature of the
/// source curve is equal to the offset curve's distance.
///
/// Note: there is a potential division by zero when the derivative vanishes.
/// We avoid doing so for interior points by regularizing the cubic beforehand.
/// We avoid doing so for endpoints by calling `endpoint_cusp` instead.
fn cusp_sign(&self, t: f64) -> f64 {
let ds2 = self.q.eval(t).to_vec2().hypot2();
((self.c2 * t + self.c1) * t + self.c0) / (ds2 * ds2.sqrt()) + 1.0
}
/// Compute cusp value of endpoint.
///
/// This is a special case of [`Self::cusp_sign`]. For the start point, `tan` should be
/// the start point tangent and `y` should be `c0`. For the end point, `tan` should be
/// the end point tangent and `y` should be `c0 + c1 + c2`.
///
/// This is just evaluating the polynomial at t=0 and t=1.
///
/// See [`Self::cusp_sign`] for a description of what "cusp value" means.
fn endpoint_cusp(&self, tan: Point, y: f64) -> f64 {
// Robustness to avoid divide-by-zero when derivatives vanish
const TAN_DIST_EPSILON: f64 = 1e-12;
let tan_dist = tan.to_vec2().hypot().max(TAN_DIST_EPSILON);
let rsqrt = 1.0 / tan_dist;
y * (rsqrt * rsqrt * rsqrt) + 1.0
}
/// Primary entry point for recursive subdivision.
///
/// At a high level, this method determines whether subdivision is necessary. If
/// so, it determines a subdivision point and then recursively calls itself on
/// both subdivisions. If not, it computes a single cubic Bézier to approximate
/// the offset curve, and appends it to `result`.
fn offset_rec(&self, rec: &OffsetRec, result: &mut BezPath) {
// First, determine whether the offset curve contains a cusp. If the sign
// of the cusp value (curvature times offset plus 1) is different at the
// subdivision endpoints, then there is definitely a cusp inside. Find it and
// subdivide there.
//
// Note that there's a possibility the curve has two (or, potentially, any
// even number). We don't rigorously check for this case; if the measured
// error comes in under the tolerance, we simply accept it. Otherwise, in
// the common case we expect to detect a sign crossing from the new
// subdivision point.
if rec.cusp0 * rec.cusp1 < 0.0 {
let a = rec.t0;
let b = rec.t1;
let s = rec.cusp1.signum();
let f = |t| s * self.cusp_sign(t);
let k1 = 0.2 / (b - a);
const ITP_EPS: f64 = 1e-12;
let t = solve_itp(f, a, b, ITP_EPS, 1, k1, s * rec.cusp0, s * rec.cusp1);
// TODO(robustness): If we're unlucky, there will be 3 cusps between t0
// and t1, and the solver will land on the middle one. In that case, the
// derivative on cusp will be the opposite sign as expected.
//
// If we're even more unlucky, there is a second-order cusp, both zero
// cusp value and zero derivative.
let utan_t = self.q.eval(t).to_vec2().normalize();
let cusp_t_minus = CUSP_EPSILON.copysign(rec.cusp0);
let cusp_t_plus = CUSP_EPSILON.copysign(rec.cusp1);
self.subdivide(rec, result, t, utan_t, cusp_t_minus, cusp_t_plus);
return;
}
// We determine the first approximation to the offset curve.
let (mut a, mut b) = self.draw_arc(rec);
let dt = (rec.t1 - rec.t0) * (1.0 / (N_LSE + 1) as f64);
// These represent t values on the source curve.
let mut ts = core::array::from_fn(|i| rec.t0 + (i + 1) as f64 * dt);
let mut c_approx = self.apply(rec, a, b);
let err_init = self.eval_err(rec, c_approx, &mut ts);
let mut err = err_init;
// Number of least-squares refinement steps. More gives a smaller
// error, but takes more time.
const N_REFINE: usize = 2;
for _ in 0..N_REFINE {
if err.err_squared <= self.tolerance * self.tolerance {
break;
}
let (a2, b2) = self.refine_least_squares(rec, a, b, &err);
let c_approx2 = self.apply(rec, a2, b2);
let err2 = self.eval_err(rec, c_approx2, &mut ts);
if err2.err_squared >= err.err_squared {
break;
}
err = err2;
(a, b) = (a2, b2);
c_approx = c_approx2;
}
if rec.depth < MAX_DEPTH && err.err_squared > self.tolerance * self.tolerance {
let SubdivisionPoint { t, utan } = self.find_subdivision_point(rec);
// TODO(robustness): if cusp is extremely near zero, then assign epsilon
// with alternate signs based on derivative of cusp.
let cusp = self.cusp_sign(t);
self.subdivide(rec, result, t, utan, cusp, cusp);
} else {
result.curve_to(c_approx.p1, c_approx.p2, c_approx.p3);
}
}
/// Recursively subdivide.
///
/// In the case of subdividing at a cusp, the cusp value at the subdivision point
/// is mathematically zero, but in those cases we treat it as a signed infinitesimal
/// value representing the values at t minus epsilon and t plus epsilon.
///
/// Note that unit tangents are passed down explicitly. In the general case, they
/// are equal to the derivative (evaluated at that t value) normalized to unit
/// length, but in cases where the derivative is near-zero, they are computed more
/// robustly.
fn subdivide(
&self,
rec: &OffsetRec,
result: &mut BezPath,
t: f64,
utan_t: Vec2,
cusp_t_minus: f64,
cusp_t_plus: f64,
) {
let rec0 = OffsetRec::new(
rec.t0,
t,
rec.utan0,
utan_t,
rec.cusp0,
cusp_t_minus,
rec.depth + 1,
);
self.offset_rec(&rec0, result);
let rec1 = OffsetRec::new(
t,
rec.t1,
utan_t,
rec.utan1,
cusp_t_plus,
rec.cusp1,
rec.depth + 1,
);
self.offset_rec(&rec1, result);
}
/// Convert from (a, b) parameter space to the approximate cubic Bézier.
///
/// The offset approximation can be considered `B(t) + d * D(t)`, where `D(t)`
/// is roughly a unit vector in the direction of the unit normal of the source
/// curve. (The word "roughly" is appropriate because transverse error may
/// cancel out normal error, resulting in a lower error than either alone).
/// The endpoints of `D(t)` must be the unit normals of the source curve, and
/// the endpoint tangents of `D(t)` must tangent to the endpoint tangents of
/// the source curve, to ensure G1 continuity.
///
/// The (a, b) parameters refer to the magnitude of the vector from the endpoint
/// to the corresponding control point in `D(t)`, the direction being determined
/// by the unit tangent.
///
/// When the candidate solution would lead to negative distance from the
/// endpoint to the control point, that distance is clamped to zero. Otherwise
/// such solutions should be considered invalid, and have the unpleasant
/// property of sometimes passing error tolerance checks.
fn apply(&self, rec: &OffsetRec, a: f64, b: f64) -> CubicBez {
// wondering if p0 and p3 should be in rec
// Scale factor from derivatives to displacements
let s = (1. / 3.) * (rec.t1 - rec.t0);
let p0 = self.c.eval(rec.t0) + self.d * rec.utan0.turn_90();
let l0 = s * self.q.eval(rec.t0).to_vec2().length() + a * self.d;
let mut p1 = p0;
if l0 * rec.cusp0 > 0.0 {
p1 += l0 * rec.utan0;
}
let p3 = self.c.eval(rec.t1) + self.d * rec.utan1.turn_90();
let mut p2 = p3;
let l1 = s * self.q.eval(rec.t1).to_vec2().length() - b * self.d;
if l1 * rec.cusp1 > 0.0 {
p2 -= l1 * rec.utan1;
}
CubicBez::new(p0, p1, p2, p3)
}
/// Compute arc approximation.
///
/// This is called "arc drawing" because if we just look at the delta
/// vector, it describes an arc from the initial unit normal to the final unit
/// normal, with "as smooth as possible" parametrization. This approximation
/// is not necessarily great, but is very robust, and in particular, accuracy
/// does not degrade for J shaped near-cusp source curves or when the offset
/// distance is large (with respect to the source curve arc length).
///
/// It is a pretty good approximation overall and has very clean O(n^4) scaling.
/// Its worst performance is on curves with a large cubic component, where it
/// undershoots. The theory is that the least squares refinement improves those
/// cases.
fn draw_arc(&self, rec: &OffsetRec) -> (f64, f64) {
// possible optimization: this can probably be done with vectors
// rather than arctangent
let th = rec.utan1.cross(rec.utan0).atan2(rec.utan1.dot(rec.utan0));
let a = (2. / 3.) / (1.0 + (0.5 * th).cos()) * 2.0 * (0.5 * th).sin();
let b = -a;
(a, b)
}
/// Evaluate error and also refine t values.
///
/// Returns evaluation of error including error vectors and (squared)
/// maximum error.
///
/// The vector of t values represents points on the source curve; the logic
/// here is a Newton step to bring those points closer to the normal ray of
/// the approximation.
fn eval_err(&self, rec: &OffsetRec, c_approx: CubicBez, ts: &mut [f64; N_LSE]) -> ErrEval {
let qa = c_approx.deriv();
let mut err_squared = 0.0;
let mut unorms = [Vec2::ZERO; N_LSE];
let mut err_vecs = [Vec2::ZERO; N_LSE];
for i in 0..N_LSE {
let ta = (i + 1) as f64 * (1.0 / (N_LSE + 1) as f64);
let mut t = ts[i];
let p = self.c.eval(t);
// Newton step to refine t value
let pa = c_approx.eval(ta);
let tana = qa.eval(ta).to_vec2();
t += tana.dot(pa - p) / tana.dot(self.q.eval(t).to_vec2());
t = t.max(rec.t0).min(rec.t1);
ts[i] = t;
let cusp = rec.cusp0.signum();
let unorm = cusp * tana.normalize().turn_90();
unorms[i] = unorm;
let p_new = self.c.eval(t) + self.d * unorm;
let err_vec = pa - p_new;
err_vecs[i] = err_vec;
let mut dist_err_squared = err_vec.length_squared();
if !dist_err_squared.is_finite() {
// A hack to make sure we reject bad refinements
dist_err_squared = 1e12;
}
// Note: consider also incorporating angle error
err_squared = dist_err_squared.max(err_squared);
}
ErrEval {
err_squared,
unorms,
err_vecs,
}
}
/// Refine an approximation, minimizing least squares error.
///
/// Compute the approximation that minimizes least squares error, based on the given error
/// evaluation.
///
/// The effectiveness of this refinement varies. Basically, if the curve has a large cubic
/// component, then the arc drawing will undershoot systematically and this refinement will
/// reduce error considerably. In other cases, it will eventually converge to a local
/// minimum, but convergence is slow.
///
/// The `BLEND` parameter controls a tradeoff between robustness and speed of convergence.
/// In the happy case, convergence is fast and not very sensitive to this parameter. If the
/// parameter is too small, then in near-parabola cases the determinant will be small and
/// the result not numerically stable.
///
/// A value of 1.0 for `BLEND` corresponds to essentially the Hoschek method, minimizing
/// Euclidean distance (which tends to over-anchor on the given t values). A value of 0 would
/// minimize the dot product of error wrt the normal vector, ignoring the cross product
/// component.
///
/// A possible future direction would be to tune the parameter adaptively.
fn refine_least_squares(&self, rec: &OffsetRec, a: f64, b: f64, err: &ErrEval) -> (f64, f64) {
let mut aa = 0.0;
let mut ab = 0.0;
let mut ac = 0.0;
let mut bb = 0.0;
let mut bc = 0.0;
for i in 0..N_LSE {
let n = err.unorms[i];
let err_vec = err.err_vecs[i];
let c_n = err_vec.dot(n);
let c_t = err_vec.cross(n);
let a_n = A_WEIGHTS[i] * rec.utan0.dot(n);
let a_t = A_WEIGHTS[i] * rec.utan0.cross(n);
let b_n = B_WEIGHTS[i] * rec.utan1.dot(n);
let b_t = B_WEIGHTS[i] * rec.utan1.cross(n);
aa += a_n * a_n + BLEND * (a_t * a_t);
ab += a_n * b_n + BLEND * a_t * b_t;
ac += a_n * c_n + BLEND * a_t * c_t;
bb += b_n * b_n + BLEND * (b_t * b_t);
bc += b_n * c_n + BLEND * b_t * c_t;
}
let idet = 1.0 / (self.d * (aa * bb - ab * ab));
let delta_a = idet * (ac * bb - ab * bc);
let delta_b = idet * (aa * bc - ac * ab);
(a - delta_a, b - delta_b)
}
/// Decide where to subdivide when error is exceeded.
///
/// For curves not containing an inflection point, subdivide at the tangent
/// bisecting the endpoint tangents. The logic is that for a near cusp in the
/// source curve, you want the subdivided sections to be approximately
/// circular arcs with progressively smaller angles.
///
/// When there is an inflection point (or, more specifically, when the curve
/// crosses its chord), bisecting the angle can lead to very lopsided arc
/// lengths, so just subdivide by t in that case.
fn find_subdivision_point(&self, rec: &OffsetRec) -> SubdivisionPoint {
let t = 0.5 * (rec.t0 + rec.t1);
let q_t = self.q.eval(t).to_vec2();
let x0 = rec.utan0.cross(q_t).abs();
let x1 = rec.utan1.cross(q_t).abs();
const SUBDIVIDE_THRESH: f64 = 0.1;
if x0 > SUBDIVIDE_THRESH * x1 && x1 > SUBDIVIDE_THRESH * x0 {
let utan = q_t.normalize();
return SubdivisionPoint { t, utan };
}
// Note: do we want to track p0 & p3 in rec, to avoid repeated eval?
let chord = self.c.eval(rec.t1) - self.c.eval(rec.t0);
if chord.cross(rec.utan0) * chord.cross(rec.utan1) < 0.0 {
let tan = rec.utan0 + rec.utan1;
if let Some(subdivision) =
self.subdivide_for_tangent(rec.utan0, rec.t0, rec.t1, tan, false)
{
return subdivision;
}
}
// Curve definitely has an inflection point
// Try to subdivide based on integral of absolute curvature.
// Tangents at recursion endpoints and inflection points.
let mut tangents: ArrayVec<Vec2, 4> = ArrayVec::new();
let mut ts: ArrayVec<f64, 4> = ArrayVec::new();
tangents.push(rec.utan0);
ts.push(rec.t0);
for t in self.c.inflections() {
if t > rec.t0 && t < rec.t1 {
tangents.push(self.q.eval(t).to_vec2());
ts.push(t);
}
}
tangents.push(rec.utan1);
ts.push(rec.t1);
let mut arc_angles: ArrayVec<f64, 3> = ArrayVec::new();
let mut sum = 0.0;
for i in 0..tangents.len() - 1 {
let tan0 = tangents[i];
let tan1 = tangents[i + 1];
let th = tan0.cross(tan1).atan2(tan0.dot(tan1));
sum += th.abs();
arc_angles.push(th);
}
let mut target = sum * 0.5;
let mut i = 0;
while arc_angles[i].abs() < target {
target -= arc_angles[i].abs();
i += 1;
}
let rotation = Vec2::from_angle(target.copysign(arc_angles[i]));
let base = tangents[i];
let tan = base.rotate_scale(rotation);
let utan0 = if i == 0 { rec.utan0 } else { base.normalize() };
self.subdivide_for_tangent(utan0, ts[i], ts[i + 1], tan, true)
.unwrap()
}
/// Find a subdivision point, given a tangent vector.
///
/// When subdividing by bisecting the angle (or, more generally, subdividing by
/// the L1 norm of curvature when there are inflection points), we find the
/// subdivision point by solving for the tangent matching, specifically the
/// cross-product of the tangent and the curve's derivative being zero. For
/// internal cusps, subdividing near the cusp is a good thing, but there is
/// still a robustness concern for vanishing derivative at the endpoints.
fn subdivide_for_tangent(
&self,
utan0: Vec2,
t0: f64,
t1: f64,
tan: Vec2,
force: bool,
) -> Option<SubdivisionPoint> {
let mut t = 0.0;
let mut n_soln = 0;
// set up quadratic equation for matching tangents
let z0 = tan.cross(self.q.p0.to_vec2());
let z1 = tan.cross(self.q.p1.to_vec2());
let z2 = tan.cross(self.q.p2.to_vec2());
let c0 = z0;
let c1 = 2.0 * (z1 - z0);
let c2 = (z2 - z1) - (z1 - z0);
for root in solve_quadratic(c0, c1, c2) {
if root >= t0 && root <= t1 {
t = root;
n_soln += 1;
}
}
if n_soln != 1 {
if !force {
return None;
}
// Numerical failure, try to subdivide at cusp; we pick the
// smaller derivative.
if self.q.eval(t0).to_vec2().length_squared()
> self.q.eval(t1).to_vec2().length_squared()
{
t = t1;
} else {
t = t0;
}
}
let q = self.q.eval(t).to_vec2();
const UTAN_EPSILON: f64 = 1e-12;
let utan = if n_soln == 1 && q.length_squared() >= UTAN_EPSILON {
q.normalize()
} else if tan.length_squared() >= UTAN_EPSILON {
// Curve has a zero-derivative cusp but angles well defined
tan.normalize()
} else {
// 180 degree U-turn, arbitrarily pick a direction.
// If we get to this point, there will probably be a failure.
utan0.turn_90()
};
Some(SubdivisionPoint { t, utan })
}
}
impl OffsetRec {
#[allow(clippy::too_many_arguments)]
fn new(
t0: f64,
t1: f64,
utan0: Vec2,
utan1: Vec2,
cusp0: f64,
cusp1: f64,
depth: usize,
) -> Self {
OffsetRec {
t0,
t1,
utan0,
utan1,
cusp0,
cusp1,
depth,
}
}
}
/// Compute Bézier weights for evenly subdivided t values.
const fn mk_a_weights(rev: bool) -> [f64; N_LSE] {
let mut result = [0.0; N_LSE];
let mut i = 0;
while i < N_LSE {
let t = (i + 1) as f64 / (N_LSE + 1) as f64;
let mt = 1. - t;
let ix = if rev { N_LSE - 1 - i } else { i };
result[ix] = 3.0 * mt * t * mt;
i += 1;
}
result
}
const A_WEIGHTS: [f64; N_LSE] = mk_a_weights(false);
const B_WEIGHTS: [f64; N_LSE] = mk_a_weights(true);
#[cfg(test)]
mod tests {
use super::offset_cubic;
use crate::{BezPath, CubicBez, PathEl};
// This test tries combinations of parameters that have caused problems in the past.
#[test]
fn pathological_curves() {
let curve = CubicBez {
p0: (-1236.3746269978635, 152.17981429574826).into(),
p1: (-1175.18662093517, 108.04721798590596).into(),
p2: (-1152.142883879584, 105.76260301083356).into(),
p3: (-1151.842639804639, 105.73040758939104).into(),
};
let offset = 3603.7267536453924;
let accuracy = 0.1;
let mut result = BezPath::new();
offset_cubic(curve, offset, accuracy, &mut result);
assert!(matches!(result.iter().next(), Some(PathEl::MoveTo(_))));
let mut result = BezPath::new();
offset_cubic(curve, offset, accuracy, &mut result);
assert!(matches!(result.iter().next(), Some(PathEl::MoveTo(_))));
}
/// Cubic offset that used to trigger infinite recursion.
#[test]
fn infinite_recursion() {
const TOLERANCE: f64 = 0.1;
const OFFSET: f64 = -0.5;
let c = CubicBez::new(
(1096.2962962962963, 593.90243902439033),
(1043.6213991769548, 593.90243902439033),
(1030.4526748971193, 593.90243902439033),
(1056.7901234567901, 593.90243902439033),
);
let mut result = BezPath::new();
offset_cubic(c, OFFSET, TOLERANCE, &mut result);
}
#[test]
fn test_cubic_offset_simple_line() {
let cubic = CubicBez::new((0., 0.), (10., 0.), (20., 0.), (30., 0.));
let mut result = BezPath::new();
offset_cubic(cubic, 5., 1e-6, &mut result);
}
}
+221
View File
@@ -0,0 +1,221 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A trait for curves parameterized by a scalar.
use core::ops::Range;
use arrayvec::ArrayVec;
use crate::{Point, Rect, common};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A default value for methods that take an 'accuracy' argument.
///
/// This value is intended to be suitable for general-purpose use, such as
/// 2d graphics.
pub const DEFAULT_ACCURACY: f64 = 1e-6;
/// A curve parameterized by a scalar.
///
/// If the result is interpreted as a point, this represents a curve.
/// But the result can be interpreted as a vector as well.
pub trait ParamCurve: Sized {
/// Evaluate the curve at parameter `t`.
///
/// Generally `t` is in the range [0..1].
fn eval(&self, t: f64) -> Point;
/// Get a subsegment of the curve for the given parameter range.
fn subsegment(&self, range: Range<f64>) -> Self;
/// Subdivide into (roughly) halves.
#[inline]
fn subdivide(&self) -> (Self, Self) {
(self.subsegment(0.0..0.5), self.subsegment(0.5..1.0))
}
/// The start point.
fn start(&self) -> Point {
self.eval(0.0)
}
/// The end point.
fn end(&self) -> Point {
self.eval(1.0)
}
}
// TODO: I might not want to have separate traits for all these.
/// A differentiable parameterized curve.
pub trait ParamCurveDeriv {
/// The parametric curve obtained by taking the derivative of this one.
type DerivResult: ParamCurve;
/// The derivative of the curve.
///
/// Note that the type of the return value is somewhat inaccurate, as
/// the derivative of a curve (mapping of param to point) is a mapping
/// of param to vector. We choose to accept this rather than have a
/// more complex type scheme.
fn deriv(&self) -> Self::DerivResult;
/// Estimate arclength using Gaussian quadrature.
///
/// The coefficients are assumed to cover the range (-1..1), which is
/// traditional.
#[inline]
fn gauss_arclen(&self, coeffs: &[(f64, f64)]) -> f64 {
let d = self.deriv();
coeffs
.iter()
.map(|(wi, xi)| wi * d.eval(0.5 * (xi + 1.0)).to_vec2().hypot())
.sum::<f64>()
* 0.5
}
}
/// A parameterized curve that can have its arc length measured.
pub trait ParamCurveArclen: ParamCurve {
/// The arc length of the curve.
///
/// The result is accurate to the given accuracy (subject to
/// roundoff errors for ridiculously low values). Compute time
/// may vary with accuracy, if the curve needs to be subdivided.
fn arclen(&self, accuracy: f64) -> f64;
/// Solve for the parameter that has the given arc length from the start.
///
/// This implementation uses the IPT method, as provided by
/// [`common::solve_itp`]. This is as robust as bisection but
/// typically converges faster. In addition, the method takes
/// care to compute arc lengths of increasingly smaller segments
/// of the curve, as that is likely faster than repeatedly
/// computing the arc length of the segment starting at t=0.
fn inv_arclen(&self, arclen: f64, accuracy: f64) -> f64 {
if arclen <= 0.0 {
return 0.0;
}
let total_arclen = self.arclen(accuracy);
if arclen >= total_arclen {
return 1.0;
}
let mut t_last = 0.0;
let mut arclen_last = 0.0;
let epsilon = accuracy / total_arclen;
let n = 1.0 - epsilon.log2().ceil().min(0.0);
let inner_accuracy = accuracy / n;
let f = |t: f64| {
let (range, dir) = if t > t_last {
(t_last..t, 1.0)
} else {
(t..t_last, -1.0)
};
let arc = self.subsegment(range).arclen(inner_accuracy);
arclen_last += arc * dir;
t_last = t;
arclen_last - arclen
};
common::solve_itp(f, 0.0, 1.0, epsilon, 1, 0.2, -arclen, total_arclen - arclen)
}
}
/// A parameterized curve that can have its signed area measured.
pub trait ParamCurveArea {
/// Compute the signed area under the curve.
///
/// For a closed path, the signed area of the path is the sum of signed
/// areas of the segments. This is a variant of the "shoelace formula."
/// See:
/// <https://github.com/Pomax/bezierinfo/issues/44> and
/// <http://ich.deanmcnamee.com/graphics/2016/03/30/CurveArea.html>
///
/// This can be computed exactly for Béziers thanks to Green's theorem,
/// and also for simple curves such as circular arcs. For more exotic
/// curves, it's probably best to subdivide to cubics. We leave that
/// to the caller, which is why we don't give an accuracy param here.
fn signed_area(&self) -> f64;
}
/// The nearest position on a curve to some point.
///
/// This is returned by [`ParamCurveNearest::nearest`]
#[derive(Debug, Clone, Copy)]
pub struct Nearest {
/// The square of the distance from the nearest position on the curve
/// to the given point.
pub distance_sq: f64,
/// The position on the curve of the nearest point, as a parameter.
///
/// To resolve this to a [`Point`], use [`ParamCurve::eval`].
pub t: f64,
}
/// A parameterized curve that reports the nearest point.
pub trait ParamCurveNearest {
/// Find the position on the curve that is nearest to the given point.
///
/// This returns a [`Nearest`] struct that contains information about
/// the position.
fn nearest(&self, p: Point, accuracy: f64) -> Nearest;
}
/// A parameterized curve that reports its curvature.
pub trait ParamCurveCurvature: ParamCurveDeriv
where
Self::DerivResult: ParamCurveDeriv,
{
/// Compute the signed curvature at parameter `t`.
#[inline]
fn curvature(&self, t: f64) -> f64 {
let deriv = self.deriv();
let deriv2 = deriv.deriv();
let d = deriv.eval(t).to_vec2();
let d2 = deriv2.eval(t).to_vec2();
// TODO: What's the convention for sign? I think it should match signed
// area - a positive area curve should have positive curvature.
d2.cross(d) * d.hypot2().powf(-1.5)
}
}
/// The maximum number of extrema that can be reported in the `ParamCurveExtrema` trait.
///
/// This is 4 to support cubic Béziers. If other curves are used, they should be
/// subdivided to limit the number of extrema.
pub const MAX_EXTREMA: usize = 4;
/// A parameterized curve that reports its extrema.
pub trait ParamCurveExtrema: ParamCurve {
/// Compute the extrema of the curve.
///
/// Only extrema within the interior of the curve count.
/// At most four extrema can be reported, which is sufficient for
/// cubic Béziers.
///
/// The extrema should be reported in increasing parameter order.
fn extrema(&self) -> ArrayVec<f64, MAX_EXTREMA>;
/// Return parameter ranges, each of which is monotonic within the range.
fn extrema_ranges(&self) -> ArrayVec<Range<f64>, { MAX_EXTREMA + 1 }> {
let mut result = ArrayVec::new();
let mut t0 = 0.0;
for t in self.extrema() {
result.push(t0..t);
t0 = t;
}
result.push(t0..1.0);
result
}
/// The smallest rectangle that encloses the curve in the range (0..1).
fn bounding_box(&self) -> Rect {
let mut bbox = Rect::from_points(self.start(), self.end());
for t in self.extrema() {
bbox = bbox.union_pt(self.eval(t));
}
bbox
}
}
+398
View File
@@ -0,0 +1,398 @@
// Copyright 2019 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A 2D point.
use core::fmt;
use core::ops::{Add, AddAssign, Sub, SubAssign};
use crate::common::FloatExt;
use crate::{Axis, Vec2};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A 2D point.
///
/// This type represents a point in 2D space. It has the same layout as [`Vec2`], but
/// its meaning is different: `Vec2` represents a change in location (for example velocity).
///
/// In general, `kurbo` overloads math operators where it makes sense, for example implementing
/// `Affine * Point` as the point under the affine transformation. However `Point + Point` and
/// `f64 * Point` are not implemented, because the operations do not make geometric sense. If you
/// need to apply these operations, then 1) check what you're doing makes geometric sense, then 2)
/// use [`Point::to_vec2`] to convert the point to a `Vec2`.
#[derive(Clone, Copy, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Point {
/// The x coordinate.
pub x: f64,
/// The y coordinate.
pub y: f64,
}
impl Point {
/// The point (0, 0).
pub const ZERO: Point = Point::new(0., 0.);
/// The point at the origin; (0, 0).
pub const ORIGIN: Point = Point::new(0., 0.);
/// Create a new `Point` with the provided `x` and `y` coordinates.
#[inline(always)]
pub const fn new(x: f64, y: f64) -> Self {
Point { x, y }
}
/// Convert this point into a `Vec2`.
#[inline(always)]
pub const fn to_vec2(self) -> Vec2 {
Vec2::new(self.x, self.y)
}
/// Linearly interpolate between two points.
#[inline]
pub fn lerp(self, other: Point, t: f64) -> Point {
self.to_vec2().lerp(other.to_vec2(), t).to_point()
}
/// Determine the midpoint of two points.
#[inline]
pub const fn midpoint(self, other: Point) -> Point {
Point::new(0.5 * (self.x + other.x), 0.5 * (self.y + other.y))
}
/// Euclidean distance.
///
/// See [`Vec2::hypot`] for the same operation on [`Vec2`].
#[inline]
pub fn distance(self, other: Point) -> f64 {
(self - other).hypot()
}
/// Squared Euclidean distance.
///
/// See [`Vec2::hypot2`] for the same operation on [`Vec2`].
#[inline]
pub fn distance_squared(self, other: Point) -> f64 {
(self - other).hypot2()
}
/// Returns a new `Point`, with `x` and `y` [rounded] to the nearest integer.
///
/// # Examples
///
/// ```
/// use kurbo::Point;
/// let a = Point::new(3.3, 3.6).round();
/// let b = Point::new(3.0, -3.1).round();
/// assert_eq!(a.x, 3.0);
/// assert_eq!(a.y, 4.0);
/// assert_eq!(b.x, 3.0);
/// assert_eq!(b.y, -3.0);
/// ```
///
/// [rounded]: f64::round
#[inline]
pub fn round(self) -> Point {
Point::new(self.x.round(), self.y.round())
}
/// Returns a new `Point`,
/// with `x` and `y` [rounded up] to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Point;
/// let a = Point::new(3.3, 3.6).ceil();
/// let b = Point::new(3.0, -3.1).ceil();
/// assert_eq!(a.x, 4.0);
/// assert_eq!(a.y, 4.0);
/// assert_eq!(b.x, 3.0);
/// assert_eq!(b.y, -3.0);
/// ```
///
/// [rounded up]: f64::ceil
#[inline]
pub fn ceil(self) -> Point {
Point::new(self.x.ceil(), self.y.ceil())
}
/// Returns a new `Point`,
/// with `x` and `y` [rounded down] to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Point;
/// let a = Point::new(3.3, 3.6).floor();
/// let b = Point::new(3.0, -3.1).floor();
/// assert_eq!(a.x, 3.0);
/// assert_eq!(a.y, 3.0);
/// assert_eq!(b.x, 3.0);
/// assert_eq!(b.y, -4.0);
/// ```
///
/// [rounded down]: f64::floor
#[inline]
pub fn floor(self) -> Point {
Point::new(self.x.floor(), self.y.floor())
}
/// Returns a new `Point`,
/// with `x` and `y` [rounded away] from zero to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Point;
/// let a = Point::new(3.3, 3.6).expand();
/// let b = Point::new(3.0, -3.1).expand();
/// assert_eq!(a.x, 4.0);
/// assert_eq!(a.y, 4.0);
/// assert_eq!(b.x, 3.0);
/// assert_eq!(b.y, -4.0);
/// ```
///
/// [rounded away]: FloatExt::expand
#[inline]
pub fn expand(self) -> Point {
Point::new(self.x.expand(), self.y.expand())
}
/// Returns a new `Point`,
/// with `x` and `y` [rounded towards] zero to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Point;
/// let a = Point::new(3.3, 3.6).trunc();
/// let b = Point::new(3.0, -3.1).trunc();
/// assert_eq!(a.x, 3.0);
/// assert_eq!(a.y, 3.0);
/// assert_eq!(b.x, 3.0);
/// assert_eq!(b.y, -3.0);
/// ```
///
/// [rounded towards]: f64::trunc
#[inline]
pub fn trunc(self) -> Point {
Point::new(self.x.trunc(), self.y.trunc())
}
/// Is this point [finite]?
///
/// [finite]: f64::is_finite
#[inline]
pub const fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
/// Is this point [`NaN`]?
///
/// [`NaN`]: f64::is_nan
#[inline]
pub const fn is_nan(self) -> bool {
self.x.is_nan() || self.y.is_nan()
}
/// Get the member matching the given axis.
#[inline]
pub const fn get_coord(self, axis: Axis) -> f64 {
match axis {
Axis::Horizontal => self.x,
Axis::Vertical => self.y,
}
}
/// Get a mutable reference to the member matching the given axis.
#[inline]
pub const fn get_coord_mut(&mut self, axis: Axis) -> &mut f64 {
match axis {
Axis::Horizontal => &mut self.x,
Axis::Vertical => &mut self.y,
}
}
/// Set the member matching the given axis to the given value.
#[inline]
pub const fn set_coord(&mut self, axis: Axis, value: f64) {
match axis {
Axis::Horizontal => self.x = value,
Axis::Vertical => self.y = value,
}
}
}
impl From<(f32, f32)> for Point {
#[inline(always)]
fn from(v: (f32, f32)) -> Point {
Point {
x: v.0 as f64,
y: v.1 as f64,
}
}
}
impl From<(f64, f64)> for Point {
#[inline(always)]
fn from(v: (f64, f64)) -> Point {
Point { x: v.0, y: v.1 }
}
}
impl From<Point> for (f64, f64) {
#[inline(always)]
fn from(v: Point) -> (f64, f64) {
(v.x, v.y)
}
}
impl Add<Vec2> for Point {
type Output = Point;
#[inline]
fn add(self, other: Vec2) -> Self {
Point::new(self.x + other.x, self.y + other.y)
}
}
impl AddAssign<Vec2> for Point {
#[inline]
fn add_assign(&mut self, other: Vec2) {
*self = Point::new(self.x + other.x, self.y + other.y);
}
}
impl Sub<Vec2> for Point {
type Output = Point;
#[inline]
fn sub(self, other: Vec2) -> Self {
Point::new(self.x - other.x, self.y - other.y)
}
}
impl SubAssign<Vec2> for Point {
#[inline]
fn sub_assign(&mut self, other: Vec2) {
*self = Point::new(self.x - other.x, self.y - other.y);
}
}
impl Add<(f64, f64)> for Point {
type Output = Point;
#[inline]
fn add(self, (x, y): (f64, f64)) -> Self {
Point::new(self.x + x, self.y + y)
}
}
impl AddAssign<(f64, f64)> for Point {
#[inline]
fn add_assign(&mut self, (x, y): (f64, f64)) {
*self = Point::new(self.x + x, self.y + y);
}
}
impl Sub<(f64, f64)> for Point {
type Output = Point;
#[inline]
fn sub(self, (x, y): (f64, f64)) -> Self {
Point::new(self.x - x, self.y - y)
}
}
impl SubAssign<(f64, f64)> for Point {
#[inline]
fn sub_assign(&mut self, (x, y): (f64, f64)) {
*self = Point::new(self.x - x, self.y - y);
}
}
impl Sub<Point> for Point {
type Output = Vec2;
#[inline]
fn sub(self, other: Point) -> Vec2 {
Vec2::new(self.x - other.x, self.y - other.y)
}
}
impl fmt::Debug for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({:?}, {:?})", self.x, self.y)
}
}
impl fmt::Display for Point {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "(")?;
fmt::Display::fmt(&self.x, formatter)?;
write!(formatter, ", ")?;
fmt::Display::fmt(&self.y, formatter)?;
write!(formatter, ")")
}
}
#[cfg(feature = "mint")]
impl From<Point> for mint::Point2<f64> {
#[inline(always)]
fn from(p: Point) -> mint::Point2<f64> {
mint::Point2 { x: p.x, y: p.y }
}
}
#[cfg(feature = "mint")]
impl From<mint::Point2<f64>> for Point {
#[inline(always)]
fn from(p: mint::Point2<f64>) -> Point {
Point { x: p.x, y: p.y }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn point_arithmetic() {
assert_eq!(
Point::new(0., 0.) - Vec2::new(10., 0.),
Point::new(-10., 0.)
);
assert_eq!(
Point::new(0., 0.) - Point::new(-5., 101.),
Vec2::new(5., -101.)
);
}
#[test]
#[allow(clippy::float_cmp)]
fn distance() {
let p1 = Point::new(0., 10.);
let p2 = Point::new(0., 5.);
assert_eq!(p1.distance(p2), 5.);
let p1 = Point::new(-11., 1.);
let p2 = Point::new(-7., -2.);
assert_eq!(p1.distance(p2), 5.);
}
#[test]
fn display() {
let p = Point::new(0.12345, 9.87654);
assert_eq!(format!("{p}"), "(0.12345, 9.87654)");
let p = Point::new(0.12345, 9.87654);
assert_eq!(format!("{p:.2}"), "(0.12, 9.88)");
}
}
+594
View File
@@ -0,0 +1,594 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Quadratic Bézier segments.
use core::ops::{Mul, Range};
use arrayvec::ArrayVec;
use crate::MAX_EXTREMA;
use crate::common::{solve_cubic, solve_quadratic};
use crate::{
Affine, CubicBez, Line, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea,
ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point,
Rect, Shape,
};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A single quadratic Bézier segment.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[allow(missing_docs)]
pub struct QuadBez {
pub p0: Point,
pub p1: Point,
pub p2: Point,
}
impl QuadBez {
/// Create a new quadratic Bézier segment.
#[inline]
pub fn new<V: Into<Point>>(p0: V, p1: V, p2: V) -> QuadBez {
QuadBez {
p0: p0.into(),
p1: p1.into(),
p2: p2.into(),
}
}
/// Raise the order by 1.
///
/// Returns a cubic Bézier segment that exactly represents this quadratic.
#[inline]
pub fn raise(&self) -> CubicBez {
CubicBez::new(
self.p0,
self.p0 + (2.0 / 3.0) * (self.p1 - self.p0),
self.p2 + (2.0 / 3.0) * (self.p1 - self.p2),
self.p2,
)
}
/// Estimate the number of subdivisions for flattening.
pub(crate) fn estimate_subdiv(&self, sqrt_tol: f64) -> FlattenParams {
// Determine transformation to $y = x^2$ parabola.
let d01 = self.p1 - self.p0;
let d12 = self.p2 - self.p1;
let dd = d01 - d12;
let cross = (self.p2 - self.p0).cross(dd);
let x0 = d01.dot(dd) * cross.recip();
let x2 = d12.dot(dd) * cross.recip();
let scale = (cross / (dd.hypot() * (x2 - x0))).abs();
// Compute number of subdivisions needed.
let a0 = approx_parabola_integral(x0);
let a2 = approx_parabola_integral(x2);
let val = if scale.is_finite() {
let da = (a2 - a0).abs();
let sqrt_scale = scale.sqrt();
if x0.signum() == x2.signum() {
da * sqrt_scale
} else {
// Handle cusp case (segment contains curvature maximum)
let xmin = sqrt_tol / sqrt_scale;
sqrt_tol * da / approx_parabola_integral(xmin)
}
} else {
0.0
};
let u0 = approx_parabola_inv_integral(a0);
let u2 = approx_parabola_inv_integral(a2);
let uscale = (u2 - u0).recip();
FlattenParams {
a0,
a2,
u0,
uscale,
val,
}
}
// Maps a value from 0..1 to 0..1.
pub(crate) fn determine_subdiv_t(&self, params: &FlattenParams, x: f64) -> f64 {
let a = params.a0 + (params.a2 - params.a0) * x;
let u = approx_parabola_inv_integral(a);
(u - params.u0) * params.uscale
}
/// Is this quadratic Bezier curve finite?
#[inline]
pub const fn is_finite(&self) -> bool {
self.p0.is_finite() && self.p1.is_finite() && self.p2.is_finite()
}
/// Is this quadratic Bezier curve NaN?
#[inline]
pub const fn is_nan(&self) -> bool {
self.p0.is_nan() || self.p1.is_nan() || self.p2.is_nan()
}
/// Finds the value of `t` for which `self.eval(t)` is about `y`.
///
/// Assumes that this segment is monotonic in `y` and that it crosses
/// the height `y`. (Under these assumptions, there is a unique answer.)
pub(crate) fn solve_monotonic_for_y(&self, y: f64) -> f64 {
let start = self.start();
let end = self.end();
debug_assert!(start.y.min(end.y) <= y && y <= start.y.max(end.y));
let a = end.y - 2.0 * self.p1.y + start.y;
let b = 2.0 * (self.p1.y - start.y);
let c = start.y - y;
for t in solve_quadratic(c, b, a) {
if (0.0..=1.0).contains(&t) {
return t;
}
}
// Even though we asserted that our y range contains `y`, it's possible
// that we failed to find a solution numerically. (For example, rounding
// of a, b, or c might have pushed the root outside of [0.0, 1.0].)
// If we failed to find a solution, the real solution should be close
// to one of the endpoints. So just find whichever endpoint was closer.
if (start.y - y).abs() <= (end.y - y).abs() {
0.0
} else {
1.0
}
}
}
/// An iterator for quadratic beziers.
pub struct QuadBezIter {
quad: QuadBez,
ix: usize,
}
impl Shape for QuadBez {
type PathElementsIter<'iter> = QuadBezIter;
#[inline]
fn path_elements(&self, _tolerance: f64) -> QuadBezIter {
QuadBezIter { quad: *self, ix: 0 }
}
fn area(&self) -> f64 {
0.0
}
#[inline]
fn perimeter(&self, accuracy: f64) -> f64 {
self.arclen(accuracy)
}
fn winding(&self, _pt: Point) -> i32 {
0
}
#[inline]
fn bounding_box(&self) -> Rect {
ParamCurveExtrema::bounding_box(self)
}
}
impl Iterator for QuadBezIter {
type Item = PathEl;
fn next(&mut self) -> Option<PathEl> {
self.ix += 1;
match self.ix {
1 => Some(PathEl::MoveTo(self.quad.p0)),
2 => Some(PathEl::QuadTo(self.quad.p1, self.quad.p2)),
_ => None,
}
}
}
pub(crate) struct FlattenParams {
a0: f64,
a2: f64,
u0: f64,
uscale: f64,
/// The number of `subdivisions * 2 * sqrt_tol`.
pub(crate) val: f64,
}
/// An approximation to $\int (1 + 4x^2) ^ -0.25 dx$
///
/// This is used for flattening curves.
fn approx_parabola_integral(x: f64) -> f64 {
const D: f64 = 0.67;
x / (1.0 - D + (D.powi(4) + 0.25 * x * x).sqrt().sqrt())
}
/// An approximation to the inverse parabola integral.
fn approx_parabola_inv_integral(x: f64) -> f64 {
const B: f64 = 0.39;
x * (1.0 - B + (B * B + 0.25 * x * x).sqrt())
}
impl ParamCurve for QuadBez {
#[inline]
fn eval(&self, t: f64) -> Point {
let mt = 1.0 - t;
(self.p0.to_vec2() * (mt * mt)
+ (self.p1.to_vec2() * (mt * 2.0) + self.p2.to_vec2() * t) * t)
.to_point()
}
fn subsegment(&self, range: Range<f64>) -> QuadBez {
let (t0, t1) = (range.start, range.end);
let p0 = self.eval(t0);
let p2 = self.eval(t1);
let p1 = p0 + (self.p1 - self.p0).lerp(self.p2 - self.p1, t0) * (t1 - t0);
QuadBez { p0, p1, p2 }
}
/// Subdivide into halves, using de Casteljau.
#[inline]
fn subdivide(&self) -> (QuadBez, QuadBez) {
let pm = self.eval(0.5);
(
QuadBez::new(self.p0, self.p0.midpoint(self.p1), pm),
QuadBez::new(pm, self.p1.midpoint(self.p2), self.p2),
)
}
#[inline]
fn start(&self) -> Point {
self.p0
}
#[inline]
fn end(&self) -> Point {
self.p2
}
}
impl ParamCurveDeriv for QuadBez {
type DerivResult = Line;
#[inline]
fn deriv(&self) -> Line {
Line::new(
(2.0 * (self.p1.to_vec2() - self.p0.to_vec2())).to_point(),
(2.0 * (self.p2.to_vec2() - self.p1.to_vec2())).to_point(),
)
}
}
impl ParamCurveArclen for QuadBez {
/// Arclength of a quadratic Bézier segment.
///
/// This computation is based on an analytical formula. Since that formula suffers
/// from numerical instability when the curve is very close to a straight line, we
/// detect that case and fall back to Legendre-Gauss quadrature.
///
/// Accuracy should be better than 1e-13 over the entire range.
///
/// Adapted from <http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/>
/// with permission.
fn arclen(&self, _accuracy: f64) -> f64 {
let d2 = self.p0.to_vec2() - 2.0 * self.p1.to_vec2() + self.p2.to_vec2();
let a = d2.hypot2();
let d1 = self.p1 - self.p0;
let c = d1.hypot2();
if a < 5e-4 * c {
// This case happens for nearly straight Béziers.
//
// Calculate arclength using Legendre-Gauss quadrature using formula from Behdad
// in https://github.com/Pomax/BezierInfo-2/issues/77
let v0 = (-0.492943519233745 * self.p0.to_vec2()
+ 0.430331482911935 * self.p1.to_vec2()
+ 0.0626120363218102 * self.p2.to_vec2())
.hypot();
let v1 = ((self.p2 - self.p0) * 0.4444444444444444).hypot();
let v2 = (-0.0626120363218102 * self.p0.to_vec2()
- 0.430331482911935 * self.p1.to_vec2()
+ 0.492943519233745 * self.p2.to_vec2())
.hypot();
return v0 + v1 + v2;
}
let b = 2.0 * d2.dot(d1);
let sabc = (a + b + c).sqrt();
let a2 = a.powf(-0.5);
let a32 = a2.powi(3);
let c2 = 2.0 * c.sqrt();
let ba_c2 = b * a2 + c2;
let v0 = 0.25 * a2 * a2 * b * (2.0 * sabc - c2) + sabc;
// TODO: justify and fine-tune this exact constant.
// The factor of a2 here is a little arbitrary: we really want
// to test whether ba_c2 is small, but it's also important for
// this comparison to be scale-invariant. We chose a2 (instead of,
// for example, c2 on the rhs) because it's unchanged under
// reversing the parametrization.
if ba_c2 * a2 < 1e-13 {
// This case happens for Béziers with a sharp kink.
v0
} else {
v0 + 0.25
* a32
* (4.0 * c * a - b * b)
* (((2.0 * a + b) * a2 + 2.0 * sabc) / ba_c2).ln()
}
}
}
impl ParamCurveArea for QuadBez {
#[inline]
fn signed_area(&self) -> f64 {
(self.p0.x * (2.0 * self.p1.y + self.p2.y) + 2.0 * self.p1.x * (self.p2.y - self.p0.y)
- self.p2.x * (self.p0.y + 2.0 * self.p1.y))
* (1.0 / 6.0)
}
}
impl ParamCurveNearest for QuadBez {
/// Find the nearest point, using analytical algorithm based on cubic root finding.
fn nearest(&self, p: Point, _accuracy: f64) -> Nearest {
fn eval_t(p: Point, t_best: &mut f64, r_best: &mut Option<f64>, t: f64, p0: Point) {
let r = (p0 - p).hypot2();
if r_best.map(|r_best| r < r_best).unwrap_or(true) {
*r_best = Some(r);
*t_best = t;
}
}
fn try_t(
q: &QuadBez,
p: Point,
t_best: &mut f64,
r_best: &mut Option<f64>,
t: f64,
) -> bool {
if !(0.0..=1.0).contains(&t) {
return true;
}
eval_t(p, t_best, r_best, t, q.eval(t));
false
}
let d0 = self.p1 - self.p0;
let d1 = self.p0.to_vec2() + self.p2.to_vec2() - 2.0 * self.p1.to_vec2();
let d = self.p0 - p;
let c0 = d.dot(d0);
let c1 = 2.0 * d0.hypot2() + d.dot(d1);
let c2 = 3.0 * d1.dot(d0);
let c3 = d1.hypot2();
let roots = solve_cubic(c0, c1, c2, c3);
let mut r_best = None;
let mut t_best = 0.0;
let mut need_ends = false;
if roots.is_empty() {
need_ends = true;
}
for &t in &roots {
need_ends |= try_t(self, p, &mut t_best, &mut r_best, t);
}
if need_ends {
eval_t(p, &mut t_best, &mut r_best, 0.0, self.p0);
eval_t(p, &mut t_best, &mut r_best, 1.0, self.p2);
}
Nearest {
t: t_best,
distance_sq: r_best.unwrap(),
}
}
}
impl ParamCurveCurvature for QuadBez {}
impl ParamCurveExtrema for QuadBez {
fn extrema(&self) -> ArrayVec<f64, MAX_EXTREMA> {
let mut result = ArrayVec::new();
let d0 = self.p1 - self.p0;
let d1 = self.p2 - self.p1;
let dd = d1 - d0;
if dd.x != 0.0 {
let t = -d0.x / dd.x;
if t > 0.0 && t < 1.0 {
result.push(t);
}
}
if dd.y != 0.0 {
let t = -d0.y / dd.y;
if t > 0.0 && t < 1.0 {
result.push(t);
if result.len() == 2 && result[0] > t {
result.swap(0, 1);
}
}
}
result
}
}
impl Mul<QuadBez> for Affine {
type Output = QuadBez;
#[inline]
fn mul(self, other: QuadBez) -> QuadBez {
QuadBez {
p0: self * other.p0,
p1: self * other.p1,
p2: self * other.p2,
}
}
}
#[cfg(test)]
mod tests {
use crate::{
Affine, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv,
ParamCurveExtrema, ParamCurveNearest, Point, QuadBez,
};
fn assert_near(p0: Point, p1: Point, epsilon: f64) {
assert!((p1 - p0).hypot() < epsilon, "{p0:?} != {p1:?}");
}
#[test]
fn quadbez_deriv() {
let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0));
let deriv = q.deriv();
let n = 10;
for i in 0..=n {
let t = (i as f64) * (n as f64).recip();
let delta = 1e-6;
let p = q.eval(t);
let p1 = q.eval(t + delta);
let d_approx = (p1 - p) * delta.recip();
let d = deriv.eval(t).to_vec2();
assert!((d - d_approx).hypot() < delta * 2.0);
}
}
#[test]
fn quadbez_arclen() {
let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0));
let true_arclen = 0.5 * 5.0f64.sqrt() + 0.25 * (2.0 + 5.0f64.sqrt()).ln();
for i in 0..12 {
let accuracy = 0.1f64.powi(i);
let est = q.arclen(accuracy);
let error = est - true_arclen;
assert!(error.abs() < accuracy, "{est} != {true_arclen}");
}
}
#[test]
fn quadbez_arclen_pathological() {
let q = QuadBez::new((-1.0, 0.0), (1.03, 0.0), (1.0, 0.0));
let true_arclen = 2.0008737864167325; // A rough empirical calculation
let accuracy = 1e-11;
let est = q.arclen(accuracy);
assert!(
(est - true_arclen).abs() < accuracy,
"{est} != {true_arclen}"
);
}
#[test]
fn quadbez_subsegment() {
let q = QuadBez::new((3.1, 4.1), (5.9, 2.6), (5.3, 5.8));
let t0 = 0.1;
let t1 = 0.8;
let qs = q.subsegment(t0..t1);
let epsilon = 1e-12;
let n = 10;
for i in 0..=n {
let t = (i as f64) * (n as f64).recip();
let ts = t0 + t * (t1 - t0);
assert_near(q.eval(ts), qs.eval(t), epsilon);
}
}
#[test]
fn quadbez_raise() {
let q = QuadBez::new((3.1, 4.1), (5.9, 2.6), (5.3, 5.8));
let c = q.raise();
let qd = q.deriv();
let cd = c.deriv();
let epsilon = 1e-12;
let n = 10;
for i in 0..=n {
let t = (i as f64) * (n as f64).recip();
assert_near(q.eval(t), c.eval(t), epsilon);
assert_near(qd.eval(t), cd.eval(t), epsilon);
}
}
#[test]
fn quadbez_signed_area() {
// y = 1 - x^2
let q = QuadBez::new((1.0, 0.0), (0.5, 1.0), (0.0, 1.0));
let epsilon = 1e-12;
assert!((q.signed_area() - 2.0 / 3.0).abs() < epsilon);
assert!(((Affine::rotate(0.5) * q).signed_area() - 2.0 / 3.0).abs() < epsilon);
assert!(((Affine::translate((0.0, 1.0)) * q).signed_area() - 3.5 / 3.0).abs() < epsilon);
assert!(((Affine::translate((1.0, 0.0)) * q).signed_area() - 3.5 / 3.0).abs() < epsilon);
}
fn verify(result: Nearest, expected: f64) {
assert!(
(result.t - expected).abs() < 1e-6,
"got {result:?} expected {expected}"
);
}
#[test]
fn quadbez_nearest() {
// y = x^2
let q = QuadBez::new((-1.0, 1.0), (0.0, -1.0), (1.0, 1.0));
verify(q.nearest((0.0, 0.0).into(), 1e-3), 0.5);
verify(q.nearest((0.0, 0.1).into(), 1e-3), 0.5);
verify(q.nearest((0.0, -0.1).into(), 1e-3), 0.5);
verify(q.nearest((0.5, 0.25).into(), 1e-3), 0.75);
verify(q.nearest((1.0, 1.0).into(), 1e-3), 1.0);
verify(q.nearest((1.1, 1.1).into(), 1e-3), 1.0);
verify(q.nearest((-1.1, 1.1).into(), 1e-3), 0.0);
let a = Affine::rotate(0.5);
verify((a * q).nearest(a * Point::new(0.5, 0.25), 1e-3), 0.75);
}
// This test exposes a degenerate case in the solver used internally
// by the "nearest" calculation - the cubic term is zero.
#[test]
fn quadbez_nearest_low_order() {
let q = QuadBez::new((-1.0, 0.0), (0.0, 0.0), (1.0, 0.0));
verify(q.nearest((0.0, 0.0).into(), 1e-3), 0.5);
verify(q.nearest((0.0, 1.0).into(), 1e-3), 0.5);
}
#[test]
fn quadbez_nearest_rounding_panic() {
let quad = QuadBez::new(
(-1.0394736842105263, 0.0),
(0.8210526315789474, -1.511111111111111),
(0.0, 1.9333333333333333),
);
let test = Point::new(-1.7976931348623157e308, 0.8571428571428571);
// accuracy ignored
let _res = quad.nearest(test, 1e-6);
// if we got here then we didn't panic
}
#[test]
fn quadbez_extrema() {
// y = x^2
let q = QuadBez::new((-1.0, 1.0), (0.0, -1.0), (1.0, 1.0));
let extrema = q.extrema();
assert_eq!(extrema.len(), 1);
assert!((extrema[0] - 0.5).abs() < 1e-6);
let q = QuadBez::new((0.0, 0.5), (1.0, 1.0), (0.5, 0.0));
let extrema = q.extrema();
assert_eq!(extrema.len(), 2);
assert!((extrema[0] - 1.0 / 3.0).abs() < 1e-6);
assert!((extrema[1] - 2.0 / 3.0).abs() < 1e-6);
// Reverse direction
let q = QuadBez::new((0.5, 0.0), (1.0, 1.0), (0.0, 0.5));
let extrema = q.extrema();
assert_eq!(extrema.len(), 2);
assert!((extrema[0] - 1.0 / 3.0).abs() < 1e-6);
assert!((extrema[1] - 2.0 / 3.0).abs() < 1e-6);
}
// A regression test for #477: the approximate-linearity test for
// using the analytic solution needs to be scale-invariant.
#[test]
fn perimeter_not_nan() {
let q = QuadBez::new((2685., -1251.), (2253., -1303.), (2253., -1303.));
let len = q.arclen(crate::DEFAULT_ACCURACY);
assert!(len.is_finite());
}
}
+130
View File
@@ -0,0 +1,130 @@
// Copyright 2021 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Quadratic Bézier splines.
use crate::Point;
use crate::QuadBez;
use alloc::vec::Vec;
/// A quadratic Bézier spline in [B-spline](https://en.wikipedia.org/wiki/B-spline) format.
#[derive(Clone, Debug, PartialEq)]
pub struct QuadSpline(Vec<Point>);
impl QuadSpline {
/// Construct a new `QuadSpline` from an array of [`Point`]s.
#[inline(always)]
pub fn new(points: Vec<Point>) -> Self {
Self(points)
}
/// Return the spline's control [`Point`]s.
#[inline(always)]
pub fn points(&self) -> &[Point] {
&self.0
}
/// Return an iterator over the implied [`QuadBez`] sequence.
///
/// The returned quads are guaranteed to be G1 continuous.
#[inline(always)]
pub fn to_quads(&self) -> impl Iterator<Item = QuadBez> + '_ {
ToQuadBez {
idx: 0,
points: &self.0,
}
}
}
struct ToQuadBez<'a> {
idx: usize,
points: &'a Vec<Point>,
}
impl Iterator for ToQuadBez<'_> {
type Item = QuadBez;
fn next(&mut self) -> Option<Self::Item> {
let [mut p0, p1, mut p2]: [Point; 3] =
self.points.get(self.idx..=self.idx + 2)?.try_into().ok()?;
if self.idx != 0 {
p0 = p0.midpoint(p1);
}
if self.idx + 2 < self.points.len() - 1 {
p2 = p1.midpoint(p2);
}
self.idx += 1;
Some(QuadBez { p0, p1, p2 })
}
}
#[cfg(test)]
mod tests {
use crate::{Point, QuadBez, QuadSpline};
#[test]
fn no_points_no_quads() {
assert!(QuadSpline::new(Vec::new()).to_quads().next().is_none());
}
#[test]
fn one_point_no_quads() {
assert!(
QuadSpline::new(vec![Point::new(1.0, 1.0)])
.to_quads()
.next()
.is_none()
);
}
#[test]
fn two_points_no_quads() {
assert!(
QuadSpline::new(vec![Point::new(1.0, 1.0), Point::new(1.0, 1.0)])
.to_quads()
.next()
.is_none()
);
}
#[test]
fn three_points_same_quad() {
let p0 = Point::new(1.0, 1.0);
let p1 = Point::new(2.0, 2.0);
let p2 = Point::new(3.0, 3.0);
assert_eq!(
vec![QuadBez { p0, p1, p2 }],
QuadSpline::new(vec![p0, p1, p2])
.to_quads()
.collect::<Vec<_>>()
);
}
#[test]
fn four_points_implicit_on_curve() {
let p0 = Point::new(1.0, 1.0);
let p1 = Point::new(3.0, 3.0);
let p2 = Point::new(5.0, 5.0);
let p3 = Point::new(8.0, 8.0);
assert_eq!(
vec![
QuadBez {
p0,
p1,
p2: p1.midpoint(p2)
},
QuadBez {
p0: p1.midpoint(p2),
p1: p2,
p2: p3
}
],
QuadSpline::new(vec![p0, p1, p2, p3])
.to_quads()
.collect::<Vec<_>>()
);
}
}
+1053
View File
File diff suppressed because it is too large. Load diff
+489
View File
@@ -0,0 +1,489 @@
// Copyright 2019 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A rectangle with rounded corners.
use core::f64::consts::{FRAC_PI_2, FRAC_PI_4};
use core::ops::{Add, Sub};
use crate::{Arc, PathEl, Point, Rect, RoundedRectRadii, Shape, Size, Vec2, arc::ArcAppendIter};
#[allow(unused_imports)] // This is unused in later versions of Rust because of additions to core::f32
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A rectangle with rounded corners.
///
/// By construction the rounded rectangle will have
/// non-negative dimensions and radii clamped to half size of the rect.
/// The rounded rectangle can have different radii for each corner.
///
/// The easiest way to create a `RoundedRect` is often to create a [`Rect`],
/// and then call [`to_rounded_rect`].
///
/// ```
/// use kurbo::{RoundedRect, RoundedRectRadii};
///
/// // Create a rounded rectangle with a single radius for all corners:
/// RoundedRect::new(0.0, 0.0, 10.0, 10.0, 5.0);
///
/// // Or, specify different radii for each corner, clockwise from the top-left:
/// RoundedRect::new(0.0, 0.0, 10.0, 10.0, (1.0, 2.0, 3.0, 4.0));
/// ```
///
/// [`to_rounded_rect`]: Rect::to_rounded_rect
#[derive(Clone, Copy, Default, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RoundedRect {
/// Coordinates of the rectangle.
rect: Rect,
/// Radius of all four corners.
radii: RoundedRectRadii,
}
impl RoundedRect {
/// A new rectangle from minimum and maximum coordinates.
///
/// The result will have non-negative width, height and radii.
#[inline]
pub fn new(
x0: f64,
y0: f64,
x1: f64,
y1: f64,
radii: impl Into<RoundedRectRadii>,
) -> RoundedRect {
RoundedRect::from_rect(Rect::new(x0, y0, x1, y1), radii)
}
/// A new rounded rectangle from a rectangle and corner radii.
///
/// The result will have non-negative width, height and radii.
///
/// See also [`Rect::to_rounded_rect`], which offers the same utility.
#[inline]
pub fn from_rect(rect: Rect, radii: impl Into<RoundedRectRadii>) -> RoundedRect {
let rect = rect.abs();
let shortest_side_length = (rect.width()).min(rect.height());
let radii = radii.into().abs().clamp(shortest_side_length / 2.0);
RoundedRect { rect, radii }
}
/// A new rectangle from two [`Point`]s.
///
/// The result will have non-negative width, height and radius.
#[inline]
pub fn from_points(
p0: impl Into<Point>,
p1: impl Into<Point>,
radii: impl Into<RoundedRectRadii>,
) -> RoundedRect {
Rect::from_points(p0, p1).to_rounded_rect(radii)
}
/// A new rectangle from origin and size.
///
/// The result will have non-negative width, height and radius.
#[inline]
pub fn from_origin_size(
origin: impl Into<Point>,
size: impl Into<Size>,
radii: impl Into<RoundedRectRadii>,
) -> RoundedRect {
Rect::from_origin_size(origin, size).to_rounded_rect(radii)
}
/// The width of the rectangle.
#[inline]
pub const fn width(&self) -> f64 {
self.rect.width()
}
/// The height of the rectangle.
#[inline]
pub const fn height(&self) -> f64 {
self.rect.height()
}
/// Radii of the rounded corners.
#[inline(always)]
pub const fn radii(&self) -> RoundedRectRadii {
self.radii
}
/// The (non-rounded) rectangle.
#[inline(always)]
pub const fn rect(&self) -> Rect {
self.rect
}
/// The origin of the rectangle.
///
/// This is the top left corner in a y-down space.
#[inline(always)]
pub const fn origin(&self) -> Point {
self.rect.origin()
}
/// The center point of the rectangle.
#[inline]
pub const fn center(&self) -> Point {
self.rect.center()
}
/// Is this rounded rectangle finite?
#[inline]
pub const fn is_finite(&self) -> bool {
self.rect.is_finite() && self.radii.is_finite()
}
/// Is this rounded rectangle NaN?
#[inline]
pub const fn is_nan(&self) -> bool {
self.rect.is_nan() || self.radii.is_nan()
}
}
#[doc(hidden)]
pub struct RoundedRectPathIter {
idx: usize,
rect: RectPathIter,
arcs: [ArcAppendIter; 4],
}
impl Shape for RoundedRect {
type PathElementsIter<'iter> = RoundedRectPathIter;
fn path_elements(&self, tolerance: f64) -> RoundedRectPathIter {
let radii = self.radii();
let build_arc_iter = |i, center, ellipse_radii| {
let arc = Arc {
center,
radii: ellipse_radii,
start_angle: FRAC_PI_2 * i as f64,
sweep_angle: FRAC_PI_2,
x_rotation: 0.0,
};
arc.append_iter(tolerance)
};
// Note: order follows the rectangle path iterator.
let arcs = [
build_arc_iter(
2,
Point {
x: self.rect.x0 + radii.top_left,
y: self.rect.y0 + radii.top_left,
},
Vec2 {
x: radii.top_left,
y: radii.top_left,
},
),
build_arc_iter(
3,
Point {
x: self.rect.x1 - radii.top_right,
y: self.rect.y0 + radii.top_right,
},
Vec2 {
x: radii.top_right,
y: radii.top_right,
},
),
build_arc_iter(
0,
Point {
x: self.rect.x1 - radii.bottom_right,
y: self.rect.y1 - radii.bottom_right,
},
Vec2 {
x: radii.bottom_right,
y: radii.bottom_right,
},
),
build_arc_iter(
1,
Point {
x: self.rect.x0 + radii.bottom_left,
y: self.rect.y1 - radii.bottom_left,
},
Vec2 {
x: radii.bottom_left,
y: radii.bottom_left,
},
),
];
let rect = RectPathIter {
rect: self.rect,
ix: 0,
radii,
};
RoundedRectPathIter { idx: 0, rect, arcs }
}
#[inline]
fn area(&self) -> f64 {
// A corner is a quarter-circle, i.e.
// .............#
// . ######
// . #########
// . ###########
// . ############
// .#############
// ##############
// |-----r------|
// For each corner, we need to subtract the square that bounds this
// quarter-circle, and add back in the area of quarter circle.
let radii = self.radii();
// Start with the area of the bounding rectangle. For each corner,
// subtract the area of the corner under the quarter-circle, and add
// back the area of the quarter-circle.
self.rect.area()
+ [
radii.top_left,
radii.top_right,
radii.bottom_right,
radii.bottom_left,
]
.iter()
.map(|radius| (FRAC_PI_4 - 1.0) * radius * radius)
.sum::<f64>()
}
#[inline]
fn perimeter(&self, _accuracy: f64) -> f64 {
// A corner is a quarter-circle, i.e.
// .............#
// . #
// . #
// . #
// . #
// .#
// #
// |-----r------|
// If we start with the bounding rectangle, then subtract 2r (the
// straight edge outside the circle) and add 1/4 * pi * (2r) (the
// perimeter of the quarter-circle) for each corner with radius r, we
// get the perimeter of the shape.
let radii = self.radii();
// Start with the full perimeter. For each corner, subtract the
// border surrounding the rounded corner and add the quarter-circle
// perimeter.
self.rect.perimeter(1.0)
+ ([
radii.top_left,
radii.top_right,
radii.bottom_right,
radii.bottom_left,
])
.iter()
.map(|radius| (-2.0 + FRAC_PI_2) * radius)
.sum::<f64>()
}
#[inline]
fn winding(&self, mut pt: Point) -> i32 {
let center = self.center();
// 1. Translate the point relative to the center of the rectangle.
pt.x -= center.x;
pt.y -= center.y;
// 2. Pick a radius value to use based on which quadrant the point is
// in.
let radius = {
/// Calculates `if !cond { a } else { b }`.
///
/// This function is theoretically pretty nonsensical to have, as the compiler should
/// pretty trivially be able to compile both this function and the explicit
/// `if`-statement equivalent to the same thing. However, for some reason, writing
/// these bit operations explicitly causes the compiler to be better about prefetching
/// the rounded rect data.
///
/// See <https://github.com/linebender/kurbo/pull/534> for more.
#[inline(always)]
fn select(a: f64, b: f64, cond: bool) -> f64 {
let mask = (cond as u64).wrapping_neg(); // 0 or !0
f64::from_bits((a.to_bits() & !mask) | (b.to_bits() & mask))
}
let radii = self.radii();
let radius_top = select(radii.top_left, radii.top_right, pt.x >= 0.);
let radius_bottom = select(radii.bottom_left, radii.bottom_right, pt.x >= 0.);
select(radius_top, radius_bottom, pt.y >= 0.)
};
// 3. This is the width and height of a rectangle with one corner at
// the center of the rounded rectangle, and another corner at the
// center of the relevant corner circle.
let inside_half_width = (self.width() / 2.0 - radius).max(0.0);
let inside_half_height = (self.height() / 2.0 - radius).max(0.0);
// 4. Three things are happening here.
//
// First, the x- and y-values are being reflected into the positive
// (bottom-right quadrant). The radius has already been determined,
// so it doesn't matter what quadrant is used.
//
// After reflecting, the points are clamped so that their x- and y-
// values can't be lower than the x- and y- values of the center of
// the corner circle, and the coordinate system is transformed
// again, putting (0, 0) at the center of the corner circle.
let px = (pt.x.abs() - inside_half_width).max(0.0);
let py = (pt.y.abs() - inside_half_height).max(0.0);
// 5. The transforms above clamp all input points such that they will
// be inside the rounded rectangle if the corresponding output point
// (px, py) is inside a circle centered around the origin with the
// given radius.
let inside = px * px + py * py <= radius * radius;
if inside { 1 } else { 0 }
}
#[inline]
fn bounding_box(&self) -> Rect {
self.rect.bounding_box()
}
#[inline(always)]
fn as_rounded_rect(&self) -> Option<RoundedRect> {
Some(*self)
}
}
struct RectPathIter {
rect: Rect,
radii: RoundedRectRadii,
ix: usize,
}
// This is clockwise in a y-down coordinate system for positive area.
impl Iterator for RectPathIter {
type Item = PathEl;
fn next(&mut self) -> Option<PathEl> {
self.ix += 1;
match self.ix {
1 => Some(PathEl::MoveTo(Point::new(
self.rect.x0,
self.rect.y0 + self.radii.top_left,
))),
2 => Some(PathEl::LineTo(Point::new(
self.rect.x1 - self.radii.top_right,
self.rect.y0,
))),
3 => Some(PathEl::LineTo(Point::new(
self.rect.x1,
self.rect.y1 - self.radii.bottom_right,
))),
4 => Some(PathEl::LineTo(Point::new(
self.rect.x0 + self.radii.bottom_left,
self.rect.y1,
))),
5 => Some(PathEl::ClosePath),
_ => None,
}
}
}
// This is clockwise in a y-down coordinate system for positive area.
impl Iterator for RoundedRectPathIter {
type Item = PathEl;
fn next(&mut self) -> Option<PathEl> {
if self.idx > 4 {
return None;
}
// Iterate between rectangle and arc iterators.
// Rect iterator will start and end the path.
// Initial point set by the rect iterator
if self.idx == 0 {
self.idx += 1;
return self.rect.next();
}
// Generate the arc curve elements.
// If we reached the end of the arc, add a line towards next arc (rect iterator).
match self.arcs[self.idx - 1].next() {
Some(elem) => Some(elem),
None => {
self.idx += 1;
self.rect.next()
}
}
}
}
impl Add<Vec2> for RoundedRect {
type Output = RoundedRect;
#[inline]
fn add(self, v: Vec2) -> RoundedRect {
RoundedRect::from_rect(self.rect + v, self.radii)
}
}
impl Sub<Vec2> for RoundedRect {
type Output = RoundedRect;
#[inline]
fn sub(self, v: Vec2) -> RoundedRect {
RoundedRect::from_rect(self.rect - v, self.radii)
}
}
#[cfg(test)]
mod tests {
use crate::{Circle, Point, Rect, RoundedRect, Shape};
#[test]
fn area() {
let epsilon = 1e-9;
// Extremum: 0.0 radius corner -> rectangle
let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
let rounded_rect = RoundedRect::new(0.0, 0.0, 100.0, 100.0, 0.0);
assert!((rect.area() - rounded_rect.area()).abs() < epsilon);
// Extremum: half-size radius corner -> circle
let circle = Circle::new((0.0, 0.0), 50.0);
let rounded_rect = RoundedRect::new(0.0, 0.0, 100.0, 100.0, 50.0);
assert!((circle.area() - rounded_rect.area()).abs() < epsilon);
}
#[test]
fn winding() {
let rect = RoundedRect::new(-5.0, -5.0, 10.0, 20.0, (5.0, 5.0, 5.0, 0.0));
assert_eq!(rect.winding(Point::new(0.0, 0.0)), 1);
assert_eq!(rect.winding(Point::new(-5.0, 0.0)), 1); // left edge
assert_eq!(rect.winding(Point::new(0.0, 20.0)), 1); // bottom edge
assert_eq!(rect.winding(Point::new(10.0, 20.0)), 0); // bottom-right corner
assert_eq!(rect.winding(Point::new(-5.0, 20.0)), 1); // bottom-left corner (has a radius of 0)
assert_eq!(rect.winding(Point::new(-10.0, 0.0)), 0);
let rect = RoundedRect::new(-10.0, -20.0, 10.0, 20.0, 0.0); // rectangle
assert_eq!(rect.winding(Point::new(10.0, 20.0)), 1); // bottom-right corner
}
#[test]
fn bez_conversion() {
let rect = RoundedRect::new(-5.0, -5.0, 10.0, 20.0, 5.0);
let p = rect.to_path(1e-9);
// Note: could be more systematic about tolerance tightness.
let epsilon = 1e-7;
assert!((rect.area() - p.area()).abs() < epsilon);
assert_eq!(p.winding(Point::new(0.0, 0.0)), 1);
}
}
+124
View File
@@ -0,0 +1,124 @@
// Copyright 2021 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A description of the radii for each corner of a rounded rectangle.
use core::convert::From;
#[allow(unused_imports)] // This is unused in later versions of Rust because of additions to core::f32
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// Radii for each corner of a rounded rectangle.
///
/// The use of `top` as in `top_left` assumes a y-down coordinate space. Piet
/// (and Druid by extension) uses a y-down coordinate space, but Kurbo also
/// supports a y-up coordinate space, in which case `top_left` would actually
/// refer to the bottom-left corner, and vice versa. Top may not always
/// actually be the top, but `top` corners will always have a smaller y-value
/// than `bottom` corners.
#[derive(Clone, Copy, Default, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RoundedRectRadii {
/// The radius of the top-left corner.
pub top_left: f64,
/// The radius of the top-right corner.
pub top_right: f64,
/// The radius of the bottom-right corner.
pub bottom_right: f64,
/// The radius of the bottom-left corner.
pub bottom_left: f64,
}
impl RoundedRectRadii {
/// Create a new `RoundedRectRadii`. This function takes radius values for
/// the four corners. The argument order is `top_left`, `top_right`,
/// `bottom_right`, `bottom_left`, or clockwise starting from `top_left`.
#[inline(always)]
pub const fn new(top_left: f64, top_right: f64, bottom_right: f64, bottom_left: f64) -> Self {
RoundedRectRadii {
top_left,
top_right,
bottom_right,
bottom_left,
}
}
/// Create a new `RoundedRectRadii` from a single radius. The `radius`
/// argument will be set as the radius for all four corners.
#[inline(always)]
pub const fn from_single_radius(radius: f64) -> Self {
RoundedRectRadii {
top_left: radius,
top_right: radius,
bottom_right: radius,
bottom_left: radius,
}
}
/// Takes the absolute value of all corner radii.
pub const fn abs(&self) -> Self {
RoundedRectRadii::new(
self.top_left.abs(),
self.top_right.abs(),
self.bottom_right.abs(),
self.bottom_left.abs(),
)
}
/// For each corner, takes the min of that corner's radius and `max`.
pub const fn clamp(&self, max: f64) -> Self {
RoundedRectRadii::new(
self.top_left.min(max),
self.top_right.min(max),
self.bottom_right.min(max),
self.bottom_left.min(max),
)
}
/// Returns `true` if all radius values are finite.
pub const fn is_finite(&self) -> bool {
self.top_left.is_finite()
&& self.top_right.is_finite()
&& self.bottom_right.is_finite()
&& self.bottom_left.is_finite()
}
/// Returns `true` if any corner radius value is NaN.
pub const fn is_nan(&self) -> bool {
self.top_left.is_nan()
|| self.top_right.is_nan()
|| self.bottom_right.is_nan()
|| self.bottom_left.is_nan()
}
/// If all radii are equal, returns the value of the radii. Otherwise,
/// returns `None`.
pub const fn as_single_radius(&self) -> Option<f64> {
let epsilon = 1e-9;
if (self.top_left - self.top_right).abs() < epsilon
&& (self.top_right - self.bottom_right).abs() < epsilon
&& (self.bottom_right - self.bottom_left).abs() < epsilon
{
Some(self.top_left)
} else {
None
}
}
}
impl From<f64> for RoundedRectRadii {
#[inline(always)]
fn from(radius: f64) -> Self {
RoundedRectRadii::from_single_radius(radius)
}
}
impl From<(f64, f64, f64, f64)> for RoundedRectRadii {
#[inline(always)]
fn from(radii: (f64, f64, f64, f64)) -> Self {
RoundedRectRadii::new(radii.0, radii.1, radii.2, radii.3)
}
}
+229
View File
@@ -0,0 +1,229 @@
// Copyright 2019 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A generic trait for shapes.
use crate::{BezPath, Circle, Line, PathEl, Point, Rect, RoundedRect, Segments, segments};
/// A generic trait for open and closed shapes.
///
/// This trait provides conversion from shapes to [`BezPath`]s, as well as
/// general geometry functionality like computing [`area`], [`bounding_box`]es,
/// and [`winding`] number.
///
/// [`area`]: Shape::area
/// [`bounding_box`]: Shape::bounding_box
/// [`winding`]: Shape::winding
pub trait Shape {
/// The iterator returned by the [`path_elements`] method.
///
/// [`path_elements`]: Shape::path_elements
type PathElementsIter<'iter>: Iterator<Item = PathEl> + 'iter
where
Self: 'iter;
/// Returns an iterator over this shape expressed as [`PathEl`]s;
/// that is, as Bézier path _elements_.
///
/// All shapes can be represented as Béziers, but in many situations
/// (such as when interfacing with a platform drawing API) there are more
/// efficient native types for specific concrete shapes. In this case,
/// the user should exhaust the `as_` methods ([`as_rect`], [`as_line`], etc)
/// before converting to a [`BezPath`], as those are likely to be more
/// efficient.
///
/// In many cases, shapes are able to iterate their elements without
/// allocating; however creating a [`BezPath`] object always allocates.
/// If you need an owned [`BezPath`] you can use [`to_path`] instead.
///
/// # Tolerance
///
/// The `tolerance` parameter controls the accuracy of
/// conversion of geometric primitives to Bézier curves, as
/// curves such as circles cannot be represented exactly but
/// only approximated. For drawing as in UI elements, a value
/// of 0.1 is appropriate, as it is unlikely to be visible to
/// the eye. For scientific applications, a smaller value
/// might be appropriate. Note that in general the number of
/// cubic Bézier segments scales as `tolerance ^ (-1/6)`.
///
/// [`as_rect`]: Shape::as_rect
/// [`as_line`]: Shape::as_line
/// [`to_path`]: Shape::to_path
fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_>;
/// Convert to a Bézier path.
///
/// This always allocates. It is appropriate when both the source
/// shape and the resulting path are to be retained.
///
/// If you only need to iterate the elements (such as to convert them to
/// drawing commands for a given 2D graphics API) you should prefer
/// [`path_elements`], which can avoid allocating where possible.
///
/// The `tolerance` parameter is the same as for [`path_elements`].
///
/// [`path_elements`]: Shape::path_elements
fn to_path(&self, tolerance: f64) -> BezPath {
self.path_elements(tolerance).collect()
}
/// Convert into a Bézier path.
///
/// This allocates in the general case, but is zero-cost if the
/// shape is already a [`BezPath`].
///
/// The `tolerance` parameter is the same as for [`path_elements()`].
///
/// [`path_elements()`]: Shape::path_elements
fn into_path(self, tolerance: f64) -> BezPath
where
Self: Sized,
{
self.to_path(tolerance)
}
/// Returns an iterator over this shape expressed as Bézier path
/// _segments_ ([`PathSeg`]s).
///
/// The allocation behaviour and `tolerance` parameter are the
/// same as for [`path_elements()`]
///
/// [`PathSeg`]: crate::PathSeg
/// [`path_elements()`]: Shape::path_elements
fn path_segments(&self, tolerance: f64) -> Segments<Self::PathElementsIter<'_>> {
segments(self.path_elements(tolerance))
}
/// Signed area.
///
/// This method only produces meaningful results with closed shapes.
///
/// The convention for positive area is that y increases when x is
/// positive. Thus, it is clockwise when down is increasing y (the
/// usual convention for graphics), and anticlockwise when
/// up is increasing y (the usual convention for math).
fn area(&self) -> f64;
/// Total length of perimeter.
//FIXME: document the accuracy param
fn perimeter(&self, accuracy: f64) -> f64;
/// The [winding number] of a point.
///
/// This method only produces meaningful results with closed shapes.
///
/// The sign of the winding number is consistent with that of [`area`],
/// meaning it is +1 when the point is inside a positive area shape
/// and -1 when it is inside a negative area shape. Of course, greater
/// magnitude values are also possible when the shape is more complex.
///
/// [`area`]: Shape::area
/// [winding number]: https://mathworld.wolfram.com/ContourWindingNumber.html
fn winding(&self, pt: Point) -> i32;
/// Returns `true` if the [`Point`] is inside this shape.
///
/// This is only meaningful for closed shapes. Some shapes may have specialized
/// implementations of this function or of [`winding`] determination.
///
/// The default implementation uses the non-zero winding rule.
///
/// To determine containment using the even-odd winding rule, check the
/// [`winding`] directly.
///
/// [`winding`]: Self::winding
fn contains(&self, pt: Point) -> bool {
self.winding(pt) != 0
}
/// The smallest rectangle that encloses the shape.
fn bounding_box(&self) -> Rect;
/// If the shape is a line, make it available.
fn as_line(&self) -> Option<Line> {
None
}
/// If the shape is a rectangle, make it available.
fn as_rect(&self) -> Option<Rect> {
None
}
/// If the shape is a rounded rectangle, make it available.
fn as_rounded_rect(&self) -> Option<RoundedRect> {
None
}
/// If the shape is a circle, make it available.
fn as_circle(&self) -> Option<Circle> {
None
}
/// If the shape is stored as a slice of path elements, make
/// that available.
///
/// Note: when GAT's land, a method like `path_elements` would be
/// able to iterate through the slice with no extra allocation,
/// without making any assumption that storage is contiguous.
fn as_path_slice(&self) -> Option<&[PathEl]> {
None
}
}
/// Blanket implementation so `impl Shape` will accept owned or reference.
impl<'a, T: Shape> Shape for &'a T {
type PathElementsIter<'iter>
= T::PathElementsIter<'iter>
where
T: 'iter,
'a: 'iter;
fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_> {
(*self).path_elements(tolerance)
}
fn to_path(&self, tolerance: f64) -> BezPath {
(*self).to_path(tolerance)
}
fn path_segments(&self, tolerance: f64) -> Segments<Self::PathElementsIter<'_>> {
(*self).path_segments(tolerance)
}
fn area(&self) -> f64 {
(*self).area()
}
fn perimeter(&self, accuracy: f64) -> f64 {
(*self).perimeter(accuracy)
}
fn winding(&self, pt: Point) -> i32 {
(*self).winding(pt)
}
fn bounding_box(&self) -> Rect {
(*self).bounding_box()
}
fn as_line(&self) -> Option<Line> {
(*self).as_line()
}
fn as_rect(&self) -> Option<Rect> {
(*self).as_rect()
}
fn as_rounded_rect(&self) -> Option<RoundedRect> {
(*self).as_rounded_rect()
}
fn as_circle(&self) -> Option<Circle> {
(*self).as_circle()
}
fn as_path_slice(&self) -> Option<&[PathEl]> {
(*self).as_path_slice()
}
}
+396
View File
@@ -0,0 +1,396 @@
// Copyright 2022 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Simplification of a Bézier path.
//!
//! This module is currently experimental.
//!
//! The methods in this module create a `SimplifyBezPath` object, which can then
//! be fed to [`fit_to_bezpath`] or [`fit_to_bezpath_opt`] depending on the degree
//! of optimization desired.
//!
//! The implementation uses a number of techniques to achieve high performance and
//! accuracy. The parameter (generally written `t`) evenly divides the curve segments
//! in the original, so sampling can be done in constant time. The derivatives are
//! computed analytically, as that is straightforward with Béziers.
//!
//! The areas and moments are computed analytically (using Green's theorem), and
//! the prefix sum is stored. Thus, it is possible to analytically compute the area
//! and moment of any subdivision of the curve, also in constant time, by taking
//! the difference of two stored prefix sum values, then fixing up the subsegments.
//!
//! A current limitation (hoped to be addressed in the future) is that non-regular
//! cubic segments may have tangents computed incorrectly. This can easily happen,
//! for example when setting a control point equal to an endpoint.
//!
//! In addition, this method does not report corners (adjoining segments where the
//! tangents are not continuous). It is not clear whether it's best to handle such
//! cases here, or in client code.
//!
//! [`fit_to_bezpath`]: crate::fit_to_bezpath
//! [`fit_to_bezpath_opt`]: crate::fit_to_bezpath_opt
use alloc::vec::Vec;
use core::ops::Range;
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
use crate::{
BezPath, CubicBez, CurveFitSample, Line, ParamCurve, ParamCurveDeriv, ParamCurveFit, PathEl,
PathSeg, Point, QuadBez, Vec2, fit_to_bezpath, fit_to_bezpath_opt,
};
/// A Bézier path which has been prepared for simplification.
///
/// See the [module-level documentation] for a bit more discussion of the approach,
/// and how this struct is to be used.
///
/// [module-level documentation]: crate::simplify
pub struct SimplifyBezPath(Vec<SimplifyCubic>);
struct SimplifyCubic {
c: CubicBez,
// The inclusive prefix sum of the moment integrals
moments: (f64, f64, f64),
}
/// Options for simplifying paths.
pub struct SimplifyOptions {
/// The tangent of the minimum angle below which the path is considered smooth.
angle_thresh: f64,
opt_level: SimplifyOptLevel,
}
/// Optimization level for simplification.
pub enum SimplifyOptLevel {
/// Subdivide; faster but not as optimized results.
Subdivide,
/// Optimize subdivision points.
Optimize,
}
impl Default for SimplifyOptions {
fn default() -> Self {
let opt_level = SimplifyOptLevel::Subdivide;
SimplifyOptions {
angle_thresh: 1e-3,
opt_level,
}
}
}
#[doc(hidden)]
/// Compute moment integrals.
///
/// This is exposed for testing purposes but is an internal detail. We can
/// add to the public, documented interface if there is a use case.
pub fn moment_integrals(c: CubicBez) -> (f64, f64, f64) {
let (x0, y0) = (c.p0.x, c.p0.y);
let (x1, y1) = (c.p1.x - x0, c.p1.y - y0);
let (x2, y2) = (c.p2.x - x0, c.p2.y - y0);
let (x3, y3) = (c.p3.x - x0, c.p3.y - y0);
let r0 = 3. * x1;
let r1 = 3. * y1;
let r2 = x2 * y3;
let r3 = x3 * y2;
let r4 = x3 * y3;
let r5 = 27. * y1;
let r6 = x1 * x2;
let r7 = 27. * y2;
let r8 = 45. * r2;
let r9 = 18. * x3;
let r10 = x1 * y1;
let r11 = 30. * x1;
let r12 = 45. * x3;
let r13 = x2 * y1;
let r14 = 45. * r3;
let r15 = x1.powi(2);
let r16 = 18. * y3;
let r17 = x2.powi(2);
let r18 = 45. * y3;
let r19 = x3.powi(2);
let r20 = 30. * y1;
let r21 = y2.powi(2);
let r22 = y3.powi(2);
let r23 = y1.powi(2);
let a = -r0 * y2 - r0 * y3 + r1 * x2 + r1 * x3 - 6. * r2 + 6. * r3 + 10. * r4;
// Scale and add chord
let lift = x3 * y0;
let area = a * 0.05 + lift;
let x = r10 * r9 - r11 * r4 + r12 * r13 + r14 * x2 - r15 * r16 - r15 * r7 - r17 * r18
+ r17 * r5
+ r19 * r20
+ 105. * r19 * y2
+ 280. * r19 * y3
- 105. * r2 * x3
+ r5 * r6
- r6 * r7
- r8 * x1;
let y = -r10 * r16 - r10 * r7 - r11 * r22 + r12 * r21 + r13 * r7 + r14 * y1 - r18 * x1 * y2
+ r20 * r4
- 27. * r21 * x1
- 105. * r22 * x2
+ 140. * r22 * x3
+ r23 * r9
+ 27. * r23 * x2
+ 105. * r3 * y3
- r8 * y2;
let mx = x * (1. / 840.) + x0 * area + 0.5 * x3 * lift;
let my = y * (1. / 420.) + y0 * a * 0.1 + y0 * lift;
(area, mx, my)
}
impl SimplifyBezPath {
/// Set up a new Bézier path for simplification.
///
/// Currently this is not dealing with discontinuities at all, but it
/// could be extended to do so.
pub fn new(path: impl IntoIterator<Item = PathEl>) -> Self {
let (mut a, mut x, mut y) = (0.0, 0.0, 0.0);
let els = crate::segments(path)
.map(|seg| {
let c = seg.to_cubic();
let (ai, xi, yi) = moment_integrals(c);
a += ai;
x += xi;
y += yi;
SimplifyCubic {
c,
moments: (a, x, y),
}
})
.collect();
SimplifyBezPath(els)
}
/// Resolve a `t` value to a cubic.
///
/// Also return the resulting `t` value for the selected cubic.
fn scale(&self, t: f64) -> (usize, f64) {
let t_scale = t * self.0.len() as f64;
let t_floor = t_scale.floor();
(t_floor as usize, t_scale - t_floor)
}
fn moment_integrals(&self, i: usize, range: Range<f64>) -> (f64, f64, f64) {
if range.end == range.start {
(0.0, 0.0, 0.0)
} else {
moment_integrals(self.0[i].c.subsegment(range))
}
}
}
impl ParamCurveFit for SimplifyBezPath {
fn sample_pt_deriv(&self, t: f64) -> (Point, Vec2) {
let (mut i, mut t0) = self.scale(t);
let n = self.0.len();
if i == n {
i -= 1;
t0 = 1.0;
}
let c = self.0[i].c;
(c.eval(t0), c.deriv().eval(t0).to_vec2() * n as f64)
}
fn sample_pt_tangent(&self, t: f64, _: f64) -> CurveFitSample {
let (mut i, mut t0) = self.scale(t);
if i == self.0.len() {
i -= 1;
t0 = 1.0;
}
let c = self.0[i].c;
let p = c.eval(t0);
let tangent = c.deriv().eval(t0).to_vec2();
CurveFitSample { p, tangent }
}
// We could use the default implementation, but provide our own, mostly
// because it is possible to efficiently provide an analytically accurate
// answer.
fn moment_integrals(&self, range: Range<f64>) -> (f64, f64, f64) {
let (i0, t0) = self.scale(range.start);
let (i1, t1) = self.scale(range.end);
if i0 == i1 {
self.moment_integrals(i0, t0..t1)
} else {
let (a0, x0, y0) = self.moment_integrals(i0, t0..1.0);
let (a1, x1, y1) = self.moment_integrals(i1, 0.0..t1);
let (mut a, mut x, mut y) = (a0 + a1, x0 + x1, y0 + y1);
if i1 > i0 + 1 {
let (a2, x2, y2) = self.0[i0].moments;
let (a3, x3, y3) = self.0[i1 - 1].moments;
a += a3 - a2;
x += x3 - x2;
y += y3 - y2;
}
(a, x, y)
}
}
fn break_cusp(&self, _: Range<f64>) -> Option<f64> {
None
}
}
#[derive(Default)]
struct SimplifyState {
queue: BezPath,
result: BezPath,
needs_moveto: bool,
}
impl SimplifyState {
fn add_seg(&mut self, seg: PathSeg) {
if self.queue.is_empty() {
self.queue.move_to(seg.start());
}
match seg {
PathSeg::Line(l) => self.queue.line_to(l.p1),
PathSeg::Quad(q) => self.queue.quad_to(q.p1, q.p2),
PathSeg::Cubic(c) => self.queue.curve_to(c.p1, c.p2, c.p3),
}
}
fn flush(&mut self, accuracy: f64, options: &SimplifyOptions) {
if self.queue.is_empty() {
return;
}
if self.queue.elements().len() == 2 {
// Queue is just one segment (count is moveto + primitive)
// Just output the segment, no simplification is possible.
self.result
.extend(self.queue.iter().skip(!self.needs_moveto as usize));
} else {
let s = SimplifyBezPath::new(&self.queue);
let b = match options.opt_level {
SimplifyOptLevel::Subdivide => fit_to_bezpath(&s, accuracy),
SimplifyOptLevel::Optimize => fit_to_bezpath_opt(&s, accuracy),
};
self.result
.extend(b.iter().skip(!self.needs_moveto as usize));
}
self.needs_moveto = false;
self.queue.truncate(0);
}
}
/// Simplify a Bézier path.
///
/// This function simplifies an arbitrary Bézier path; it is designed to handle
/// multiple subpaths and also corners.
///
/// The underlying curve-fitting approach works best if the source path is very
/// smooth. If it contains higher frequency noise, then results may be poor, as
/// the resulting curve matches the original with G1 continuity at each subdivision
/// point, and also preserves the area. For such inputs, consider some form of
/// smoothing or low-pass filtering before simplification. In particular, if the
/// input is derived from a sequence of points, consider fitting a smooth spline.
///
/// We may add such capabilities in the future, possibly as opt-in smoothing
/// specified through the options.
pub fn simplify_bezpath(
path: impl IntoIterator<Item = PathEl>,
accuracy: f64,
options: &SimplifyOptions,
) -> BezPath {
let mut last_pt = None;
let mut last_seg: Option<PathSeg> = None;
let mut state = SimplifyState::default();
for el in path {
let mut this_seg = None;
match el {
PathEl::MoveTo(p) => {
state.flush(accuracy, options);
state.needs_moveto = true;
last_pt = Some(p);
}
PathEl::LineTo(p) => {
let last = last_pt.unwrap();
if last == p {
continue;
}
this_seg = Some(PathSeg::Line(Line::new(last, p)));
}
PathEl::QuadTo(p1, p2) => {
let last = last_pt.unwrap();
if last == p1 && last == p2 {
continue;
}
this_seg = Some(PathSeg::Quad(QuadBez::new(last, p1, p2)));
}
PathEl::CurveTo(p1, p2, p3) => {
let last = last_pt.unwrap();
if last == p1 && last == p2 && last == p3 {
continue;
}
this_seg = Some(PathSeg::Cubic(CubicBez::new(last, p1, p2, p3)));
}
PathEl::ClosePath => {
state.flush(accuracy, options);
state.result.close_path();
state.needs_moveto = true;
last_seg = None;
continue;
}
}
if let Some(seg) = this_seg {
if let Some(last) = last_seg {
let last_tan = last.tangents().1;
let this_tan = seg.tangents().0;
if last_tan.cross(this_tan).abs()
> last_tan.dot(this_tan).abs() * options.angle_thresh
{
state.flush(accuracy, options);
}
}
last_pt = Some(seg.end());
state.add_seg(seg);
}
last_seg = this_seg;
}
state.flush(accuracy, options);
state.result
}
impl SimplifyOptions {
/// Set optimization level.
pub fn opt_level(mut self, level: SimplifyOptLevel) -> Self {
self.opt_level = level;
self
}
/// Set angle threshold.
///
/// The tangent of the angle below which joins are considered smooth and
/// not corners. The default is approximately 1 milliradian.
pub fn angle_thresh(mut self, thresh: f64) -> Self {
self.angle_thresh = thresh;
self
}
}
#[cfg(test)]
mod tests {
use crate::BezPath;
use super::{SimplifyOptions, simplify_bezpath};
#[test]
fn simplify_lines_corner() {
// Make sure lines are passed through unchanged if there is a corner.
let mut path = BezPath::new();
path.move_to((1., 2.));
path.line_to((3., 4.));
path.line_to((10., 5.));
let options = SimplifyOptions::default();
let simplified = simplify_bezpath(path.clone(), 1.0, &options);
assert_eq!(path, simplified);
}
}
+492
View File
@@ -0,0 +1,492 @@
// Copyright 2019 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A 2D size.
use core::fmt;
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
use crate::common::FloatExt;
use crate::{Axis, Rect, RoundedRect, RoundedRectRadii, Vec2};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A 2D size.
#[derive(Clone, Copy, Default, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Size {
/// The width.
pub width: f64,
/// The height.
pub height: f64,
}
impl Size {
/// A size with zero width or height.
pub const ZERO: Size = Size::new(0., 0.);
/// A size with width and height set to `f64::INFINITY`.
pub const INFINITY: Size = Size::new(f64::INFINITY, f64::INFINITY);
/// Create a new `Size` with the provided `width` and `height`.
#[inline(always)]
pub const fn new(width: f64, height: f64) -> Self {
Size { width, height }
}
/// Returns the max of `width` and `height`.
///
/// # Examples
///
/// ```
/// use kurbo::Size;
/// let size = Size::new(-10.5, 42.0);
/// assert_eq!(size.max_side(), 42.0);
/// ```
pub const fn max_side(self) -> f64 {
self.width.max(self.height)
}
/// Returns the min of `width` and `height`.
///
/// # Examples
///
/// ```
/// use kurbo::Size;
/// let size = Size::new(-10.5, 42.0);
/// assert_eq!(size.min_side(), -10.5);
/// ```
pub const fn min_side(self) -> f64 {
self.width.min(self.height)
}
/// The area covered by this size.
#[inline]
pub const fn area(self) -> f64 {
self.width * self.height
}
/// Whether this size has zero area.
#[doc(alias = "is_empty")]
#[inline]
pub const fn is_zero_area(self) -> bool {
self.area() == 0.0
}
/// Returns the component-wise minimum of `self` and `other`.
///
/// # Examples
///
/// ```
/// use kurbo::Size;
///
/// let this = Size::new(0., 100.);
/// let other = Size::new(10., 10.);
///
/// assert_eq!(this.min(other), Size::new(0., 10.));
/// ```
pub const fn min(self, other: Size) -> Self {
Size {
width: self.width.min(other.width),
height: self.height.min(other.height),
}
}
/// Returns the component-wise maximum of `self` and `other`.
///
/// # Examples
///
/// ```
/// use kurbo::Size;
///
/// let this = Size::new(0., 100.);
/// let other = Size::new(10., 10.);
///
/// assert_eq!(this.max(other), Size::new(10., 100.));
/// ```
pub const fn max(self, other: Size) -> Self {
Size {
width: self.width.max(other.width),
height: self.height.max(other.height),
}
}
/// Returns a new size bounded by `min` and `max.`
///
/// # Examples
///
/// ```
/// use kurbo::Size;
///
/// let this = Size::new(0., 100.);
/// let min = Size::new(10., 10.,);
/// let max = Size::new(50., 50.);
/// assert_eq!(this.clamp(min, max), Size::new(10., 50.))
/// ```
pub const fn clamp(self, min: Size, max: Size) -> Self {
self.max(min).min(max)
}
/// Convert this size into a [`Vec2`], with `width` mapped to `x` and `height`
/// mapped to `y`.
#[inline(always)]
pub const fn to_vec2(self) -> Vec2 {
Vec2::new(self.width, self.height)
}
/// Returns a new `Size`,
/// with `width` and `height` [rounded] to the nearest integer.
///
/// # Examples
///
/// ```
/// use kurbo::Size;
/// let size_pos = Size::new(3.3, 3.6).round();
/// assert_eq!(size_pos.width, 3.0);
/// assert_eq!(size_pos.height, 4.0);
/// let size_neg = Size::new(-3.3, -3.6).round();
/// assert_eq!(size_neg.width, -3.0);
/// assert_eq!(size_neg.height, -4.0);
/// ```
///
/// [rounded]: f64::round
#[inline]
pub fn round(self) -> Size {
Size::new(self.width.round(), self.height.round())
}
/// Returns a new `Size`,
/// with `width` and `height` [rounded up] to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Size;
/// let size_pos = Size::new(3.3, 3.6).ceil();
/// assert_eq!(size_pos.width, 4.0);
/// assert_eq!(size_pos.height, 4.0);
/// let size_neg = Size::new(-3.3, -3.6).ceil();
/// assert_eq!(size_neg.width, -3.0);
/// assert_eq!(size_neg.height, -3.0);
/// ```
///
/// [rounded up]: f64::ceil
#[inline]
pub fn ceil(self) -> Size {
Size::new(self.width.ceil(), self.height.ceil())
}
/// Returns a new `Size`,
/// with `width` and `height` [rounded down] to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Size;
/// let size_pos = Size::new(3.3, 3.6).floor();
/// assert_eq!(size_pos.width, 3.0);
/// assert_eq!(size_pos.height, 3.0);
/// let size_neg = Size::new(-3.3, -3.6).floor();
/// assert_eq!(size_neg.width, -4.0);
/// assert_eq!(size_neg.height, -4.0);
/// ```
///
/// [rounded down]: f64::floor
#[inline]
pub fn floor(self) -> Size {
Size::new(self.width.floor(), self.height.floor())
}
/// Returns a new `Size`,
/// with `width` and `height` [rounded away] from zero to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Size;
/// let size_pos = Size::new(3.3, 3.6).expand();
/// assert_eq!(size_pos.width, 4.0);
/// assert_eq!(size_pos.height, 4.0);
/// let size_neg = Size::new(-3.3, -3.6).expand();
/// assert_eq!(size_neg.width, -4.0);
/// assert_eq!(size_neg.height, -4.0);
/// ```
///
/// [rounded away]: FloatExt::expand
#[inline]
pub fn expand(self) -> Size {
Size::new(self.width.expand(), self.height.expand())
}
/// Returns a new `Size`,
/// with `width` and `height` [rounded towards] zero to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Size;
/// let size_pos = Size::new(3.3, 3.6).trunc();
/// assert_eq!(size_pos.width, 3.0);
/// assert_eq!(size_pos.height, 3.0);
/// let size_neg = Size::new(-3.3, -3.6).trunc();
/// assert_eq!(size_neg.width, -3.0);
/// assert_eq!(size_neg.height, -3.0);
/// ```
///
/// [rounded towards]: f64::trunc
#[inline]
pub fn trunc(self) -> Size {
Size::new(self.width.trunc(), self.height.trunc())
}
/// Returns the aspect ratio of a rectangle with this size.
///
/// The aspect ratio is the ratio of the width to the height.
///
/// If the height is `0`, the output will be `sign(self.width) * infinity`. If the width and
/// height are both `0`, then the output will be `NaN`.
#[inline]
pub const fn aspect_ratio_width(self) -> f64 {
// ratio is determined by width / height
// https://en.wikipedia.org/wiki/Aspect_ratio_(image)
// https://en.wikipedia.org/wiki/Ratio
self.width / self.height
}
/// Returns **the inverse** of the aspect ratio of a rectangle with this size.
///
/// Aspect ratios are usually defined as the ratio of the width to the height, but
/// this method incorrectly returns the ratio of height to width.
/// You should generally prefer [`aspect_ratio_width`](Self::aspect_ratio_width).
///
/// If the width is `0`, the output will be `sign(self.height) * infinity`. If the width and
/// height are both `0`, then the output will be `NaN`.
#[deprecated(
note = "You should use `aspect_ratio_width` instead, as this method returns a potentially unexpected value.",
since = "0.12.0"
)]
#[inline]
// TODO: When we remove this, we should also work out what to do with aspect_ratio_width
// The tentatitive plan is to rename `aspect_ratio_width` back to this name
pub const fn aspect_ratio(self) -> f64 {
self.height / self.width
}
/// Convert this `Size` into a [`Rect`] with origin `(0.0, 0.0)`.
#[inline(always)]
pub const fn to_rect(self) -> Rect {
Rect::new(0., 0., self.width, self.height)
}
/// Convert this `Size` into a [`RoundedRect`] with origin `(0.0, 0.0)` and
/// the provided corner radius.
#[inline]
pub fn to_rounded_rect(self, radii: impl Into<RoundedRectRadii>) -> RoundedRect {
self.to_rect().to_rounded_rect(radii)
}
/// Is this size [finite]?
///
/// [finite]: f64::is_finite
#[inline]
pub const fn is_finite(self) -> bool {
self.width.is_finite() && self.height.is_finite()
}
/// Is this size [NaN]?
///
/// [NaN]: f64::is_nan
#[inline]
pub const fn is_nan(self) -> bool {
self.width.is_nan() || self.height.is_nan()
}
/// Get the member matching the given axis.
#[inline]
pub const fn get_coord(self, axis: Axis) -> f64 {
match axis {
Axis::Horizontal => self.width,
Axis::Vertical => self.height,
}
}
/// Get a mutable reference to the member matching the given axis.
#[inline]
pub const fn get_coord_mut(&mut self, axis: Axis) -> &mut f64 {
match axis {
Axis::Horizontal => &mut self.width,
Axis::Vertical => &mut self.height,
}
}
/// Set the member matching the given axis to the given value.
#[inline]
pub const fn set_coord(&mut self, axis: Axis, value: f64) {
match axis {
Axis::Horizontal => self.width = value,
Axis::Vertical => self.height = value,
}
}
}
impl fmt::Debug for Size {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}W×{:?}H", self.width, self.height)
}
}
impl fmt::Display for Size {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "(")?;
fmt::Display::fmt(&self.width, formatter)?;
write!(formatter, "×")?;
fmt::Display::fmt(&self.height, formatter)?;
write!(formatter, ")")
}
}
impl MulAssign<f64> for Size {
#[inline]
fn mul_assign(&mut self, other: f64) {
*self = Size {
width: self.width * other,
height: self.height * other,
};
}
}
impl Mul<Size> for f64 {
type Output = Size;
#[inline]
fn mul(self, other: Size) -> Size {
other * self
}
}
impl Mul<f64> for Size {
type Output = Size;
#[inline]
fn mul(self, other: f64) -> Size {
Size {
width: self.width * other,
height: self.height * other,
}
}
}
impl DivAssign<f64> for Size {
#[inline]
fn div_assign(&mut self, other: f64) {
*self = Size {
width: self.width / other,
height: self.height / other,
};
}
}
impl Div<f64> for Size {
type Output = Size;
#[inline]
fn div(self, other: f64) -> Size {
Size {
width: self.width / other,
height: self.height / other,
}
}
}
impl Add<Size> for Size {
type Output = Size;
#[inline]
fn add(self, other: Size) -> Size {
Size {
width: self.width + other.width,
height: self.height + other.height,
}
}
}
impl AddAssign<Size> for Size {
#[inline]
fn add_assign(&mut self, other: Size) {
*self = *self + other;
}
}
impl Sub<Size> for Size {
type Output = Size;
#[inline]
fn sub(self, other: Size) -> Size {
Size {
width: self.width - other.width,
height: self.height - other.height,
}
}
}
impl SubAssign<Size> for Size {
#[inline]
fn sub_assign(&mut self, other: Size) {
*self = *self - other;
}
}
impl From<(f64, f64)> for Size {
#[inline(always)]
fn from(v: (f64, f64)) -> Size {
Size {
width: v.0,
height: v.1,
}
}
}
impl From<Size> for (f64, f64) {
#[inline(always)]
fn from(v: Size) -> (f64, f64) {
(v.width, v.height)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display() {
let s = Size::new(-0.12345, 9.87654);
assert_eq!(format!("{s}"), "(-0.12345×9.87654)");
let s = Size::new(-0.12345, 9.87654);
assert_eq!(format!("{s:+6.2}"), "( -0.12× +9.88)");
}
#[test]
#[expect(deprecated, reason = "Testing deprecated function.")]
fn aspect_ratio() {
let s = Size::new(1.0, 1.0);
assert!((s.aspect_ratio() - 1.0).abs() < 1e-6);
}
#[test]
fn aspect_ratio_width() {
let s = Size::new(1.0, 1.0);
assert!((s.aspect_ratio_width() - 1.0).abs() < 1e-6);
// 3:2 film (mm)
let s = Size::new(36.0, 24.0);
assert!((s.aspect_ratio_width() - 1.5).abs() < 1e-6);
// 4k screen
let s = Size::new(3840.0, 2160.0);
assert!((s.aspect_ratio_width() - (16. / 9.)).abs() < 1e-6);
}
}
+1267
View File
File diff suppressed because it is too large. Load diff
+692
View File
@@ -0,0 +1,692 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! SVG path representation.
use alloc::vec::Vec;
use core::error::Error;
use core::f64::consts::PI;
use core::fmt::{self, Display, Formatter};
#[cfg(feature = "std")]
use std::io::{self, Write};
use crate::{Arc, BezPath, ParamCurve, PathEl, PathSeg, Point, Vec2};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
// Note: the SVG arc logic is heavily adapted from https://github.com/nical/lyon
/// A single SVG arc segment.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SvgArc {
/// The arc's start point.
pub from: Point,
/// The arc's end point.
pub to: Point,
/// The arc's radii, where the vector's x-component is the radius in the
/// positive x direction after applying `x_rotation`.
pub radii: Vec2,
/// How much the arc is rotated, in radians.
pub x_rotation: f64,
/// Does this arc sweep through more than π radians?
pub large_arc: bool,
/// Determines if the arc should begin moving at positive angles.
pub sweep: bool,
}
impl BezPath {
/// Create a `BezPath` with segments corresponding to the sequence of
/// `PathSeg`s
pub fn from_path_segments(segments: impl Iterator<Item = PathSeg>) -> BezPath {
let mut path_elements = Vec::new();
let mut current_pos = None;
for segment in segments {
let start = segment.start();
if Some(start) != current_pos {
path_elements.push(PathEl::MoveTo(start));
}
path_elements.push(match segment {
PathSeg::Line(l) => PathEl::LineTo(l.p1),
PathSeg::Quad(q) => PathEl::QuadTo(q.p1, q.p2),
PathSeg::Cubic(c) => PathEl::CurveTo(c.p1, c.p2, c.p3),
});
current_pos = Some(segment.end());
}
BezPath::from_vec(path_elements)
}
/// Convert the path to an SVG path string representation.
///
/// The current implementation doesn't take any special care to produce a
/// short string (reducing precision, using relative movement).
#[cfg(feature = "std")]
pub fn to_svg(&self) -> String {
let mut buffer = Vec::new();
self.write_to(&mut buffer).unwrap();
String::from_utf8(buffer).unwrap()
}
/// Write the SVG representation of this path to the provided buffer.
#[cfg(feature = "std")]
pub fn write_to<W: Write>(&self, mut writer: W) -> io::Result<()> {
for (i, el) in self.elements().iter().enumerate() {
if i > 0 {
write!(writer, " ")?;
}
match *el {
PathEl::MoveTo(p) => write!(writer, "M{},{}", p.x, p.y)?,
PathEl::LineTo(p) => write!(writer, "L{},{}", p.x, p.y)?,
PathEl::QuadTo(p1, p2) => write!(writer, "Q{},{} {},{}", p1.x, p1.y, p2.x, p2.y)?,
PathEl::CurveTo(p1, p2, p3) => write!(
writer,
"C{},{} {},{} {},{}",
p1.x, p1.y, p2.x, p2.y, p3.x, p3.y
)?,
PathEl::ClosePath => write!(writer, "Z")?,
}
}
Ok(())
}
/// Try to parse a bezier path from an SVG path element.
///
/// This is implemented on a best-effort basis, intended for cases where the
/// user controls the source of paths, and is not intended as a replacement
/// for a general, robust SVG parser.
pub fn from_svg(data: &str) -> Result<BezPath, SvgParseError> {
let mut lexer = SvgLexer::new(data);
let mut path = BezPath::new();
let mut last_cmd = 0;
let mut last_ctrl = None;
let mut first_pt = Point::ORIGIN;
let mut implicit_moveto = None;
while let Some(c) = lexer.get_cmd(last_cmd) {
if c != b'm' && c != b'M' {
if path.elements().is_empty() {
return Err(SvgParseError::UninitializedPath);
}
if let Some(pt) = implicit_moveto.take() {
path.move_to(pt);
}
}
match c {
b'm' | b'M' => {
implicit_moveto = None;
let pt = lexer.get_maybe_relative(c)?;
path.move_to(pt);
lexer.last_pt = pt;
first_pt = pt;
last_ctrl = Some(pt);
last_cmd = c - (b'M' - b'L');
}
b'l' | b'L' => {
let pt = lexer.get_maybe_relative(c)?;
path.line_to(pt);
lexer.last_pt = pt;
last_ctrl = Some(pt);
last_cmd = c;
}
b'h' | b'H' => {
let mut x = lexer.get_number()?;
lexer.opt_comma();
if c == b'h' {
x += lexer.last_pt.x;
}
let pt = Point::new(x, lexer.last_pt.y);
path.line_to(pt);
lexer.last_pt = pt;
last_ctrl = Some(pt);
last_cmd = c;
}
b'v' | b'V' => {
let mut y = lexer.get_number()?;
lexer.opt_comma();
if c == b'v' {
y += lexer.last_pt.y;
}
let pt = Point::new(lexer.last_pt.x, y);
path.line_to(pt);
lexer.last_pt = pt;
last_ctrl = Some(pt);
last_cmd = c;
}
b'q' | b'Q' => {
let p1 = lexer.get_maybe_relative(c)?;
let p2 = lexer.get_maybe_relative(c)?;
path.quad_to(p1, p2);
last_ctrl = Some(p1);
lexer.last_pt = p2;
last_cmd = c;
}
b't' | b'T' => {
let p1 = match last_ctrl {
Some(ctrl) => (2.0 * lexer.last_pt.to_vec2() - ctrl.to_vec2()).to_point(),
None => lexer.last_pt,
};
let p2 = lexer.get_maybe_relative(c)?;
path.quad_to(p1, p2);
last_ctrl = Some(p1);
lexer.last_pt = p2;
last_cmd = c;
}
b'c' | b'C' => {
let p1 = lexer.get_maybe_relative(c)?;
let p2 = lexer.get_maybe_relative(c)?;
let p3 = lexer.get_maybe_relative(c)?;
path.curve_to(p1, p2, p3);
last_ctrl = Some(p2);
lexer.last_pt = p3;
last_cmd = c;
}
b's' | b'S' => {
let p1 = match last_ctrl {
Some(ctrl) => (2.0 * lexer.last_pt.to_vec2() - ctrl.to_vec2()).to_point(),
None => lexer.last_pt,
};
let p2 = lexer.get_maybe_relative(c)?;
let p3 = lexer.get_maybe_relative(c)?;
path.curve_to(p1, p2, p3);
last_ctrl = Some(p2);
lexer.last_pt = p3;
last_cmd = c;
}
b'a' | b'A' => {
let radii = lexer.get_number_pair()?;
let x_rotation = lexer.get_number()?.to_radians();
lexer.opt_comma();
let large_arc = lexer.get_flag()?;
lexer.opt_comma();
let sweep = lexer.get_flag()?;
lexer.opt_comma();
let p = lexer.get_maybe_relative(c)?;
let svg_arc = SvgArc {
from: lexer.last_pt,
to: p,
radii: radii.to_vec2(),
x_rotation,
large_arc,
sweep,
};
match Arc::from_svg_arc(&svg_arc) {
Some(arc) => {
// TODO: consider making tolerance configurable
arc.to_cubic_beziers(0.1, |p1, p2, p3| {
path.curve_to(p1, p2, p3);
});
}
None => {
path.line_to(p);
}
}
last_ctrl = Some(p);
lexer.last_pt = p;
last_cmd = c;
}
b'z' | b'Z' => {
path.close_path();
lexer.last_pt = first_pt;
implicit_moveto = Some(first_pt);
}
_ => return Err(SvgParseError::UnknownCommand(c as char)),
}
}
Ok(path)
}
}
/// An error which can be returned when parsing an SVG.
#[derive(Debug)]
#[non_exhaustive]
pub enum SvgParseError {
/// A number was expected.
Wrong,
/// The input string ended while still expecting input.
UnexpectedEof,
/// Encountered an unknown command letter.
UnknownCommand(char),
/// Encountered a command that precedes expected 'moveto' command.
UninitializedPath,
}
impl Display for SvgParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
SvgParseError::Wrong => write!(f, "Unable to parse a number"),
SvgParseError::UnexpectedEof => write!(f, "Unexpected EOF"),
SvgParseError::UnknownCommand(letter) => write!(f, "Unknown command, \"{letter}\""),
SvgParseError::UninitializedPath => {
write!(f, "Uninitialized path (missing moveto command)")
}
}
}
}
impl Error for SvgParseError {}
struct SvgLexer<'a> {
data: &'a str,
ix: usize,
pub last_pt: Point,
}
impl SvgLexer<'_> {
fn new(data: &str) -> SvgLexer<'_> {
SvgLexer {
data,
ix: 0,
last_pt: Point::ORIGIN,
}
}
fn skip_ws(&mut self) {
while let Some(&c) = self.data.as_bytes().get(self.ix) {
if !(c == b' ' || c == 9 || c == 10 || c == 12 || c == 13) {
break;
}
self.ix += 1;
}
}
fn get_cmd(&mut self, last_cmd: u8) -> Option<u8> {
self.skip_ws();
if let Some(c) = self.get_byte() {
if c.is_ascii_lowercase() || c.is_ascii_uppercase() {
return Some(c);
} else if last_cmd != 0 && (c == b'-' || c == b'.' || c.is_ascii_digit()) {
// Plausible number start
self.unget();
return Some(last_cmd);
} else {
self.unget();
}
}
None
}
fn get_byte(&mut self) -> Option<u8> {
self.data.as_bytes().get(self.ix).map(|&c| {
self.ix += 1;
c
})
}
fn unget(&mut self) {
self.ix -= 1;
}
fn get_number(&mut self) -> Result<f64, SvgParseError> {
self.skip_ws();
let start = self.ix;
let c = self.get_byte().ok_or(SvgParseError::UnexpectedEof)?;
if !(c == b'-' || c == b'+') {
self.unget();
}
let mut digit_count = 0;
let mut seen_period = false;
while let Some(c) = self.get_byte() {
if c.is_ascii_digit() {
digit_count += 1;
} else if c == b'.' && !seen_period {
seen_period = true;
} else {
self.unget();
break;
}
}
if let Some(c) = self.get_byte() {
if c == b'e' || c == b'E' {
let mut c = self.get_byte().ok_or(SvgParseError::Wrong)?;
if c == b'-' || c == b'+' {
c = self.get_byte().ok_or(SvgParseError::Wrong)?;
}
if !c.is_ascii_digit() {
return Err(SvgParseError::Wrong);
}
while let Some(c) = self.get_byte() {
if !c.is_ascii_digit() {
self.unget();
break;
}
}
} else {
self.unget();
}
}
if digit_count > 0 {
self.data[start..self.ix]
.parse()
.map_err(|_| SvgParseError::Wrong)
} else {
Err(SvgParseError::Wrong)
}
}
fn get_flag(&mut self) -> Result<bool, SvgParseError> {
self.skip_ws();
match self.get_byte().ok_or(SvgParseError::UnexpectedEof)? {
b'0' => Ok(false),
b'1' => Ok(true),
_ => Err(SvgParseError::Wrong),
}
}
fn get_number_pair(&mut self) -> Result<Point, SvgParseError> {
let x = self.get_number()?;
self.opt_comma();
let y = self.get_number()?;
self.opt_comma();
Ok(Point::new(x, y))
}
fn get_maybe_relative(&mut self, cmd: u8) -> Result<Point, SvgParseError> {
let pt = self.get_number_pair()?;
if cmd.is_ascii_lowercase() {
Ok(self.last_pt + pt.to_vec2())
} else {
Ok(pt)
}
}
fn opt_comma(&mut self) {
self.skip_ws();
if let Some(c) = self.get_byte() {
if c != b',' {
self.unget();
}
}
}
}
impl SvgArc {
/// Checks that arc is actually a straight line.
///
/// In this case, it can be replaced with a `LineTo`.
pub fn is_straight_line(&self) -> bool {
self.radii.x.abs() <= 1e-5 || self.radii.y.abs() <= 1e-5 || self.from == self.to
}
}
impl Arc {
/// Creates an `Arc` from a `SvgArc`.
///
/// Returns `None` if `arc` is actually a straight line.
pub fn from_svg_arc(arc: &SvgArc) -> Option<Arc> {
// Have to check this first, otherwise `sum_of_sq` will be 0.
if arc.is_straight_line() {
return None;
}
let mut rx = arc.radii.x.abs();
let mut ry = arc.radii.y.abs();
let xr = arc.x_rotation % (2.0 * PI);
let (sin_phi, cos_phi) = xr.sin_cos();
let hd_x = (arc.from.x - arc.to.x) * 0.5;
let hd_y = (arc.from.y - arc.to.y) * 0.5;
let hs_x = (arc.from.x + arc.to.x) * 0.5;
let hs_y = (arc.from.y + arc.to.y) * 0.5;
// F6.5.1
let p = Vec2::new(
cos_phi * hd_x + sin_phi * hd_y,
-sin_phi * hd_x + cos_phi * hd_y,
);
// Sanitize the radii.
// If rf > 1 it means the radii are too small for the arc to
// possibly connect the end points. In this situation we scale
// them up according to the formula provided by the SVG spec.
// F6.6.2
let rf = p.x * p.x / (rx * rx) + p.y * p.y / (ry * ry);
if rf > 1.0 {
let scale = rf.sqrt();
rx *= scale;
ry *= scale;
}
let rxry = rx * ry;
let rxpy = rx * p.y;
let rypx = ry * p.x;
let sum_of_sq = rxpy * rxpy + rypx * rypx;
debug_assert!(sum_of_sq != 0.0);
// F6.5.2
let sign_coe = if arc.large_arc == arc.sweep {
-1.0
} else {
1.0
};
let coe = sign_coe * ((rxry * rxry - sum_of_sq) / sum_of_sq).abs().sqrt();
let transformed_cx = coe * rxpy / ry;
let transformed_cy = -coe * rypx / rx;
// F6.5.3
let center = Point::new(
cos_phi * transformed_cx - sin_phi * transformed_cy + hs_x,
sin_phi * transformed_cx + cos_phi * transformed_cy + hs_y,
);
let start_v = Vec2::new((p.x - transformed_cx) / rx, (p.y - transformed_cy) / ry);
let end_v = Vec2::new((-p.x - transformed_cx) / rx, (-p.y - transformed_cy) / ry);
let start_angle = start_v.atan2();
let mut sweep_angle = (end_v.atan2() - start_angle) % (2.0 * PI);
if arc.sweep && sweep_angle < 0.0 {
sweep_angle += 2.0 * PI;
} else if !arc.sweep && sweep_angle > 0.0 {
sweep_angle -= 2.0 * PI;
}
Some(Arc {
center,
radii: Vec2::new(rx, ry),
start_angle,
sweep_angle,
x_rotation: arc.x_rotation,
})
}
}
#[cfg(test)]
mod tests {
use crate::{BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez, Shape};
#[test]
fn test_parse_svg() {
let path = BezPath::from_svg("m10 10 100 0 0 100 -100 0z").unwrap();
assert_eq!(path.segments().count(), 4);
}
#[test]
fn test_parse_svg2() {
let path =
BezPath::from_svg("M3.5 8a.5.5 0 01.5-.5h8a.5.5 0 010 1H4a.5.5 0 01-.5-.5z").unwrap();
assert_eq!(path.segments().count(), 6);
}
#[test]
fn test_parse_svg_arc() {
let path = BezPath::from_svg("M 100 100 A 25 25 0 1 0 -25 25 z").unwrap();
assert_eq!(path.segments().count(), 3);
}
// Regression test for #51
#[test]
#[allow(clippy::float_cmp)]
fn test_parse_svg_arc_pie() {
let path = BezPath::from_svg("M 100 100 h 25 a 25 25 0 1 0 -25 25 z").unwrap();
// Approximate figures, but useful for regression testing
assert_eq!(path.area().round(), -1473.0);
assert_eq!(path.perimeter(1e-6).round(), 168.0);
}
#[test]
fn test_parse_svg_uninitialized() {
let path = BezPath::from_svg("L10 10 100 0 0 100");
assert!(path.is_err());
}
#[test]
#[allow(clippy::float_cmp)]
fn test_parse_scientific_notation() {
let path = BezPath::from_svg("M 0 0 L 1e-123 -4E+5").unwrap();
assert_eq!(
path.elements(),
&[
PathEl::MoveTo(Point { x: 0.0, y: 0.0 }),
PathEl::LineTo(Point {
x: 1e-123,
y: -4E+5
})
]
);
}
#[test]
fn test_write_svg_single() {
let segments = [CubicBez::new(
Point::new(10., 10.),
Point::new(20., 20.),
Point::new(30., 30.),
Point::new(40., 40.),
)
.into()];
let path = BezPath::from_path_segments(segments.iter().cloned());
assert_eq!(path.to_svg(), "M10,10 C20,20 30,30 40,40");
}
#[test]
fn test_write_svg_two_nomove() {
let segments = [
CubicBez::new(
Point::new(10., 10.),
Point::new(20., 20.),
Point::new(30., 30.),
Point::new(40., 40.),
)
.into(),
CubicBez::new(
Point::new(40., 40.),
Point::new(30., 30.),
Point::new(20., 20.),
Point::new(10., 10.),
)
.into(),
];
let path = BezPath::from_path_segments(segments.iter().cloned());
assert_eq!(
path.to_svg(),
"M10,10 C20,20 30,30 40,40 C30,30 20,20 10,10"
);
}
#[test]
fn test_write_svg_two_move() {
let segments = [
CubicBez::new(
Point::new(10., 10.),
Point::new(20., 20.),
Point::new(30., 30.),
Point::new(40., 40.),
)
.into(),
CubicBez::new(
Point::new(50., 50.),
Point::new(30., 30.),
Point::new(20., 20.),
Point::new(10., 10.),
)
.into(),
];
let path = BezPath::from_path_segments(segments.iter().cloned());
assert_eq!(
path.to_svg(),
"M10,10 C20,20 30,30 40,40 M50,50 C30,30 20,20 10,10"
);
}
use rand::prelude::*;
// Suppress the unused_crate_dependencies lint for getrandom.
#[cfg(all(
target_arch = "wasm32",
target_vendor = "unknown",
target_os = "unknown"
))]
use getrandom as _;
fn gen_random_path_sequence(rng: &mut impl Rng) -> Vec<PathSeg> {
const MAX_LENGTH: u32 = 10;
let mut elements = vec![];
let mut position = None;
let length = rng.random_range(0..MAX_LENGTH);
for _ in 0..length {
let should_follow: bool = rand::random_bool(0.5);
let kind = rng.random_range(0..3);
let first = position
.filter(|_| should_follow)
.unwrap_or_else(|| Point::new(rng.random(), rng.random()));
let element: PathSeg = match kind {
0 => Line::new(first, Point::new(rng.random(), rng.random())).into(),
1 => QuadBez::new(
first,
Point::new(rng.random(), rng.random()),
Point::new(rng.random(), rng.random()),
)
.into(),
2 => CubicBez::new(
first,
Point::new(rng.random(), rng.random()),
Point::new(rng.random(), rng.random()),
Point::new(rng.random(), rng.random()),
)
.into(),
_ => unreachable!(),
};
position = Some(element.end());
elements.push(element);
}
elements
}
#[test]
fn test_serialize_deserialize() {
const N_TESTS: u32 = 100;
let mut rng = rand::rng();
for _ in 0..N_TESTS {
let vec = gen_random_path_sequence(&mut rng);
let ser = BezPath::from_path_segments(vec.iter().cloned()).to_svg();
let deser = BezPath::from_svg(&ser).expect("failed deserialization");
let deser_vec = deser.segments().collect::<Vec<PathSeg>>();
assert_eq!(vec, deser_vec);
}
}
}
+345
View File
@@ -0,0 +1,345 @@
// Copyright 2019 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A transformation that includes both scale and translation.
use core::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign};
use crate::{
Affine, Circle, CubicBez, Line, Point, QuadBez, Rect, RoundedRect, RoundedRectRadii, Vec2,
};
/// A transformation consisting of a uniform scaling followed by a translation.
///
/// If the translation is `(x, y)` and the scale is `s`, then this
/// transformation represents this augmented matrix:
///
/// ```text
/// | s 0 x |
/// | 0 s y |
/// | 0 0 1 |
/// ```
///
/// See [`Affine`] for more details about the
/// equivalence with augmented matrices.
///
/// Various multiplication ops are defined, and these are all defined
/// to be consistent with matrix multiplication. Therefore,
/// `TranslateScale * Point` is defined but not the other way around.
///
/// Also note that multiplication is not commutative. Thus,
/// `TranslateScale::scale(2.0) * TranslateScale::translate(Vec2::new(1.0, 0.0))`
/// has a translation of (2, 0), while
/// `TranslateScale::translate(Vec2::new(1.0, 0.0)) * TranslateScale::scale(2.0)`
/// has a translation of (1, 0). (Both have a scale of 2; also note that
/// the first case can be written
/// `2.0 * TranslateScale::translate(Vec2::new(1.0, 0.0))` as this case
/// has an implicit conversion).
///
/// This transformation is less powerful than [`Affine`], but can be applied
/// to more primitives, especially including [`Rect`].
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TranslateScale {
/// The translation component of this transformation
pub translation: Vec2,
/// The scale component of this transformation
pub scale: f64,
}
impl TranslateScale {
/// Create a new transformation from translation and scale.
#[inline(always)]
pub const fn new(translation: Vec2, scale: f64) -> TranslateScale {
TranslateScale { translation, scale }
}
/// Create a new transformation with scale only.
#[inline(always)]
pub const fn scale(s: f64) -> TranslateScale {
TranslateScale::new(Vec2::ZERO, s)
}
/// Create a new transformation with translation only.
#[inline(always)]
pub fn translate(translation: impl Into<Vec2>) -> TranslateScale {
TranslateScale::new(translation.into(), 1.0)
}
/// Create a transform that scales about a point other than the origin.
///
/// # Examples
///
/// ```
/// # use kurbo::{Point, TranslateScale};
/// # fn assert_near(p0: Point, p1: Point) {
/// # assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}");
/// # }
/// let center = Point::new(1., 1.);
/// let ts = TranslateScale::from_scale_about(2., center);
/// // Should keep the point (1., 1.) stationary
/// assert_near(ts * center, center);
/// // (2., 2.) -> (3., 3.)
/// assert_near(ts * Point::new(2., 2.), Point::new(3., 3.));
/// ```
#[inline]
pub fn from_scale_about(scale: f64, focus: impl Into<Point>) -> Self {
// We need to create a transform that is equivalent to translating `focus`
// to the origin, followed by a normal scale, followed by reversing the translation.
// We need to find the (translation ∘ scale) that matches this.
let focus = focus.into().to_vec2();
let translation = focus - focus * scale;
Self::new(translation, scale)
}
/// Compute the inverse transform.
///
/// Multiplying a transform with its inverse (either on the
/// left or right) results in the identity transform
/// (modulo floating point rounding errors).
///
/// Produces NaN values when scale is zero.
#[inline]
pub fn inverse(self) -> TranslateScale {
let scale_recip = self.scale.recip();
TranslateScale {
translation: self.translation * -scale_recip,
scale: scale_recip,
}
}
/// Is this translate/scale [finite]?
///
/// [finite]: f64::is_finite
#[inline]
pub fn is_finite(&self) -> bool {
self.translation.is_finite() && self.scale.is_finite()
}
/// Is this translate/scale [NaN]?
///
/// [NaN]: f64::is_nan
#[inline]
pub fn is_nan(&self) -> bool {
self.translation.is_nan() || self.scale.is_nan()
}
}
impl Default for TranslateScale {
#[inline(always)]
fn default() -> TranslateScale {
TranslateScale::new(Vec2::ZERO, 1.0)
}
}
impl From<TranslateScale> for Affine {
#[inline(always)]
fn from(ts: TranslateScale) -> Affine {
let TranslateScale { translation, scale } = ts;
Affine::new([scale, 0.0, 0.0, scale, translation.x, translation.y])
}
}
impl Mul<Point> for TranslateScale {
type Output = Point;
#[inline]
fn mul(self, other: Point) -> Point {
(self.scale * other.to_vec2()).to_point() + self.translation
}
}
impl Mul for TranslateScale {
type Output = TranslateScale;
#[inline]
fn mul(self, other: TranslateScale) -> TranslateScale {
TranslateScale {
translation: self.translation + self.scale * other.translation,
scale: self.scale * other.scale,
}
}
}
impl MulAssign for TranslateScale {
#[inline]
fn mul_assign(&mut self, other: TranslateScale) {
*self = self.mul(other);
}
}
impl Mul<TranslateScale> for f64 {
type Output = TranslateScale;
#[inline]
fn mul(self, other: TranslateScale) -> TranslateScale {
TranslateScale {
translation: other.translation * self,
scale: other.scale * self,
}
}
}
impl Add<Vec2> for TranslateScale {
type Output = TranslateScale;
#[inline]
fn add(self, other: Vec2) -> TranslateScale {
TranslateScale {
translation: self.translation + other,
scale: self.scale,
}
}
}
impl Add<TranslateScale> for Vec2 {
type Output = TranslateScale;
#[inline]
fn add(self, other: TranslateScale) -> TranslateScale {
other + self
}
}
impl AddAssign<Vec2> for TranslateScale {
#[inline]
fn add_assign(&mut self, other: Vec2) {
*self = self.add(other);
}
}
impl Sub<Vec2> for TranslateScale {
type Output = TranslateScale;
#[inline]
fn sub(self, other: Vec2) -> TranslateScale {
TranslateScale {
translation: self.translation - other,
scale: self.scale,
}
}
}
impl SubAssign<Vec2> for TranslateScale {
#[inline]
fn sub_assign(&mut self, other: Vec2) {
*self = self.sub(other);
}
}
impl Mul<Circle> for TranslateScale {
type Output = Circle;
#[inline]
fn mul(self, other: Circle) -> Circle {
Circle::new(self * other.center, self.scale * other.radius)
}
}
impl Mul<Line> for TranslateScale {
type Output = Line;
#[inline]
fn mul(self, other: Line) -> Line {
Line::new(self * other.p0, self * other.p1)
}
}
impl Mul<Rect> for TranslateScale {
type Output = Rect;
#[inline]
fn mul(self, other: Rect) -> Rect {
let pt0 = self * Point::new(other.x0, other.y0);
let pt1 = self * Point::new(other.x1, other.y1);
(pt0, pt1).into()
}
}
impl Mul<RoundedRect> for TranslateScale {
type Output = RoundedRect;
#[inline]
fn mul(self, other: RoundedRect) -> RoundedRect {
RoundedRect::from_rect(self * other.rect(), self * other.radii())
}
}
impl Mul<RoundedRectRadii> for TranslateScale {
type Output = RoundedRectRadii;
#[inline]
fn mul(self, other: RoundedRectRadii) -> RoundedRectRadii {
RoundedRectRadii::new(
self.scale * other.top_left,
self.scale * other.top_right,
self.scale * other.bottom_right,
self.scale * other.bottom_left,
)
}
}
impl Mul<QuadBez> for TranslateScale {
type Output = QuadBez;
#[inline]
fn mul(self, other: QuadBez) -> QuadBez {
QuadBez::new(self * other.p0, self * other.p1, self * other.p2)
}
}
impl Mul<CubicBez> for TranslateScale {
type Output = CubicBez;
#[inline]
fn mul(self, other: CubicBez) -> CubicBez {
CubicBez::new(
self * other.p0,
self * other.p1,
self * other.p2,
self * other.p3,
)
}
}
#[cfg(test)]
mod tests {
use crate::{Affine, Point, TranslateScale, Vec2};
fn assert_near(p0: Point, p1: Point) {
assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}");
}
#[test]
fn translate_scale() {
let p = Point::new(3.0, 4.0);
let ts = TranslateScale::new(Vec2::new(5.0, 6.0), 2.0);
assert_near(ts * p, Point::new(11.0, 14.0));
}
#[test]
fn conversions() {
let p = Point::new(3.0, 4.0);
let s = 2.0;
let t = Vec2::new(5.0, 6.0);
let ts = TranslateScale::new(t, s);
// Test that conversion to affine is consistent.
let a: Affine = ts.into();
assert_near(ts * p, a * p);
assert_near((s * p.to_vec2()).to_point(), TranslateScale::scale(s) * p);
assert_near(p + t, TranslateScale::translate(t) * p);
}
#[test]
fn inverse() {
let p = Point::new(3.0, 4.0);
let ts = TranslateScale::new(Vec2::new(5.0, 6.0), 2.0);
assert_near(p, (ts * ts.inverse()) * p);
assert_near(p, (ts.inverse() * ts) * p);
}
}
+373
View File
@@ -0,0 +1,373 @@
// Copyright 2024 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Triangle shape
use crate::{Circle, PathEl, Point, Rect, Shape, Vec2};
use core::cmp::*;
use core::f64::consts::FRAC_PI_4;
use core::ops::{Add, Sub};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// Triangle
// A
// *
// / \
// / \
// *-----*
// B C
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Triangle {
/// vertex a.
pub a: Point,
/// vertex b.
pub b: Point,
/// vertex c.
pub c: Point,
}
impl Triangle {
/// The empty [`Triangle`] at the origin.
pub const ZERO: Self = Self::from_coords((0., 0.), (0., 0.), (0., 0.));
/// Equilateral [`Triangle`] with the x-axis unit vector as its base.
pub const EQUILATERAL: Self = Self::from_coords(
(
1.0 / 2.0,
1.732050807568877293527446341505872367_f64 / 2.0, /* (sqrt 3)/2 */
),
(0.0, 0.0),
(1.0, 0.0),
);
/// A new [`Triangle`] from three vertices ([`Point`]s).
#[inline(always)]
pub fn new(a: impl Into<Point>, b: impl Into<Point>, c: impl Into<Point>) -> Self {
Self {
a: a.into(),
b: b.into(),
c: c.into(),
}
}
/// A new [`Triangle`] from three float vertex coordinates.
///
/// Works as a constant [`Triangle::new`].
#[inline(always)]
pub const fn from_coords(a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> Self {
Self {
a: Point::new(a.0, a.1),
b: Point::new(b.0, b.1),
c: Point::new(c.0, c.1),
}
}
/// The centroid of the [`Triangle`].
#[inline]
pub fn centroid(&self) -> Point {
(1.0 / 3.0 * (self.a.to_vec2() + self.b.to_vec2() + self.c.to_vec2())).to_point()
}
/// The offset of each vertex from the centroid.
#[inline]
pub fn offsets(&self) -> [Vec2; 3] {
let centroid = self.centroid().to_vec2();
[
(self.a.to_vec2() - centroid),
(self.b.to_vec2() - centroid),
(self.c.to_vec2() - centroid),
]
}
/// The area of the [`Triangle`].
#[inline]
pub fn area(&self) -> f64 {
0.5 * (self.b - self.a).cross(self.c - self.a)
}
/// Whether this [`Triangle`] has zero area.
#[doc(alias = "is_empty")]
#[inline]
pub fn is_zero_area(&self) -> bool {
self.area() == 0.0
}
/// The inscribed circle of [`Triangle`].
///
/// This is defined as the greatest [`Circle`] that lies within the [`Triangle`].
#[doc(alias = "incircle")]
#[inline]
pub fn inscribed_circle(&self) -> Circle {
let ab = self.a.distance(self.b);
let bc = self.b.distance(self.c);
let ac = self.a.distance(self.c);
// [`Vec2::div`] also multiplies by the reciprocal of the argument, but as this reciprocal
// is reused below to calculate the radius, there's explicitly only one division needed.
let perimeter_recip = 1. / (ab + bc + ac);
let incenter = (self.a.to_vec2() * bc + self.b.to_vec2() * ac + self.c.to_vec2() * ab)
* perimeter_recip;
Circle::new(incenter.to_point(), 2.0 * self.area() * perimeter_recip)
}
/// The circumscribed circle of [`Triangle`].
///
/// This is defined as the smallest [`Circle`] which intercepts each vertex of the [`Triangle`].
#[doc(alias = "circumcircle")]
#[inline]
pub fn circumscribed_circle(&self) -> Circle {
let b = self.b - self.a;
let c = self.c - self.a;
let b_len2 = b.hypot2();
let c_len2 = c.hypot2();
let d_recip = 0.5 / b.cross(c);
let x = (c.y * b_len2 - b.y * c_len2) * d_recip;
let y = (b.x * c_len2 - c.x * b_len2) * d_recip;
let r = (b_len2 * c_len2).sqrt() * (c - b).hypot() * d_recip;
Circle::new(self.a + Vec2::new(x, y), r)
}
/// Expand the triangle by a constant amount (`scalar`) in all directions.
#[doc(alias = "offset")]
pub fn inflate(&self, scalar: f64) -> Self {
let centroid = self.centroid();
Self::new(
centroid + (0.0, scalar),
centroid + scalar * Vec2::from_angle(5.0 * FRAC_PI_4),
centroid + scalar * Vec2::from_angle(7.0 * FRAC_PI_4),
)
}
/// Is this [`Triangle`] [finite]?
///
/// [finite]: f64::is_finite
#[inline]
pub const fn is_finite(&self) -> bool {
self.a.is_finite() && self.b.is_finite() && self.c.is_finite()
}
/// Is this [`Triangle`] [NaN]?
///
/// [NaN]: f64::is_nan
#[inline]
pub const fn is_nan(&self) -> bool {
self.a.is_nan() || self.b.is_nan() || self.c.is_nan()
}
}
impl From<(Point, Point, Point)> for Triangle {
fn from(points: (Point, Point, Point)) -> Triangle {
Triangle::new(points.0, points.1, points.2)
}
}
impl Add<Vec2> for Triangle {
type Output = Triangle;
#[inline]
fn add(self, v: Vec2) -> Triangle {
Triangle::new(self.a + v, self.b + v, self.c + v)
}
}
impl Sub<Vec2> for Triangle {
type Output = Triangle;
#[inline]
fn sub(self, v: Vec2) -> Triangle {
Triangle::new(self.a - v, self.b - v, self.c - v)
}
}
#[doc(hidden)]
pub struct TrianglePathIter {
triangle: Triangle,
ix: usize,
}
impl Shape for Triangle {
type PathElementsIter<'iter> = TrianglePathIter;
fn path_elements(&self, _tolerance: f64) -> TrianglePathIter {
TrianglePathIter {
triangle: *self,
ix: 0,
}
}
#[inline]
fn area(&self) -> f64 {
Triangle::area(self)
}
#[inline]
fn perimeter(&self, _accuracy: f64) -> f64 {
self.a.distance(self.b) + self.b.distance(self.c) + self.c.distance(self.a)
}
#[inline]
fn winding(&self, pt: Point) -> i32 {
let s0 = (self.b - self.a).cross(pt - self.a).signum();
let s1 = (self.c - self.b).cross(pt - self.b).signum();
let s2 = (self.a - self.c).cross(pt - self.c).signum();
if s0 == s1 && s1 == s2 { s0 as i32 } else { 0 }
}
#[inline]
fn bounding_box(&self) -> Rect {
Rect::new(
self.a.x.min(self.b.x.min(self.c.x)),
self.a.y.min(self.b.y.min(self.c.y)),
self.a.x.max(self.b.x.max(self.c.x)),
self.a.y.max(self.b.y.max(self.c.y)),
)
}
}
// Note: vertices a, b and c are not guaranteed to be in order as described in the struct comments
// (i.e. as "vertex a is topmost, vertex b is leftmost, and vertex c is rightmost")
impl Iterator for TrianglePathIter {
type Item = PathEl;
fn next(&mut self) -> Option<PathEl> {
self.ix += 1;
match self.ix {
1 => Some(PathEl::MoveTo(self.triangle.a)),
2 => Some(PathEl::LineTo(self.triangle.b)),
3 => Some(PathEl::LineTo(self.triangle.c)),
4 => Some(PathEl::ClosePath),
_ => None,
}
}
}
// TODO: better and more tests
#[cfg(test)]
mod tests {
use crate::{Point, Triangle, Vec2};
fn assert_approx_eq(x: f64, y: f64, max_relative_error: f64) {
assert!(
(x - y).abs() <= f64::max(x.abs(), y.abs()) * max_relative_error,
"{x} != {y}"
);
}
fn assert_approx_eq_point(x: Point, y: Point, max_relative_error: f64) {
assert_approx_eq(x.x, y.x, max_relative_error);
assert_approx_eq(x.y, y.y, max_relative_error);
}
#[test]
fn centroid() {
let test = Triangle::from_coords((-90.02, 3.5), (7.2, -9.3), (8.0, 9.1)).centroid();
let expected = Point::new(-24.94, 1.1);
assert_approx_eq_point(test, expected, f64::EPSILON * 100.);
}
#[test]
fn offsets() {
let test = Triangle::from_coords((-20.0, 180.2), (1.2, 0.0), (290.0, 100.0)).offsets();
let expected = [
Vec2::new(-110.4, 86.8),
Vec2::new(-89.2, -93.4),
Vec2::new(199.6, 6.6),
];
test.iter().zip(expected.iter()).for_each(|(t, e)| {
assert_approx_eq_point(t.to_point(), e.to_point(), f64::EPSILON * 100.);
});
}
#[test]
fn area() {
let test = Triangle::new(
(12123.423, 2382.7834),
(7892.729, 238.459),
(7820.2, 712.23),
);
let expected = 1079952.9157407999;
// initial
assert_approx_eq(test.area(), -expected, f64::EPSILON * 100.);
// permutate vertex
let test = Triangle::new(test.b, test.a, test.c);
assert_approx_eq(test.area(), expected, f64::EPSILON * 100.);
}
#[test]
fn circumcenter() {
let test = Triangle::EQUILATERAL.circumscribed_circle().center;
let expected = Point::new(0.5, 0.28867513459481288);
assert_approx_eq_point(test, expected, f64::EPSILON * 100.);
}
#[test]
fn inradius() {
let test = Triangle::EQUILATERAL.inscribed_circle().radius;
let expected = 0.28867513459481287;
assert_approx_eq(test, expected, f64::EPSILON * 100.);
}
#[test]
fn circumradius() {
let test = Triangle::EQUILATERAL;
let expected = 0.57735026918962576;
assert_approx_eq(
test.circumscribed_circle().radius,
expected,
f64::EPSILON * 100.,
);
// permute vertex
let test = Triangle::new(test.b, test.a, test.c);
assert_approx_eq(
test.circumscribed_circle().radius,
-expected,
f64::EPSILON * 100.,
);
}
#[test]
fn inscribed_circle() {
let test = Triangle::new((-4., 1.), (-4., -1.), (10., 3.));
let inscribed = test.inscribed_circle();
assert_approx_eq_point(
inscribed.center,
(-3.0880178529263671, 0.20904207741504303).into(),
f64::EPSILON * 100.,
);
assert_approx_eq(inscribed.radius, 0.91198214707363295, f64::EPSILON * 100.);
}
#[test]
fn circumscribed_circle() {
let test = Triangle::new((-4., 1.), (-4., -1.), (10., 3.));
let circumscribed = test.circumscribed_circle();
assert_approx_eq_point(
circumscribed.center,
(3.2857142857142857, 0.).into(),
f64::EPSILON * 100.,
);
assert_approx_eq(
circumscribed.radius,
7.3540215292764288,
f64::EPSILON * 100.,
);
}
}
+568
View File
@@ -0,0 +1,568 @@
// Copyright 2018 the Kurbo Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A simple 2D vector.
use core::fmt;
use core::iter::Sum;
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use crate::common::FloatExt;
use crate::{Axis, Point, Size};
#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
/// A 2D vector.
///
/// This is intended primarily for a vector in the mathematical sense,
/// but it can be interpreted as a translation, and converted to and
/// from a [`Point`] (vector relative to the origin) and [`Size`].
#[derive(Clone, Copy, Default, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Vec2 {
/// The x-coordinate.
pub x: f64,
/// The y-coordinate.
pub y: f64,
}
impl Vec2 {
/// The vector (0, 0).
pub const ZERO: Vec2 = Vec2::new(0., 0.);
/// Create a new vector.
#[inline(always)]
pub const fn new(x: f64, y: f64) -> Vec2 {
Vec2 { x, y }
}
/// Convert this vector into a [`Point`].
#[inline(always)]
pub const fn to_point(self) -> Point {
Point::new(self.x, self.y)
}
/// Convert this vector into a [`Size`].
#[inline(always)]
pub const fn to_size(self) -> Size {
Size::new(self.x, self.y)
}
/// Create a vector with the same value for `x` and `y`.
#[inline(always)]
pub const fn splat(v: f64) -> Self {
Vec2 { x: v, y: v }
}
/// Dot product of two vectors.
#[inline]
pub const fn dot(self, other: Vec2) -> f64 {
self.x * other.x + self.y * other.y
}
/// Cross product of two vectors.
///
/// This is signed so that `(1, 0) × (0, 1) = 1`.
///
/// The following relations hold:
///
/// `u.cross(v) = -v.cross(u)`
///
/// `v.cross(v) = 0.0`
#[inline]
pub const fn cross(self, other: Vec2) -> f64 {
self.x * other.y - self.y * other.x
}
/// Magnitude of vector.
///
/// See [`Point::distance`] for the same operation on [`Point`].
///
/// # Examples
///
/// ```
/// use kurbo::Vec2;
/// let v = Vec2::new(3.0, 4.0);
/// assert_eq!(v.hypot(), 5.0);
/// ```
#[inline]
pub fn hypot(self) -> f64 {
// Avoid f64::hypot as it calls a slow library function.
self.hypot2().sqrt()
}
/// Magnitude of vector.
///
/// This is an alias for [`Vec2::hypot`].
#[inline]
pub fn length(self) -> f64 {
self.hypot()
}
/// Magnitude squared of vector.
///
/// See [`Point::distance_squared`] for the same operation on [`Point`].
///
/// # Examples
///
/// ```
/// use kurbo::Vec2;
/// let v = Vec2::new(3.0, 4.0);
/// assert_eq!(v.hypot2(), 25.0);
/// ```
#[inline]
pub const fn hypot2(self) -> f64 {
self.dot(self)
}
/// Magnitude squared of vector.
///
/// This is an alias for [`Vec2::hypot2`].
#[inline]
pub const fn length_squared(self) -> f64 {
self.hypot2()
}
/// Find the angle in radians between this vector and the vector `Vec2 { x: 1.0, y: 0.0 }`
/// in the positive `y` direction.
///
/// If the vector is interpreted as a complex number, this is the argument.
/// The angle is expressed in radians.
#[inline]
pub fn atan2(self) -> f64 {
self.y.atan2(self.x)
}
/// Find the angle in radians between this vector and the vector `Vec2 { x: 1.0, y: 0.0 }`
/// in the positive `y` direction.
///
/// This is an alias for [`Vec2::atan2`].
#[inline]
pub fn angle(self) -> f64 {
self.atan2()
}
/// A unit vector of the given angle.
///
/// With `th` at zero, the result is the positive X unit vector, and
/// at π/2, it is the positive Y unit vector. The angle is expressed
/// in radians.
///
/// Thus, in a Y-down coordinate system (as is common for graphics),
/// it is a clockwise rotation, and in Y-up (traditional for math), it
/// is anti-clockwise. This convention is consistent with
/// [`Affine::rotate`].
///
/// [`Affine::rotate`]: crate::Affine::rotate
#[inline]
pub fn from_angle(th: f64) -> Vec2 {
let (th_sin, th_cos) = th.sin_cos();
Vec2 {
x: th_cos,
y: th_sin,
}
}
/// Linearly interpolate between two vectors.
#[inline]
pub fn lerp(self, other: Vec2, t: f64) -> Vec2 {
self + t * (other - self)
}
/// Returns a vector of [magnitude] 1.0 with the same angle as `self`; i.e.
/// a unit/direction vector.
///
/// This produces `NaN` values when the magnitude is `0`.
///
/// [magnitude]: Self::hypot
#[inline]
pub fn normalize(self) -> Vec2 {
self / self.hypot()
}
/// Returns a new `Vec2`,
/// with `x` and `y` [rounded] to the nearest integer.
///
/// # Examples
///
/// ```
/// use kurbo::Vec2;
/// let a = Vec2::new(3.3, 3.6).round();
/// let b = Vec2::new(3.0, -3.1).round();
/// assert_eq!(a.x, 3.0);
/// assert_eq!(a.y, 4.0);
/// assert_eq!(b.x, 3.0);
/// assert_eq!(b.y, -3.0);
/// ```
///
/// [rounded]: f64::round
#[inline]
pub fn round(self) -> Vec2 {
Vec2::new(self.x.round(), self.y.round())
}
/// Returns a new `Vec2`,
/// with `x` and `y` [rounded up] to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Vec2;
/// let a = Vec2::new(3.3, 3.6).ceil();
/// let b = Vec2::new(3.0, -3.1).ceil();
/// assert_eq!(a.x, 4.0);
/// assert_eq!(a.y, 4.0);
/// assert_eq!(b.x, 3.0);
/// assert_eq!(b.y, -3.0);
/// ```
///
/// [rounded up]: f64::ceil
#[inline]
pub fn ceil(self) -> Vec2 {
Vec2::new(self.x.ceil(), self.y.ceil())
}
/// Returns a new `Vec2`,
/// with `x` and `y` [rounded down] to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Vec2;
/// let a = Vec2::new(3.3, 3.6).floor();
/// let b = Vec2::new(3.0, -3.1).floor();
/// assert_eq!(a.x, 3.0);
/// assert_eq!(a.y, 3.0);
/// assert_eq!(b.x, 3.0);
/// assert_eq!(b.y, -4.0);
/// ```
///
/// [rounded down]: f64::floor
#[inline]
pub fn floor(self) -> Vec2 {
Vec2::new(self.x.floor(), self.y.floor())
}
/// Returns a new `Vec2`,
/// with `x` and `y` [rounded away] from zero to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Vec2;
/// let a = Vec2::new(3.3, 3.6).expand();
/// let b = Vec2::new(3.0, -3.1).expand();
/// assert_eq!(a.x, 4.0);
/// assert_eq!(a.y, 4.0);
/// assert_eq!(b.x, 3.0);
/// assert_eq!(b.y, -4.0);
/// ```
///
/// [rounded away]: FloatExt::expand
#[inline]
pub fn expand(self) -> Vec2 {
Vec2::new(self.x.expand(), self.y.expand())
}
/// Returns a new `Vec2`,
/// with `x` and `y` [rounded towards] zero to the nearest integer,
/// unless they are already an integer.
///
/// # Examples
///
/// ```
/// use kurbo::Vec2;
/// let a = Vec2::new(3.3, 3.6).trunc();
/// let b = Vec2::new(3.0, -3.1).trunc();
/// assert_eq!(a.x, 3.0);
/// assert_eq!(a.y, 3.0);
/// assert_eq!(b.x, 3.0);
/// assert_eq!(b.y, -3.0);
/// ```
///
/// [rounded towards]: f64::trunc
#[inline]
pub fn trunc(self) -> Vec2 {
Vec2::new(self.x.trunc(), self.y.trunc())
}
/// Is this `Vec2` [finite]?
///
/// [finite]: f64::is_finite
#[inline]
pub const fn is_finite(self) -> bool {
self.x.is_finite() && self.y.is_finite()
}
/// Is this `Vec2` [`NaN`]?
///
/// [`NaN`]: f64::is_nan
#[inline]
pub const fn is_nan(self) -> bool {
self.x.is_nan() || self.y.is_nan()
}
/// Divides this `Vec2` by a scalar.
///
/// Unlike the division by scalar operator, which multiplies by the
/// reciprocal for performance, this performs the division
/// per-component for consistent rounding behavior.
pub(crate) fn div_exact(self, divisor: f64) -> Vec2 {
Vec2 {
x: self.x / divisor,
y: self.y / divisor,
}
}
/// Turn by 90 degrees.
///
/// The rotation is clockwise in a Y-down coordinate system. The following relations hold:
///
/// `u.dot(v) = u.cross(v.turn_90())`
///
/// `u.cross(v) = u.turn_90().dot(v)`
#[inline]
pub const fn turn_90(self) -> Vec2 {
Vec2::new(-self.y, self.x)
}
/// Combine two vectors interpreted as rotation and scaling.
///
/// Interpret both vectors as a rotation and a scale, and combine
/// their effects. by adding the angles and multiplying the magnitudes.
/// This operation is equivalent to multiplication when the vectors
/// are interpreted as complex numbers. It is commutative.
#[inline]
pub const fn rotate_scale(self, rhs: Vec2) -> Vec2 {
Vec2::new(
self.x * rhs.x - self.y * rhs.y,
self.x * rhs.y + self.y * rhs.x,
)
}
/// Get the member matching the given axis.
#[inline]
pub const fn get_coord(self, axis: Axis) -> f64 {
match axis {
Axis::Horizontal => self.x,
Axis::Vertical => self.y,
}
}
/// Get a mutable reference to the member matching the given axis.
#[inline]
pub const fn get_coord_mut(&mut self, axis: Axis) -> &mut f64 {
match axis {
Axis::Horizontal => &mut self.x,
Axis::Vertical => &mut self.y,
}
}
/// Set the member matching the given axis to the given value.
#[inline]
pub const fn set_coord(&mut self, axis: Axis, value: f64) {
match axis {
Axis::Horizontal => self.x = value,
Axis::Vertical => self.y = value,
}
}
}
impl From<(f64, f64)> for Vec2 {
#[inline(always)]
fn from(v: (f64, f64)) -> Vec2 {
Vec2 { x: v.0, y: v.1 }
}
}
impl From<Vec2> for (f64, f64) {
#[inline(always)]
fn from(v: Vec2) -> (f64, f64) {
(v.x, v.y)
}
}
impl Add for Vec2 {
type Output = Vec2;
#[inline]
fn add(self, other: Vec2) -> Vec2 {
Vec2 {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl AddAssign for Vec2 {
#[inline]
fn add_assign(&mut self, other: Vec2) {
*self = Vec2 {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl Sum for Vec2 {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Vec2::ZERO, |sum, v| sum + v)
}
}
impl Sub for Vec2 {
type Output = Vec2;
#[inline]
fn sub(self, other: Vec2) -> Vec2 {
Vec2 {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl SubAssign for Vec2 {
#[inline]
fn sub_assign(&mut self, other: Vec2) {
*self = Vec2 {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl Mul<f64> for Vec2 {
type Output = Vec2;
#[inline]
fn mul(self, other: f64) -> Vec2 {
Vec2 {
x: self.x * other,
y: self.y * other,
}
}
}
impl MulAssign<f64> for Vec2 {
#[inline]
fn mul_assign(&mut self, other: f64) {
*self = Vec2 {
x: self.x * other,
y: self.y * other,
};
}
}
impl Mul<Vec2> for f64 {
type Output = Vec2;
#[inline]
fn mul(self, other: Vec2) -> Vec2 {
other * self
}
}
impl Div<f64> for Vec2 {
type Output = Vec2;
/// Note: division by a scalar is implemented by multiplying by the reciprocal.
///
/// This is more efficient but has different roundoff behavior than division.
#[inline]
#[allow(clippy::suspicious_arithmetic_impl)]
fn div(self, other: f64) -> Vec2 {
self * other.recip()
}
}
impl DivAssign<f64> for Vec2 {
#[inline]
fn div_assign(&mut self, other: f64) {
self.mul_assign(other.recip());
}
}
impl Neg for Vec2 {
type Output = Vec2;
#[inline]
fn neg(self) -> Vec2 {
Vec2 {
x: -self.x,
y: -self.y,
}
}
}
impl fmt::Display for Vec2 {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "𝐯=(")?;
fmt::Display::fmt(&self.x, formatter)?;
write!(formatter, ", ")?;
fmt::Display::fmt(&self.y, formatter)?;
write!(formatter, ")")
}
}
// Conversions to and from mint
#[cfg(feature = "mint")]
impl From<Vec2> for mint::Vector2<f64> {
#[inline(always)]
fn from(p: Vec2) -> mint::Vector2<f64> {
mint::Vector2 { x: p.x, y: p.y }
}
}
#[cfg(feature = "mint")]
impl From<mint::Vector2<f64>> for Vec2 {
#[inline(always)]
fn from(p: mint::Vector2<f64>) -> Vec2 {
Vec2 { x: p.x, y: p.y }
}
}
#[cfg(test)]
mod tests {
use core::f64::consts::FRAC_PI_2;
use super::*;
#[test]
fn display() {
let v = Vec2::new(1.2332421, 532.10721213123);
let s = format!("{v:.2}");
assert_eq!(s.as_str(), "𝐯=(1.23, 532.11)");
}
#[test]
fn cross_sign() {
let v = Vec2::new(1., 0.).cross(Vec2::new(0., 1.));
assert_eq!(v, 1.);
}
#[test]
fn turn_90() {
let u = Vec2::new(0.1, 0.2);
let turned = u.turn_90();
// This should be exactly equal by IEEE rules, might fail
// in fastmath conditions.
assert_eq!(u.length(), turned.length());
const EPSILON: f64 = 1e-12;
assert!((u.angle() + FRAC_PI_2 - turned.angle()).abs() < EPSILON);
}
#[test]
fn rotate_scale() {
let u = Vec2::new(0.1, 0.2);
let v = Vec2::new(0.3, -0.4);
let uv = u.rotate_scale(v);
const EPSILON: f64 = 1e-12;
assert!((u.length() * v.length() - uv.length()).abs() < EPSILON);
assert!((u.angle() + v.angle() - uv.angle()).abs() < EPSILON);
}
}