mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e23496e978 | ||
|
|
3704a954ca | ||
|
|
9ecbbb408b | ||
|
|
d743b22f1b | ||
|
|
b6459371a9 | ||
|
|
814c988592 | ||
|
|
264d8493ef | ||
|
|
68b7c25f52 | ||
|
|
10b57c9719 | ||
|
|
b1c0b6c173 | ||
|
|
16fc449a3c | ||
|
|
411d9f64b3 |
No files matched your search
Generated
+158
-10
@@ -1238,7 +1238,7 @@ dependencies = [
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"tinyvec",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
@@ -2135,6 +2135,9 @@ name = "float-cmp"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
@@ -2154,6 +2157,15 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.12.7"
|
||||
@@ -2195,7 +2207,7 @@ dependencies = [
|
||||
"linebender_resource_handle",
|
||||
"memmap2",
|
||||
"parlance",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -2432,6 +2444,21 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glifo"
|
||||
version = "0.4.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"foldhash 0.2.0",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"peniko",
|
||||
"skrifa 0.44.0",
|
||||
"smallvec",
|
||||
"vello_common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.4"
|
||||
@@ -2679,6 +2706,7 @@ dependencies = [
|
||||
"rendering",
|
||||
"repeat-nodes",
|
||||
"reqwest",
|
||||
"svg-convert",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
@@ -3038,7 +3066,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -3426,6 +3454,12 @@ dependencies = [
|
||||
"quick-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "imagesize"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
|
||||
|
||||
[[package]]
|
||||
name = "imagesize"
|
||||
version = "0.15.0"
|
||||
@@ -3798,6 +3832,33 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
"flate2",
|
||||
"float-cmp",
|
||||
"gif",
|
||||
"image-webp",
|
||||
"imagesize 0.14.0",
|
||||
"indexmap",
|
||||
"pdf-writer",
|
||||
"png 0.18.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"siphasher",
|
||||
"skrifa 0.42.1",
|
||||
"smallvec",
|
||||
"subsetter",
|
||||
"tiny-skia-path",
|
||||
"xmp-writer",
|
||||
"yoke",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kurbo"
|
||||
version = "0.13.1"
|
||||
@@ -5031,7 +5092,7 @@ dependencies = [
|
||||
"parlance",
|
||||
"parley_data",
|
||||
"parley_emoji",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5062,6 +5123,18 @@ dependencies = [
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdf-writer"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peer-transport"
|
||||
version = "0.0.0"
|
||||
@@ -5864,6 +5937,16 @@ dependencies = [
|
||||
"yasna",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.39.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.41.0"
|
||||
@@ -5871,7 +5954,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
@@ -6014,16 +6097,19 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"glifo",
|
||||
"graphene-application-io",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"krilla",
|
||||
"kurbo",
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
@@ -6601,6 +6687,12 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
@@ -6962,6 +7054,16 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.42.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
@@ -6969,7 +7071,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7148,6 +7250,18 @@ version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subsetter"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"rustc-hash 2.1.3",
|
||||
"skrifa 0.42.1",
|
||||
"write-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "substring"
|
||||
version = "1.4.5"
|
||||
@@ -7163,6 +7277,18 @@ version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "svg-convert"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"usvg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "svgtypes"
|
||||
version = "0.16.2"
|
||||
@@ -7318,7 +7444,7 @@ dependencies = [
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"thiserror 2.0.21",
|
||||
"titlecase",
|
||||
"tsify",
|
||||
@@ -7918,14 +8044,14 @@ dependencies = [
|
||||
"flate2",
|
||||
"fontdb",
|
||||
"harfrust",
|
||||
"imagesize",
|
||||
"imagesize 0.15.0",
|
||||
"kurbo",
|
||||
"log",
|
||||
"pico-args",
|
||||
"roxmltree 0.21.2",
|
||||
"simplecss",
|
||||
"siphasher",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"strict-num",
|
||||
"svgtypes",
|
||||
"tiny-skia-path",
|
||||
@@ -8010,6 +8136,7 @@ dependencies = [
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsify",
|
||||
@@ -8086,6 +8213,7 @@ version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"glifo",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
@@ -8568,6 +8696,7 @@ dependencies = [
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"vello_gpu",
|
||||
"web-sys",
|
||||
@@ -9268,6 +9397,19 @@ dependencies = [
|
||||
"toml 0.5.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "write-fonts"
|
||||
version = "0.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
|
||||
dependencies = [
|
||||
"font-types 0.11.3",
|
||||
"indexmap",
|
||||
"kurbo",
|
||||
"log",
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
@@ -9408,6 +9550,12 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||
|
||||
[[package]]
|
||||
name = "xmp-writer"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "yansi"
|
||||
version = "1.0.1"
|
||||
|
||||
+5
-1
@@ -99,6 +99,7 @@ graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
|
||||
brush-types = { path = "node-graph/libraries/brush-types" }
|
||||
rendering = { path = "node-graph/libraries/rendering" }
|
||||
svg-convert = { path = "node-graph/libraries/svg-convert" }
|
||||
brush-nodes = { path = "node-graph/nodes/brush" }
|
||||
blending-nodes = { path = "node-graph/nodes/blending" }
|
||||
graphene-core = { path = "node-graph/nodes/gcore" }
|
||||
@@ -214,7 +215,9 @@ url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support", "text"] }
|
||||
glifo = { version = "0.4", default-features = false, features = ["std"] }
|
||||
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
|
||||
usvg = "0.49"
|
||||
simplecss = "0.2"
|
||||
parley = { version = "0.12", default-features = false, features = ["std"] }
|
||||
@@ -317,3 +320,4 @@ fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "2
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
glifo = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
Generated
BIN
Binary file not shown.
@@ -1,4 +1,3 @@
|
||||
//! Migrations of the nodes in `graphene_std`.
|
||||
|
||||
mod rasterize_v1;
|
||||
mod renames;
|
||||
@@ -1,68 +0,0 @@
|
||||
use migration_core::{Inputs, MigrationError, NodeInput, migration};
|
||||
use serde::Serialize;
|
||||
|
||||
const EXECUTOR: u32 = 2;
|
||||
const EXECUTOR_SCOPE: &str = "graphene_std::platform_application_io::WgpuExecutorNode";
|
||||
|
||||
/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses.
|
||||
#[derive(Serialize)]
|
||||
enum Reflected {
|
||||
DocumentNodePath,
|
||||
}
|
||||
|
||||
/// Rasterize gained an input holding its own document node path. Nodes stored without the executor input get it first, so the path lands after it.
|
||||
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
|
||||
pub fn rasterize_v1(inputs: &mut Inputs) -> Result<(), MigrationError> {
|
||||
if inputs.len() < EXECUTOR as usize {
|
||||
return Err(MigrationError::invariant("Rasterize has Data and Footprint inputs"));
|
||||
}
|
||||
if inputs.len() == EXECUTOR as usize {
|
||||
inputs.push(NodeInput::Scope(EXECUTOR_SCOPE.into()));
|
||||
}
|
||||
|
||||
inputs.push_reflection(Reflected::DocumentNodePath);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
fn migrate(inputs: Vec<NodeInput>) -> Vec<NodeInput> {
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let rasterize = fixture.add(decl!("graphene_std::platform_application_io::RasterizeNode"@1), inputs);
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let own_path = &migrated.node_instances[&rasterize].inputs()[3];
|
||||
assert_eq!(own_path.attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
|
||||
|
||||
fixture.inputs(&migrated, rasterize)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RasterizeV1, &contract());
|
||||
check_undo(&RasterizeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gives_the_node_its_path() {
|
||||
let inputs = vec![literal(1.), literal(2.), NodeInput::Scope(EXECUTOR_SCOPE.into())];
|
||||
|
||||
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Reflection]].concat());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_stored_without_its_executor_gets_it_before_its_path() {
|
||||
let inputs = vec![literal(1.), literal(2.)];
|
||||
|
||||
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Scope(EXECUTOR_SCOPE.into()), NodeInput::Reflection]].concat());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
use migration_core::attr::node::ui::POSITION;
|
||||
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, Inputs, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Integer(i64),
|
||||
DVec2([f64; 2]),
|
||||
MandelbrotFractal(MandelbrotFractal),
|
||||
MandelbrotExterior(MandelbrotExterior),
|
||||
MandelbrotInterior(MandelbrotInterior),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MandelbrotFractal {
|
||||
ClassicMandelbrot,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MandelbrotExterior {
|
||||
SmoothEscape,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MandelbrotInterior {
|
||||
Flat,
|
||||
}
|
||||
|
||||
/// How far the old unit square, which spanned the complex plane from -2 to 1, placed the plane's origin from the pattern's.
|
||||
const OLD_ORIGIN: [f64; 2] = [2. / 3., 0.5];
|
||||
|
||||
/// 'Mandelbrot' gained a scale and settings for its fractal, its slice toward the Julia set, and its interior and exterior, and the complex plane's origin moved to the pattern's.
|
||||
/// A third of a unit's scale and a Transform moving the pattern back to the old origin keep its look.
|
||||
#[migration("raster_nodes::std_nodes::MandelbrotNode"@2 => @3)]
|
||||
pub fn mandelbrot_v2(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) {
|
||||
for input in new_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
|
||||
let consumers = downstream.consumers(0);
|
||||
if consumers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let origin = downstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
inputs: vec![
|
||||
NodeInput::Node { id: node.id(), index: 0 },
|
||||
literal(Tagged::DVec2(OLD_ORIGIN)),
|
||||
literal(Tagged::Number(0.)),
|
||||
literal(Tagged::DVec2([1., 1.])),
|
||||
literal(Tagged::DVec2([0., 0.])),
|
||||
],
|
||||
},
|
||||
"origin",
|
||||
);
|
||||
for consumer in consumers {
|
||||
downstream.connect(OutputConnector { node: origin, output: 0 }, consumer);
|
||||
}
|
||||
|
||||
// The Transform takes the pattern's place, with the pattern before it
|
||||
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
|
||||
attributes.set(origin, POSITION, &stored);
|
||||
}
|
||||
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
|
||||
}
|
||||
|
||||
/// The settings 'Mandelbrot' gained, in the order of its parameters, with the scale matching the old unit square's three units of the plane.
|
||||
fn new_inputs() -> [NodeInput; 10] {
|
||||
[
|
||||
literal(Tagged::MandelbrotFractal(MandelbrotFractal::ClassicMandelbrot)),
|
||||
literal(Tagged::MandelbrotExterior(MandelbrotExterior::SmoothEscape)),
|
||||
literal(Tagged::MandelbrotInterior(MandelbrotInterior::Flat)),
|
||||
literal(Tagged::Integer(1)),
|
||||
literal(Tagged::Number(1. / 3.)),
|
||||
literal(Tagged::Integer(256)),
|
||||
literal(Tagged::Number(2.)),
|
||||
literal(Tagged::Number(0.)),
|
||||
literal(Tagged::DVec2([0., 0.])),
|
||||
literal(Tagged::DVec2([-0.8, 0.156])),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(1, |_, _| literal(Tagged::None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MandelbrotV2, &contract());
|
||||
check_undo(&MandelbrotV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_primary_input_and_adds_the_settings() {
|
||||
let mut fixture = Fixture::new(&MandelbrotV2);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@2), vec![literal(Tagged::None)]);
|
||||
let migrated = fixture.migrate(&MandelbrotV2).unwrap();
|
||||
|
||||
let mut expected = vec![literal(Tagged::None)];
|
||||
expected.extend(new_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, mandelbrot), Some(decl!("raster_nodes::std_nodes::MandelbrotNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, mandelbrot), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whatever_read_the_pattern_reads_it_moved_back_to_the_old_origin() {
|
||||
let mut fixture = Fixture::new(&MandelbrotV2);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@2), vec![literal(Tagged::None)]);
|
||||
let consumer = fixture.add(decl!("migration_testing::consumer"@1), vec![NodeInput::Node { id: mandelbrot, index: 0 }]);
|
||||
let migrated = fixture.migrate(&MandelbrotV2).unwrap();
|
||||
|
||||
let NodeInput::Node { id: origin, .. } = fixture.inputs(&migrated, consumer)[0] else {
|
||||
panic!("the consumer should read a node")
|
||||
};
|
||||
assert_eq!(fixture.declaration_of(&migrated, origin), Some(decl!("transform_nodes::transform_nodes::TransformNode"@1)));
|
||||
|
||||
let inputs = fixture.inputs(&migrated, origin);
|
||||
assert_eq!(inputs[0], NodeInput::Node { id: mandelbrot, index: 0 });
|
||||
assert_eq!(inputs[1], literal(Tagged::DVec2(OLD_ORIGIN)));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Migrations of the nodes in `raster_nodes`.
|
||||
|
||||
mod mandelbrot_v1;
|
||||
mod mandelbrot_v2;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod pattern_square;
|
||||
|
||||
@@ -6,3 +6,5 @@ rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_n
|
||||
// Version 2 only adds `InjectFootprint` to the context bounds, so stored nodes keep their layout
|
||||
rename!("core_types::vector::AreaNode"@1 => @2);
|
||||
rename!("core_types::vector::CentroidNode"@1 => @2);
|
||||
// Version 2 only lets its output carry an error, so stored nodes keep their layout
|
||||
rename!("core_types::vector::ScatterPointsNode"@1 => @2);
|
||||
@@ -18,7 +18,8 @@ pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.;
|
||||
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
|
||||
pub const VIEWPORT_ZOOM_MOUSE_RATE: f64 = 1. / 400.;
|
||||
pub const VIEWPORT_ZOOM_SCALE_MIN: f64 = 0.000_000_1;
|
||||
pub const VIEWPORT_ZOOM_SCALE_MAX: f64 = 10_000.;
|
||||
/// Deep enough to reach the limits of 64-bit precision, which still places each pixel precisely around document coordinates in the thousands.
|
||||
pub const VIEWPORT_ZOOM_SCALE_MAX: f64 = 10_000_000_000.;
|
||||
pub const VIEWPORT_ZOOM_MIN_FRACTION_COVER: f64 = 0.01;
|
||||
pub const VIEWPORT_ZOOM_LEVELS: [f64; 74] = [
|
||||
0.0001, 0.000125, 0.00016, 0.0002, 0.00025, 0.00032, 0.0004, 0.0005, 0.00064, 0.0008, 0.001, 0.0016, 0.002, 0.0025, 0.0032, 0.004, 0.005, 0.0064, 0.008, 0.01, 0.01125, 0.015, 0.02, 0.025, 0.03,
|
||||
|
||||
@@ -103,22 +103,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
DialogMessage::RequestExportDialog => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
let artboards = document
|
||||
.metadata()
|
||||
.all_layers()
|
||||
.filter(|&layer| document.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| {
|
||||
let name = document
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
.collect();
|
||||
|
||||
self.export_dialog.artboards = artboards;
|
||||
self.export_dialog.artboards = document.artboard_names().into_iter().collect();
|
||||
|
||||
if let ExportBounds::Artboard(layer) = self.export_dialog.bounds
|
||||
&& !self.export_dialog.artboards.contains_key(&layer)
|
||||
|
||||
@@ -94,9 +94,9 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||
|
||||
impl LayoutHolder for ExportDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
// The vector type, then the raster ones
|
||||
// The vector types, then the raster ones
|
||||
let file_types = [
|
||||
vec![(FileType::Svg, "SVG")],
|
||||
vec![(FileType::Svg, "SVG"), (FileType::Pdf, "PDF")],
|
||||
vec![
|
||||
(FileType::Png, "PNG"),
|
||||
(FileType::Jpg, "JPG"),
|
||||
@@ -131,14 +131,25 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let scale_description = match self.file_type {
|
||||
FileType::Pdf => "Resolution of the images of effects and other content PDF can't draw itself, where 1 is 300 DPI.",
|
||||
_ => "Size of the exported image relative to the document's size.",
|
||||
};
|
||||
let resolution = vec![
|
||||
TextLabel::new("Scale Factor").table_align(true).sizing(WidgetSizing::fixed(100)).widget_instance(),
|
||||
TextLabel::new("Scale Factor")
|
||||
.table_align(true)
|
||||
.sizing(WidgetSizing::fixed(100))
|
||||
.tooltip_label("Scale Factor")
|
||||
.tooltip_description(scale_description)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.scale_factor))
|
||||
.unit("")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.increment_step(0.5)
|
||||
.tooltip_label("Scale Factor")
|
||||
.tooltip_description(scale_description)
|
||||
.disabled(self.file_type == FileType::Svg)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
||||
.sizing(WidgetSizing::default().min_width(200))
|
||||
|
||||
@@ -78,6 +78,7 @@ pub enum FileType {
|
||||
Tga,
|
||||
Ico,
|
||||
Svg,
|
||||
Pdf,
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
@@ -91,9 +92,15 @@ impl FileType {
|
||||
FileType::Tga => "tga",
|
||||
FileType::Ico => "ico",
|
||||
FileType::Svg => "svg",
|
||||
FileType::Pdf => "pdf",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file holds vector content rather than an image of the export's area.
|
||||
pub fn is_vector(self) -> bool {
|
||||
matches!(self, FileType::Svg | FileType::Pdf)
|
||||
}
|
||||
|
||||
pub fn file_filter(self) -> FileFilter {
|
||||
let name = match self {
|
||||
FileType::Png => "PNG Image",
|
||||
@@ -104,6 +111,7 @@ impl FileType {
|
||||
FileType::Tga => "TGA Image",
|
||||
FileType::Ico => "ICO Image",
|
||||
FileType::Svg => "SVG Image",
|
||||
FileType::Pdf => "PDF Document",
|
||||
};
|
||||
FileFilter {
|
||||
name: name.into(),
|
||||
@@ -129,7 +137,7 @@ impl FileType {
|
||||
FileType::Bmp => ImageFormat::Bmp,
|
||||
FileType::Tga => ImageFormat::Tga,
|
||||
FileType::Ico => ImageFormat::Ico,
|
||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||
FileType::Svg | FileType::Pdf => return Err(format!("{} cannot be exported from an image buffer", self.extension().to_uppercase())),
|
||||
};
|
||||
if self == FileType::Ico && (width > 256 || height > 256) {
|
||||
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
|
||||
@@ -228,6 +236,7 @@ mod tests {
|
||||
#[test]
|
||||
fn file_types_that_cannot_hold_the_image_say_so() {
|
||||
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Pdf.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
|
||||
|
||||
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
|
||||
|
||||
@@ -16,8 +16,8 @@ use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
use graphene_std::raster::{
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior,
|
||||
NoiseType, RedGreenBlue, RelativeAbsolute, SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::text::TextAlign;
|
||||
@@ -436,6 +436,9 @@ macro_rules! inspectable_types {
|
||||
List<CellularDistanceFunction>,
|
||||
List<CellularReturnType>,
|
||||
List<DomainWarpType>,
|
||||
List<MandelbrotFractal>,
|
||||
List<MandelbrotExterior>,
|
||||
List<MandelbrotInterior>,
|
||||
List<RealTimeMode>,
|
||||
List<GridType>,
|
||||
List<GridTopology>,
|
||||
@@ -493,6 +496,9 @@ macro_rules! inspectable_types {
|
||||
Item<CellularDistanceFunction>,
|
||||
Item<CellularReturnType>,
|
||||
Item<DomainWarpType>,
|
||||
Item<MandelbrotFractal>,
|
||||
Item<MandelbrotExterior>,
|
||||
Item<MandelbrotInterior>,
|
||||
Item<RealTimeMode>,
|
||||
Item<GridType>,
|
||||
Item<GridTopology>,
|
||||
@@ -1291,6 +1297,9 @@ impl_table_item_layout_for_choice_enum!(
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
MandelbrotFractal,
|
||||
MandelbrotExterior,
|
||||
MandelbrotInterior,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
GridTopology,
|
||||
@@ -1472,6 +1481,9 @@ macro_rules! known_item_types {
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
MandelbrotFractal,
|
||||
MandelbrotExterior,
|
||||
MandelbrotInterior,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
GridTopology,
|
||||
|
||||
@@ -319,9 +319,6 @@ pub enum DocumentMessage {
|
||||
UpdateTextFrames {
|
||||
text_frames: HashMap<NodeId, DAffine2>,
|
||||
},
|
||||
UpdateFootprintAreas {
|
||||
footprint_areas: HashMap<NodeId, DAffine2>,
|
||||
},
|
||||
UpdateClipTargets {
|
||||
clip_targets: HashSet<NodeId>,
|
||||
},
|
||||
|
||||
@@ -1914,9 +1914,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_text_frames(layer_text_frames);
|
||||
}
|
||||
DocumentMessage::UpdateFootprintAreas { footprint_areas } => {
|
||||
self.network_interface.update_footprint_areas(footprint_areas);
|
||||
}
|
||||
DocumentMessage::UpdateClipTargets { clip_targets } => {
|
||||
self.network_interface.update_clip_targets(clip_targets);
|
||||
}
|
||||
@@ -2159,15 +2156,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
} else {
|
||||
self.network_interface.document_bounds_document_space(true)
|
||||
};
|
||||
if let Some(bounds) = bounds {
|
||||
if self.document_ptz.flip {
|
||||
responses.add(NavigationMessage::CanvasFlip);
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
|
||||
responses.add(NavigationMessage::FitViewportToBounds { bounds, prevent_zoom_past_100: true });
|
||||
} else {
|
||||
warn!("Cannot zoom due to no bounds")
|
||||
// With nothing to frame, like a generator's pattern filling the plane, a tiny area at the origin is framed, which centers the origin at 100%
|
||||
let bounds = bounds.unwrap_or([DVec2::splat(-1.), DVec2::splat(1.)]);
|
||||
|
||||
if self.document_ptz.flip {
|
||||
responses.add(NavigationMessage::CanvasFlip);
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
|
||||
responses.add(NavigationMessage::FitViewportToBounds { bounds, prevent_zoom_past_100: true });
|
||||
}
|
||||
DocumentMessage::Noop => (),
|
||||
}
|
||||
@@ -2449,6 +2445,20 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
/// The document's artboards with their names, called "Artboard" while left unnamed.
|
||||
pub fn artboard_names(&self) -> Vec<(LayerNodeIdentifier, String)> {
|
||||
(self.metadata().all_layers())
|
||||
.filter(|&layer| self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| {
|
||||
let name = (self.network_interface.node_metadata(&layer.to_node(), &[]))
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
|
||||
&self.breadcrumb_network_path
|
||||
}
|
||||
@@ -4730,8 +4740,8 @@ pub fn navigation_controls(ptz: &PTZ, navigation_handler: &NavigationMessageHand
|
||||
vec![
|
||||
NumberInput::new(Some(navigation_handler.snapped_zoom(ptz.zoom()) * 100.))
|
||||
.unit("%")
|
||||
.min(0.000001)
|
||||
.max(1000000.)
|
||||
.min(crate::consts::VIEWPORT_ZOOM_SCALE_MIN * 100.)
|
||||
.max(crate::consts::VIEWPORT_ZOOM_SCALE_MAX * 100.)
|
||||
.tooltip_label(if node_graph { "Node Graph Zoom" } else { "Canvas Zoom" })
|
||||
.sizing(WidgetSizing::default().min_width(80))
|
||||
.on_update(|number_input: &NumberInput| {
|
||||
@@ -4798,6 +4808,69 @@ mod document_message_handler_tests {
|
||||
use crate::messages::portfolio::document::utility_types::misc::GridType;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn zooming_to_fit_nothing_centers_the_origin_at_100_percent() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
|
||||
|
||||
// Zoomed, panned, and tilted away in a document with nothing to frame
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 7. }).await;
|
||||
editor.handle_message(NavigationMessage::CanvasPan { delta: DVec2::new(300., -200.) }).await;
|
||||
editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 0.5 }).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::ZoomCanvasToFitAll).await;
|
||||
|
||||
let ptz = editor.active_document().document_ptz;
|
||||
assert_eq!(ptz.zoom(), 1.);
|
||||
assert_eq!(ptz.tilt(), 0.);
|
||||
assert!(ptz.pan.length() < 1e-9, "the view is panned by {}", ptz.pan);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn zooming_to_100_percent_reaches_it_with_only_a_tiny_shape_in_the_document() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
|
||||
|
||||
// A shape about a millionth of a unit across, drawn while zoomed far in
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 10_000_000. }).await;
|
||||
editor.draw_ellipse(100., 100., 110., 110.).await;
|
||||
assert!(editor.active_document().network_interface.document_bounds_document_space(true).is_some());
|
||||
|
||||
editor.handle_message(DocumentMessage::ZoomCanvasTo100Percent).await;
|
||||
assert_eq!(editor.active_document().document_ptz.zoom(), 1.);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wheeling_in_at_the_deepest_zoom_leaves_the_view_in_place() {
|
||||
use crate::consts::VIEWPORT_ZOOM_SCALE_MAX;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta};
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: VIEWPORT_ZOOM_SCALE_MAX }).await;
|
||||
let pan = editor.active_document().document_ptz.pan;
|
||||
|
||||
// Ctrl+wheel zooming in, which heads toward the pointer away from the viewport's center
|
||||
let editor_mouse_state = EditorPointerState {
|
||||
editor_position: DVec2::new(100., 100.),
|
||||
scroll_delta: ScrollDelta { x: 0., y: -100., z: 0. },
|
||||
..Default::default()
|
||||
};
|
||||
editor
|
||||
.input(InputPreprocessorMessage::WheelScroll {
|
||||
editor_mouse_state,
|
||||
modifier_keys: ModifierKeys::CONTROL,
|
||||
})
|
||||
.await;
|
||||
|
||||
let ptz = editor.active_document().document_ptz;
|
||||
assert_eq!(ptz.zoom(), VIEWPORT_ZOOM_SCALE_MAX);
|
||||
assert_eq!(ptz.pan, pan);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deleting_the_bottom_layer_leaves_the_layer_above_it_the_empty_stack_value() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -206,9 +206,6 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||
]);
|
||||
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
|
||||
.expect("Text to Vector node does not exist")
|
||||
.default_node_template();
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
@@ -216,17 +213,13 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.expect("Fill node does not exist")
|
||||
.default_node_template();
|
||||
|
||||
// Build the chain `Text -> Text to Vector -> Transform -> Fill -> layer`
|
||||
// Build the chain `Text -> Transform -> Fill -> layer`, keeping the text native so backends lay out and draw its glyphs
|
||||
let text_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_id, text, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
|
||||
|
||||
self.responses.add(DocumentMessage::Resource(ResourceMessage::AddFont { resource_id: font_resource_id, font }));
|
||||
|
||||
let text_to_vector_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_to_vector_id, text_to_vector, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_to_vector_id, layer, &[], self.import);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
|
||||
|
||||
@@ -211,22 +211,36 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
}
|
||||
NavigationMessage::CanvasZoomDecrease { center_on_mouse } => {
|
||||
let document_bounds = if !graph_view_overlay_open {
|
||||
// TODO: Cache this in node graph coordinates and apply the transform to the rectangle to get viewport coordinates
|
||||
network_interface.document_bounds_viewport_space(true)
|
||||
} else {
|
||||
network_interface.graph_bounds_viewport_space(breadcrumb_network_path)
|
||||
};
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let new_scale = *VIEWPORT_ZOOM_LEVELS.iter().rev().find(|scale| **scale < ptz.zoom()).unwrap_or(&ptz.zoom());
|
||||
let new_scale = zoom_levels().take_while(|&scale| scale < ptz.zoom()).last().unwrap_or(ptz.zoom());
|
||||
let new_scale = (new_scale * Self::clamp_zoom(new_scale, document_bounds, old_zoom, viewport)).clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
|
||||
if center_on_mouse {
|
||||
responses.add(self.center_zoom(viewport.size().into(), new_scale / ptz.zoom(), ipp.mouse.position));
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasZoomSet { zoom_factor: new_scale });
|
||||
}
|
||||
NavigationMessage::CanvasZoomIncrease { center_on_mouse } => {
|
||||
let document_bounds = if !graph_view_overlay_open {
|
||||
// TODO: Cache this in node graph coordinates and apply the transform to the rectangle to get viewport coordinates
|
||||
network_interface.document_bounds_viewport_space(true)
|
||||
} else {
|
||||
network_interface.graph_bounds_viewport_space(breadcrumb_network_path)
|
||||
};
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let new_scale = *VIEWPORT_ZOOM_LEVELS.iter().find(|scale| **scale > ptz.zoom()).unwrap_or(&ptz.zoom());
|
||||
let new_scale = zoom_levels().find(|&scale| scale > ptz.zoom()).unwrap_or(ptz.zoom());
|
||||
let new_scale = (new_scale * Self::clamp_zoom(new_scale, document_bounds, old_zoom, viewport)).clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
|
||||
if center_on_mouse {
|
||||
responses.add(self.center_zoom(viewport.size().into(), new_scale / ptz.zoom(), ipp.mouse.position));
|
||||
}
|
||||
@@ -250,25 +264,18 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
|
||||
zoom_factor *= Self::clamp_zoom(ptz.zoom() * zoom_factor, document_bounds, old_zoom, viewport);
|
||||
|
||||
responses.add(self.center_zoom(viewport.size().into(), zoom_factor, ipp.mouse.position));
|
||||
responses.add(NavigationMessage::CanvasZoomSet {
|
||||
zoom_factor: ptz.zoom() * zoom_factor,
|
||||
});
|
||||
// Held to the zoom range before panning toward the pointer, so wheeling against a limit leaves the view in place
|
||||
let zoom = (ptz.zoom() * zoom_factor).clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
|
||||
responses.add(self.center_zoom(viewport.size().into(), zoom / ptz.zoom(), ipp.mouse.position));
|
||||
responses.add(NavigationMessage::CanvasZoomSet { zoom_factor: zoom });
|
||||
}
|
||||
// Sets exactly the zoom asked for, since the steps and gestures that keep the content from shrinking out of sight do so before sending it
|
||||
NavigationMessage::CanvasZoomSet { zoom_factor } => {
|
||||
let document_bounds = if !graph_view_overlay_open {
|
||||
// TODO: Cache this in node graph coordinates and apply the transform to the rectangle to get viewport coordinates
|
||||
network_interface.document_bounds_viewport_space(true)
|
||||
} else {
|
||||
network_interface.graph_bounds_viewport_space(breadcrumb_network_path)
|
||||
};
|
||||
let Some(ptz) = get_ptz_mut(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
log::error!("Could not get mutable PTZ in CanvasZoomSet");
|
||||
return;
|
||||
};
|
||||
let zoom = zoom_factor.clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
|
||||
let zoom = zoom * Self::clamp_zoom(zoom, document_bounds, old_zoom, viewport);
|
||||
ptz.set_zoom(zoom);
|
||||
ptz.set_zoom(zoom_factor.clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX));
|
||||
if graph_view_overlay_open {
|
||||
responses.add(NodeGraphMessage::UpdateGraphBarRight);
|
||||
} else {
|
||||
@@ -591,8 +598,31 @@ impl NavigationMessageHandler {
|
||||
|
||||
pub fn snapped_zoom(navigation_operation: &NavigationOperation, zoom: f64) -> f64 {
|
||||
if matches!(navigation_operation, NavigationOperation::Zoom { snap: true, .. }) {
|
||||
*VIEWPORT_ZOOM_LEVELS.iter().min_by(|a, b| (**a - zoom).abs().partial_cmp(&(**b - zoom).abs()).unwrap()).unwrap_or(&zoom)
|
||||
zoom_levels().min_by(|a, b| (a - zoom).abs().total_cmp(&(b - zoom).abs())).unwrap_or(zoom)
|
||||
} else {
|
||||
zoom
|
||||
}
|
||||
}
|
||||
|
||||
/// The preset zoom levels, ascending: the listed ones, then 1, 1.25, and 1.5625 times each power of two (as the list ends with) up to the deepest zoom.
|
||||
fn zoom_levels() -> impl Iterator<Item = f64> {
|
||||
let last_listed = VIEWPORT_ZOOM_LEVELS[VIEWPORT_ZOOM_LEVELS.len() - 1];
|
||||
let doubling_steps = (0..).flat_map(|power| [1., 1.25, 1.5625].map(|step| 2_f64.powi(power) * step));
|
||||
|
||||
VIEWPORT_ZOOM_LEVELS
|
||||
.into_iter()
|
||||
.chain(doubling_steps.skip_while(move |&level| level <= last_listed).take_while(|&level| level < VIEWPORT_ZOOM_SCALE_MAX))
|
||||
.chain([VIEWPORT_ZOOM_SCALE_MAX])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_zoom_levels_step_up_evenly_to_the_deepest_zoom() {
|
||||
let levels: Vec<f64> = zoom_levels().collect();
|
||||
assert!(levels.windows(2).all(|pair| pair[1] > pair[0] && pair[1] / pair[0] <= 1.6), "{levels:?}");
|
||||
assert_eq!(levels.last(), Some(&VIEWPORT_ZOOM_SCALE_MAX));
|
||||
}
|
||||
}
|
||||
@@ -924,6 +924,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
&unit,
|
||||
min,
|
||||
is_integer,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
);
|
||||
@@ -1077,6 +1078,49 @@ fn static_input_inspector() -> InputInspector {
|
||||
Ok(vec![cellular_return_type])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"mandelbrot_inspector_frequency".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let tendrils_or_rays = node_inspector::query_mandelbrot_tendrils_or_rays(node_id, context)?;
|
||||
let frequency = node_inspector::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default().min(1.).max(64.).is_integer(true).disabled(!tendrils_or_rays),
|
||||
);
|
||||
Ok(vec![frequency.into()])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"mandelbrot_inspector_mandelbrot_slice".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mandelbrot_to_julia = node_inspector::query_mandelbrot_to_julia(node_id, context)?;
|
||||
let mandelbrot_slice = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
mandelbrot_slice,
|
||||
"X",
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"mandelbrot_inspector_julia_slice".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mandelbrot_to_julia = node_inspector::query_mandelbrot_to_julia(node_id, context)?;
|
||||
let julia_slice = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
julia_slice,
|
||||
"X",
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_cellular_jitter".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -1179,6 +1223,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
" px",
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
);
|
||||
@@ -1193,6 +1238,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"x",
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
);
|
||||
@@ -1311,7 +1357,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"vec2_uv".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false)])
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false, false)])
|
||||
}),
|
||||
);
|
||||
map
|
||||
|
||||
@@ -23,8 +23,8 @@ use graph_craft::{Type, concrete, item};
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::{
|
||||
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, MandelbrotExterior, MandelbrotFractal,
|
||||
MandelbrotInterior, NoiseType, RedGreenBlue, RelativeAbsolute, SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
@@ -384,7 +384,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
true => text_area_widget(default_info).into(),
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false),
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
@@ -419,6 +419,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
Some(x) if id_is::<MandelbrotFractal>(x) => enum_choice::<MandelbrotFractal>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MandelbrotExterior>(x) => enum_choice::<MandelbrotExterior>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MandelbrotInterior>(x) => enum_choice::<MandelbrotInterior>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
@@ -877,7 +880,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
||||
}
|
||||
}
|
||||
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool) -> LayoutGroup {
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
@@ -894,6 +897,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -904,6 +908,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -918,6 +923,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -928,6 +934,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -1637,6 +1644,38 @@ pub fn query_node_and_input_info<'a>(node_id: NodeId, input_index: usize, contex
|
||||
Ok((document_node, name, description))
|
||||
}
|
||||
|
||||
/// Whether a Mandelbrot node's exterior or interior has tendrils or rays for Frequency to set, which a wired one may.
|
||||
pub fn query_mandelbrot_tendrils_or_rays(node_id: NodeId, context: &NodeInspectorContext) -> Result<bool, String> {
|
||||
let document_node = get_document_node(node_id, context)?;
|
||||
|
||||
let exterior = document_node.inputs.iter().find_map(|input| match input.as_value() {
|
||||
Some(&TaggedValue::MandelbrotExterior(exterior)) => Some(exterior),
|
||||
_ => None,
|
||||
});
|
||||
let interior = document_node.inputs.iter().find_map(|input| match input.as_value() {
|
||||
Some(&TaggedValue::MandelbrotInterior(interior)) => Some(interior),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let exterior_uses_frequency = matches!(exterior, None | Some(MandelbrotExterior::Tendrils | MandelbrotExterior::Rays));
|
||||
let interior_uses_frequency = matches!(interior, None | Some(MandelbrotInterior::Rays));
|
||||
Ok(exterior_uses_frequency || interior_uses_frequency)
|
||||
}
|
||||
|
||||
/// A Mandelbrot node's Mandelbrot-to-Julia percentage, unless it's wired.
|
||||
pub fn query_mandelbrot_to_julia(node_id: NodeId, context: &NodeInspectorContext) -> Result<Option<f64>, String> {
|
||||
let document_node = get_document_node(node_id, context)?;
|
||||
Ok(
|
||||
match document_node
|
||||
.input(graphene_std::raster_nodes::std_nodes::mandelbrot::MandelbrotToJuliaInput)
|
||||
.and_then(|input| input.as_value())
|
||||
{
|
||||
Some(&TaggedValue::Number(percent)) => Some(percent),
|
||||
_ => None,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn query_noise_pattern_state(node_id: NodeId, context: &NodeInspectorContext) -> Result<(bool, bool, bool, bool, bool, bool), String> {
|
||||
let document_node = get_document_node(node_id, context)?;
|
||||
let current_noise_type = document_node.inputs.iter().find_map(|input| match input.as_value() {
|
||||
@@ -2721,10 +2760,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
||||
NumberInput::default().label("H").min(0.).unit(" px"),
|
||||
));
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false);
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false);
|
||||
widgets.extend([spacing, angles]);
|
||||
} else {
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false);
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false);
|
||||
widgets.push(spacing);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -638,6 +638,73 @@ fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static
|
||||
VelloSceneBuilder::new(size.x as u16, size.y as u16, Affine::IDENTITY, MAX_TEXTURE_SIZE)
|
||||
}
|
||||
|
||||
/// How closely the segments that [`pieces_in_view`] walks follow an overlay's curves, in logical pixels.
|
||||
const OVERLAY_SHAPE_TOLERANCE: f64 = 0.1;
|
||||
|
||||
/// Whether `outer` contains all of `inner`.
|
||||
fn rect_contains(outer: kurbo::Rect, inner: kurbo::Rect) -> bool {
|
||||
inner.x0 >= outer.x0 && inner.y0 >= outer.y0 && inner.x1 <= outer.x1 && inner.y1 <= outer.y1
|
||||
}
|
||||
|
||||
/// The parts of `path` that may show within `visible`, each with how far along its subpath it starts.
|
||||
/// A segment crossing the edge of `visible` is split in half until each half lies inside or outside it, so one far larger than the viewport costs only the log of its size.
|
||||
fn pieces_in_view(path: &BezPath, visible: kurbo::Rect) -> Vec<(f64, BezPath)> {
|
||||
// Halves this small are kept whole, as are those split this many times
|
||||
const SMALLEST_SPLIT: f64 = 1.;
|
||||
const MAX_SPLITS: u32 = 64;
|
||||
const ARC_LENGTH_ACCURACY: f64 = 1e-3;
|
||||
|
||||
let overlaps = |bounds: kurbo::Rect| bounds.x0 <= visible.x1 && bounds.x1 >= visible.x0 && bounds.y0 <= visible.y1 && bounds.y1 >= visible.y0;
|
||||
|
||||
let mut pieces: Vec<(f64, BezPath)> = Vec::new();
|
||||
let (mut previous, mut subpath_start) = (kurbo::Point::ZERO, kurbo::Point::ZERO);
|
||||
let mut distance = 0.;
|
||||
// Whether the last piece ends where the next kept segment starts, so that segment extends it
|
||||
let mut continuing = false;
|
||||
|
||||
for element in path.elements() {
|
||||
let segment = match *element {
|
||||
kurbo::PathEl::MoveTo(point) => {
|
||||
(previous, subpath_start, distance, continuing) = (point, point, 0., false);
|
||||
continue;
|
||||
}
|
||||
kurbo::PathEl::LineTo(point) => PathSeg::Line(kurbo::Line::new(previous, point)),
|
||||
kurbo::PathEl::QuadTo(control, point) => PathSeg::Quad(kurbo::QuadBez::new(previous, control, point)),
|
||||
kurbo::PathEl::CurveTo(control_start, control_end, point) => PathSeg::Cubic(kurbo::CubicBez::new(previous, control_start, control_end, point)),
|
||||
kurbo::PathEl::ClosePath => PathSeg::Line(kurbo::Line::new(previous, subpath_start)),
|
||||
};
|
||||
previous = segment.end();
|
||||
|
||||
// Halves wait on a stack, the second beneath the first, so they're visited in order along the path
|
||||
let mut pending = vec![(segment, 0)];
|
||||
while let Some((segment, splits)) = pending.pop() {
|
||||
let bounds = kurbo::Shape::bounding_box(&segment);
|
||||
let kept = overlaps(bounds);
|
||||
if kept && !rect_contains(visible, bounds) && bounds.width().max(bounds.height()) > SMALLEST_SPLIT && splits < MAX_SPLITS {
|
||||
let (first, second) = segment.subdivide();
|
||||
pending.push((second, splits + 1));
|
||||
pending.push((first, splits + 1));
|
||||
continue;
|
||||
}
|
||||
|
||||
if kept {
|
||||
if !continuing {
|
||||
let mut piece = BezPath::new();
|
||||
piece.move_to(segment.start());
|
||||
pieces.push((distance, piece));
|
||||
}
|
||||
if let Some((_, piece)) = pieces.last_mut() {
|
||||
piece.push(segment.as_path_el());
|
||||
}
|
||||
}
|
||||
continuing = kept;
|
||||
distance += kurbo::ParamCurveArclen::arclen(&segment, ARC_LENGTH_ACCURACY);
|
||||
}
|
||||
}
|
||||
|
||||
pieces
|
||||
}
|
||||
|
||||
impl OverlayContextInternal {
|
||||
fn new(viewport: ViewportMessageHandler) -> Self {
|
||||
Self {
|
||||
@@ -715,7 +782,7 @@ impl OverlayContextInternal {
|
||||
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap]);
|
||||
}
|
||||
|
||||
self.scene.stroke(&stroke, transform, Self::parse_color(stroke_color), None, &path);
|
||||
self.stroke_in_view(&stroke, Self::parse_color(stroke_color), &path);
|
||||
}
|
||||
|
||||
fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
|
||||
@@ -724,8 +791,6 @@ impl OverlayContextInternal {
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn dashed_line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
let transform = self.get_transform();
|
||||
|
||||
let start = self.snap_to_physical_pixel_center(start);
|
||||
let end = self.snap_to_physical_pixel_center(end);
|
||||
|
||||
@@ -740,7 +805,7 @@ impl OverlayContextInternal {
|
||||
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap]);
|
||||
}
|
||||
|
||||
self.scene.stroke(&stroke, transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &path);
|
||||
self.stroke_in_view(&stroke, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), &path);
|
||||
}
|
||||
|
||||
fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
@@ -860,6 +925,26 @@ impl OverlayContextInternal {
|
||||
kurbo::Affine::scale(self.viewport.scale())
|
||||
}
|
||||
|
||||
/// Strokes `shape`, given in logical pixels, dashing only the parts near the viewport when the stroke is dashed, since a shape reaching far past it
|
||||
/// (as deep zoom makes them) would have more dashes than memory holds. Each part keeps the dash phase it has along the whole shape.
|
||||
fn stroke_in_view(&mut self, stroke: &kurbo::Stroke, color: peniko::Color, shape: &impl kurbo::Shape) {
|
||||
let transform = self.get_transform();
|
||||
|
||||
let margin = stroke.width + 1.;
|
||||
let size = self.viewport.size().into_dvec2();
|
||||
let visible = kurbo::Rect::new(-margin, -margin, size.x + margin, size.y + margin);
|
||||
|
||||
if stroke.dash_pattern.is_empty() || rect_contains(visible, shape.bounding_box()) {
|
||||
self.scene.stroke(stroke, transform, color, None, shape);
|
||||
return;
|
||||
}
|
||||
|
||||
for (distance, piece) in pieces_in_view(&shape.to_path(OVERLAY_SHAPE_TOLERANCE), visible) {
|
||||
let piece_stroke = stroke.clone().with_dashes(stroke.dash_offset + distance, stroke.dash_pattern.iter().copied());
|
||||
self.scene.stroke(&piece_stroke, transform, color, None, &piece);
|
||||
}
|
||||
}
|
||||
|
||||
fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) {
|
||||
let size = size.unwrap_or(MANIPULATOR_GROUP_MARKER_SIZE);
|
||||
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
|
||||
@@ -940,7 +1025,7 @@ impl OverlayContextInternal {
|
||||
if let Some(dash_width) = dash_width {
|
||||
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap_width.unwrap_or(1.)]);
|
||||
}
|
||||
self.scene.stroke(&stroke, transform, Self::parse_color(color_stroke.unwrap_or(COLOR_OVERLAY_BLUE)), None, &arc);
|
||||
self.stroke_in_view(&stroke, Self::parse_color(color_stroke.unwrap_or(COLOR_OVERLAY_BLUE)), &arc);
|
||||
}
|
||||
|
||||
fn draw_arc(&mut self, center: DVec2, radius: f64, start_from: f64, end_at: f64) {
|
||||
@@ -1431,3 +1516,39 @@ impl OverlayContextInternal {
|
||||
(physical_corner / scale, physical_size / scale)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const VISIBLE: kurbo::Rect = kurbo::Rect::new(0., 0., 800., 600.);
|
||||
|
||||
#[test]
|
||||
fn a_huge_line_keeps_only_its_part_in_view_at_its_distance_along_the_line() {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((-1e12, 300.));
|
||||
path.line_to((1e12, 300.));
|
||||
|
||||
let pieces = pieces_in_view(&path, VISIBLE);
|
||||
assert_eq!(pieces.len(), 1);
|
||||
|
||||
// The piece starts as far along as its start lies from the line's, so its dashes line up with the whole line's
|
||||
let (distance, piece) = &pieces[0];
|
||||
let start = piece.elements()[0].end_point().unwrap_or_default();
|
||||
assert!((-2.0..=0.).contains(&start.x), "the piece starts at {start:?}");
|
||||
assert!((distance - (start.x + 1e12)).abs() < 1e-3, "the piece starts {distance} along the line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_circle_through_the_view_keeps_a_few_short_pieces() {
|
||||
let radius = 1e12;
|
||||
let circle = kurbo::Circle::new((400. - radius, 300.), radius);
|
||||
|
||||
// The circle's path starts at its rightmost point, in view, so the part in view is split between its start and end
|
||||
let pieces = pieces_in_view(&kurbo::Shape::to_path(&circle, OVERLAY_SHAPE_TOLERANCE), VISIBLE);
|
||||
assert!((1..=2).contains(&pieces.len()), "{} pieces", pieces.len());
|
||||
|
||||
let elements: usize = pieces.iter().map(|(_, piece)| piece.elements().len()).sum();
|
||||
assert!(elements < 1000, "{elements} elements");
|
||||
}
|
||||
}
|
||||
@@ -46,8 +46,6 @@ pub struct DocumentMetadata {
|
||||
pub text_frames: HashMap<LayerNodeIdentifier, DAffine2>,
|
||||
pub clip_targets: HashSet<NodeId>,
|
||||
pub vector_modify: HashMap<NodeId, VectorGeometry>,
|
||||
/// Per node with a footprint input, the unit square mapped onto its area in document space.
|
||||
pub footprint_areas: HashMap<NodeId, DAffine2>,
|
||||
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
|
||||
/// This provides accurate SegmentIds for layers without explicit Path nodes.
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
|
||||
|
||||
@@ -138,7 +138,6 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.upstream_footprints.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.local_transforms.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.vector_modify.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.footprint_areas.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.click_targets.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
self.document_metadata.outlines.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
self.document_metadata.text_frames.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
@@ -190,11 +189,6 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.vector_modify = new_vector_modify;
|
||||
}
|
||||
|
||||
/// Update the cached document space areas of the nodes with a footprint input
|
||||
pub fn update_footprint_areas(&mut self, new_footprint_areas: HashMap<NodeId, DAffine2>) {
|
||||
self.document_metadata.footprint_areas = new_footprint_areas;
|
||||
}
|
||||
|
||||
/// Update the layer vector data (for layers without Path nodes)
|
||||
pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>) {
|
||||
self.document_metadata.mark_changed();
|
||||
|
||||
@@ -12,6 +12,7 @@ use graph_craft::document::DocumentNode;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
|
||||
use graph_craft::{Type, concrete, item, list};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::ParameterRef;
|
||||
use graphene_std::ProtoNodeIdentifier;
|
||||
use graphene_std::extract_xy::XY;
|
||||
@@ -1898,6 +1899,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if let Some(size) = clipped_size {
|
||||
fill_square_with_pattern(document, node_id, network_path, *size);
|
||||
}
|
||||
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
|
||||
move_mandelbrot_to_old_origin(document, node_id, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||
@@ -2031,6 +2035,46 @@ fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Keeps an old Mandelbrot's look now that the complex plane's origin is its pattern's, with a third of a unit's scale and a Transform moving the pattern back to where
|
||||
/// the old unit square, which spanned the plane from -2 to 1, put that origin.
|
||||
fn move_mandelbrot_to_old_origin(document: &mut DocumentMessageHandler, mandelbrot_node_id: &NodeId, network_path: &[NodeId]) -> Option<()> {
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*mandelbrot_node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let transform_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER))?.default_node_template();
|
||||
|
||||
let origin_transform_id = NodeId::new();
|
||||
document.network_interface.insert_node(origin_transform_id, transform_template, network_path);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*mandelbrot_node_id, graphene_std::raster_nodes::std_nodes::mandelbrot::ScaleInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Number(1. / 3.), false),
|
||||
network_path,
|
||||
);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(origin_transform_id, 1),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5)), false),
|
||||
network_path,
|
||||
);
|
||||
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(origin_transform_id, 0), NodeInput::node(*mandelbrot_node_id, 0), network_path);
|
||||
for consumer in &downstream_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(origin_transform_id, 0), network_path);
|
||||
}
|
||||
|
||||
// The Transform takes the pattern's place, and the pattern moves before it
|
||||
if let Some(position) = document.network_interface.position(mandelbrot_node_id, network_path) {
|
||||
document.network_interface.set_absolute_position(&origin_transform_id, position, network_path);
|
||||
document.network_interface.set_absolute_position(mandelbrot_node_id, position + IVec2::new(-7, 0), network_path);
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -6213,13 +6257,24 @@ mod tests {
|
||||
|
||||
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
|
||||
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
|
||||
assert_eq!(upstream(paint, 0), Some(pattern));
|
||||
|
||||
// The Mandelbrot is also moved back to where its old unit square put the complex plane's origin
|
||||
let mut read = upstream(paint, 0).expect("the paint should read the pattern");
|
||||
if pattern == mandelbrot {
|
||||
assert_eq!(value(read, 1), Some(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5))));
|
||||
read = upstream(read, 0).expect("the origin transform should read the pattern");
|
||||
}
|
||||
assert_eq!(read, pattern);
|
||||
}
|
||||
|
||||
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
|
||||
// Noise settings shift past the removed Clip toggle, and Mandelbrot gains its primary input and settings, its scale a third of a unit like its old unit square's
|
||||
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
|
||||
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
|
||||
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
|
||||
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 11);
|
||||
assert_eq!(
|
||||
value(mandelbrot, graphene_std::raster_nodes::std_nodes::mandelbrot::ScaleInput::INDEX),
|
||||
Some(TaggedValue::Number(1. / 3.))
|
||||
);
|
||||
}
|
||||
|
||||
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
||||
|
||||
@@ -1,332 +0,0 @@
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::transformation_cage::{BoundingBoxManager, SelectedEdges};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::context::bake_footprint;
|
||||
use graphene_std::platform_application_io::rasterize;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::transform::Footprint;
|
||||
|
||||
/// A transform cage that resizes and moves the area of the selected node with a footprint input.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FootprintCage {
|
||||
target: Option<CageTarget>,
|
||||
drag: Option<CageDrag>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct CageTarget {
|
||||
footprint_input: InputConnector,
|
||||
area: Footprint,
|
||||
/// Spans the area, with the unit square as its bounds.
|
||||
bounding_box: BoundingBoxManager,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct CageDrag {
|
||||
footprint_input: InputConnector,
|
||||
original_area: Footprint,
|
||||
unit_square_to_viewport: DAffine2,
|
||||
kind: CageDragKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum CageDragKind {
|
||||
Resize(SelectedEdges),
|
||||
Move { grab: DVec2 },
|
||||
}
|
||||
|
||||
impl FootprintCage {
|
||||
/// Places the cage on the area of the selected node with a footprint input, or removes it if it is hidden or there is none.
|
||||
pub fn refresh(&mut self, document: &DocumentMessageHandler, visible: bool) {
|
||||
self.target = visible.then(|| Self::find_target(document)).flatten();
|
||||
}
|
||||
|
||||
fn find_target(document: &DocumentMessageHandler) -> Option<CageTarget> {
|
||||
let network_path = document.selection_network_path();
|
||||
let network_interface = &document.network_interface;
|
||||
|
||||
let selected_nodes = network_interface.selected_nodes_in_nested_network(network_path)?;
|
||||
let mut footprint_inputs = selected_nodes.selected_nodes().filter_map(|&node_id| footprint_input(node_id, network_interface, network_path));
|
||||
let footprint_input = footprint_inputs.next()?;
|
||||
if footprint_inputs.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
let node_id = footprint_input.node_id()?;
|
||||
|
||||
let input = network_interface.input_from_connector(&footprint_input, network_path)?;
|
||||
let &TaggedValue::Footprint(area) = input.as_non_exposed_value()? else { return None };
|
||||
|
||||
let unit_square_to_document = *document.metadata().footprint_areas.get(&node_id)?;
|
||||
let unit_square_to_viewport = document.metadata().document_to_viewport * unit_square_to_document;
|
||||
if unit_square_to_viewport.matrix2.determinant() == 0. {
|
||||
return None;
|
||||
}
|
||||
|
||||
let bounding_box = BoundingBoxManager {
|
||||
bounds: [DVec2::ZERO, DVec2::ONE],
|
||||
transform: unit_square_to_viewport,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Some(CageTarget { footprint_input, area, bounding_box })
|
||||
}
|
||||
|
||||
pub fn overlays(&mut self, overlay_context: &mut OverlayContext) {
|
||||
if let Some(target) = &mut self.target {
|
||||
target.bounding_box.render_overlays(overlay_context, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The cursor for the part of the cage under the pointer, if any.
|
||||
pub fn cursor(&self, input: &InputPreprocessorMessageHandler) -> Option<MouseCursorIcon> {
|
||||
let target = self.target.as_ref()?;
|
||||
|
||||
let edge_cursor = target.bounding_box.get_cursor(input, false, false, None);
|
||||
if edge_cursor != MouseCursorIcon::Default {
|
||||
return Some(edge_cursor);
|
||||
}
|
||||
|
||||
target.contains(input.mouse.position).then_some(MouseCursorIcon::Move)
|
||||
}
|
||||
|
||||
/// Begins resizing or moving the area if the pointer is on the cage, returning whether it did.
|
||||
pub fn begin_drag(&mut self, mouse: DVec2, responses: &mut VecDeque<Message>) -> bool {
|
||||
let Some(target) = &self.target else { return false };
|
||||
let bounding_box = &target.bounding_box;
|
||||
|
||||
let kind = if let Some((top, bottom, left, right)) = bounding_box.check_selected_edges(mouse) {
|
||||
CageDragKind::Resize(SelectedEdges::new(top, bottom, left, right, bounding_box.bounds))
|
||||
} else if target.contains(mouse) {
|
||||
CageDragKind::Move {
|
||||
grab: bounding_box.transform.inverse().transform_point2(mouse),
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.drag = Some(CageDrag {
|
||||
footprint_input: target.footprint_input,
|
||||
original_area: target.area,
|
||||
unit_square_to_viewport: bounding_box.transform,
|
||||
kind,
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
responses.add(DocumentMessage::NameInteraction { action: "Changed a Footprint".into() });
|
||||
true
|
||||
}
|
||||
|
||||
/// Moves or resizes the area to follow the pointer, keeping its pixel density.
|
||||
pub fn update_drag(&mut self, mouse: DVec2, centered: bool, constrain: bool, responses: &mut VecDeque<Message>) {
|
||||
let Some(drag) = &self.drag else { return };
|
||||
|
||||
let (position, size) = match &drag.kind {
|
||||
CageDragKind::Resize(edges) => {
|
||||
let center = drag.unit_square_to_viewport.transform_point2(DVec2::splat(0.5));
|
||||
let (position, size) = edges.new_size(mouse, drag.unit_square_to_viewport, centered.then_some(center), constrain, None);
|
||||
(position.min(position + size), size.abs())
|
||||
}
|
||||
CageDragKind::Move { grab } => {
|
||||
let pointer = drag.unit_square_to_viewport.inverse().transform_point2(mouse);
|
||||
(pointer - *grab, DVec2::ONE)
|
||||
}
|
||||
};
|
||||
|
||||
let original_area = drag.original_area;
|
||||
let one_pixel = original_area.resolution.as_dvec2().recip();
|
||||
let size = size.max(one_pixel);
|
||||
|
||||
let area = Footprint {
|
||||
transform: original_area.transform * DAffine2::from_scale_angle_translation(size, 0., position),
|
||||
resolution: (original_area.resolution.as_dvec2() * size).round().as_uvec2().max(UVec2::ONE),
|
||||
..original_area
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: drag.footprint_input,
|
||||
input: NodeInput::value(TaggedValue::Footprint(area), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Keeps the drag in place on the document while the viewport pans by `shift`.
|
||||
pub fn pan(&mut self, shift: DVec2) {
|
||||
if let Some(drag) = &mut self.drag {
|
||||
drag.unit_square_to_viewport.translation += shift;
|
||||
}
|
||||
}
|
||||
|
||||
/// Finishes the drag, undoing its changes if it was aborted.
|
||||
pub fn end_drag(&mut self, aborted: bool, responses: &mut VecDeque<Message>) {
|
||||
if self.drag.take().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(if aborted { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction });
|
||||
}
|
||||
}
|
||||
|
||||
/// The input holding the footprint of a node that has one.
|
||||
fn footprint_input(node_id: NodeId, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option<InputConnector> {
|
||||
let reference = network_interface.reference(&node_id, network_path)?;
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER) {
|
||||
Some(InputConnector::node(node_id, bake_footprint::FootprintInput))
|
||||
} else if reference == DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER) {
|
||||
Some(InputConnector::node(node_id, rasterize::FootprintInput))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl CageTarget {
|
||||
fn contains(&self, viewport_point: DVec2) -> bool {
|
||||
(self.bounding_box.transform * Quad::from_box(self.bounding_box.bounds)).contains(viewport_point)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bake_footprint_node_in_a_layer_reports_where_its_area_lies() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
|
||||
let document = editor.active_document();
|
||||
let input = document.network_interface.input_from_connector(&InputConnector::node(node_id, bake_footprint::FootprintInput), &[]);
|
||||
let Some(&TaggedValue::Footprint(area)) = input.and_then(NodeInput::as_non_exposed_value) else {
|
||||
panic!("the node should have a footprint value")
|
||||
};
|
||||
|
||||
let metadata = document.metadata();
|
||||
let baked_area = metadata.footprint_areas.get(&node_id).expect("the render should report where the node baked its area");
|
||||
let layer_content_to_viewport = metadata.upstream_footprints.get(&layer.to_node()).expect("the render should report the layer's footprint").transform;
|
||||
let expected = metadata.rendered_document_to_viewport.inverse() * layer_content_to_viewport * area.transform;
|
||||
assert!(baked_area.abs_diff_eq(expected, 1e-9), "{baked_area:?} should be {expected:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_baked_area_moves_with_a_transform_applied_after_it() {
|
||||
use graphene_std::transform_nodes::transform;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let bake_footprint_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
|
||||
node_id: bake_footprint_node,
|
||||
parent: layer,
|
||||
})
|
||||
.await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
let untransformed = *editor.active_document().metadata().footprint_areas.get(&bake_footprint_node).expect("the area should be reported");
|
||||
|
||||
let transform_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(transform::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
|
||||
node_id: transform_node,
|
||||
parent: layer,
|
||||
})
|
||||
.await;
|
||||
let translation = DVec2::new(100., 50.);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(transform_node, transform::TranslationInput),
|
||||
input: NodeInput::value(TaggedValue::DVec2(translation), false),
|
||||
})
|
||||
.await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
|
||||
let transformed = *editor
|
||||
.active_document()
|
||||
.metadata()
|
||||
.footprint_areas
|
||||
.get(&bake_footprint_node)
|
||||
.expect("the area should still be reported");
|
||||
let expected = DAffine2::from_translation(translation) * untransformed;
|
||||
assert!(transformed.abs_diff_eq(expected, 1e-9), "{transformed:?} should be {expected:?}");
|
||||
}
|
||||
|
||||
/// Drags the cage of a 'Bake Footprint' node in a layer between two points of its unit square, giving its area before and after.
|
||||
async fn drag_cage(from: DVec2, to: DVec2) -> (Footprint, Footprint) {
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
|
||||
let area = Footprint {
|
||||
transform: DAffine2::from_scale(DVec2::splat(100.)),
|
||||
resolution: UVec2::splat(200),
|
||||
..Default::default()
|
||||
};
|
||||
let footprint_input = InputConnector::node(node_id, bake_footprint::FootprintInput);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInput {
|
||||
input_connector: footprint_input,
|
||||
input: NodeInput::value(TaggedValue::Footprint(area), false),
|
||||
})
|
||||
.await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }).await;
|
||||
|
||||
let metadata = editor.active_document().metadata();
|
||||
let unit_square_to_viewport = metadata.document_to_viewport * *metadata.footprint_areas.get(&node_id).expect("the area should be reported");
|
||||
let (from, to) = (unit_square_to_viewport.transform_point2(from), unit_square_to_viewport.transform_point2(to));
|
||||
|
||||
editor.select_tool(ToolType::Select).await;
|
||||
editor.handle_message(SelectToolMessage::Overlays { context: OverlayContext::default() }).await;
|
||||
editor.move_mouse(from.x, from.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(from.x, from.y, ModifierKeys::empty()).await;
|
||||
editor.move_mouse(to.x, to.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
editor.left_mouseup(to.x, to.y, ModifierKeys::empty()).await;
|
||||
|
||||
let input = editor.active_document().network_interface.input_from_connector(&footprint_input, &[]);
|
||||
let Some(&TaggedValue::Footprint(dragged)) = input.and_then(NodeInput::as_non_exposed_value) else {
|
||||
panic!("the node should have a footprint value")
|
||||
};
|
||||
(area, dragged)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dragging_the_right_edge_of_the_cage_widens_the_area_and_its_resolution() {
|
||||
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(1.5, 0.5)).await;
|
||||
|
||||
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(1.5, 1.));
|
||||
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
|
||||
assert_eq!(dragged.resolution, UVec2::new(300, 200));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dragging_the_right_edge_onto_the_left_one_keeps_one_pixel_of_width() {
|
||||
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(0., 0.5)).await;
|
||||
|
||||
let one_pixel = 1. / area.resolution.x as f64;
|
||||
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(one_pixel, 1.));
|
||||
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
|
||||
assert_eq!(dragged.resolution, UVec2::new(1, 200));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,2 @@
|
||||
pub mod footprint_cage;
|
||||
pub mod gizmo_manager;
|
||||
pub mod shape_gizmos;
|
||||
@@ -15,7 +15,6 @@ use crate::messages::tool::common_functionality::color_selector::{
|
||||
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, has_paintable_selection, swap_fill_and_stroke, sync_drawing_state,
|
||||
};
|
||||
use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose};
|
||||
use crate::messages::tool::common_functionality::gizmos::footprint_cage::FootprintCage;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::measure;
|
||||
use crate::messages::tool::common_functionality::pivot::{Pivot, PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget};
|
||||
@@ -506,7 +505,6 @@ enum SelectToolFsmState {
|
||||
},
|
||||
RotatingBounds,
|
||||
DraggingPivot,
|
||||
DraggingFootprintCage,
|
||||
}
|
||||
|
||||
impl Default for SelectToolFsmState {
|
||||
@@ -547,7 +545,6 @@ struct SelectToolData {
|
||||
axis_align: bool,
|
||||
non_duplicated_layers: Option<Vec<LayerNodeIdentifier>>,
|
||||
bounding_box_manager: Option<BoundingBoxManager>,
|
||||
footprint_cage: FootprintCage,
|
||||
cursor: MouseCursorIcon,
|
||||
pivot_gizmo: PivotGizmo,
|
||||
/// The pivot as it was when a drag of it began, restored if the drag is aborted.
|
||||
@@ -957,9 +954,6 @@ impl Fsm for SelectToolFsmState {
|
||||
(_, SelectToolMessage::Overlays { context: mut overlay_context }) => {
|
||||
crate::messages::tool::common_functionality::layer_origin_cross::draw_for_selected_layers(&mut overlay_context, document);
|
||||
|
||||
tool_data.footprint_cage.refresh(document, overlay_context.visibility_settings.transform_cage());
|
||||
tool_data.footprint_cage.overlays(&mut overlay_context);
|
||||
|
||||
let selected_layers_count = document.network_interface.selected_nodes().selected_unlocked_layers(&document.network_interface).count();
|
||||
let paintable_layers_selected = has_paintable_selection(document);
|
||||
tool_data.selected_layers_changed = selected_layers_count != tool_data.selected_layers_count || paintable_layers_selected != tool_data.paintable_layers_selected;
|
||||
@@ -1394,10 +1388,6 @@ impl Fsm for SelectToolFsmState {
|
||||
tool_data.drag_current = input.mouse.position;
|
||||
tool_data.selection_mode = None;
|
||||
|
||||
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_none() && tool_data.footprint_cage.begin_drag(input.mouse.position, responses) {
|
||||
return SelectToolFsmState::DraggingFootprintCage;
|
||||
}
|
||||
|
||||
let mut selected: Vec<_> = document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface).collect();
|
||||
let intersection_list = document.click_list(input, viewport).collect::<Vec<_>>();
|
||||
let intersection = document.find_deepest(&intersection_list);
|
||||
@@ -1630,18 +1620,6 @@ impl Fsm for SelectToolFsmState {
|
||||
remove,
|
||||
}
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerMove { modifier_keys }) => {
|
||||
let (centered, constrain) = (input.keyboard.key(modifier_keys.center), input.keyboard.key(modifier_keys.axis_align));
|
||||
tool_data.footprint_cage.update_drag(input.mouse.position, centered, constrain, responses);
|
||||
|
||||
let messages = [
|
||||
SelectToolMessage::PointerOutsideViewport { modifier_keys: modifier_keys.clone() }.into(),
|
||||
SelectToolMessage::PointerMove { modifier_keys }.into(),
|
||||
];
|
||||
tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses);
|
||||
|
||||
SelectToolFsmState::DraggingFootprintCage
|
||||
}
|
||||
(SelectToolFsmState::ResizingBounds, SelectToolMessage::PointerMove { modifier_keys }) => {
|
||||
if let Some(bounds) = &mut tool_data.bounding_box_manager {
|
||||
resize_bounds(
|
||||
@@ -1743,10 +1721,6 @@ impl Fsm for SelectToolFsmState {
|
||||
.as_ref()
|
||||
.map_or(MouseCursorIcon::Default, |bounds| bounds.get_cursor(input, true, dragging_bounds, Some(tool_data.skew_edge)));
|
||||
|
||||
if let Some(footprint_cage_cursor) = tool_data.footprint_cage.cursor(input) {
|
||||
cursor = footprint_cage_cursor;
|
||||
}
|
||||
|
||||
// Dragging the pivot overrules the other operations
|
||||
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_some() {
|
||||
cursor = MouseCursorIcon::Move;
|
||||
@@ -1798,14 +1772,6 @@ impl Fsm for SelectToolFsmState {
|
||||
|
||||
self
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// Auto-panning
|
||||
if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) {
|
||||
tool_data.footprint_cage.pan(shift);
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
(SelectToolFsmState::DraggingPivot, SelectToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// Auto-panning
|
||||
let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses);
|
||||
@@ -1951,14 +1917,6 @@ impl Fsm for SelectToolFsmState {
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::DragStop { .. } | SelectToolMessage::Enter) => {
|
||||
let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON;
|
||||
tool_data.footprint_cage.end_drag(drag_too_small, responses);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::Drawing { selection_shape, .. }, SelectToolMessage::DragStop { remove_from_selection }) => {
|
||||
let quad = tool_data.selection_quad();
|
||||
|
||||
@@ -2048,13 +2006,6 @@ impl Fsm for SelectToolFsmState {
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::Abort) => {
|
||||
tool_data.footprint_cage.end_drag(true, responses);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::Dragging { .. }, SelectToolMessage::Abort) => {
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
tool_data.axis_align = false;
|
||||
@@ -2224,13 +2175,6 @@ impl Fsm for SelectToolFsmState {
|
||||
]);
|
||||
hint_data.send_layout(responses);
|
||||
}
|
||||
SelectToolFsmState::DraggingFootprintCage => {
|
||||
let hint_data = HintData(vec![
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
|
||||
HintGroup(vec![HintInfo::keys([Key::Alt], "From Center"), HintInfo::keys([Key::Shift], "Preserve Aspect Ratio")]),
|
||||
]);
|
||||
hint_data.send_layout(responses);
|
||||
}
|
||||
SelectToolFsmState::RotatingBounds => {
|
||||
let hint_data = HintData(vec![
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
|
||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
@@ -10,26 +11,23 @@ use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{Vector, graphic_types, no_paths, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic};
|
||||
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
|
||||
mod observations;
|
||||
#[cfg(test)]
|
||||
mod recompile_tests;
|
||||
mod runtime;
|
||||
pub use observations::ObservationKey;
|
||||
use observations::{path_content_observations, path_contents};
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ExecutionRequest {
|
||||
execution_id: u64,
|
||||
render_config: RenderConfig,
|
||||
@@ -45,6 +43,18 @@ pub struct ExecutionResponse {
|
||||
observations: HashMap<ObservationKey, InspectResult>,
|
||||
}
|
||||
|
||||
/// Names an observation so it can be changed or stopped without touching the others.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ObservationKey {
|
||||
/// The node the Data panel inspects.
|
||||
DataPanel,
|
||||
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
|
||||
PathContent(NodeId),
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// The "Fill" node whose geometry a gradient migration measures.
|
||||
FillMeasurement,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ExecutionResult {
|
||||
Pending,
|
||||
@@ -346,6 +356,7 @@ impl NodeGraphExecutor {
|
||||
render_mode: document.render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
metadata: None,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -413,6 +424,7 @@ impl NodeGraphExecutor {
|
||||
render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: true,
|
||||
metadata: None,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -437,10 +449,12 @@ impl NodeGraphExecutor {
|
||||
let previewed = document.network_interface.previewed_nodes();
|
||||
let resources = document.resources.registry.clone();
|
||||
|
||||
let export_format = if export_config.file_type == FileType::Svg {
|
||||
graphene_std::application_io::ExportFormat::Svg
|
||||
} else {
|
||||
graphene_std::application_io::ExportFormat::Raster
|
||||
let export_format = match export_config.file_type {
|
||||
FileType::Svg => graphene_std::application_io::ExportFormat::Svg,
|
||||
FileType::Pdf => graphene_std::application_io::ExportFormat::Pdf {
|
||||
artboards_as_pages: export_config.bounds == ExportBounds::AllArtwork,
|
||||
},
|
||||
_ => graphene_std::application_io::ExportFormat::Raster,
|
||||
};
|
||||
|
||||
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
|
||||
@@ -473,6 +487,10 @@ impl NodeGraphExecutor {
|
||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
metadata: Some(graphene_std::application_io::ExportMetadata {
|
||||
title: export_config.name.clone(),
|
||||
artboard_names: (document.artboard_names().into_iter()).map(|(layer, name)| (layer.to_node(), name)).collect(),
|
||||
}),
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -632,7 +650,6 @@ impl NodeGraphExecutor {
|
||||
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
|
||||
document.network_interface.update_outlines(HashMap::new());
|
||||
document.network_interface.update_vector_modify(HashMap::new());
|
||||
document.network_interface.update_footprint_areas(HashMap::new());
|
||||
if let Some(message) = &message {
|
||||
log::error!("Node graph evaluation failed:\n{message}");
|
||||
}
|
||||
@@ -709,7 +726,6 @@ impl NodeGraphExecutor {
|
||||
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
|
||||
document.network_interface.update_outlines(HashMap::new());
|
||||
document.network_interface.update_vector_modify(HashMap::new());
|
||||
document.network_interface.update_footprint_areas(HashMap::new());
|
||||
|
||||
// The graph only shows errors tied to nodes, so the console gets the others
|
||||
if node_graph_errors.is_empty() {
|
||||
@@ -916,6 +932,7 @@ impl NodeGraphExecutor {
|
||||
render_mode: document.render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
metadata: None,
|
||||
};
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
@@ -1047,6 +1064,11 @@ impl NodeGraphExecutor {
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
return;
|
||||
}
|
||||
RenderOutputType::Pdf { data } => {
|
||||
log::error!("Invalid node graph output type: a PDF document of {} bytes", data.len());
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let RenderMetadata {
|
||||
@@ -1057,7 +1079,6 @@ impl NodeGraphExecutor {
|
||||
outlines,
|
||||
group_layers,
|
||||
text_frames,
|
||||
footprint_areas,
|
||||
clip_targets,
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
@@ -1065,9 +1086,6 @@ impl NodeGraphExecutor {
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
let viewport_to_document = document_to_viewport.inverse();
|
||||
let footprint_areas = footprint_areas.into_iter().map(|(node_id, area)| (node_id, viewport_to_document * area)).collect();
|
||||
|
||||
// Run these update state messages immediately
|
||||
responses.add(DocumentMessage::UpdateUpstreamTransforms {
|
||||
upstream_footprints,
|
||||
@@ -1078,7 +1096,6 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClickTargets { click_targets, group_layers });
|
||||
responses.add(DocumentMessage::UpdateOutlines { outlines });
|
||||
responses.add(DocumentMessage::UpdateTextFrames { text_frames });
|
||||
responses.add(DocumentMessage::UpdateFootprintAreas { footprint_areas });
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
@@ -1119,10 +1136,20 @@ impl NodeGraphExecutor {
|
||||
content: svg.into_bytes().into(),
|
||||
});
|
||||
}
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Pdf { data }, ..
|
||||
}) if file_type == FileType::Pdf => {
|
||||
responses.add(FrontendMessage::TriggerSaveFile {
|
||||
name,
|
||||
folder,
|
||||
filters,
|
||||
content: data.into(),
|
||||
});
|
||||
}
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Buffer { data, width, height },
|
||||
..
|
||||
}) if file_type != FileType::Svg => {
|
||||
}) if !file_type.is_vector() => {
|
||||
let content = match file_type.encode(width, height, data) {
|
||||
Ok(content) => content.into(),
|
||||
Err(description) => {
|
||||
@@ -1227,6 +1254,37 @@ fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
||||
}
|
||||
}
|
||||
|
||||
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
|
||||
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
|
||||
|
||||
path_nodes.into_iter().filter_map(|node_path| {
|
||||
let key = ObservationKey::PathContent(*node_path.last()?);
|
||||
let observation = Observation {
|
||||
node_path,
|
||||
connector: ObservedConnector::Input(path::ContentInput::INDEX),
|
||||
overrides: ContextOverrides::default(),
|
||||
};
|
||||
Some((key, observation))
|
||||
})
|
||||
}
|
||||
|
||||
/// The incoming geometry of each 'Path' node, read from its observed content.
|
||||
fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
|
||||
observations
|
||||
.iter()
|
||||
.filter_map(|(key, result)| {
|
||||
let ObservationKey::PathContent(path_node) = *key else { return None };
|
||||
let value = result.data.as_ref()?;
|
||||
|
||||
let geometry = match value.downcast_ref::<List<Vector>>() {
|
||||
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
|
||||
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
|
||||
};
|
||||
Some((path_node, geometry))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Re-export for usage by tests in other modules
|
||||
#[cfg(test)]
|
||||
pub use test::Instrumented;
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
use super::{InspectResult, Observation, ObservedConnector};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::vector::{Vector, VectorGeometry, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ContextOverrides, NodeParameter};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Names an observation so it can be changed or stopped without touching the others.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ObservationKey {
|
||||
/// The node the Data panel inspects.
|
||||
DataPanel,
|
||||
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
|
||||
PathContent(NodeId),
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// The "Fill" node whose geometry a gradient migration measures.
|
||||
FillMeasurement,
|
||||
}
|
||||
|
||||
pub(super) fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
|
||||
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
|
||||
|
||||
path_nodes.into_iter().filter_map(|node_path| {
|
||||
let key = ObservationKey::PathContent(*node_path.last()?);
|
||||
let observation = Observation {
|
||||
node_path,
|
||||
connector: ObservedConnector::Input(path::ContentInput::INDEX),
|
||||
overrides: ContextOverrides::default(),
|
||||
};
|
||||
Some((key, observation))
|
||||
})
|
||||
}
|
||||
|
||||
/// The incoming geometry of each 'Path' node, read from its observed content.
|
||||
pub(super) fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
|
||||
observations
|
||||
.iter()
|
||||
.filter_map(|(key, result)| {
|
||||
let ObservationKey::PathContent(path_node) = *key else { return None };
|
||||
let value = result.data.as_ref()?;
|
||||
|
||||
let geometry = match value.downcast_ref::<List<Vector>>() {
|
||||
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
|
||||
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
|
||||
};
|
||||
Some((path_node, geometry))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -294,12 +294,12 @@ impl NodeRuntime {
|
||||
let dirty = self.dirty.swap(false, Ordering::Acquire);
|
||||
let mut texture = None;
|
||||
|
||||
if let Some(export) = self.pending_export {
|
||||
if let Some(export) = self.pending_export.clone() {
|
||||
if dirty {
|
||||
self.run_export(export).await;
|
||||
}
|
||||
} else {
|
||||
let viewport = if dirty { self.pending } else { None };
|
||||
let viewport = if dirty { self.pending.clone() } else { None };
|
||||
|
||||
if let Some(document_id) = self.pending_thumbnails.take()
|
||||
&& viewport.is_none()
|
||||
@@ -336,9 +336,10 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> {
|
||||
let execution_id = request.execution_id;
|
||||
self.thumbnails.set_scale(request.render_config.scale);
|
||||
|
||||
let mut result = self.evaluate(request)?;
|
||||
let mut result = self.evaluate(request.clone())?;
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
@@ -390,7 +391,7 @@ impl NodeRuntime {
|
||||
None
|
||||
};
|
||||
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
self.respond(execution_id, result, observations).await;
|
||||
texture
|
||||
}
|
||||
|
||||
@@ -435,6 +436,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
async fn run_export(&mut self, request: ExecutionRequest) {
|
||||
let execution_id = request.execution_id;
|
||||
let result = self.evaluate(request);
|
||||
if matches!(result, Some(ExecutionResult::Pending)) {
|
||||
return;
|
||||
@@ -451,12 +453,12 @@ impl NodeRuntime {
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
}
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
self.respond(execution_id, result, observations).await;
|
||||
}
|
||||
|
||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||
// Eyedropper should use the same time and pointer to not invalidate the cache
|
||||
if let Some(viewport) = self.pending {
|
||||
if let Some(viewport) = &self.pending {
|
||||
request.render_config.time = viewport.render_config.time;
|
||||
request.render_config.pointer = viewport.render_config.pointer;
|
||||
}
|
||||
@@ -484,10 +486,11 @@ impl NodeRuntime {
|
||||
render_config.export_format = ExportFormat::Svg;
|
||||
}
|
||||
|
||||
let for_export = render_config.for_export;
|
||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) {
|
||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
||||
Ok(Ok(Poll::Fallback(boxed))) => {
|
||||
@@ -788,7 +791,7 @@ mod tests {
|
||||
|
||||
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
|
||||
fn last_request(editor: &EditorTestUtils) -> Option<u64> {
|
||||
editor.runtime.pending.map(|request| request.execution_id)
|
||||
editor.runtime.pending.as_ref().map(|request| request.execution_id)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1080,6 +1083,60 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pdf_export_saves_a_pdf_document() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
send_export(&mut editor, FileType::Pdf);
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
|
||||
let saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveFile { name, content, .. } => Some((name, content)),
|
||||
_ => None,
|
||||
});
|
||||
let Some((name, content)) = saved else { panic!("the export should save a file") };
|
||||
|
||||
assert!(name.ends_with(".pdf"), "the file should be named as a PDF: {name}");
|
||||
assert!(content.starts_with(b"%PDF-"), "the file should hold a PDF document");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pdf_export_draws_effects_as_images_the_gpu_renders() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use graphene_std::blending_nodes::effects::drop_shadow;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
let node_type = DefinitionIdentifier::ProtoNode(drop_shadow::IDENTIFIER);
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||
|
||||
// The export waits for the render node to read the image of the shadowed rectangle back into the PDF
|
||||
send_export(&mut editor, FileType::Pdf);
|
||||
let mut saved = None;
|
||||
for _ in 0..100 {
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
|
||||
_ => None,
|
||||
});
|
||||
if saved.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(saved) = saved else { panic!("the export never finished") };
|
||||
|
||||
assert!(saved.starts_with(b"%PDF-"), "the file should hold a PDF document");
|
||||
let embeds_image = saved.windows(b"/Subtype/Image".len()).any(|window| window == b"/Subtype/Image");
|
||||
assert!(embeds_image, "the shadowed rectangle should be an image the GPU rendered");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_svg_export_draws_effects_svg_filters_cannot_carry_out_as_images_the_gpu_renders() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
|
||||
+16
-2
@@ -34,12 +34,24 @@
|
||||
background: #222;
|
||||
}
|
||||
|
||||
body.loading-progress::before {
|
||||
background-image:
|
||||
url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' rx='2' fill='%23eee'/></svg>"),
|
||||
url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' rx='2' fill='%23444'/></svg>");
|
||||
background-position: left calc(50vw - 80px) top calc(50vh + 64px);
|
||||
background-size:
|
||||
calc(var(--loading-progress, 0) * 160px) 4px,
|
||||
160px 4px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
body::after {
|
||||
content: "";
|
||||
display: block;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
border-radius: 50%;
|
||||
@@ -50,6 +62,8 @@
|
||||
@media (prefers-reduced-motion) {
|
||||
border: none;
|
||||
animation: none;
|
||||
width: auto;
|
||||
height: auto;
|
||||
content: "Loading…";
|
||||
font-family: Arial, sans-serif;
|
||||
font-size: 24px;
|
||||
@@ -58,10 +72,10 @@
|
||||
|
||||
@keyframes spinning-loading-indicator {
|
||||
0% {
|
||||
transform: translate(-30px, -30px) rotate(0deg);
|
||||
transform: translate(-50%, -50%) rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: translate(-30px, -30px) rotate(360deg);
|
||||
transform: translate(-50%, -50%) rotate(360deg);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import type { MessageName, SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import { joinSessionFromUrl, loadDemoArtwork } from "/src/utility-functions/network";
|
||||
import { operatingSystem } from "/src/utility-functions/platform";
|
||||
import { registerServiceWorker } from "/src/utility-functions/service-worker";
|
||||
import { initWasm } from "/src/utility-functions/wasm-loader";
|
||||
import { EditorWrapper, receiveNativeMessage } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { FrontendMessage } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
@@ -18,6 +19,10 @@
|
||||
try {
|
||||
// Initialize the editor wrapper
|
||||
const wrapper = await initWasm();
|
||||
|
||||
// Register the service worker, except in dev mode and native builds
|
||||
if (!import.meta.env.DEV && import.meta.env.MODE !== "native" && "serviceWorker" in navigator) registerServiceWorker();
|
||||
|
||||
for (const [name, f] of Object.entries(wrapper)) {
|
||||
if (name.startsWith("__node_registry") || name.startsWith("__migration_registry")) f();
|
||||
}
|
||||
@@ -57,6 +62,12 @@
|
||||
{/if}
|
||||
|
||||
<style lang="scss">
|
||||
// Disable the loading indicator
|
||||
body:has(.main-window, .startup-error)::before,
|
||||
body:has(.main-window, .startup-error)::after {
|
||||
content: none !important;
|
||||
}
|
||||
|
||||
.startup-error {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
@@ -82,12 +82,6 @@
|
||||
<MainWindow />
|
||||
|
||||
<style lang="scss">
|
||||
// Disable the spinning loading indicator
|
||||
body::before,
|
||||
body::after {
|
||||
content: none !important;
|
||||
}
|
||||
|
||||
:root {
|
||||
--color-0-black: #000;
|
||||
--color-1-nearblack: #111;
|
||||
|
||||
@@ -84,10 +84,12 @@
|
||||
--row-height: 24px;
|
||||
|
||||
&:has(.slider-input) {
|
||||
margin-top: 16px;
|
||||
margin-top: 8px;
|
||||
|
||||
.number-input {
|
||||
flex: 0 0 auto;
|
||||
// Level with the gradient strip, below the slider's room for its midpoint diamonds
|
||||
margin-top: 8px;
|
||||
margin-left: 8px;
|
||||
min-width: 0;
|
||||
width: calc(24px + 8px + 24px);
|
||||
|
||||
@@ -670,7 +670,7 @@
|
||||
|
||||
<LayoutCol
|
||||
class="slider-input"
|
||||
classes={{ narrow, disabled, "range-slider": rangeSlider }}
|
||||
classes={{ narrow, disabled, "range-slider": rangeSlider, "with-midpoints": showMidpoints }}
|
||||
styles={{
|
||||
"--gradient-start": trackStartCSS,
|
||||
"--gradient-end": trackEndCSS,
|
||||
@@ -830,11 +830,17 @@
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
// Room for the diamonds above the strip, inside the widget so rows that clip their overflow still show them
|
||||
&.with-midpoints {
|
||||
padding-top: 8px;
|
||||
}
|
||||
|
||||
.midpoint-track {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: var(--marker-half-width);
|
||||
right: var(--marker-half-width);
|
||||
height: 8px;
|
||||
|
||||
.midpoint {
|
||||
position: absolute;
|
||||
|
||||
Vendored
+2
-1
@@ -6,8 +6,9 @@ interface Window {
|
||||
receiveNativeMessage?: (buffer: ArrayBuffer) => void;
|
||||
}
|
||||
|
||||
// Build-time constant injected by the `wasmSplitting` plugin in `vite.config.ts`
|
||||
// Build-time constants injected by plugins in `vite.config.ts`
|
||||
declare const __WASM_PART_COUNT__: number;
|
||||
declare const __WASM_SIZE__: number;
|
||||
|
||||
// Graphite's custom "pointerlockmove" event dispatched by input.ts for pointer lock in the CEF desktop app
|
||||
interface WindowEventMap {
|
||||
|
||||
@@ -2,12 +2,6 @@
|
||||
|
||||
import { mount, unmount } from "svelte";
|
||||
import App from "/src/App.svelte";
|
||||
import { registerServiceWorker } from "/src/utility-functions/service-worker";
|
||||
|
||||
// Register the service worker, except in dev mode and native (CEF) builds
|
||||
if (!import.meta.env.DEV && import.meta.env.MODE !== "native" && "serviceWorker" in navigator) {
|
||||
registerServiceWorker();
|
||||
}
|
||||
|
||||
document.body.setAttribute("data-app-container", "");
|
||||
|
||||
|
||||
@@ -19,6 +19,11 @@ const DEFERRED_ENTRIES = new Map(DEFERRED_CACHE_MANIFEST.map((entry) => [new URL
|
||||
// Caching strategies
|
||||
// ==================
|
||||
|
||||
function withoutRedirect(response) {
|
||||
if (!response.redirected) return response;
|
||||
return new Response(response.body, { status: response.status, statusText: response.statusText, headers: response.headers });
|
||||
}
|
||||
|
||||
function isCacheable(response) {
|
||||
// Cache normal successful responses and opaque responses (cross-origin no-cors, e.g. <link> stylesheets)
|
||||
return response.ok || response.type === "opaque";
|
||||
@@ -47,6 +52,20 @@ async function networkFirst(request, cacheName) {
|
||||
}
|
||||
}
|
||||
|
||||
async function latestIndexHtml(request) {
|
||||
const cache = await caches.open(STATIC_CACHE_NAME);
|
||||
const cached = await cache.match("/index.html");
|
||||
if (!cached) return fetch(request);
|
||||
if (!navigator.onLine) return cached;
|
||||
|
||||
const network = fetch("/", { cache: "no-cache" }).then(
|
||||
(response) => (response.ok ? withoutRedirect(response) : cached),
|
||||
() => cached,
|
||||
);
|
||||
const timeout = new Promise((resolve) => setTimeout(() => resolve(cached), 1000));
|
||||
return Promise.race([network, timeout]);
|
||||
}
|
||||
|
||||
// ================
|
||||
// Lifecycle events
|
||||
// ================
|
||||
@@ -60,15 +79,7 @@ self.addEventListener("install", (event) => {
|
||||
PRECACHE_MANIFEST.map(async (entry) => {
|
||||
const response = await fetch(entry.url);
|
||||
if (!response.ok) throw new Error(`Precache fetch failed for ${entry.url}: ${response.status}`);
|
||||
// Strip the `redirected` flag which causes errors when served via respondWith
|
||||
const cleaned = response.redirected
|
||||
? new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: response.headers,
|
||||
})
|
||||
: response;
|
||||
await cache.put(entry.url, cleaned);
|
||||
await cache.put(entry.url, withoutRedirect(response));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -148,15 +159,9 @@ self.addEventListener("fetch", (event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Navigation requests: serve cached index.html for all routes (SPA pattern)
|
||||
// Navigation requests: serve index.html for all routes (SPA pattern)
|
||||
if (request.mode === "navigate") {
|
||||
event.respondWith(
|
||||
(async () => {
|
||||
const cache = await caches.open(STATIC_CACHE_NAME);
|
||||
const cached = await cache.match("/index.html");
|
||||
return cached || fetch(request);
|
||||
})(),
|
||||
);
|
||||
event.respondWith(latestIndexHtml(request));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
export async function registerServiceWorker() {
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.register("/service-worker.js", { scope: "/" });
|
||||
|
||||
// When a new service worker is found, auto-reload once it activates
|
||||
registration.addEventListener("updatefound", () => {
|
||||
const newWorker = registration.installing;
|
||||
newWorker?.addEventListener("statechange", () => {
|
||||
// Only reload if there was a previous controller, meaning this is an update, not first install
|
||||
if (newWorker.state === "activated" && navigator.serviceWorker.controller) window.location.reload();
|
||||
});
|
||||
navigator.serviceWorker.addEventListener("controllerchange", () => {
|
||||
const controller = navigator.serviceWorker.controller;
|
||||
const reloadIfRemoved = async () => {
|
||||
if (controller?.state === "activated" && !(await caches.match(import.meta.url))) window.location.reload();
|
||||
};
|
||||
reloadIfRemoved();
|
||||
controller?.addEventListener("statechange", reloadIfRemoved);
|
||||
});
|
||||
|
||||
const registration = await navigator.serviceWorker.register("/service-worker.js", { scope: "/" });
|
||||
|
||||
const activeWorker = registration.active || registration.waiting || registration.installing;
|
||||
if (!activeWorker) return;
|
||||
|
||||
|
||||
@@ -4,22 +4,57 @@ import wasmBinaryUrl from "/wrapper/pkg/graphite_wasm_wrapper_bg.wasm?url";
|
||||
// Initializes the editor's Wasm module, rejoining the parts that CI deployments split the binary into
|
||||
// to fit under the single-file size limit (see `wasmSplitting` in `vite.config.ts`)
|
||||
export async function initWasm() {
|
||||
// Local and native builds keep the binary whole, letting the wasm-bindgen glue code load it directly
|
||||
if (__WASM_PART_COUNT__ <= 1) return init();
|
||||
if (__WASM_PART_COUNT__ <= 1 && __WASM_SIZE__ === 0) return init();
|
||||
|
||||
// Fetch all parts in parallel (served from the service worker's precache once it is installed)
|
||||
const partRequests = [];
|
||||
for (let index = 0; index < __WASM_PART_COUNT__; index += 1) {
|
||||
partRequests.push(fetch(wasmBinaryUrl.replace(/\.wasm$/, `-part${index}.wasm`)));
|
||||
}
|
||||
const partResponses = await Promise.all(partRequests);
|
||||
const partUrls = __WASM_PART_COUNT__ <= 1 ? [wasmBinaryUrl] : Array.from({ length: __WASM_PART_COUNT__ }, (_, index) => wasmBinaryUrl.replace(/\.wasm$/, `-part${index}.wasm`));
|
||||
// Read the parts straight from the service worker's precache when it has them
|
||||
const partResponses = (await cachedParts(partUrls)) || downloadParts(partUrls);
|
||||
|
||||
const failedResponse = partResponses.find((response) => !response.ok);
|
||||
if (failedResponse) throw new Error(`Failed to fetch Wasm binary part (status ${failedResponse.status}): ${failedResponse.url}`);
|
||||
// eslint-disable-next-line camelcase
|
||||
if (partResponses.length === 1) return init({ module_or_path: await partResponses[0] });
|
||||
|
||||
// Rejoin the parts and hand them to wasm-bindgen as a single response, with the MIME type needed for streaming compilation
|
||||
const parts = await Promise.all(partResponses.map((response) => response.blob()));
|
||||
const parts = await Promise.all(partResponses.map(async (response) => (await response).blob()));
|
||||
const joined = new Response(new Blob(parts), { headers: { "Content-Type": "application/wasm" } });
|
||||
// eslint-disable-next-line camelcase
|
||||
return init({ module_or_path: joined });
|
||||
}
|
||||
|
||||
async function cachedParts(urls: string[]): Promise<Response[] | undefined> {
|
||||
try {
|
||||
const responses = await Promise.all(urls.map((url) => caches.match(url)));
|
||||
if (responses.every((response): response is Response => response !== undefined)) return responses;
|
||||
} catch {
|
||||
// Cache Storage is unavailable, such as in some private windows
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function downloadParts(urls: string[]): Promise<Response>[] {
|
||||
const trackProgress = trackDownloadProgress();
|
||||
|
||||
return urls.map(async (url) => {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(`Failed to fetch Wasm binary part (status ${response.status}): ${response.url}`);
|
||||
return trackProgress(response);
|
||||
});
|
||||
}
|
||||
|
||||
function trackDownloadProgress(): (response: Response) => Response {
|
||||
let loadedBytes = 0;
|
||||
document.body.style.setProperty("--loading-progress", "0");
|
||||
document.body.classList.add("loading-progress");
|
||||
|
||||
return (response) => {
|
||||
if (!response.body) return response;
|
||||
|
||||
const counter = new TransformStream<Uint8Array, Uint8Array>({
|
||||
transform(chunk, controller) {
|
||||
loadedBytes += chunk.byteLength;
|
||||
document.body.style.setProperty("--loading-progress", String(Math.min(loadedBytes / __WASM_SIZE__, 1)));
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
});
|
||||
return new Response(response.body.pipeThrough(counter), { status: response.status, statusText: response.statusText, headers: response.headers });
|
||||
};
|
||||
}
|
||||
+16
-1
@@ -18,11 +18,12 @@ export default defineConfig(({ mode }) => {
|
||||
wasmEditorReload(),
|
||||
staticAssets(),
|
||||
mode !== "native" && thirdPartyLicenses(),
|
||||
mode !== "native" && wasmSize(),
|
||||
mode !== "native" && wasmSplitting(),
|
||||
mode !== "native" && serviceWorker(),
|
||||
],
|
||||
// Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active
|
||||
define: { __WASM_PART_COUNT__: "1" },
|
||||
define: { __WASM_SIZE__: "0", __WASM_PART_COUNT__: "1" },
|
||||
resolve: {
|
||||
alias: [
|
||||
...(mode === "native" ? [{ find: /^\/wrapper\/pkg\//, replacement: "/wrapper/pkg-native/" }] : []),
|
||||
@@ -177,6 +178,20 @@ function thirdPartyLicenses(): PluginOption {
|
||||
};
|
||||
}
|
||||
|
||||
function wasmSize(): PluginOption {
|
||||
return {
|
||||
name: "wasm-size",
|
||||
config(_, { command }) {
|
||||
if (command !== "build") return;
|
||||
|
||||
const wasmPath = path.resolve(projectRootDir, "wrapper/pkg/graphite_wasm_wrapper_bg.wasm");
|
||||
if (!existsSync(wasmPath)) return;
|
||||
|
||||
return { define: { __WASM_SIZE__: String(statSync(wasmPath).size) } };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Splits the Wasm binary into parts small enough for Cloudflare Pages' 25 MiB single-file limit, rejoined at runtime by `initWasm()` in `src/utility-functions/wasm-loader.ts`.
|
||||
// Only active when the `SPLIT_WASM` environment variable is set, which CI does for deployments; local builds keep the single file.
|
||||
function wasmSplitting(): PluginOption {
|
||||
|
||||
@@ -531,6 +531,9 @@ tagged_value! {
|
||||
CellularDistanceFunction(raster_nodes::adjustments::CellularDistanceFunction),
|
||||
CellularReturnType(raster_nodes::adjustments::CellularReturnType),
|
||||
DomainWarpType(raster_nodes::adjustments::DomainWarpType),
|
||||
MandelbrotFractal(raster_nodes::adjustments::MandelbrotFractal),
|
||||
MandelbrotExterior(raster_nodes::adjustments::MandelbrotExterior),
|
||||
MandelbrotInterior(raster_nodes::adjustments::MandelbrotInterior),
|
||||
RelativeAbsolute(raster_nodes::adjustments::RelativeAbsolute),
|
||||
SelectiveColorChoice(raster_nodes::adjustments::SelectiveColorChoice),
|
||||
TonalRange(raster_nodes::adjustments::TonalRange),
|
||||
@@ -921,6 +924,8 @@ pub enum RenderOutputType {
|
||||
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
|
||||
image_data: Vec<(u64, CanvasImage)>,
|
||||
},
|
||||
/// A PDF document's file contents.
|
||||
Pdf { data: Vec<u8> },
|
||||
#[cfg(target_family = "wasm")]
|
||||
CanvasFrame { canvas_id: u64, resolution: DVec2 },
|
||||
}
|
||||
@@ -939,6 +944,7 @@ impl CacheHash for RenderOutputType {
|
||||
svg.cache_hash(state);
|
||||
image_data.cache_hash(state);
|
||||
}
|
||||
Self::Pdf { data } => data.cache_hash(state),
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::CanvasFrame { canvas_id, resolution } => {
|
||||
canvas_id.cache_hash(state);
|
||||
|
||||
@@ -18,6 +18,7 @@ use std::time::Duration;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FileType {
|
||||
Svg,
|
||||
Pdf,
|
||||
Png,
|
||||
Jpg,
|
||||
Webp,
|
||||
@@ -29,7 +30,7 @@ pub enum FileType {
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
/// The image format of a file type encoded from a single image, which excludes SVG and GIF.
|
||||
/// The image format of a file type encoded from a single image, which excludes SVG, PDF, and GIF.
|
||||
fn raster_format(self) -> Option<ImageFormat> {
|
||||
match self {
|
||||
FileType::Png => Some(ImageFormat::Png),
|
||||
@@ -39,7 +40,7 @@ impl FileType {
|
||||
FileType::Bmp => Some(ImageFormat::Bmp),
|
||||
FileType::Tga => Some(ImageFormat::Tga),
|
||||
FileType::Ico => Some(ImageFormat::Ico),
|
||||
FileType::Svg | FileType::Gif => None,
|
||||
FileType::Svg | FileType::Pdf | FileType::Gif => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +48,7 @@ impl FileType {
|
||||
pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
|
||||
match path.extension().and_then(|s| s.to_str()) {
|
||||
Some("svg") => Ok(FileType::Svg),
|
||||
Some("pdf") => Ok(FileType::Pdf),
|
||||
Some("png") => Ok(FileType::Png),
|
||||
Some("jpg" | "jpeg") => Ok(FileType::Jpg),
|
||||
Some("webp") => Ok(FileType::Webp),
|
||||
@@ -55,13 +57,14 @@ pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
|
||||
Some("tga") => Ok(FileType::Tga),
|
||||
Some("ico") => Ok(FileType::Ico),
|
||||
Some("gif") => Ok(FileType::Gif),
|
||||
_ => Err("Unsupported file extension. Supported formats: .svg, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif".to_string()),
|
||||
_ => Err("Unsupported file extension. Supported formats: .svg, .pdf, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// One rendered frame of the document, as SVG text or as 8-bit RGBA pixels with straight alpha.
|
||||
/// One rendered frame of the document, as SVG text, a PDF document, or 8-bit RGBA pixels with straight alpha.
|
||||
pub enum RenderedFrame {
|
||||
Svg(String),
|
||||
Pdf(Vec<u8>),
|
||||
Raster { data: Vec<u8>, width: u32, height: u32 },
|
||||
}
|
||||
|
||||
@@ -165,7 +168,11 @@ pub(crate) async fn render_frame(
|
||||
size: (width, height),
|
||||
..
|
||||
} = settings;
|
||||
let export_format = if file_type == FileType::Svg { ExportFormat::Svg } else { ExportFormat::Raster };
|
||||
let export_format = match file_type {
|
||||
FileType::Svg => ExportFormat::Svg,
|
||||
FileType::Pdf => ExportFormat::Pdf { artboards_as_pages: false },
|
||||
_ => ExportFormat::Raster,
|
||||
};
|
||||
|
||||
// Create render config with export settings and the animation time
|
||||
let mut render_config = RenderConfig {
|
||||
@@ -190,6 +197,7 @@ pub(crate) async fn render_frame(
|
||||
match execute_until_settled(executor, runtime, spawner, render_config).await? {
|
||||
TaggedValue::RenderOutput(output) => match output.data {
|
||||
RenderOutputType::Svg { svg, .. } => Ok(RenderedFrame::Svg(svg)),
|
||||
RenderOutputType::Pdf { data } => Ok(RenderedFrame::Pdf(data)),
|
||||
RenderOutputType::Texture(texture) => {
|
||||
// Convert GPU texture to CPU buffer
|
||||
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
||||
@@ -199,7 +207,7 @@ pub(crate) async fn render_frame(
|
||||
}
|
||||
RenderOutputType::Buffer { data, width, height } => Ok(RenderedFrame::Raster { data, width, height }),
|
||||
#[cfg(target_family = "wasm")]
|
||||
other => Err(format!("Unexpected render output type: {other:?}. Expected Texture, Buffer for raster export or Svg for SVG export.").into()),
|
||||
other => Err(format!("Unexpected render output type: {other:?}. Expected Texture or Buffer for raster export, Svg for SVG export, or Pdf for PDF export.").into()),
|
||||
},
|
||||
other => Err(format!("Expected RenderOutput, got: {other:?}").into()),
|
||||
}
|
||||
@@ -209,6 +217,7 @@ pub(crate) async fn render_frame(
|
||||
fn write_frame(path: &Path, settings: ExportSettings, frame: RenderedFrame) -> Result<(), Box<dyn Error>> {
|
||||
let contents = match frame {
|
||||
RenderedFrame::Svg(svg) => svg.into_bytes(),
|
||||
RenderedFrame::Pdf(pdf) => pdf,
|
||||
RenderedFrame::Raster { data, width, height } => encode_raster(settings.file_type, data, width, height, settings.transparent)?,
|
||||
};
|
||||
std::fs::write(path, contents)?;
|
||||
@@ -391,7 +400,7 @@ pub async fn export_image_sequence(
|
||||
}
|
||||
|
||||
pub async fn execute_until_settled(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner, render_config: RenderConfig) -> Result<TaggedValue, Box<dyn Error>> {
|
||||
let execute = || executor.execute(render_config.into_context_with_generations(runtime.snapshot()));
|
||||
let execute = || executor.execute(render_config.clone().into_context_with_generations(runtime.snapshot()));
|
||||
let mut frame = execute()?;
|
||||
while spawner.join().await {
|
||||
frame = execute()?;
|
||||
@@ -469,6 +478,7 @@ mod tests {
|
||||
assert_eq!(detect_file_type(Path::new("frame.tif")), Ok(FileType::Tiff));
|
||||
assert_eq!(detect_file_type(Path::new("frame.jpeg")), Ok(FileType::Jpg));
|
||||
assert_eq!(detect_file_type(Path::new("frame.webp")), Ok(FileType::Webp));
|
||||
assert_eq!(detect_file_type(Path::new("frame.pdf")), Ok(FileType::Pdf));
|
||||
assert!(detect_file_type(Path::new("frame.exr")).is_err());
|
||||
assert!(detect_file_type(Path::new("frame")).is_err());
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ enum Command {
|
||||
/// Path to the .graphite document
|
||||
document: PathBuf,
|
||||
|
||||
/// Output file path (extension determines format: .svg, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif)
|
||||
/// Output file path (extension determines format: .svg, .pdf, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif)
|
||||
#[clap(long, short = 'o')]
|
||||
output: PathBuf,
|
||||
|
||||
|
||||
@@ -300,6 +300,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
MandelbrotFractal,
|
||||
MandelbrotExterior,
|
||||
MandelbrotInterior,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
GridTopology,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{Context, Generations, OwnedContextImpl};
|
||||
use dyn_any::{DynAny, StaticType, StaticTypeSized};
|
||||
use glam::DVec2;
|
||||
@@ -43,6 +44,19 @@ pub enum ExportFormat {
|
||||
#[default]
|
||||
Svg,
|
||||
Raster,
|
||||
Pdf {
|
||||
/// Puts each artboard on a page of its own, sized to it, rather than all of the export's area on one page.
|
||||
artboards_as_pages: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// What an exported document records about itself, where its format has a place for it.
|
||||
#[derive(Debug, Default, Clone, PartialEq, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ExportMetadata {
|
||||
pub title: String,
|
||||
/// The names of the artboards by the IDs of their layers, which a PDF's bookmarks of their pages take.
|
||||
pub artboard_names: Vec<(NodeId, String)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
|
||||
@@ -52,7 +66,7 @@ pub struct TimingInformation {
|
||||
pub animation_time: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
|
||||
#[derive(Debug, Default, Clone, PartialEq, DynAny, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct RenderConfig {
|
||||
pub viewport: Footprint,
|
||||
@@ -64,6 +78,9 @@ pub struct RenderConfig {
|
||||
pub export_format: ExportFormat,
|
||||
pub for_export: bool,
|
||||
pub for_eyedropper: bool,
|
||||
/// What an exported document records about itself.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub metadata: Option<ExportMetadata>,
|
||||
}
|
||||
|
||||
impl RenderConfig {
|
||||
|
||||
@@ -32,10 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_FOOTPRINT_AREAS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS,
|
||||
ATTR_EDITOR_TEXT_FRAME, ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE,
|
||||
ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START,
|
||||
ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD,
|
||||
ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
|
||||
ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use num_traits;
|
||||
|
||||
@@ -40,9 +40,6 @@ pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
|
||||
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
|
||||
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
|
||||
/// `List<NodeIdPath>` of the nodes with a footprint input this item passed through.
|
||||
/// Each row's transform maps the unit square onto that node's area in this item's local space.
|
||||
pub const ATTR_EDITOR_FOOTPRINT_AREAS: &str = "editor:footprint_areas";
|
||||
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
|
||||
pub const ATTR_START: &str = "start";
|
||||
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
|
||||
|
||||
@@ -113,36 +113,7 @@ impl RuntimeInner {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Slots<T>(Arc<Mutex<SlotTable<T>>>);
|
||||
|
||||
struct SlotTable<T> {
|
||||
slots: HashMap<u64, Slot<T>>,
|
||||
/// The number of started evaluations, which orders them.
|
||||
started: u64,
|
||||
/// The value of the latest started evaluation that has landed, with its order.
|
||||
latest: Option<(u64, T)>,
|
||||
}
|
||||
|
||||
impl<T: Clone> SlotTable<T> {
|
||||
fn start(&mut self) -> u64 {
|
||||
self.started += 1;
|
||||
self.started
|
||||
}
|
||||
|
||||
fn land(&mut self, key: u64, order: u64, state: Poll<T>) {
|
||||
let superseded = self.latest.as_ref().is_some_and(|(latest_order, _)| *latest_order > order);
|
||||
if !superseded && let Some(value) = state.clone().value() {
|
||||
self.latest = Some((order, value));
|
||||
}
|
||||
self.slots.insert(key, Slot::Ready(state));
|
||||
}
|
||||
|
||||
/// The value a pending evaluation returns, preferring the latest landed value if `keep_previous` is set.
|
||||
fn stand_in(&self, placeholder: Option<T>, keep_previous: bool) -> Poll<T> {
|
||||
let previous = if keep_previous { self.latest.as_ref().map(|(_, value)| value.clone()) } else { None };
|
||||
previous.or(placeholder).map_or(Poll::Pending, Poll::Partial)
|
||||
}
|
||||
}
|
||||
pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>);
|
||||
|
||||
enum Slot<T> {
|
||||
Ready(Poll<T>),
|
||||
@@ -159,11 +130,7 @@ impl<T> Drop for Slot<T> {
|
||||
|
||||
impl<T> Default for Slots<T> {
|
||||
fn default() -> Self {
|
||||
Self(Arc::new(Mutex::new(SlotTable {
|
||||
slots: HashMap::new(),
|
||||
started: 0,
|
||||
latest: None,
|
||||
})))
|
||||
Self(Arc::default())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,46 +147,42 @@ impl<T> std::fmt::Debug for Slots<T> {
|
||||
}
|
||||
|
||||
impl<T: Clone + WasmNotSend + 'static> Slots<T> {
|
||||
/// The landed state for `key`, or else starts its evaluation and returns its stand-in.
|
||||
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, keep_previous: bool, future: impl FnOnce() -> F) -> Poll<T>
|
||||
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, future: impl FnOnce() -> F) -> Poll<T>
|
||||
where
|
||||
F: Future<Output = Poll<T>> + WasmNotSend + 'static,
|
||||
{
|
||||
let order = {
|
||||
let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match table.slots.get(&key) {
|
||||
Some(Slot::Ready(landed)) => return landed.clone(),
|
||||
Some(Slot::Pending(_)) => return table.stand_in(placeholder, keep_previous),
|
||||
None => table.start(),
|
||||
}
|
||||
};
|
||||
match self.0.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
|
||||
Some(Slot::Ready(landed)) => return landed.clone(),
|
||||
Some(Slot::Pending(_)) => return placeholder.map_or(Poll::Pending, Poll::Partial),
|
||||
None => {}
|
||||
}
|
||||
|
||||
// Fast path for futures that are ready immediately
|
||||
// TODO(Timon): check if this would ever cause a problem; running a future on the graph executor thread might also be a bit wierd
|
||||
let mut future = Box::pin(future());
|
||||
if let std::task::Poll::Ready(state) = future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state.clone());
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state.clone()));
|
||||
return state;
|
||||
}
|
||||
|
||||
let (handle, registration) = AbortHandle::new_pair();
|
||||
let table = Arc::downgrade(&self.0);
|
||||
let slots = Arc::downgrade(&self.0);
|
||||
runtime.spawn(
|
||||
source,
|
||||
Box::pin(async move {
|
||||
if let Ok(state) = Abortable::new(future, registration).await
|
||||
&& let Some(table) = table.upgrade()
|
||||
&& let Some(slots) = slots.upgrade()
|
||||
{
|
||||
table.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state);
|
||||
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state));
|
||||
}
|
||||
}),
|
||||
);
|
||||
let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match table.slots.get(&key) {
|
||||
let mut slots = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match slots.get(&key) {
|
||||
Some(Slot::Ready(landed)) => landed.clone(),
|
||||
_ => {
|
||||
table.slots.insert(key, Slot::Pending(handle));
|
||||
table.stand_in(placeholder, keep_previous)
|
||||
slots.insert(key, Slot::Pending(handle));
|
||||
placeholder.map_or(Poll::Pending, Poll::Partial)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -252,13 +215,6 @@ mod tests {
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
fn drain_newest_first(&self) {
|
||||
let tasks = std::mem::take(&mut *self.0.lock().unwrap());
|
||||
for mut task in tasks.into_iter().rev() {
|
||||
while !poll_once(&mut task) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BlockingSpawner;
|
||||
@@ -320,7 +276,7 @@ mod tests {
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
|
||||
let slots = Slots::default();
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
assert_eq!(spawner.drain(), 0);
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
|
||||
|
||||
@@ -341,77 +297,11 @@ mod tests {
|
||||
Poll::Final(42u32)
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Partial(0));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Partial(0));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
|
||||
assert_eq!(spawner.drain(), 1, "an in-flight slot is not spawned twice");
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slot_keeping_the_previous_value_serves_it_until_the_next_response_lands() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
let fetch = |value: u32| {
|
||||
move || async move {
|
||||
YieldOnce(false).await;
|
||||
Poll::Final(value)
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)),
|
||||
Poll::Partial(0),
|
||||
"nothing landed yet, so the placeholder stands in"
|
||||
);
|
||||
spawner.drain();
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)), Poll::Final(1));
|
||||
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Partial(1), "the previous value stands in");
|
||||
spawner.drain();
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Final(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_response_landing_late_does_not_replace_the_previous_value() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
let fetch = |value: u32| {
|
||||
move || async move {
|
||||
YieldOnce(false).await;
|
||||
Poll::Final(value)
|
||||
}
|
||||
};
|
||||
|
||||
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1));
|
||||
slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2));
|
||||
spawner.drain_newest_first();
|
||||
|
||||
assert_eq!(slots.resolve(3, &runtime, SOURCE, Some(0), true, fetch(3)), Poll::Partial(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fallback_response_stands_in_as_the_previous_value() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
|
||||
slots.resolve(1, &runtime, SOURCE, Some(0), true, || async {
|
||||
YieldOnce(false).await;
|
||||
Poll::fallback(1, "failed")
|
||||
});
|
||||
spawner.drain();
|
||||
|
||||
let fetch = || async {
|
||||
YieldOnce(false).await;
|
||||
Poll::Final(2)
|
||||
};
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch), Poll::Partial(1));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42));
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -424,7 +314,7 @@ mod tests {
|
||||
Poll::Final(42u32)
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42));
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)]);
|
||||
}
|
||||
|
||||
@@ -438,11 +328,11 @@ mod tests {
|
||||
Poll::Final(42u32)
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
|
||||
let clone = slots.clone();
|
||||
drop(slots);
|
||||
assert_eq!(spawner.drain(), 1);
|
||||
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Final(42));
|
||||
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, fetch), Poll::Final(42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -460,7 +350,7 @@ mod tests {
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
|
||||
drop(slots);
|
||||
assert_eq!(spawner.drain(), 1);
|
||||
assert!(!finished.load(Ordering::Relaxed));
|
||||
|
||||
@@ -5,7 +5,7 @@ use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DAffine2;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use std::any::Any;
|
||||
|
||||
/// Style of noise pattern.
|
||||
@@ -109,23 +109,139 @@ pub struct NoiseSettings {
|
||||
pub cellular_jitter: f64,
|
||||
}
|
||||
|
||||
/// The fractal's family, from the classic Mandelbrot set to variations with their own signature shapes.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
pub enum MandelbrotFractal {
|
||||
/// A cardioid body ringed by rounded bulbs and branching filaments (at the default settings).
|
||||
#[default]
|
||||
ClassicMandelbrot,
|
||||
/// A curved triangular body with a bulb-and-spike arm on each corner (at the default settings).
|
||||
Tricorn,
|
||||
/// An asymmetric body fringed with jagged spires and flame-like detail (at the default settings).
|
||||
BurningShip,
|
||||
}
|
||||
|
||||
/// What the brightness outside the set comes from.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum MandelbrotExterior {
|
||||
/// No brightness throughout, leaving the set as a silhouette.
|
||||
Flat,
|
||||
#[menu_separator]
|
||||
/// How many iterations a point takes to escape, in a flat band for each iteration.
|
||||
DiscreteEscape,
|
||||
/// How many iterations a point takes to escape, smoothed into soft gradients.
|
||||
#[default]
|
||||
SmoothEscape,
|
||||
#[menu_separator]
|
||||
/// How close a point lies to the set's edge, revealing its finest filaments. This is the classic distance estimate, worked out from how quickly the orbit's derivative grows.
|
||||
Proximity,
|
||||
/// Which way around the set a point lies, as one turn of brightness circling it. This is the set's external angle, worked out from the directions its orbit escapes in, and the counterpart of the internal angle inside each bulb. It levels off when zoomed in far.
|
||||
Angle,
|
||||
/// Rays radiating out from the set along the directions points escape in. These are the set's external rays, also called its field lines.
|
||||
Rays,
|
||||
#[menu_separator]
|
||||
/// How close a point's orbit comes to the origin before escaping, relative to where its first iteration lands, casting soft shadows around each bulb. This is the classic orbit trap coloring, with the trap at the origin.
|
||||
ClosestApproach,
|
||||
/// The iteration bringing a point's orbit closest to the origin before it escapes, in a flat band for each, which ring the bulbs like the Closest Iteration's petals inside them.
|
||||
ClosestIteration,
|
||||
/// Streaks following the paths points take as they escape. This is the classic stripe average coloring, which averages the direction each iteration's value points in.
|
||||
Tendrils,
|
||||
}
|
||||
|
||||
/// What the brightness inside the set comes from.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum MandelbrotInterior {
|
||||
/// Full brightness throughout.
|
||||
#[default]
|
||||
Flat,
|
||||
#[menu_separator]
|
||||
/// How many iterations a point's orbit takes to settle into its cycle, in a flat band for each iteration, darkest at each bulb's center. This is the counterpart of the Discrete Escape outside the set.
|
||||
DiscreteSettling,
|
||||
/// How slowly a point's orbit settles into its cycle, as a smooth gradient darkest at each bulb's center, the counterpart of the Smooth Escape outside the set. It shows how weakly the orbit is drawn together, which is its Lyapunov exponent as the average factor each iteration scales distances by.
|
||||
SmoothSettling,
|
||||
#[menu_separator]
|
||||
/// How far a point lies from its bulb's center toward its edge, measured by how weakly its orbit is drawn into its cycle. This is the bulb's internal radius.
|
||||
Radius,
|
||||
/// How close a point lies to its bulb's edge, brightening toward the set's edge like the Proximity outside. This is the classic interior distance estimate, worked out from how its cycle's multiplier changes from point to point, so it dims toward the Julia end, where every point inside shares one cycle.
|
||||
Proximity,
|
||||
/// Which way a point lies from its bulb's center, measured by how its orbit turns around its cycle, giving rays out from each center. This is the bulb's internal angle.
|
||||
Angle,
|
||||
/// Rays radiating out from each bulb's center along the directions its orbit turns around its cycle, as many for each turn as the Frequency. These are the bulb's internal rays, the counterpart of the external rays outside the set.
|
||||
Rays,
|
||||
/// How many values a point's orbit cycles through, which is the same across each bulb of the set.
|
||||
Period,
|
||||
#[menu_separator]
|
||||
/// How close a point's orbit comes to the origin, relative to where its first iteration lands.
|
||||
ClosestApproach,
|
||||
/// The iteration bringing a point's orbit closest to the origin, splitting each bulb into petal-shaped bands. This is the classic closest approach iteration coloring.
|
||||
ClosestIteration,
|
||||
/// How far from the origin a point's value lies after the last iteration, which is the orbit's final magnitude.
|
||||
FinalDistance,
|
||||
/// Which way from the origin a point's value lies after the last iteration, which changes along with the number of iterations.
|
||||
FinalAngle,
|
||||
}
|
||||
|
||||
/// The settings of a Mandelbrot-style fractal, with Mandelbrot-to-Julia in percent like the Mandelbrot node's parameter.
|
||||
#[derive(Debug, Clone, Default, PartialEq, CacheHash)]
|
||||
pub struct MandelbrotSettings {
|
||||
pub fractal: MandelbrotFractal,
|
||||
pub exterior: MandelbrotExterior,
|
||||
pub interior: MandelbrotInterior,
|
||||
pub frequency: i64,
|
||||
pub scale: f64,
|
||||
pub iterations: i64,
|
||||
pub power: f64,
|
||||
pub mandelbrot_to_julia: f64,
|
||||
pub mandelbrot_slice: DVec2,
|
||||
pub julia_slice: DVec2,
|
||||
}
|
||||
|
||||
impl MandelbrotSettings {
|
||||
/// Stamps every setting onto the generator's item, whatever its value, so which attributes the item carries doesn't depend on them.
|
||||
pub fn stamp(&self, item: &mut Item<Generator>) {
|
||||
self.clone().visit_parameters(&mut StampParameters(item));
|
||||
}
|
||||
|
||||
/// Visits each setting with the attribute it rides, named after the Mandelbrot node's parameter, and its default, which is the node's.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
visitor.parameter("fractal", &mut self.fractal, MandelbrotFractal::default());
|
||||
visitor.parameter("exterior", &mut self.exterior, MandelbrotExterior::default());
|
||||
visitor.parameter("interior", &mut self.interior, MandelbrotInterior::default());
|
||||
visitor.parameter("frequency", &mut self.frequency, 1);
|
||||
visitor.parameter("scale", &mut self.scale, 100.);
|
||||
visitor.parameter("iterations", &mut self.iterations, 256);
|
||||
visitor.parameter("power", &mut self.power, 2.);
|
||||
visitor.parameter("mandelbrot_to_julia", &mut self.mandelbrot_to_julia, 0.);
|
||||
visitor.parameter("mandelbrot_slice", &mut self.mandelbrot_slice, DVec2::ZERO);
|
||||
visitor.parameter("julia_slice", &mut self.julia_slice, DVec2::new(-0.8, 0.156));
|
||||
}
|
||||
}
|
||||
|
||||
/// A procedural pattern, a function of position in its own space that renders across any area at any resolution.
|
||||
#[derive(Debug, Clone, PartialEq, CacheHash)]
|
||||
pub enum GeneratorPattern {
|
||||
Noise(NoiseSettings),
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
/// A Mandelbrot-style fractal, with its space's origin at the complex plane's and the scale's number of units spanning one unit of the plane.
|
||||
Mandelbrot(MandelbrotSettings),
|
||||
}
|
||||
|
||||
/// A procedural pattern filling the whole plane, which renderers draw at whatever resolution they need across whatever part they see.
|
||||
/// The item's transform places the pattern's own space, and a noise pattern's settings ride the item as attributes named after the Noise Pattern node's parameters.
|
||||
/// The item's transform places the pattern's own space, and its settings ride the item as attributes named after its node's parameters.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny)]
|
||||
pub enum Generator {
|
||||
#[default]
|
||||
Noise,
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
/// A Mandelbrot-style fractal, with its space's origin at the complex plane's and the scale's number of units spanning one unit of the plane.
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
@@ -177,7 +293,7 @@ impl NoiseSettings {
|
||||
}
|
||||
|
||||
impl GeneratorPattern {
|
||||
/// The pattern a generator draws, reading a noise pattern's settings with `attribute`, which looks one of the item's attributes up by key.
|
||||
/// The pattern a generator draws, reading its settings with `attribute`, which looks one of the item's attributes up by key.
|
||||
/// Each setting the item lacks takes its default.
|
||||
pub fn decode<'a>(generator: Generator, attribute: &'a dyn Fn(&str) -> Option<&'a dyn Any>) -> Self {
|
||||
match generator {
|
||||
@@ -186,7 +302,11 @@ impl GeneratorPattern {
|
||||
settings.visit_parameters(&mut ReadParameters(attribute));
|
||||
Self::Noise(settings)
|
||||
}
|
||||
Generator::Mandelbrot => Self::Mandelbrot,
|
||||
Generator::Mandelbrot => {
|
||||
let mut settings = MandelbrotSettings::default();
|
||||
settings.visit_parameters(&mut ReadParameters(attribute));
|
||||
Self::Mandelbrot(settings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
//! The kernels rendering each [`GeneratorPattern`] across any area of its space at any resolution.
|
||||
|
||||
use crate::mandelbrot::{MandelbrotSetup, resolves_in_32_bits};
|
||||
use core_types::Color;
|
||||
use glam::{DVec2, IVec2, Vec2};
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{Image, ImageError};
|
||||
|
||||
/// The most iterations a point is tested for escaping the Mandelbrot set, beyond which it counts as inside.
|
||||
const MANDELBROT_ITERATIONS: u32 = 255;
|
||||
|
||||
/// The pattern across `area` of its own space, from its minimum to its maximum corner, sampled at the centers of a `width` by `height` grid of pixels.
|
||||
/// Fails where an image of that size can't be allocated.
|
||||
/// The rows are rendered in parallel on native targets.
|
||||
@@ -24,12 +22,16 @@ pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32,
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = Color::from_luminance(noise.sample(pixel_center(x, y))));
|
||||
});
|
||||
}
|
||||
GeneratorPattern::Mandelbrot => {
|
||||
GeneratorPattern::Mandelbrot(settings) => {
|
||||
let setup = MandelbrotSetup::new(settings);
|
||||
let (plane_area, plane_texel) = (area.map(|point| setup.plane_point(point)), (pixel_size / setup.scale).min_element());
|
||||
let reference = setup.reference_orbit(plane_area, plane_texel);
|
||||
let interior_test = setup.has_interior_test() && resolves_in_32_bits(plane_area, plane_texel);
|
||||
// The brightness is gamma-encoded, so a Gradient Map takes it as the position along its gradient
|
||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| {
|
||||
let c = pixel_center(x, y) * 3. - DVec2::new(2., 1.5);
|
||||
let value = mandelbrot_escape_iterations(c) as f32 / MANDELBROT_ITERATIONS as f32;
|
||||
*pixel = Color::from_rgbaf32_unchecked(value, value, value, 1.);
|
||||
let value = setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test).clamp(0., 1.);
|
||||
*pixel = Color::from_gamma_srgb_channels(value, value, value, 1.);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -38,6 +40,14 @@ pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32,
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
/// The area of the pattern's own space that a thumbnail frames, for a pattern with a part worth framing rather than one alike across the whole plane.
|
||||
pub fn thumbnail_area(pattern: &GeneratorPattern) -> Option<[DVec2; 2]> {
|
||||
match pattern {
|
||||
GeneratorPattern::Noise(_) => None,
|
||||
GeneratorPattern::Mandelbrot(settings) => Some(MandelbrotSetup::new(settings).thumbnail_area()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples a noise pattern's luminance, from 0 to 1, at positions in its space.
|
||||
struct NoiseSampler {
|
||||
noise: fastnoise_lite::FastNoiseLite,
|
||||
@@ -155,19 +165,6 @@ fn pcg3d(input: [u32; 3]) -> [u32; 3] {
|
||||
mix(v.map(|value| value ^ (value >> 16)))
|
||||
}
|
||||
|
||||
/// How many iterations `c` takes to escape the Mandelbrot set, or the iteration limit if it doesn't. In f32, which a GPU can match near the boundary.
|
||||
fn mandelbrot_escape_iterations(c: DVec2) -> u32 {
|
||||
let c = c.as_vec2();
|
||||
let mut z = Vec2::ZERO;
|
||||
for iteration in 0..MANDELBROT_ITERATIONS {
|
||||
z = Vec2::new(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c;
|
||||
if z.length_squared() > 4. {
|
||||
return iteration;
|
||||
}
|
||||
}
|
||||
MANDELBROT_ITERATIONS
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod color_lookup_table;
|
||||
pub mod effect_kernels;
|
||||
pub mod generators;
|
||||
mod kernel;
|
||||
pub mod mandelbrot;
|
||||
pub mod raster_effects;
|
||||
pub mod value_effects;
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -26,6 +26,7 @@ brush-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
graphene-application-io = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
@@ -38,6 +39,8 @@ vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
glifo = { workspace = true }
|
||||
krilla = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
parley = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
|
||||
@@ -21,7 +21,7 @@ pub enum PaintTarget {
|
||||
}
|
||||
|
||||
impl PaintTarget {
|
||||
fn paint_attr(self) -> &'static str {
|
||||
pub(crate) fn paint_attr(self) -> &'static str {
|
||||
match self {
|
||||
Self::Fill => "fill",
|
||||
Self::Stroke => "stroke",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,7 @@ use glam::{DAffine2, DMat2, DVec2, UVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use graphic_types::raster_types::{CPU, ImageError, Raster, Texture};
|
||||
use graphic_types::raster_types::{CPU, Raster, Texture};
|
||||
use graphic_types::{Adjustment, EffectOperation, Effects};
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
|
||||
use std::borrow::Cow;
|
||||
@@ -44,6 +44,30 @@ pub struct VelloSceneBuilder<'a> {
|
||||
effects_renderer: Option<&'a mut dyn EffectsRenderer>,
|
||||
/// The coverage the next effects group drawn outputs in place of its result, for an SVG map of it.
|
||||
effect_capture: Option<EffectCapture>,
|
||||
/// Caches the outlines of glyph runs drawn natively. A scene without it can't draw glyph runs.
|
||||
glyph_resources: Option<&'a dyn GlyphResources>,
|
||||
}
|
||||
|
||||
/// Lends out the renderer's resources that glyph runs cache their outlines in.
|
||||
pub trait GlyphResources: Sync {
|
||||
/// Calls `draw` with the resources, held exclusively until it returns.
|
||||
fn with_resources(&self, draw: &mut dyn FnMut(&mut vello_gpu::Resources));
|
||||
}
|
||||
|
||||
/// The font and styling shared by the glyphs of one glyph run.
|
||||
pub struct GlyphRunStyle<'b> {
|
||||
pub font: &'b peniko::FontData,
|
||||
pub font_size: f32,
|
||||
/// The variation coordinates of a variable font, empty for its default instance.
|
||||
pub normalized_coords: &'b [i16],
|
||||
/// Places each glyph's outline relative to its origin, like a skew for faux italics.
|
||||
pub glyph_transform: Affine,
|
||||
}
|
||||
|
||||
/// Whether a glyph run's outlines are filled or stroked.
|
||||
pub enum GlyphPaintMode<'b> {
|
||||
Fill,
|
||||
Stroke(&'b Stroke),
|
||||
}
|
||||
|
||||
/// Renders the content of a scene's effects groups offscreen and carries out their effects, while the scene is drawn.
|
||||
@@ -79,7 +103,7 @@ pub enum SceneImage {
|
||||
Texture(Texture),
|
||||
/// Premultiplied pixels of an effects group's result, rendered for this scene.
|
||||
Rendered(wgpu::Texture),
|
||||
/// One tile of a generator's pattern, rendered on the CPU the first time it's drawn.
|
||||
/// One tile of a generator's pattern, rendered the first time it's drawn.
|
||||
GeneratorTile { pattern: GeneratorPattern, tile: GeneratorTile },
|
||||
}
|
||||
|
||||
@@ -107,12 +131,6 @@ impl GeneratorTile {
|
||||
/// The samples across and down the tile and its border.
|
||||
pub const SAMPLES: u32 = GENERATOR_TILE_PIXELS + 2 * GENERATOR_TILE_BORDER;
|
||||
|
||||
/// The pattern's pixels across the tile and its border, rendered on the CPU.
|
||||
pub fn render(&self, pattern: &GeneratorPattern) -> Result<Raster<CPU>, ImageError> {
|
||||
let (corner, texel) = self.corner_and_texel();
|
||||
raster_kernels::generators::render_pattern(pattern, [corner, corner + DVec2::splat(Self::SAMPLES as f64 * texel)], Self::SAMPLES, Self::SAMPLES).map(Raster::new_cpu)
|
||||
}
|
||||
|
||||
/// The corner of the tile's samples, including its border, in the pattern's space, and the span of one sample.
|
||||
pub fn corner_and_texel(&self) -> (DVec2, f64) {
|
||||
let span = 2_f64.powi(-self.level);
|
||||
@@ -154,6 +172,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
pushed: Vec::new(),
|
||||
effects_renderer: None,
|
||||
effect_capture: None,
|
||||
glyph_resources: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,6 +182,17 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Draws glyph runs natively, caching their outlines in `resources`.
|
||||
pub fn with_glyph_resources(mut self, resources: &'a dyn GlyphResources) -> Self {
|
||||
self.glyph_resources = Some(resources);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether [`Self::draw_glyphs`] can draw, which needs glyph resources.
|
||||
pub fn can_draw_glyphs(&self) -> bool {
|
||||
self.glyph_resources.is_some()
|
||||
}
|
||||
|
||||
/// Has the next effects group drawn output the coverage `capture` names in place of its result, leaving the groups drawn within it as they are.
|
||||
pub fn capture_next_effects(&mut self, capture: EffectCapture) {
|
||||
self.effect_capture = Some(capture);
|
||||
@@ -243,6 +273,42 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self.scene.stroke_path(&finite_path(&shape.to_path(SHAPE_TOLERANCE)));
|
||||
}
|
||||
|
||||
/// Draws a run of glyphs positioned in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
||||
/// Draws nothing without glyph resources, which [`Self::can_draw_glyphs`] tells.
|
||||
pub fn draw_glyphs<'b>(&mut self, style: &GlyphRunStyle, mode: GlyphPaintMode, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, glyphs: &[glifo::Glyph]) {
|
||||
let Some(glyph_resources) = self.glyph_resources else {
|
||||
log::error!("A scene without glyph resources was asked to draw glyphs");
|
||||
return;
|
||||
};
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(Fill::NonZero);
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
if let GlyphPaintMode::Stroke(stroke) = mode {
|
||||
self.scene.set_stroke(stroke.clone());
|
||||
}
|
||||
|
||||
let scene = &mut self.scene;
|
||||
glyph_resources.with_resources(&mut |resources| {
|
||||
// Unhinted, so outlines keep their shapes at every zoom like the rest of the artwork
|
||||
let glyph_run = (scene.glyph_run(resources, style.font))
|
||||
.font_size(style.font_size)
|
||||
.normalized_coords(style.normalized_coords)
|
||||
.glyph_transform(style.glyph_transform)
|
||||
.hint(false);
|
||||
|
||||
let drawn = match mode {
|
||||
GlyphPaintMode::Fill => glyph_run.fill_glyphs(glyphs.iter().copied()),
|
||||
GlyphPaintMode::Stroke(_) => glyph_run.stroke_glyphs(glyphs.iter().copied()),
|
||||
};
|
||||
if let Err(error) = drawn {
|
||||
log::warn!("Some glyphs failed to draw: {error:?}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content.
|
||||
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "svg-convert"
|
||||
description = "Converts SVG documents into Graphene graphic content"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
core-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
linesweeper = { workspace = true }
|
||||
usvg = { workspace = true }
|
||||
@@ -0,0 +1,22 @@
|
||||
use core_types::BlendMode;
|
||||
|
||||
pub fn blend_mode(group: &usvg::Group) -> Option<BlendMode> {
|
||||
match group.blend_mode() {
|
||||
usvg::BlendMode::Normal | usvg::BlendMode::PlusLighter => None,
|
||||
usvg::BlendMode::Multiply => Some(BlendMode::Multiply),
|
||||
usvg::BlendMode::Screen => Some(BlendMode::Screen),
|
||||
usvg::BlendMode::Overlay => Some(BlendMode::Overlay),
|
||||
usvg::BlendMode::Darken => Some(BlendMode::Darken),
|
||||
usvg::BlendMode::Lighten => Some(BlendMode::Lighten),
|
||||
usvg::BlendMode::ColorDodge => Some(BlendMode::ColorDodge),
|
||||
usvg::BlendMode::ColorBurn => Some(BlendMode::ColorBurn),
|
||||
usvg::BlendMode::HardLight => Some(BlendMode::HardLight),
|
||||
usvg::BlendMode::SoftLight => Some(BlendMode::SoftLight),
|
||||
usvg::BlendMode::Difference => Some(BlendMode::Difference),
|
||||
usvg::BlendMode::Exclusion => Some(BlendMode::Exclusion),
|
||||
usvg::BlendMode::Hue => Some(BlendMode::Hue),
|
||||
usvg::BlendMode::Saturation => Some(BlendMode::Saturation),
|
||||
usvg::BlendMode::Color => Some(BlendMode::Color),
|
||||
usvg::BlendMode::Luminosity => Some(BlendMode::Luminosity),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::{affine, graphic_list};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_CLIPPING_MASK, ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||||
use glam::DAffine2;
|
||||
use graphic_types::{Graphic, IntoGraphicList};
|
||||
|
||||
pub fn clipped(group: &usvg::Group, content: List<Graphic>) -> List<Graphic> {
|
||||
std::iter::successors(group.clip_path(), |clip_path| clip_path.clip_path()).fold(content, |content, clip_path| clipped_to(clipper(clip_path), content))
|
||||
}
|
||||
|
||||
pub fn clipped_to(clipper: Item<Graphic>, mut content: List<Graphic>) -> List<Graphic> {
|
||||
content.set_attribute_values(ATTR_CLIPPING_MASK, vec![true; content.len()]);
|
||||
[clipper.with_attribute(ATTR_OPACITY_FILL, 0.), Item::new_from_element(Graphic::GraphicList(content))]
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn clipper(clip_path: &usvg::ClipPath) -> Item<Graphic> {
|
||||
let mut shapes = Item::new_from_element(Graphic::GraphicList(graphic_list(clip_path.root())));
|
||||
let transform = affine(clip_path.transform());
|
||||
if transform != DAffine2::IDENTITY {
|
||||
shapes.set_attribute(ATTR_TRANSFORM, transform);
|
||||
}
|
||||
Item::new_from_element(Graphic::VectorList(List::new_from_item(shapes).into_flattened_list()))
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use core_types::list::{ATTR_APPEARANCE, Item, List};
|
||||
use graphic_types::{Appearance, Cover, Vector};
|
||||
use kurbo::{BezPath, PathEl, Shape};
|
||||
use linesweeper::topology::{OutputSegIdx, Topology};
|
||||
|
||||
pub fn nonzero_vectors(vector: Item<Vector>, geometry: &BezPath) -> List<Vector> {
|
||||
let appearance = vector.attribute::<Appearance>(ATTR_APPEARANCE).cloned().unwrap_or_default();
|
||||
let Some(region) = appearance.has_cover(Cover::Fill).then(|| even_odd_region(geometry)).flatten() else {
|
||||
return List::new_from_item(vector);
|
||||
};
|
||||
|
||||
let only = |item: Item<Vector>, cover| {
|
||||
let mut appearance = appearance.clone();
|
||||
appearance.retain_cover(cover);
|
||||
item.with_attribute(ATTR_APPEARANCE, appearance)
|
||||
};
|
||||
let fill = only(Vector::item_from_bezpath(®ion), Cover::Fill);
|
||||
if !appearance.has_cover(Cover::Stroke) {
|
||||
return List::new_from_item(fill);
|
||||
}
|
||||
let stroke = only(vector, Cover::Stroke);
|
||||
let paint_order = if appearance.fill_and_stroke().stroke_below { [stroke, fill] } else { [fill, stroke] };
|
||||
paint_order.into_iter().collect()
|
||||
}
|
||||
|
||||
fn even_odd_region(geometry: &BezPath) -> Option<BezPath> {
|
||||
let bounds = geometry.bounding_box();
|
||||
let magnitude = [bounds.x0, bounds.y0, bounds.x1, bounds.y1].into_iter().map(f64::abs).fold(0., f64::max);
|
||||
let topology = Topology::from_path(&closed_subpaths(geometry), (magnitude * f64::EPSILON * 64.).max(1e-6)).ok()?;
|
||||
|
||||
let rules_differ = (topology.segment_indices().map(OutputSegIdx::first_half))
|
||||
.flat_map(|half| [*topology.winding_clockwise(half), *topology.winding_counter_clockwise(half)])
|
||||
.any(|winding| winding != 0 && winding % 2 == 0);
|
||||
rules_differ.then(|| topology.contours(|winding| winding % 2 != 0).into_contours().flat_map(|contour| contour.path).collect())
|
||||
}
|
||||
|
||||
fn closed_subpaths(geometry: &BezPath) -> BezPath {
|
||||
let ends_closed = |path: &BezPath| matches!(path.elements().last(), None | Some(PathEl::ClosePath));
|
||||
let mut closed = BezPath::new();
|
||||
for element in geometry {
|
||||
if matches!(element, PathEl::MoveTo(_)) && !ends_closed(&closed) {
|
||||
closed.close_path();
|
||||
}
|
||||
closed.push(element);
|
||||
}
|
||||
if !ends_closed(&closed) {
|
||||
closed.close_path();
|
||||
}
|
||||
closed
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use crate::color;
|
||||
use core_types::ATTR_EFFECTS;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use graphic_types::{EffectOperation, Effects, Graphic};
|
||||
use usvg::filter::{ColorInterpolation, Input, Kind, Primitive};
|
||||
|
||||
pub fn filtered(group: &usvg::Group, content: List<Graphic>) -> List<Graphic> {
|
||||
let operations = (group.filters().iter())
|
||||
.filter_map(|filter| operation(filter.primitives()))
|
||||
.filter(|operation| !operation.changes_nothing());
|
||||
let effects = Effects::from_operations(operations);
|
||||
if effects.is_empty() {
|
||||
return content;
|
||||
}
|
||||
|
||||
List::new_from_item(Item::new_from_element(Graphic::GraphicList(content)).with_attribute(ATTR_EFFECTS, effects))
|
||||
}
|
||||
|
||||
fn operation(primitives: &[Primitive]) -> Option<EffectOperation> {
|
||||
let (primitive, rest) = primitives.split_first()?;
|
||||
let passes_through = |next: &Primitive| match next.kind() {
|
||||
Kind::Offset(offset) => offset.dx() == 0. && offset.dy() == 0. && matches!(offset.input(), Input::Reference(name) if name == primitive.result()),
|
||||
_ => false,
|
||||
};
|
||||
if rest.len() > 1 || !rest.iter().all(passes_through) {
|
||||
return None;
|
||||
}
|
||||
|
||||
match primitive.kind() {
|
||||
Kind::GaussianBlur(blur) if *blur.input() == Input::SourceGraphic => Some(EffectOperation::Blur {
|
||||
radius: standard_deviation(blur.std_dev_x().get(), blur.std_dev_y().get()),
|
||||
box_blur: false,
|
||||
gamma: primitive.color_interpolation() == ColorInterpolation::SRGB,
|
||||
}),
|
||||
Kind::DropShadow(shadow) if *shadow.input() == Input::SourceGraphic => {
|
||||
let (dx, dy) = (f64::from(shadow.dx()), f64::from(shadow.dy()));
|
||||
let tent = standard_deviation(shadow.std_dev_x().get(), shadow.std_dev_y().get()) * 6_f64.sqrt();
|
||||
Some(EffectOperation::DropShadow {
|
||||
color: color(shadow.color(), shadow.opacity().get()),
|
||||
angle: dy.atan2(-dx).to_degrees(),
|
||||
distance: dx.hypot(dy),
|
||||
spread: 0.,
|
||||
size: if tent >= 2. { tent } else { tent / 2. },
|
||||
contour: TransferCurve::default(),
|
||||
knockout: true,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn standard_deviation(along_x: f32, along_y: f32) -> f64 {
|
||||
(f64::from(along_x) * f64::from(along_y)).sqrt()
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use crate::{affine, color};
|
||||
use core_types::list::{ATTR_POSITION, Item};
|
||||
use core_types::{ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_TRANSFORM};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::vector_types::{Gradient, GradientForm, GradientSpace, GradientSpread};
|
||||
|
||||
pub fn linear(gradient: &usvg::LinearGradient, opacity: usvg::Opacity) -> Graphic {
|
||||
let start = DVec2::new(gradient.x1().into(), gradient.y1().into());
|
||||
let direction = DVec2::new(gradient.x2().into(), gradient.y2().into()) - start;
|
||||
if direction == DVec2::ZERO
|
||||
&& let Some(last) = gradient.stops().last()
|
||||
{
|
||||
return Graphic::from(color(last.color(), last.opacity().get() * opacity.get()));
|
||||
}
|
||||
paint(gradient, GradientForm::Linear, DAffine2::from_cols(direction, direction.perp(), start), opacity)
|
||||
}
|
||||
|
||||
pub fn radial(gradient: &usvg::RadialGradient, opacity: usvg::Opacity) -> Graphic {
|
||||
let radius = DVec2::splat(gradient.r().get().into());
|
||||
let center = DVec2::new(gradient.cx().into(), gradient.cy().into());
|
||||
paint(gradient, GradientForm::Radial, DAffine2::from_scale_angle_translation(radius, 0., center), opacity)
|
||||
}
|
||||
|
||||
fn paint(gradient: &usvg::BaseGradient, form: GradientForm, unit_placement: DAffine2, opacity: usvg::Opacity) -> Graphic {
|
||||
let stops = gradient
|
||||
.stops()
|
||||
.iter()
|
||||
.map(|stop| Item::new_from_element(color(stop.color(), stop.opacity().get() * opacity.get())).with_attribute(ATTR_POSITION, f64::from(stop.offset().get())))
|
||||
.collect();
|
||||
let mut item = Item::new_from_element(Gradient(stops)).with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma);
|
||||
|
||||
if form != GradientForm::default() {
|
||||
item.set_attribute(ATTR_GRADIENT_FORM, form);
|
||||
}
|
||||
let spread = match gradient.spread_method() {
|
||||
usvg::SpreadMethod::Pad => GradientSpread::Pad,
|
||||
usvg::SpreadMethod::Reflect => GradientSpread::Reflect,
|
||||
usvg::SpreadMethod::Repeat => GradientSpread::Repeat,
|
||||
};
|
||||
if !spread.is_default() {
|
||||
item.set_attribute(ATTR_GRADIENT_SPREAD, spread);
|
||||
}
|
||||
let transform = affine(gradient.transform()) * unit_placement;
|
||||
if transform != DAffine2::IDENTITY {
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
}
|
||||
|
||||
Graphic::Gradient(item)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Converts SVG documents into [`Graphic`] content.
|
||||
//!
|
||||
//! Parsing and style resolution are left to `usvg`. This crate maps the resulting tree onto Graphene's graphic types.
|
||||
//! The conversion is best effort: what has no counterpart is left out.
|
||||
|
||||
mod blend_mode;
|
||||
mod clip;
|
||||
mod even_odd;
|
||||
mod filter;
|
||||
mod gradient;
|
||||
mod mask;
|
||||
mod pattern;
|
||||
mod raster;
|
||||
mod stroke;
|
||||
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_TRANSFORM, Color};
|
||||
use glam::DAffine2;
|
||||
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||
use kurbo::{BezPath, PathEl, Point};
|
||||
use usvg::tiny_skia_path::{self, PathSegment};
|
||||
|
||||
pub use usvg::{Error, Options};
|
||||
|
||||
pub fn convert(svg: &str, options: &Options) -> Result<List<Graphic>, Error> {
|
||||
let tree = usvg::Tree::from_str(svg, options)?;
|
||||
Ok(graphic_list(tree.root()))
|
||||
}
|
||||
|
||||
fn graphic_list(group: &usvg::Group) -> List<Graphic> {
|
||||
group.children().iter().filter_map(graphic_item).collect()
|
||||
}
|
||||
|
||||
fn graphic_item(node: &usvg::Node) -> Option<Item<Graphic>> {
|
||||
match node {
|
||||
usvg::Node::Group(group) => Some(group_item(group)),
|
||||
usvg::Node::Path(path) if path.is_visible() => Some(path_item(path)),
|
||||
usvg::Node::Image(image) if image.is_visible() => image_item(image),
|
||||
usvg::Node::Text(text) => Some(group_item(text.flattened())),
|
||||
usvg::Node::Path(_) | usvg::Node::Image(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn group_item(group: &usvg::Group) -> Item<Graphic> {
|
||||
let content = graphic_list(group);
|
||||
let content = filter::filtered(group, content);
|
||||
let content = clip::clipped(group, content);
|
||||
let content = mask::masked(group, content);
|
||||
|
||||
let mut item = Item::new_from_element(Graphic::GraphicList(content));
|
||||
let transform = affine(group.transform());
|
||||
if transform != DAffine2::IDENTITY {
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
}
|
||||
if group.opacity() != usvg::Opacity::ONE {
|
||||
item.set_attribute(ATTR_OPACITY, f64::from(group.opacity().get()));
|
||||
}
|
||||
if let Some(blend_mode) = blend_mode::blend_mode(group) {
|
||||
item.set_attribute(ATTR_BLEND_MODE, blend_mode);
|
||||
}
|
||||
item
|
||||
}
|
||||
|
||||
fn path_item(path: &usvg::Path) -> Item<Graphic> {
|
||||
let geometry = bezpath(path.data());
|
||||
let mut vector = Vector::item_from_bezpath(&geometry);
|
||||
if let Some(fill) = path.fill()
|
||||
&& let Some(fill_paint) = paint(fill.paint(), fill.opacity(), path.bounding_box())
|
||||
{
|
||||
stamp_coverage(&mut vector, Coverage::new_fill(), fill_paint, CoverPlacement::Above);
|
||||
}
|
||||
if let Some(stroke) = path.stroke()
|
||||
&& let Some(stroke_paint) = paint(stroke.paint(), stroke.opacity(), path.stroke_bounding_box())
|
||||
{
|
||||
let placement = match path.paint_order() {
|
||||
usvg::PaintOrder::FillAndStroke => CoverPlacement::Above,
|
||||
usvg::PaintOrder::StrokeAndFill => CoverPlacement::Below,
|
||||
};
|
||||
stamp_coverage(&mut vector, Coverage::new_stroke(&stroke::style(stroke)), stroke_paint, placement);
|
||||
}
|
||||
|
||||
let vectors = match path.fill().map(usvg::Fill::rule) {
|
||||
Some(usvg::FillRule::EvenOdd) => even_odd::nonzero_vectors(vector, &geometry),
|
||||
Some(usvg::FillRule::NonZero) | None => List::new_from_item(vector),
|
||||
};
|
||||
Item::new_from_element(Graphic::VectorList(vectors))
|
||||
}
|
||||
|
||||
fn image_item(image: &usvg::Image) -> Option<Item<Graphic>> {
|
||||
match image.kind() {
|
||||
usvg::ImageKind::SVG(tree) => Some(group_item(tree.root())),
|
||||
usvg::ImageKind::PNG(data) | usvg::ImageKind::JPEG(data) | usvg::ImageKind::GIF(data) | usvg::ImageKind::WEBP(data) => raster::raster_item(data, image.size()),
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(paint: &usvg::Paint, opacity: usvg::Opacity, covered: usvg::Rect) -> Option<Graphic> {
|
||||
match paint {
|
||||
usvg::Paint::Color(rgb) => Some(Graphic::from(color(*rgb, opacity.get()))),
|
||||
usvg::Paint::LinearGradient(linear) => Some(gradient::linear(linear, opacity)),
|
||||
usvg::Paint::RadialGradient(radial) => Some(gradient::radial(radial, opacity)),
|
||||
usvg::Paint::Pattern(pattern) => pattern::tiled(pattern, covered, opacity),
|
||||
}
|
||||
}
|
||||
|
||||
fn color(color: usvg::Color, alpha: f32) -> Color {
|
||||
let [red, green, blue] = [color.red, color.green, color.blue].map(|channel| channel as f32 / 255.);
|
||||
Color::from_gamma_srgb_channels(red, green, blue, alpha)
|
||||
}
|
||||
|
||||
fn affine(transform: usvg::Transform) -> DAffine2 {
|
||||
let usvg::Transform { sx, kx, ky, sy, tx, ty } = transform;
|
||||
DAffine2::from_cols_array(&[sx, ky, kx, sy, tx, ty].map(f64::from))
|
||||
}
|
||||
|
||||
fn bezpath(path: &tiny_skia_path::Path) -> BezPath {
|
||||
let point = |point: tiny_skia_path::Point| Point::new(point.x.into(), point.y.into());
|
||||
|
||||
path.segments()
|
||||
.map(|segment| match segment {
|
||||
PathSegment::MoveTo(end) => PathEl::MoveTo(point(end)),
|
||||
PathSegment::LineTo(end) => PathEl::LineTo(point(end)),
|
||||
PathSegment::QuadTo(handle, end) => PathEl::QuadTo(point(handle), point(end)),
|
||||
PathSegment::CubicTo(start_handle, end_handle, end) => PathEl::CurveTo(point(start_handle), point(end_handle), point(end)),
|
||||
PathSegment::Close => PathEl::ClosePath,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use crate::clip::clipped_to;
|
||||
use crate::{bezpath, graphic_list};
|
||||
use core_types::Color;
|
||||
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, Item, List};
|
||||
use graphic_types::{Appearance, CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||
use usvg::tiny_skia_path::PathBuilder;
|
||||
|
||||
pub fn masked(group: &usvg::Group, content: List<Graphic>) -> List<Graphic> {
|
||||
std::iter::successors(group.mask(), |mask| mask.mask()).fold(content, |content, mask| clipped_to(masker(mask), within_region(mask, content)))
|
||||
}
|
||||
|
||||
fn masker(mask: &usvg::Mask) -> Item<Graphic> {
|
||||
let mut shapes = graphic_list(mask.root());
|
||||
match mask.kind() {
|
||||
usvg::MaskType::Luminance => luminance_to_alpha(&mut shapes),
|
||||
usvg::MaskType::Alpha => {}
|
||||
}
|
||||
Item::new_from_element(Graphic::GraphicList(shapes))
|
||||
}
|
||||
|
||||
fn within_region(mask: &usvg::Mask, content: List<Graphic>) -> List<Graphic> {
|
||||
let (region, drawn) = (mask.rect().to_rect(), mask.root().layer_bounding_box().to_rect());
|
||||
if region.intersect(&drawn) == Some(drawn) {
|
||||
return content;
|
||||
}
|
||||
|
||||
let mut clipper = Vector::item_from_bezpath(&bezpath(&PathBuilder::from_rect(region)));
|
||||
stamp_coverage(&mut clipper, Coverage::new_fill(), Graphic::from(Color::BLACK), CoverPlacement::Above);
|
||||
clipped_to(Item::new_from_element(Graphic::VectorList(List::new_from_item(clipper))), content)
|
||||
}
|
||||
|
||||
fn luminance_to_alpha(content: &mut List<Graphic>) {
|
||||
for graphic in content.iter_element_values_mut() {
|
||||
match graphic {
|
||||
Graphic::GraphicList(list) => luminance_to_alpha(list),
|
||||
Graphic::VectorList(vectors) => {
|
||||
let appearances = vectors.iter_attribute_values_mut::<Appearance>(ATTR_APPEARANCE).into_iter().flatten();
|
||||
for paint in appearances.flat_map(|appearance| appearance.0.iter_attribute_values_mut::<Graphic>(ATTR_PAINT).into_iter().flatten()) {
|
||||
match paint {
|
||||
Graphic::Color(color) => *color.element_mut() = luminance_as_alpha(*color.element()),
|
||||
Graphic::Gradient(gradient) => gradient.element_mut().0.iter_element_values_mut().for_each(|stop| *stop = luminance_as_alpha(*stop)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn luminance_as_alpha(color: Color) -> Color {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
Color::BLACK.with_alpha((0.2126 * red + 0.7152 * green + 0.0722 * blue) * alpha)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use crate::{affine, graphic_list};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_OPACITY, ATTR_TRANSFORM};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||
use kurbo::Shape;
|
||||
|
||||
const MAX_TILES: f64 = 1024.;
|
||||
|
||||
pub fn tiled(pattern: &usvg::Pattern, covered: usvg::Rect, opacity: usvg::Opacity) -> Option<Graphic> {
|
||||
let covered = covered.transform(pattern.transform().invert()?)?;
|
||||
let tile = pattern.rect();
|
||||
let (origin, size) = (DVec2::new(tile.x().into(), tile.y().into()), DVec2::new(tile.width().into(), tile.height().into()));
|
||||
let first = ((DVec2::new(covered.left().into(), covered.top().into()) - origin) / size).floor();
|
||||
let end = ((DVec2::new(covered.right().into(), covered.bottom().into()) - origin) / size).ceil().max(first + 1.);
|
||||
let count = end - first;
|
||||
if count.x * count.y > MAX_TILES {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut prototype = Vector::item_from_bezpath(&kurbo::Rect::new(0., 0., size.x, size.y).to_path(0.));
|
||||
stamp_coverage(&mut prototype, Coverage::new_fill(), Graphic::GraphicList(graphic_list(pattern.root())), CoverPlacement::Above);
|
||||
let placement = affine(pattern.transform());
|
||||
let cells = (first.y as i64..end.y as i64).flat_map(|row| (first.x as i64..end.x as i64).map(move |column| DVec2::new(column as f64, row as f64)));
|
||||
let tiles = cells.map(|cell| prototype.clone().with_attribute(ATTR_TRANSFORM, placement * DAffine2::from_translation(origin + cell * size)));
|
||||
|
||||
let mut paint = Item::new_from_element(Graphic::VectorList(tiles.collect()));
|
||||
if opacity != usvg::Opacity::ONE {
|
||||
paint.set_attribute(ATTR_OPACITY, f64::from(opacity.get()));
|
||||
}
|
||||
Some(Graphic::GraphicList(List::new_from_item(paint)))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::list::{Item, List};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
|
||||
pub fn raster_item(encoded: &[u8], size: usvg::Size) -> Option<Item<Graphic>> {
|
||||
let mut raster = Item::new_from_element(Raster::new_cpu(Image::from_encoded(encoded).ok()?));
|
||||
let transform = DAffine2::from_scale(DVec2::new(size.width().into(), size.height().into()));
|
||||
if transform != DAffine2::IDENTITY {
|
||||
raster.set_attribute(ATTR_TRANSFORM, transform);
|
||||
}
|
||||
Some(Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(raster))))
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use graphic_types::vector_types::vector::style::{Stroke, StrokeCap, StrokeJoin};
|
||||
|
||||
pub fn style(stroke: &usvg::Stroke) -> Stroke {
|
||||
let (dash_lengths, dash_offset) = match stroke.dasharray() {
|
||||
Some(lengths) => (lengths.iter().copied().map(f64::from).collect(), f64::from(stroke.dashoffset())),
|
||||
None => (Vec::new(), 0.),
|
||||
};
|
||||
|
||||
Stroke {
|
||||
weight: stroke.width().get().into(),
|
||||
dash_lengths,
|
||||
dash_offset,
|
||||
cap: match stroke.linecap() {
|
||||
usvg::LineCap::Butt => StrokeCap::Butt,
|
||||
usvg::LineCap::Round => StrokeCap::Round,
|
||||
usvg::LineCap::Square => StrokeCap::Square,
|
||||
},
|
||||
join: match stroke.linejoin() {
|
||||
usvg::LineJoin::Miter | usvg::LineJoin::MiterClip => StrokeJoin::Miter,
|
||||
usvg::LineJoin::Round => StrokeJoin::Round,
|
||||
usvg::LineJoin::Bevel => StrokeJoin::Bevel,
|
||||
},
|
||||
join_miter_limit: stroke.miterlimit().get().into(),
|
||||
..Stroke::default()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
use core_types::list::{ATTR_APPEARANCE, Item, List};
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_EFFECTS, ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, BlendMode, Color};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effects::shadow_offset;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::vector_types::vector::paths_from_list_row_attributes;
|
||||
use graphic_types::vector_types::vector::style::{StrokeCap, StrokeJoin};
|
||||
use graphic_types::vector_types::{Gradient, GradientForm, GradientSpace, GradientSpread};
|
||||
use graphic_types::{Appearance, Cover, Coverage, EffectOperation, Effects, Graphic, Vector};
|
||||
use kurbo::{BezPath, Point, Shape};
|
||||
use svg_convert::{Error, Options, convert};
|
||||
|
||||
fn converted(content: &str) -> Result<List<Graphic>, Error> {
|
||||
convert(&format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8">{content}</svg>"#), &Options::default())
|
||||
}
|
||||
|
||||
fn appearance_of(content: &List<Graphic>) -> Option<&Appearance> {
|
||||
let Some(Graphic::VectorList(vectors)) = content.element(0) else { return None };
|
||||
vectors.attribute(ATTR_APPEARANCE, 0)
|
||||
}
|
||||
|
||||
fn group(content: &List<Graphic>, index: usize) -> Option<&List<Graphic>> {
|
||||
content.element(index)?.as_graphic_list()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filled_path_becomes_a_vector_whose_fill_coverage_carries_its_color() -> Result<(), Error> {
|
||||
let content = converted(r#"<rect width="4" height="4" fill="red" fill-opacity="0.5"/>"#)?;
|
||||
|
||||
let fill = appearance_of(&content).and_then(|appearance| appearance.first_paint_of(Cover::Fill));
|
||||
assert_eq!(fill, Some(&Graphic::from(Color::from_gamma_srgb_channels(1., 0., 0., 0.5))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_becomes_an_item_carrying_its_transform() -> Result<(), Error> {
|
||||
let content = converted(r#"<g transform="translate(3 4)"><rect width="4" height="4"/></g>"#)?;
|
||||
|
||||
assert!(matches!(content.element(0), Some(Graphic::GraphicList(children)) if children.len() == 1));
|
||||
assert_eq!(content.attribute::<DAffine2>(ATTR_TRANSFORM, 0), Some(&DAffine2::from_translation(DVec2::new(3., 4.))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_item_carries_its_opacity_only_when_below_one() -> Result<(), Error> {
|
||||
let half = converted(r#"<g opacity="0.5"><rect width="4" height="4"/></g>"#)?;
|
||||
let full = converted(r#"<g opacity="1"><rect width="4" height="4"/></g>"#)?;
|
||||
|
||||
assert_eq!(half.attribute::<f64>(ATTR_OPACITY, 0), Some(&0.5));
|
||||
assert_eq!(full.attribute::<f64>(ATTR_OPACITY, 0), None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_item_carries_its_blend_mode_unless_it_is_plus_lighter() -> Result<(), Error> {
|
||||
let multiply = converted(r#"<g style="mix-blend-mode: multiply"><rect width="4" height="4"/></g>"#)?;
|
||||
let plus_lighter = converted(r#"<g style="mix-blend-mode: plus-lighter"><rect width="4" height="4"/></g>"#)?;
|
||||
|
||||
assert_eq!(multiply.attribute::<BlendMode>(ATTR_BLEND_MODE, 0), Some(&BlendMode::Multiply));
|
||||
assert_eq!(plus_lighter.attribute::<BlendMode>(ATTR_BLEND_MODE, 0), None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_becomes_a_group_of_glyph_outlines_when_its_font_is_given() -> Result<(), Error> {
|
||||
let mut options = Options::default();
|
||||
options.fontdb_mut().load_font_data(include_bytes!("../../../nodes/text/src/source-sans-pro-regular.ttf").to_vec());
|
||||
let content = convert(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><text x="2" y="15" font-family="Source Sans Pro" font-size="12">Hi</text></svg>"#,
|
||||
&options,
|
||||
)?;
|
||||
|
||||
assert!(matches!(content.element(0), Some(Graphic::GraphicList(glyphs)) if matches!(glyphs.element(0), Some(Graphic::VectorList(_)))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_svg_image_becomes_a_group_of_its_content() -> Result<(), Error> {
|
||||
let content = converted(
|
||||
r#"<image width="4" height="4" href="data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20width=%224%22%20height=%224%22%3E%3Crect%20width=%224%22%20height=%224%22/%3E%3C/svg%3E"/>"#,
|
||||
)?;
|
||||
|
||||
let nested_root = group(&content, 0).and_then(|placement| placement.element(0));
|
||||
assert!(matches!(nested_root, Some(Graphic::GraphicList(nested)) if matches!(nested.element(0), Some(Graphic::VectorList(_)))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_raster_image_becomes_a_raster_scaled_to_its_pixel_size() -> Result<(), Error> {
|
||||
let png = Raster::new_cpu(Image::new(2, 1, Color::RED)).png_data_url();
|
||||
let content = converted(&format!(r#"<image href="{png}"/>"#))?;
|
||||
|
||||
let rasters = match group(&content, 0).and_then(|image| image.element(0)) {
|
||||
Some(Graphic::RasterCPUList(rasters)) => Some(rasters),
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(
|
||||
rasters.and_then(|rasters| rasters.attribute::<DAffine2>(ATTR_TRANSFORM, 0)),
|
||||
Some(&DAffine2::from_scale(DVec2::new(2., 1.)))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroked_path_carries_a_stroke_coverage_with_its_paint_width_dashes_cap_and_join() -> Result<(), Error> {
|
||||
let content = converted(r#"<path d="M1 1 H7 V7" fill="none" stroke="blue" stroke-opacity="0.5" stroke-width="3" stroke-dasharray="2" stroke-linecap="round" stroke-linejoin="miter-clip"/>"#)?;
|
||||
|
||||
let appearance = appearance_of(&content);
|
||||
assert_eq!(
|
||||
appearance.and_then(|appearance| appearance.first_paint_of(Cover::Stroke)),
|
||||
Some(&Graphic::from(Color::from_gamma_srgb_channels(0., 0., 1., 0.5)))
|
||||
);
|
||||
assert_eq!(
|
||||
appearance
|
||||
.and_then(Appearance::first_stroke_params)
|
||||
.map(|stroke| (stroke.weight, stroke.dash_lengths, stroke.cap, stroke.join)),
|
||||
Some((3., vec![2., 2.], StrokeCap::Round, StrokeJoin::Miter))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_in_a_scaled_group_is_measured_in_the_paths_own_space() -> Result<(), Error> {
|
||||
let content = converted(r#"<g transform="scale(2)"><path d="M1 1 H3" stroke="red"/></g>"#)?;
|
||||
|
||||
let stroke = group(&content, 0).and_then(appearance_of).and_then(Appearance::first_stroke_params);
|
||||
assert_eq!(stroke.map(|stroke| (stroke.weight, stroke.transform)), Some((1., DAffine2::IDENTITY)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_order_stroke_puts_the_stroke_coverage_below_the_fill() -> Result<(), Error> {
|
||||
let content = converted(r#"<rect width="4" height="4" stroke="red" paint-order="stroke"/>"#)?;
|
||||
|
||||
let stroke_below = appearance_of(&content).map(|appearance| appearance.fill_and_stroke().stroke_below);
|
||||
assert_eq!(stroke_below, Some(true));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn gradient_of(content: &List<Graphic>, cover: Cover) -> Option<&Item<Gradient>> {
|
||||
match appearance_of(content)?.first_paint_of(cover)? {
|
||||
Graphic::Gradient(gradient) => Some(gradient),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_linear_gradient_is_placed_along_its_vector_and_interpolates_in_gamma() -> Result<(), Error> {
|
||||
let content = converted(
|
||||
r#"<linearGradient id="g" gradientUnits="userSpaceOnUse" x1="1" y1="2" x2="5" y2="2" spreadMethod="reflect"><stop offset="0.25" stop-color="red"/><stop offset="1" stop-color="blue"/></linearGradient><rect width="8" height="8" fill="url(#g)"/>"#,
|
||||
)?;
|
||||
|
||||
let gradient = gradient_of(&content, Cover::Fill);
|
||||
assert_eq!(
|
||||
gradient.and_then(|gradient| gradient.attribute::<DAffine2>(ATTR_TRANSFORM)),
|
||||
Some(&DAffine2::from_cols(DVec2::new(4., 0.), DVec2::new(0., 4.), DVec2::new(1., 2.)))
|
||||
);
|
||||
assert_eq!(gradient.and_then(|gradient| gradient.attribute::<GradientSpace>(ATTR_GRADIENT_SPACE)), Some(&GradientSpace::RgbGamma));
|
||||
assert_eq!(gradient.and_then(|gradient| gradient.attribute::<GradientSpread>(ATTR_GRADIENT_SPREAD)), Some(&GradientSpread::Reflect));
|
||||
assert_eq!(gradient.map(|gradient| gradient.element().positions(false)), Some(vec![0.25, 1.]));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_length_linear_gradient_paints_the_color_of_its_last_stop() -> Result<(), Error> {
|
||||
let content = converted(
|
||||
r#"<linearGradient id="g" gradientUnits="userSpaceOnUse" x1="4" y1="4" x2="4" y2="4"><stop stop-color="red"/><stop offset="1" stop-color="blue"/></linearGradient><rect width="8" height="8" fill="url(#g)" fill-opacity="0.5"/>"#,
|
||||
)?;
|
||||
|
||||
let fill = appearance_of(&content).and_then(|appearance| appearance.first_paint_of(Cover::Fill));
|
||||
assert_eq!(fill, Some(&Graphic::from(Color::from_gamma_srgb_channels(0., 0., 1., 0.5))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bounding_box_radial_gradient_on_a_wide_shape_is_placed_as_an_ellipse() -> Result<(), Error> {
|
||||
let content = converted(r#"<radialGradient id="g"><stop stop-color="red"/><stop offset="1" stop-color="blue"/></radialGradient><rect width="8" height="4" fill="url(#g)"/>"#)?;
|
||||
|
||||
let gradient = gradient_of(&content, Cover::Fill);
|
||||
assert_eq!(gradient.and_then(|gradient| gradient.attribute::<GradientForm>(ATTR_GRADIENT_FORM)), Some(&GradientForm::Radial));
|
||||
assert_eq!(
|
||||
gradient.and_then(|gradient| gradient.attribute::<DAffine2>(ATTR_TRANSFORM)),
|
||||
Some(&DAffine2::from_cols(DVec2::new(4., 0.), DVec2::new(0., 2.), DVec2::new(4., 2.)))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_stroke_carries_the_stroke_opacity_in_its_stop_alphas() -> Result<(), Error> {
|
||||
let content = converted(
|
||||
r#"<linearGradient id="g"><stop stop-color="red"/><stop offset="1" stop-color="blue" stop-opacity="0.5"/></linearGradient><rect x="2" y="2" width="4" height="4" fill="none" stroke="url(#g)" stroke-opacity="0.5"/>"#,
|
||||
)?;
|
||||
|
||||
let stops = gradient_of(&content, Cover::Stroke).map(|gradient| [gradient.element().0.element(0), gradient.element().0.element(1)]);
|
||||
assert_eq!(
|
||||
stops,
|
||||
Some([Some(&Color::from_gamma_srgb_channels(1., 0., 0., 0.5)), Some(&Color::from_gamma_srgb_channels(0., 0., 1., 0.25))])
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_path_becomes_a_hidden_clipper_beneath_the_content_it_clips() -> Result<(), Error> {
|
||||
let content = converted(r#"<clipPath id="clip"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)"><rect width="8" height="8"/></g>"#)?;
|
||||
|
||||
let clipped = group(&content, 0);
|
||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
|
||||
assert_eq!(clipped.and_then(|clipped| clipped.attribute::<f64>(ATTR_OPACITY_FILL, 0)), Some(&0.));
|
||||
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_path_transform_places_its_shapes() -> Result<(), Error> {
|
||||
let content = converted(r#"<clipPath id="clip" transform="translate(1 2)"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)"><rect width="8" height="8"/></g>"#)?;
|
||||
|
||||
let shapes = group(&content, 0).and_then(|clipped| clipped.element(0)).and_then(Graphic::as_vector_list);
|
||||
assert_eq!(
|
||||
shapes.and_then(|shapes| shapes.attribute::<DAffine2>(ATTR_TRANSFORM, 0)),
|
||||
Some(&DAffine2::from_translation(DVec2::new(1., 2.)))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_path_with_its_own_clip_path_clips_the_content_once_more() -> Result<(), Error> {
|
||||
let content = converted(
|
||||
r#"<clipPath id="outer"><rect width="6" height="6"/></clipPath><clipPath id="inner" clip-path="url(#outer)"><rect width="4" height="4"/></clipPath><g clip-path="url(#inner)"><rect width="8" height="8"/></g>"#,
|
||||
)?;
|
||||
|
||||
let clipped_twice = group(&content, 0);
|
||||
assert!(clipped_twice.and_then(|clipped_twice| clipped_twice.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||
let clipped_once = clipped_twice.and_then(|clipped_twice| group(clipped_twice, 1));
|
||||
assert!(clipped_once.and_then(|clipped_once| clipped_once.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn contours(content: &List<Graphic>, index: usize) -> Vec<BezPath> {
|
||||
match content.element(0) {
|
||||
Some(Graphic::VectorList(vectors)) => (vectors.element(index).zip(paths_from_list_row_attributes(vectors, index)))
|
||||
.map(|(vector, paths)| vector.stroke_bezpath_iter(paths).collect())
|
||||
.unwrap_or_default(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_even_odd_hole_stays_empty_under_the_nonzero_fill() -> Result<(), Error> {
|
||||
let content = converted(r#"<path d="M0 0H8V8H0Z M2 2H6V6H2Z" fill-rule="evenodd"/>"#)?;
|
||||
|
||||
let winding_at = |point: Point| contours(&content, 0).iter().map(|contour| contour.winding(point)).sum::<i32>();
|
||||
assert_eq!(winding_at(Point::new(4., 4.)), 0);
|
||||
assert_ne!(winding_at(Point::new(1., 1.)), 0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_even_odd_path_filling_the_same_under_nonzero_converts_unchanged() -> Result<(), Error> {
|
||||
let ring = r#"d="M0 0H8V8H0Z M2 2V6H6V2Z""#;
|
||||
|
||||
assert_eq!(converted(&format!(r#"<path {ring} fill-rule="evenodd"/>"#))?, converted(&format!("<path {ring}/>"))?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroked_even_odd_path_strokes_its_original_outline_above_the_converted_fill() -> Result<(), Error> {
|
||||
let rings = r#"d="M0 0H8V8H0Z M2 2H6V6H2Z" stroke="red""#;
|
||||
let even_odd = converted(&format!(r#"<path {rings} fill-rule="evenodd"/>"#))?;
|
||||
let nonzero = converted(&format!("<path {rings}/>"))?;
|
||||
|
||||
let covers: Vec<Vec<Cover>> = match even_odd.element(0) {
|
||||
Some(Graphic::VectorList(vectors)) => vectors
|
||||
.iter_attribute_values_or_default::<Appearance>(ATTR_APPEARANCE)
|
||||
.map(|appearance| appearance.covers().map(Coverage::cover).collect())
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
assert_eq!(covers, vec![vec![Cover::Fill], vec![Cover::Stroke]]);
|
||||
assert_eq!(contours(&even_odd, 1), contours(&nonzero, 0));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_luminance_mask_masks_by_the_luminance_of_its_paints_as_alpha() -> Result<(), Error> {
|
||||
let content = converted(r##"<mask id="mask"><rect width="8" height="8" fill="#808080"/></mask><g mask="url(#mask)"><rect width="8" height="8"/></g>"##)?;
|
||||
|
||||
let masker = group(&content, 0).and_then(|masked| group(masked, 0));
|
||||
let masker_paint = masker.and_then(appearance_of).and_then(|appearance| appearance.first_paint_of(Cover::Fill));
|
||||
assert!(matches!(masker_paint, Some(Graphic::Color(color)) if color.element().with_alpha(1.) == Color::BLACK && (color.element().a() - 128. / 255.).abs() < 1e-5));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_region_that_cuts_its_content_clips_the_masked_content() -> Result<(), Error> {
|
||||
let content = converted(
|
||||
r#"<mask id="mask" mask-type="alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="4" height="8"><rect width="8" height="8"/></mask><g mask="url(#mask)"><rect width="8" height="8"/></g>"#,
|
||||
)?;
|
||||
|
||||
let within_region = group(&content, 0).and_then(|masked| masked.element(1));
|
||||
assert!(within_region.is_some_and(Graphic::had_clip_enabled));
|
||||
let clipped = within_region.and_then(Graphic::as_graphic_list);
|
||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
|
||||
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gaussian_blur_filter_becomes_a_blur_of_the_geometric_mean_of_its_standard_deviations() -> Result<(), Error> {
|
||||
let content = converted(
|
||||
r#"<filter id="blur" filterUnits="userSpaceOnUse" x="-4" y="-4" width="16" height="16" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceGraphic" stdDeviation="1 4" color-interpolation-filters="linearRGB" result="effect-1"/><feOffset in="effect-1" result="effect-2"/></filter><g filter="url(#blur)"><rect width="8" height="8"/></g>"#,
|
||||
)?;
|
||||
|
||||
let effects = group(&content, 0).and_then(|filtered| filtered.attribute::<Effects>(ATTR_EFFECTS, 0));
|
||||
assert_eq!(
|
||||
effects,
|
||||
Some(&Effects::from_operations([EffectOperation::Blur {
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false
|
||||
}]))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drop_shadow_falls_by_its_offset_in_its_color() -> Result<(), Error> {
|
||||
let content = converted(r#"<g filter="drop-shadow(3px 4px 0 red)"><rect width="4" height="4"/></g>"#)?;
|
||||
|
||||
let shadow = group(&content, 0)
|
||||
.and_then(|filtered| filtered.attribute::<Effects>(ATTR_EFFECTS, 0))
|
||||
.and_then(|effects| effects.operations().next());
|
||||
let (offset, color) = match shadow {
|
||||
Some(EffectOperation::DropShadow { color, angle, distance, .. }) => (Some(shadow_offset(angle, distance)), Some(color)),
|
||||
_ => (None, None),
|
||||
};
|
||||
assert!(offset.is_some_and(|offset| offset.abs_diff_eq(DVec2::new(3., 4.), 1e-9)));
|
||||
assert_eq!(color, Some(Color::from_gamma_srgb_channels(1., 0., 0., 1.)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filter_on_a_clipped_group_applies_to_the_content_before_the_clip() -> Result<(), Error> {
|
||||
let content = converted(r#"<clipPath id="clip"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)" filter="blur(1)"><rect width="8" height="8"/></g>"#)?;
|
||||
|
||||
let clipped_content = group(&content, 0).and_then(|clipped| group(clipped, 1));
|
||||
assert!(clipped_content.and_then(|filtered| filtered.attribute::<Effects>(ATTR_EFFECTS, 0)).is_some());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn paint_of(content: &List<Graphic>, cover: Cover) -> Option<&Graphic> {
|
||||
appearance_of(content)?.first_paint_of(cover)
|
||||
}
|
||||
|
||||
fn tiles_of(paint: &Graphic) -> Option<&List<Vector>> {
|
||||
paint.as_graphic_list()?.element(0)?.as_vector_list()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pattern_fill_paints_copies_of_its_tile_over_the_path_at_the_fill_opacity() -> Result<(), Error> {
|
||||
let content =
|
||||
converted(r#"<pattern id="p" width="10" height="10" patternUnits="userSpaceOnUse"><rect width="5" height="5"/></pattern><rect width="40" height="20" fill="url(#p)" fill-opacity="0.5"/>"#)?;
|
||||
|
||||
let paint = paint_of(&content, Cover::Fill);
|
||||
let tiles = paint.and_then(tiles_of);
|
||||
assert_eq!(tiles.map(List::len), Some(8));
|
||||
assert_eq!(
|
||||
tiles.and_then(|tiles| tiles.attribute::<DAffine2>(ATTR_TRANSFORM, 7)),
|
||||
Some(&DAffine2::from_translation(DVec2::new(30., 10.)))
|
||||
);
|
||||
assert_eq!(paint.and_then(Graphic::as_graphic_list).and_then(|paint| paint.attribute::<f64>(ATTR_OPACITY, 0)), Some(&0.5));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pattern_stroke_paints_tiles_over_the_outer_half_of_the_stroke() -> Result<(), Error> {
|
||||
let content = converted(
|
||||
r#"<pattern id="p" width="10" height="10" patternUnits="userSpaceOnUse"><rect width="5" height="5"/></pattern><rect width="10" height="10" fill="url(#p)" stroke="url(#p)" stroke-width="4"/>"#,
|
||||
)?;
|
||||
|
||||
let tile_count = |cover| paint_of(&content, cover).and_then(tiles_of).map(List::len);
|
||||
assert_eq!(tile_count(Cover::Fill), Some(1));
|
||||
assert_eq!(tile_count(Cover::Stroke), Some(9));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pattern_needing_too_many_tiles_leaves_the_fill_unpainted() -> Result<(), Error> {
|
||||
let content = converted(r#"<pattern id="p" width="1" height="1" patternUnits="userSpaceOnUse"><rect width="1" height="1"/></pattern><rect width="1000" height="1000" fill="url(#p)"/>"#)?;
|
||||
|
||||
assert_eq!(paint_of(&content, Cover::Fill), None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_input_is_an_error() {
|
||||
assert!(convert("<svg", &Options::default()).is_err());
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
use super::consts::MAX_ABSOLUTE_DIFFERENCE;
|
||||
use super::intersection::{bezpath_intersections, filtered_all_segment_intersections, pathseg_self_intersections};
|
||||
use super::poisson_disk::poisson_disk_sample;
|
||||
pub use super::poisson_disk::{PoissonDiskError, PoissonDiskSampler, poisson_disk_points};
|
||||
use super::util::pathseg_tangent;
|
||||
use crate::vector::misc::{PointSpacingType, dvec2_to_point, point_to_dvec2};
|
||||
use core_types::FallibleVec2Operations;
|
||||
use core_types::math::polynomial::pathseg_to_parametric_polynomial;
|
||||
use glam::{DMat2, DVec2};
|
||||
use kurbo::{BezPath, CubicBez, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Point, QuadBez, Rect, Shape, Vec2};
|
||||
use kurbo::{BezPath, CubicBez, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Point, QuadBez, Shape, Vec2};
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
|
||||
/// Splits the [`BezPath`] at segment index at `t` value which lie in the range of [0, 1].
|
||||
@@ -354,64 +354,6 @@ fn eval_bezpath(bezpath: &BezPath, t: TValue, precomputed_segments_length: Optio
|
||||
}
|
||||
}
|
||||
|
||||
/// Randomly places points across the filled surface of this subpath (which is assumed to be closed).
|
||||
/// The `separation_disk_diameter` determines the minimum distance between all points from one another.
|
||||
/// Conceptually, this works by "throwing a dart" at the subpath's bounding box and keeping the dart only if:
|
||||
/// - It's inside the shape
|
||||
/// - It's not closer than `separation_disk_diameter` to any other point from a previous accepted dart throw
|
||||
///
|
||||
/// This repeats until accepted darts fill all possible areas between one another.
|
||||
///
|
||||
/// While the conceptual process described above asymptotically slows down and is never guaranteed to produce a maximal set in finite time,
|
||||
/// this is implemented with an algorithm that produces a maximal set in O(n) time. The slowest part is actually checking if points are inside the subpath shape.
|
||||
pub fn poisson_disk_points(bezpath_index: usize, bezpaths: &[(BezPath, Rect)], separation_disk_diameter: f64, rng: impl FnMut() -> f64) -> Vec<DVec2> {
|
||||
let (this_bezpath, this_bbox) = bezpaths[bezpath_index].clone();
|
||||
|
||||
if this_bezpath.elements().is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let point_in_shape_checker = |point: DVec2| {
|
||||
// Check against all paths the point is contained in to compute the correct winding number
|
||||
let mut number = 0;
|
||||
|
||||
for (i, (shape, bbox)) in bezpaths.iter().enumerate() {
|
||||
if bbox.x0 > point.x || bbox.y0 > point.y || bbox.x1 < point.x || bbox.y1 < point.y {
|
||||
continue;
|
||||
}
|
||||
|
||||
let winding = shape.winding(dvec2_to_point(point));
|
||||
if winding == 0 && i == bezpath_index {
|
||||
return false;
|
||||
}
|
||||
number += winding;
|
||||
}
|
||||
|
||||
// Non-zero fill rule
|
||||
number != 0
|
||||
};
|
||||
|
||||
let line_intersect_shape_checker = |p0: (f64, f64), p1: (f64, f64)| {
|
||||
for segment in this_bezpath.segments() {
|
||||
if !segment.intersect_line(Line::new(p0, p1)).is_empty() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
};
|
||||
|
||||
let offset = DVec2::new(this_bbox.x0, this_bbox.y0);
|
||||
let width = this_bbox.width();
|
||||
let height = this_bbox.height();
|
||||
|
||||
if width.is_infinite() || height.is_infinite() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
poisson_disk_sample(offset, width, height, separation_disk_diameter, point_in_shape_checker, line_intersect_shape_checker, rng)
|
||||
}
|
||||
|
||||
// TODO: If a segment curls back on itself tightly enough it could intersect again at the portion that should be trimmed. This could cause the subpaths to be clipped
|
||||
// TODO: at the incorrect location. This can be avoided by first trimming the two subpaths at any extrema, effectively ignoring loopbacks.
|
||||
/// Helper function to clip overlap of two intersecting open BezPaths. Returns an Option because intersections may not exist for certain arrangements and distances.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -41,6 +41,7 @@ fastnoise-lite = { workspace = true, features = ["wgsl"] }
|
||||
[dev-dependencies]
|
||||
# Local dependencies
|
||||
graphene-resource = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
|
||||
# Required dependencies
|
||||
# Turns on the shader translators of every backend for the tests, whichever of them the platform's own backends build with
|
||||
|
||||
@@ -34,9 +34,9 @@ impl WgpuExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders images of the content an SVG of the view `footprint` describes defers to the GPU, with where the SVG draws each.
|
||||
/// Content out of view, or that fails to render, keeps the markup standing in for it.
|
||||
pub fn render_deferred_svg_images(&self, deferred_images: &[DeferredImage], footprint: Footprint) -> Vec<(DeferredImagePlacement, Texture)> {
|
||||
/// Renders images of the content an SVG or PDF of the view `footprint` defers to the GPU, with where each is drawn.
|
||||
/// Content out of view, or that fails to render, gets no image.
|
||||
pub fn render_deferred_images(&self, deferred_images: &[DeferredImage], footprint: Footprint) -> Vec<(DeferredImagePlacement, Texture)> {
|
||||
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
|
||||
|
||||
deferred_images
|
||||
@@ -56,9 +56,17 @@ impl WgpuExecutor {
|
||||
|
||||
/// Reads back the images of deferred content, putting each in `svg` in place of the markup standing in for its content.
|
||||
pub async fn resolve_deferred_svg_images(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, images: Vec<(DeferredImagePlacement, Texture)>) {
|
||||
for (placement, texture) in images {
|
||||
let image: Raster<CPU> = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await;
|
||||
for (placement, image) in self.read_back_deferred_images(images).await {
|
||||
substitute_deferred_image(svg, image_data, &placement, &image);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads back the images of deferred content into CPU memory, each with where it goes.
|
||||
pub async fn read_back_deferred_images(&self, images: Vec<(DeferredImagePlacement, Texture)>) -> Vec<(DeferredImagePlacement, Raster<CPU>)> {
|
||||
let mut read_back = Vec::with_capacity(images.len());
|
||||
for (placement, texture) in images {
|
||||
read_back.push((placement, Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await));
|
||||
}
|
||||
read_back
|
||||
}
|
||||
}
|
||||
@@ -3,17 +3,41 @@
|
||||
use crate::vello_render::TEXTURE_FORMAT;
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use glam::DVec2;
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
|
||||
use graphic_types::generator::{
|
||||
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseSettings, NoiseType,
|
||||
};
|
||||
use raster_kernels::mandelbrot::{MandelbrotSetup, ReferenceOrbit, resolves_in_32_bits};
|
||||
use std::iter::zip;
|
||||
use std::sync::OnceLock;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
/// How many of a 32-bit float's steps one pixel must span for the Mandelbrot set to render on the GPU, past which its deep zooms render on the CPU in 64 bits.
|
||||
const MIN_MANDELBROT_PIXEL_STEPS: f64 = 64.;
|
||||
/// The reference orbit's values in each row of its texture, matching the Mandelbrot shader's `REFERENCE_ROW_LENGTH`.
|
||||
const REFERENCE_ROW_LENGTH: usize = 1024;
|
||||
|
||||
/// The shader's patterns, matching its `PATTERN_` constants.
|
||||
const PATTERN_NOISE: u32 = 0;
|
||||
const PATTERN_WHITE_NOISE: u32 = 1;
|
||||
const PATTERN_MANDELBROT: u32 = 2;
|
||||
/// The mip levels of a tile's texture. Tiles are drawn at most √2 times smaller than their pixels in an evenly scaled view,
|
||||
/// so these reach views stretched up to 32 times more along one axis than the other.
|
||||
const TILE_MIP_LEVELS: u32 = 4;
|
||||
|
||||
/// The shader of each kind of pattern, compiled the first time a generator with it is drawn, so a document compiles only those it uses.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Shader {
|
||||
Noise,
|
||||
WhiteNoise,
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
impl Shader {
|
||||
const ALL: [Self; 3] = [Self::Noise, Self::WhiteNoise, Self::Mandelbrot];
|
||||
|
||||
fn source(self) -> String {
|
||||
let common = include_str!("vello_generators.wgsl");
|
||||
match self {
|
||||
Self::Noise => [fastnoise_lite::WGSL_SOURCE, common, include_str!("vello_generators_noise.wgsl")].concat(),
|
||||
Self::WhiteNoise => [common, include_str!("vello_generators_white_noise.wgsl")].concat(),
|
||||
Self::Mandelbrot => [common, include_str!("vello_generators_mandelbrot.wgsl")].concat(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// FastNoiseLite's `fnl_state`, laid out to match the shader's.
|
||||
#[repr(C)]
|
||||
@@ -36,19 +60,103 @@ struct NoiseState {
|
||||
domain_warp_amp: f32,
|
||||
}
|
||||
|
||||
/// The shader's parameters, laid out to match its `Parameters` struct.
|
||||
/// The noise shaders' parameters, laid out so each one's `Parameters` struct reads the part it needs.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default, Pod, Zeroable)]
|
||||
struct Parameters {
|
||||
struct NoiseParameters {
|
||||
corner: [f32; 2],
|
||||
texel: [f32; 2],
|
||||
pattern: u32,
|
||||
domain_warp: u32,
|
||||
_padding: [u32; 2],
|
||||
_padding: [u32; 3],
|
||||
noise: NoiseState,
|
||||
_end_padding: u32,
|
||||
}
|
||||
|
||||
/// The settings of a Mandelbrot-style fractal, laid out to match the Mandelbrot shader's `Mandelbrot` struct.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default, Pod, Zeroable)]
|
||||
struct MandelbrotState {
|
||||
delta_corner: [f32; 2],
|
||||
start_constant: [f32; 2],
|
||||
added_constant: [f32; 2],
|
||||
start_slope: f32,
|
||||
added_slope: f32,
|
||||
fractal: u32,
|
||||
exterior: u32,
|
||||
interior: u32,
|
||||
iterations: u32,
|
||||
power: f32,
|
||||
integer_power: u32,
|
||||
frequency: f32,
|
||||
bailout_squared: f32,
|
||||
log_bailout: f32,
|
||||
reference_length: u32,
|
||||
interior_test: u32,
|
||||
_padding: u32,
|
||||
}
|
||||
|
||||
/// The Mandelbrot shader's parameters, laid out to match its `Parameters` struct.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default, Pod, Zeroable)]
|
||||
struct MandelbrotParameters {
|
||||
corner: [f32; 2],
|
||||
texel: [f32; 2],
|
||||
mandelbrot: MandelbrotState,
|
||||
}
|
||||
|
||||
impl MandelbrotState {
|
||||
/// The state of a tile with its top left corner at `corner` of the complex plane, following `reference` if there is one, and testing for the cardioid and its
|
||||
/// left bulb with `interior_test`.
|
||||
fn new(setup: &MandelbrotSetup, corner: DVec2, reference: Option<&ReferenceOrbit>, interior_test: bool) -> Self {
|
||||
Self {
|
||||
delta_corner: reference.map_or(DVec2::ZERO, |reference| corner - reference.point).as_vec2().to_array(),
|
||||
start_constant: setup.start_constant.as_vec2().to_array(),
|
||||
added_constant: setup.added_constant.as_vec2().to_array(),
|
||||
start_slope: setup.start_slope as f32,
|
||||
added_slope: setup.added_slope as f32,
|
||||
fractal: match setup.fractal {
|
||||
MandelbrotFractal::ClassicMandelbrot => 0,
|
||||
MandelbrotFractal::BurningShip => 1,
|
||||
MandelbrotFractal::Tricorn => 2,
|
||||
},
|
||||
exterior: match setup.exterior {
|
||||
MandelbrotExterior::SmoothEscape => 0,
|
||||
MandelbrotExterior::DiscreteEscape => 4,
|
||||
MandelbrotExterior::Proximity => 1,
|
||||
MandelbrotExterior::Tendrils => 2,
|
||||
MandelbrotExterior::Rays => 3,
|
||||
MandelbrotExterior::ClosestApproach => 5,
|
||||
MandelbrotExterior::Flat => 6,
|
||||
MandelbrotExterior::Angle => 7,
|
||||
MandelbrotExterior::ClosestIteration => 8,
|
||||
},
|
||||
interior: match setup.interior {
|
||||
MandelbrotInterior::Flat => 0,
|
||||
MandelbrotInterior::FinalDistance => 1,
|
||||
MandelbrotInterior::Period => 2,
|
||||
MandelbrotInterior::ClosestApproach => 3,
|
||||
MandelbrotInterior::ClosestIteration => 4,
|
||||
MandelbrotInterior::FinalAngle => 5,
|
||||
MandelbrotInterior::Radius => 6,
|
||||
MandelbrotInterior::Angle => 7,
|
||||
MandelbrotInterior::Rays => 9,
|
||||
MandelbrotInterior::SmoothSettling => 8,
|
||||
MandelbrotInterior::DiscreteSettling => 10,
|
||||
MandelbrotInterior::Proximity => 11,
|
||||
},
|
||||
iterations: setup.iterations,
|
||||
power: setup.power as f32,
|
||||
integer_power: setup.integer_power.unwrap_or(0),
|
||||
frequency: setup.frequency,
|
||||
bailout_squared: (setup.bailout * setup.bailout) as f32,
|
||||
log_bailout: setup.bailout.ln() as f32,
|
||||
reference_length: reference.map_or(0, |reference| reference.values.len() as u32),
|
||||
interior_test: interior_test as u32,
|
||||
_padding: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NoiseState {
|
||||
/// The state FastNoiseLite's CPU sampler is given for the same settings, with whether it warps its domain.
|
||||
fn new(settings: &NoiseSettings) -> (Self, bool) {
|
||||
@@ -107,64 +215,136 @@ impl NoiseState {
|
||||
}
|
||||
}
|
||||
|
||||
impl Parameters {
|
||||
/// The parameters of a tile of `pattern` whose top left corner lies at `corner` of the pattern's space, with pixels `texel` units across.
|
||||
/// Returns `None` if the tile's pixels are too fine for 32-bit floats to place.
|
||||
fn new(pattern: &GeneratorPattern, corner: DVec2, texel: f64, pixels: u32) -> Option<Self> {
|
||||
let (pattern, corner, texel, noise, domain_warp) = match pattern {
|
||||
/// What a tile's draw needs: the shader drawing it, its parameters laid out for that shader, and the Mandelbrot reference orbit its points follow, if any.
|
||||
struct Tile {
|
||||
shader: Shader,
|
||||
parameters: Vec<u8>,
|
||||
reference: Option<ReferenceOrbit>,
|
||||
}
|
||||
|
||||
impl Tile {
|
||||
/// The tile of `pattern` with its top left corner at `corner` of the pattern's space and pixels `texel` units across.
|
||||
fn new(pattern: &GeneratorPattern, corner: DVec2, texel: f64, pixels: u32) -> Self {
|
||||
match pattern {
|
||||
GeneratorPattern::Noise(settings) => {
|
||||
let (noise, domain_warp) = NoiseState::new(settings);
|
||||
let pattern = if settings.noise_type == NoiseType::WhiteNoise { PATTERN_WHITE_NOISE } else { PATTERN_NOISE };
|
||||
(pattern, corner, texel, noise, domain_warp)
|
||||
}
|
||||
GeneratorPattern::Mandelbrot => {
|
||||
// Sampled in the complex plane rather than its unit square, so the shader's coordinates there round only once
|
||||
let (corner, texel) = (corner * 3. - DVec2::new(2., 1.5), texel * 3.);
|
||||
let farthest = corner.abs().max((corner + texel * pixels as f64).abs()).max_element();
|
||||
if texel < farthest * f32::EPSILON as f64 * MIN_MANDELBROT_PIXEL_STEPS {
|
||||
return None;
|
||||
}
|
||||
(PATTERN_MANDELBROT, corner, texel, NoiseState::default(), false)
|
||||
}
|
||||
};
|
||||
let parameters = NoiseParameters {
|
||||
corner: corner.as_vec2().to_array(),
|
||||
texel: [texel as f32; 2],
|
||||
domain_warp: domain_warp as u32,
|
||||
noise,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Some(Self {
|
||||
corner: corner.as_vec2().to_array(),
|
||||
texel: [texel as f32; 2],
|
||||
pattern,
|
||||
domain_warp: domain_warp as u32,
|
||||
noise,
|
||||
..Default::default()
|
||||
})
|
||||
let shader = if settings.noise_type == NoiseType::WhiteNoise { Shader::WhiteNoise } else { Shader::Noise };
|
||||
Self {
|
||||
shader,
|
||||
parameters: bytemuck::bytes_of(¶meters).to_vec(),
|
||||
reference: None,
|
||||
}
|
||||
}
|
||||
GeneratorPattern::Mandelbrot(settings) => {
|
||||
let setup = MandelbrotSetup::new(settings);
|
||||
|
||||
// Sampled in the complex plane rather than the pattern's space, so the shader's coordinates there round only once
|
||||
let (corner, texel) = (setup.plane_point(corner), texel / setup.scale);
|
||||
let area = [corner, corner + texel * pixels as f64];
|
||||
|
||||
// A reference orbit escaping at once leaves points to escape at once too, however imprecisely 32-bit floats place them
|
||||
let reference = setup.reference_orbit(area, texel).filter(|reference| reference.values.len() >= 2);
|
||||
let interior_test = setup.has_interior_test() && resolves_in_32_bits(area, texel);
|
||||
|
||||
let parameters = MandelbrotParameters {
|
||||
corner: corner.as_vec2().to_array(),
|
||||
texel: [texel as f32; 2],
|
||||
mandelbrot: MandelbrotState::new(&setup, corner, reference.as_ref(), interior_test),
|
||||
};
|
||||
Self {
|
||||
shader: Shader::Mandelbrot,
|
||||
parameters: bytemuck::bytes_of(¶meters).to_vec(),
|
||||
reference,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pipeline of the pass, built the first time a generator is drawn so documents without one don't compile its shader.
|
||||
/// The texture holding a reference orbit's values and their raisings for the Mandelbrot shader, in rows of `REFERENCE_ROW_LENGTH`, or one empty texel without one.
|
||||
fn reference_texture(device: &wgpu::Device, queue: &wgpu::Queue, reference: Option<&ReferenceOrbit>) -> wgpu::Texture {
|
||||
let (values, raised_values) = reference.map_or((&[][..], &[][..]), |reference| (&reference.values[..], &reference.raised_values[..]));
|
||||
let (width, height) = (values.len().clamp(1, REFERENCE_ROW_LENGTH), values.len().div_ceil(REFERENCE_ROW_LENGTH).max(1));
|
||||
|
||||
let mut texels = vec![[0_f32; 4]; width * height];
|
||||
for (texel, (value, raised)) in texels.iter_mut().zip(zip(values, raised_values)) {
|
||||
*texel = [value.x, value.y, raised.x, raised.y];
|
||||
}
|
||||
|
||||
device.create_texture_with_data(
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("vello_generator_reference_orbit"),
|
||||
size: wgpu::Extent3d {
|
||||
width: width as u32,
|
||||
height: height as u32,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba32Float,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
bytemuck::cast_slice(&texels),
|
||||
)
|
||||
}
|
||||
|
||||
/// The pipelines of the pass, one for each shader.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct GeneratorPasses {
|
||||
pipeline: OnceLock<(wgpu::RenderPipeline, wgpu::BindGroupLayout)>,
|
||||
pipelines: [OnceLock<(wgpu::RenderPipeline, wgpu::BindGroupLayout)>; Shader::ALL.len()],
|
||||
}
|
||||
|
||||
impl GeneratorPasses {
|
||||
fn pipeline(&self, device: &wgpu::Device) -> &(wgpu::RenderPipeline, wgpu::BindGroupLayout) {
|
||||
self.pipeline.get_or_init(|| {
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("vello_generators"),
|
||||
source: wgpu::ShaderSource::Wgsl([fastnoise_lite::WGSL_SOURCE, include_str!("vello_generators.wgsl")].concat().into()),
|
||||
fn pipeline(&self, device: &wgpu::Device, shader: Shader) -> &(wgpu::RenderPipeline, wgpu::BindGroupLayout) {
|
||||
self.pipelines[shader as usize].get_or_init(|| {
|
||||
// The vertex stage gets a module of its own, since GLSL translation writes all of a module's FastNoise Lite into every stage
|
||||
let vertex_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("vello_generators_vertex"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("vello_generators.wgsl").into()),
|
||||
});
|
||||
let fragment_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("vello_generators"),
|
||||
source: wgpu::ShaderSource::Wgsl(shader.source().into()),
|
||||
});
|
||||
|
||||
// Every shader reads its parameters, and the Mandelbrot shader its reference orbit too
|
||||
let parameters = wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
let reference_orbit = wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: false },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
let entries: &[_] = if shader == Shader::Mandelbrot { &[parameters, reference_orbit] } else { &[parameters] };
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("vello_generators_bind_group_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
entries,
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("vello_generators_pipeline_layout"),
|
||||
@@ -176,13 +356,13 @@ impl GeneratorPasses {
|
||||
label: Some("vello_generators"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
module: &vertex_module,
|
||||
entry_point: Some("vertex"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
module: &fragment_module,
|
||||
entry_point: Some("generate"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
@@ -205,39 +385,50 @@ impl GeneratorPasses {
|
||||
})
|
||||
}
|
||||
|
||||
/// Records the rendering of the top mip level of a square tile of `pattern`, `pixels` across, whose top left corner lies at `corner` of the pattern's space with pixels `texel` units across.
|
||||
/// Returns `None` if the GPU can't render the tile as precisely as the CPU, leaving it to the CPU.
|
||||
pub(crate) fn render_tile(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, pattern: &GeneratorPattern, corner: DVec2, texel: f64, pixels: u32) -> Option<wgpu::Texture> {
|
||||
let parameters = Parameters::new(pattern, corner, texel, pixels)?;
|
||||
let (pipeline, bind_group_layout) = self.pipeline(device);
|
||||
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
/// A texture for square tiles `pixels` across to be rendered into, with the mip levels they're drawn from.
|
||||
pub(crate) fn tile_texture(device: &wgpu::Device, pixels: u32) -> wgpu::Texture {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_generator_tile"),
|
||||
size: wgpu::Extent3d {
|
||||
width: pixels,
|
||||
height: pixels,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: pixels.ilog2() + 1,
|
||||
mip_level_count: TILE_MIP_LEVELS,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/// Records the rendering of a square tile of `pattern` into the top mip level of `texture`, with its top left corner at `corner` of the pattern's space and pixels `texel` units across.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn render_tile(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture, pattern: &GeneratorPattern, corner: DVec2, texel: f64) {
|
||||
let tile = Tile::new(pattern, corner, texel, texture.width());
|
||||
let (pipeline, bind_group_layout) = self.pipeline(device, tile.shader);
|
||||
|
||||
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("vello_generator_parameters"),
|
||||
contents: bytemuck::bytes_of(¶meters),
|
||||
contents: &tile.parameters,
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
let reference_view = (tile.shader == Shader::Mandelbrot).then(|| reference_texture(device, queue, tile.reference.as_ref()).create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
let mut entries = vec![wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
}];
|
||||
if let Some(reference_view) = &reference_view {
|
||||
entries.push(wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(reference_view),
|
||||
});
|
||||
}
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("vello_generator_bind_group"),
|
||||
layout: bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
}],
|
||||
entries: &entries,
|
||||
});
|
||||
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
@@ -263,9 +454,6 @@ impl GeneratorPasses {
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_bind_group(0, &bind_group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
drop(pass);
|
||||
|
||||
Some(texture)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,10 +461,72 @@ impl GeneratorPasses {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Translates `source` to the shading language of every backend, with the GLSL ES the web build's WebGL2 backend runs written for each entry point.
|
||||
fn translate(source: &str, entry_points: &[(naga::ShaderStage, &str)]) {
|
||||
let module = naga::front::wgsl::parse_str(source).unwrap_or_else(|error| panic!("{}", error.emit_to_string(source)));
|
||||
let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty())
|
||||
.validate(&module)
|
||||
.unwrap_or_else(|error| panic!("{}", error.emit_to_string(source)));
|
||||
|
||||
// GLSL ES 3.0
|
||||
let options = naga::back::glsl::Options {
|
||||
version: naga::back::glsl::Version::Embedded { version: 300, is_webgl: true },
|
||||
..Default::default()
|
||||
};
|
||||
for &(shader_stage, entry_point) in entry_points {
|
||||
let pipeline_options = naga::back::glsl::PipelineOptions {
|
||||
shader_stage,
|
||||
entry_point: entry_point.to_string(),
|
||||
multiview: None,
|
||||
};
|
||||
let mut glsl = String::new();
|
||||
let written = naga::back::glsl::Writer::new(&mut glsl, &module, &info, &options, &pipeline_options, naga::proc::BoundsCheckPolicies::default()).and_then(|mut writer| writer.write());
|
||||
assert!(written.is_ok(), "the {entry_point} entry point doesn't translate to GLSL: {written:?}");
|
||||
}
|
||||
|
||||
// HLSL, which Direct3D compiles natively and ANGLE's D3D11 backend compiles by way of GLSL
|
||||
let mut hlsl = String::new();
|
||||
let written = naga::back::hlsl::Writer::new(&mut hlsl, &Default::default(), &Default::default()).write(&module, &info, None);
|
||||
assert!(written.is_ok(), "the shader doesn't translate to HLSL: {written:?}");
|
||||
|
||||
// MSL for Metal, without the bindings a pipeline's layout would map, and SPIR-V for Vulkan
|
||||
let options = naga::back::msl::Options {
|
||||
fake_missing_bindings: true,
|
||||
..Default::default()
|
||||
};
|
||||
let written = naga::back::msl::write_string(&module, &info, &options, &Default::default());
|
||||
assert!(written.is_ok(), "the shader doesn't translate to MSL: {:?}", written.err());
|
||||
|
||||
let written = naga::back::spv::write_vec(&module, &info, &Default::default(), None);
|
||||
assert!(written.is_ok(), "the shader doesn't translate to SPIR-V: {:?}", written.err());
|
||||
}
|
||||
|
||||
// Each module on its own, as a pipeline compiles it
|
||||
#[test]
|
||||
fn mandelbrot_tiles_too_fine_for_32_bit_floats_are_left_to_the_cpu() {
|
||||
let corner = DVec2::new(0.25, 0.5);
|
||||
assert!(Parameters::new(&GeneratorPattern::Mandelbrot, corner, 2_f64.powi(-8), 260).is_some());
|
||||
assert!(Parameters::new(&GeneratorPattern::Mandelbrot, corner, 2_f64.powi(-30), 260).is_none());
|
||||
fn every_shader_translates_for_every_backend() {
|
||||
translate(include_str!("vello_generators.wgsl"), &[(naga::ShaderStage::Vertex, "vertex")]);
|
||||
for shader in Shader::ALL {
|
||||
translate(&shader.source(), &[(naga::ShaderStage::Fragment, "generate")]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Mandelbrot node's defaults, with `power`, at a scale placing the pattern's space on the complex plane.
|
||||
fn mandelbrot(power: f64) -> GeneratorPattern {
|
||||
match GeneratorPattern::decode(graphic_types::generator::Generator::Mandelbrot, &|_| None) {
|
||||
GeneratorPattern::Mandelbrot(settings) => GeneratorPattern::Mandelbrot(graphic_types::generator::MandelbrotSettings { power, scale: 1., ..settings }),
|
||||
GeneratorPattern::Noise(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_too_fine_for_32_bit_floats_follow_a_reference_orbit_at_any_power() {
|
||||
let corner = DVec2::new(-1.25, 0.);
|
||||
let (shallow, deep) = (2_f64.powi(-8), 2_f64.powi(-30));
|
||||
|
||||
// Integer powers follow a reference orbit at any depth, while other powers are iterated directly where they can be
|
||||
assert!(Tile::new(&mandelbrot(2.), corner, shallow, 260).reference.is_some());
|
||||
assert!(Tile::new(&mandelbrot(2.), corner, deep, 260).reference.is_some());
|
||||
assert!(Tile::new(&mandelbrot(2.5), corner, shallow, 260).reference.is_none());
|
||||
assert!(Tile::new(&mandelbrot(2.5), corner, deep, 260).reference.is_some());
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,5 @@
|
||||
// Renders a tile of a generator's pattern, sampled at the centers of the tile's pixels, as opaque gamma-encoded color like the CPU's tiles
|
||||
|
||||
const PATTERN_NOISE: u32 = 0u;
|
||||
const PATTERN_WHITE_NOISE: u32 = 1u;
|
||||
const PATTERN_MANDELBROT: u32 = 2u;
|
||||
|
||||
// The most iterations a point is tested for escaping the Mandelbrot set, beyond which it counts as inside
|
||||
const MANDELBROT_ITERATIONS: u32 = 255u;
|
||||
|
||||
struct Parameters {
|
||||
// Where the tile's top left corner lies in the space the pattern is sampled in, and the size of one of its pixels there
|
||||
corner: vec2<f32>,
|
||||
texel: vec2<f32>,
|
||||
pattern: u32,
|
||||
// Whether the noise warps its domain before it's sampled
|
||||
domain_warp: u32,
|
||||
@align(16) noise: fnl_state,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> parameters: Parameters;
|
||||
// Renders a tile of a generator's pattern, sampled at the centers of the tile's pixels, as opaque gamma-encoded color like the CPU's tiles.
|
||||
// Each pattern's shader is this followed by its own, whose `Parameters` start with the tile's top left corner in the pattern's space and its pixel size there.
|
||||
|
||||
// One triangle that covers the whole target
|
||||
@vertex
|
||||
@@ -26,69 +8,6 @@ fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
|
||||
return vec4<f32>(corner * 2. - 1., 0., 1.);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn generate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let point = parameters.corner + position.xy * parameters.texel;
|
||||
|
||||
var luminance: f32;
|
||||
switch parameters.pattern {
|
||||
case PATTERN_NOISE: {
|
||||
luminance = noise(point);
|
||||
}
|
||||
case PATTERN_WHITE_NOISE: {
|
||||
luminance = white_noise(point);
|
||||
}
|
||||
case PATTERN_MANDELBROT, default: {
|
||||
luminance = mandelbrot(point);
|
||||
}
|
||||
}
|
||||
|
||||
return vec4<f32>(vec3<f32>(linear_to_srgb(luminance)), 1.);
|
||||
}
|
||||
|
||||
fn noise(point: vec2<f32>) -> f32 {
|
||||
var x = point.x;
|
||||
var y = point.y;
|
||||
if parameters.domain_warp != 0u {
|
||||
fnlDomainWarp2D(parameters.noise, &x, &y);
|
||||
}
|
||||
return (fnlGetNoise2D(parameters.noise, x, y) + 1.) * 0.5;
|
||||
}
|
||||
|
||||
// A random value for each square of one unit, matching the CPU's
|
||||
fn white_noise(point: vec2<f32>) -> f32 {
|
||||
let cell = vec2<i32>(floor(point));
|
||||
let hash = pcg3d(vec3<u32>(bitcast<vec2<u32>>(cell), bitcast<u32>(parameters.noise.seed)));
|
||||
|
||||
// The top 24 bits, which an f32 holds exactly
|
||||
return f32(hash.x >> 8u) / 16777216.;
|
||||
}
|
||||
|
||||
// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result
|
||||
fn pcg3d(input: vec3<u32>) -> vec3<u32> {
|
||||
var v = input * 1664525u + 1013904223u;
|
||||
v.x += v.y * v.z;
|
||||
v.y += v.z * v.x;
|
||||
v.z += v.x * v.y;
|
||||
v ^= v >> vec3<u32>(16u);
|
||||
v.x += v.y * v.z;
|
||||
v.y += v.z * v.x;
|
||||
v.z += v.x * v.y;
|
||||
return v;
|
||||
}
|
||||
|
||||
// The fraction of the iteration limit that `c` takes to escape the Mandelbrot set, or 1 if it doesn't
|
||||
fn mandelbrot(c: vec2<f32>) -> f32 {
|
||||
var z = vec2<f32>(0.);
|
||||
for (var iteration = 0u; iteration < MANDELBROT_ITERATIONS; iteration++) {
|
||||
z = vec2<f32>(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c;
|
||||
if dot(z, z) > 4. {
|
||||
return f32(iteration) / f32(MANDELBROT_ITERATIONS);
|
||||
}
|
||||
}
|
||||
return 1.;
|
||||
}
|
||||
|
||||
// Clamped to the range the CPU encodes, which takes NaN as 0
|
||||
fn linear_to_srgb(unclamped: f32) -> f32 {
|
||||
let linear = select(0., min(unclamped, 1.), unclamped >= 0.);
|
||||
|
||||
@@ -0,0 +1,704 @@
|
||||
// The Mandelbrot settings' choices, matching the Rust side's
|
||||
const FRACTAL_BURNING_SHIP: u32 = 1u;
|
||||
const FRACTAL_TRICORN: u32 = 2u;
|
||||
const EXTERIOR_SMOOTH_ESCAPE: u32 = 0u;
|
||||
const EXTERIOR_DISCRETE_ESCAPE: u32 = 4u;
|
||||
const EXTERIOR_PROXIMITY: u32 = 1u;
|
||||
const EXTERIOR_TENDRILS: u32 = 2u;
|
||||
const EXTERIOR_CLOSEST_APPROACH: u32 = 5u;
|
||||
const EXTERIOR_FLAT: u32 = 6u;
|
||||
const EXTERIOR_ANGLE: u32 = 7u;
|
||||
const EXTERIOR_CLOSEST_ITERATION: u32 = 8u;
|
||||
const INTERIOR_FLAT: u32 = 0u;
|
||||
const INTERIOR_FINAL_DISTANCE: u32 = 1u;
|
||||
const INTERIOR_PERIOD: u32 = 2u;
|
||||
const INTERIOR_CLOSEST_APPROACH: u32 = 3u;
|
||||
const INTERIOR_CLOSEST_ITERATION: u32 = 4u;
|
||||
const INTERIOR_FINAL_ANGLE: u32 = 5u;
|
||||
const INTERIOR_RADIUS: u32 = 6u;
|
||||
const INTERIOR_ANGLE: u32 = 7u;
|
||||
const INTERIOR_RAYS: u32 = 9u;
|
||||
const INTERIOR_SMOOTH_SETTLING: u32 = 8u;
|
||||
const INTERIOR_DISCRETE_SETTLING: u32 = 10u;
|
||||
const INTERIOR_PROXIMITY: u32 = 11u;
|
||||
|
||||
// The reference orbit's values in each row of its texture
|
||||
const REFERENCE_ROW_LENGTH: u32 = 1024u;
|
||||
|
||||
// How close a settled orbit's value must come back to where it was to count as one turn of its cycle, however close its closest return
|
||||
const PERIOD_TOLERANCE: f32 = 1e-5;
|
||||
|
||||
// How close a settled orbit's value must come back to where it was at least once for it to count as cycling at all
|
||||
const SETTLED_TOLERANCE: f32 = 1e-2;
|
||||
|
||||
// How close a value must come to where it lands a turn of its cycle later for the orbit to count as settled into the cycle, which sets the Discrete Settling's bands
|
||||
const SETTLING_TOLERANCE: f32 = 1e-3;
|
||||
|
||||
// How many doublings of a point's distance to the set span the whole gradient
|
||||
const DISTANCE_DOUBLINGS: f32 = 16.;
|
||||
|
||||
// How far an offset can reach from the reference value, relative to it, for a power other than an integer to step the offset by itself rather than raise its value directly
|
||||
const OFFSET_STEP_REACH: f32 = 0.5;
|
||||
|
||||
// How large a number can be for the logarithm of one plus it, and its exponential less one, to be summed as series, where 32-bit functions would lose its precision
|
||||
const SERIES_REACH: f32 = 0.125;
|
||||
|
||||
// The terms of those series, which keep them within 32-bit rounding up to their reach
|
||||
const LOGARITHM_TERMS: u32 = 7u;
|
||||
const EXPONENTIAL_TERMS: u32 = 5u;
|
||||
|
||||
const TAU: f32 = 6.283185307179586;
|
||||
|
||||
// The settings of a Mandelbrot-style fractal, as the CPU's kernel iterates with them
|
||||
struct Mandelbrot {
|
||||
// The tile's top left corner relative to the reference point, for points following its orbit
|
||||
delta_corner: vec2<f32>,
|
||||
// The starting value, and the point added each iteration, at the plane's origin and how much each moves with a point of the plane
|
||||
start_constant: vec2<f32>,
|
||||
added_constant: vec2<f32>,
|
||||
start_slope: f32,
|
||||
added_slope: f32,
|
||||
fractal: u32,
|
||||
exterior: u32,
|
||||
interior: u32,
|
||||
iterations: u32,
|
||||
power: f32,
|
||||
// The power as an integer, or 0 if it isn't one
|
||||
integer_power: u32,
|
||||
frequency: f32,
|
||||
bailout_squared: f32,
|
||||
log_bailout: f32,
|
||||
// The reference orbit's length, or 0 if points are iterated directly
|
||||
reference_length: u32,
|
||||
// Whether points tested to lie inside the main cardioid or the bulb on its left skip their iterations
|
||||
interior_test: u32,
|
||||
padding: u32,
|
||||
}
|
||||
|
||||
struct Parameters {
|
||||
corner: vec2<f32>,
|
||||
texel: vec2<f32>,
|
||||
mandelbrot: Mandelbrot,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> parameters: Parameters;
|
||||
// The values of the reference orbit, in rows of `REFERENCE_ROW_LENGTH`, with each value as the formula raises it after it
|
||||
@group(0) @binding(1) var reference_orbit: texture_2d<f32>;
|
||||
|
||||
// The brightness is already gamma-encoded, so a Gradient Map takes it as the position along its gradient.
|
||||
// Under ANGLE's D3D11 backend, FXC fails to compile the reference orbit's texture reads if `mandelbrot` is called from within a `switch`.
|
||||
@fragment
|
||||
fn generate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let encoded = clamp(mandelbrot(position.xy), 0., 1.);
|
||||
return vec4<f32>(vec3<f32>(encoded), 1.);
|
||||
}
|
||||
|
||||
// A point's orbit, followed by its offset from the reference orbit if there is one, and otherwise iterated directly
|
||||
struct Orbit {
|
||||
z: vec2<f32>,
|
||||
c: vec2<f32>,
|
||||
offset: vec2<f32>,
|
||||
// How far the point added each iteration lies from the reference orbit's
|
||||
added_offset: vec2<f32>,
|
||||
index: u32,
|
||||
// The reference orbit's value at `index` and as the formula raises it, and its starting value and raising
|
||||
reference: vec4<f32>,
|
||||
reference_start: vec4<f32>,
|
||||
}
|
||||
|
||||
// What a point's orbit records about its values as it iterates, for the colorings drawn from them
|
||||
struct OrbitRecord {
|
||||
// The squared length of the first value, of the value closest to the origin, and the iteration reaching it
|
||||
first: f32,
|
||||
closest: f32,
|
||||
closest_iteration: u32,
|
||||
// The sum of the natural logarithm of how much the formula scales distances at each value
|
||||
log_derivative_sum: f32,
|
||||
}
|
||||
|
||||
// The brightness of the Mandelbrot-style fractal at the pixel `position` of the tile
|
||||
fn mandelbrot(position: vec2<f32>) -> f32 {
|
||||
let settings = parameters.mandelbrot;
|
||||
let interior = settings.interior;
|
||||
|
||||
// The interiors that don't need a point's iterations take a point the test finds inside the main cardioid or the bulb on its left from its position
|
||||
let known_by_test = interior == INTERIOR_FLAT || shows_cycle(interior);
|
||||
if settings.interior_test != 0u && known_by_test {
|
||||
let point = parameters.corner + position * parameters.texel;
|
||||
let period = cardioid_or_bulb_period(point);
|
||||
if period != 0u {
|
||||
// The cycle's multiplier is 1 - √(1 - 4c) across the cardioid, and 4(c + 1) across the bulb
|
||||
var multiplier = (point + vec2<f32>(1., 0.)) * 4.;
|
||||
if period == 1u {
|
||||
multiplier = vec2<f32>(1., 0.) - complex_square_root(vec2<f32>(1., 0.) - point * 4.);
|
||||
}
|
||||
return cycle_brightness(true, period, multiplier);
|
||||
}
|
||||
}
|
||||
|
||||
var orbit = start_orbit(position);
|
||||
|
||||
// The orbit's derivative with respect to the point, which starts at how much the starting value moves with it
|
||||
var derivative = vec2<f32>(settings.start_slope, 0.);
|
||||
var stripe_sum = 0.;
|
||||
var last_stripe = 0.;
|
||||
var escape_angle = EscapeAngle(0., 1., 0.);
|
||||
let records = settings.exterior == EXTERIOR_CLOSEST_APPROACH || settings.exterior == EXTERIOR_CLOSEST_ITERATION || interior == INTERIOR_CLOSEST_APPROACH || interior == INTERIOR_CLOSEST_ITERATION || interior == INTERIOR_SMOOTH_SETTLING;
|
||||
var record = OrbitRecord(0., 3.4e38, 0u, 0.);
|
||||
|
||||
for (var iteration = 1u; iteration <= settings.iterations; iteration++) {
|
||||
if settings.exterior == EXTERIOR_PROXIMITY {
|
||||
derivative = derivative_step(orbit_value(orbit), derivative);
|
||||
}
|
||||
|
||||
orbit_step(&orbit);
|
||||
let z = orbit_value(orbit);
|
||||
|
||||
if settings.exterior == EXTERIOR_TENDRILS {
|
||||
last_stripe = 0.5 * sin(settings.frequency * atan2(z.y, z.x)) + 0.5;
|
||||
stripe_sum += last_stripe;
|
||||
}
|
||||
|
||||
if settings.exterior == EXTERIOR_ANGLE {
|
||||
visit_escape_angle(&escape_angle, iteration, z);
|
||||
}
|
||||
|
||||
if dot(z, z) > settings.bailout_squared {
|
||||
return exterior(iteration, z, derivative, stripe_sum, last_stripe, escape_angle, record);
|
||||
}
|
||||
|
||||
if records {
|
||||
record_value(&record, iteration, z);
|
||||
}
|
||||
}
|
||||
|
||||
return interior_brightness(&orbit, record, position);
|
||||
}
|
||||
|
||||
// The orbit of the point at the pixel `position` of the tile, before its first iteration
|
||||
fn start_orbit(position: vec2<f32>) -> Orbit {
|
||||
let settings = parameters.mandelbrot;
|
||||
var orbit: Orbit;
|
||||
if follows_reference() {
|
||||
let offset = settings.delta_corner + position * parameters.texel;
|
||||
orbit.offset = offset * settings.start_slope;
|
||||
orbit.added_offset = offset * settings.added_slope;
|
||||
orbit.reference_start = reference_value(0u);
|
||||
orbit.reference = orbit.reference_start;
|
||||
} else {
|
||||
let point = parameters.corner + position * parameters.texel;
|
||||
orbit.z = point * settings.start_slope + settings.start_constant;
|
||||
orbit.c = point * settings.added_slope + settings.added_constant;
|
||||
}
|
||||
return orbit;
|
||||
}
|
||||
|
||||
// The external angle a point's orbit escapes along, which turns once around the set. It sums the first value's angle and each later value's turn
|
||||
// past the raised value before it, with weights shrinking by the power.
|
||||
struct EscapeAngle {
|
||||
radians: f32,
|
||||
// The weight of the next value's turn past the raised one before it, which also flips its sign with each mirroring of the Tricorn
|
||||
weight: f32,
|
||||
// The angle that raising the last value to the power turned it to
|
||||
raised: f32,
|
||||
}
|
||||
|
||||
// Adds the value `z` the orbit reached on `iteration` to its external angle
|
||||
fn visit_escape_angle(escape_angle: ptr<function, EscapeAngle>, iteration: u32, z: vec2<f32>) {
|
||||
let settings = parameters.mandelbrot;
|
||||
let angle = atan2(z.y, z.x);
|
||||
if iteration == 1u {
|
||||
(*escape_angle).radians = angle;
|
||||
} else {
|
||||
(*escape_angle).weight /= select(settings.power, -settings.power, settings.fractal == FRACTAL_TRICORN);
|
||||
let turn = angle - (*escape_angle).raised;
|
||||
(*escape_angle).radians += (*escape_angle).weight * (turn - TAU * round(turn / TAU));
|
||||
}
|
||||
|
||||
var folded = angle;
|
||||
if settings.fractal == FRACTAL_BURNING_SHIP {
|
||||
folded = atan2(abs(z.y), abs(z.x));
|
||||
} else if settings.fractal == FRACTAL_TRICORN {
|
||||
folded = -angle;
|
||||
}
|
||||
(*escape_angle).raised = settings.power * folded;
|
||||
}
|
||||
|
||||
// Records the value `z` the orbit reached on `iteration`
|
||||
fn record_value(record: ptr<function, OrbitRecord>, iteration: u32, z: vec2<f32>) {
|
||||
let power = parameters.mandelbrot.power;
|
||||
let length_squared = dot(z, z);
|
||||
if iteration == 1u {
|
||||
(*record).first = length_squared;
|
||||
}
|
||||
if length_squared < (*record).closest {
|
||||
(*record).closest = length_squared;
|
||||
(*record).closest_iteration = iteration;
|
||||
}
|
||||
|
||||
// The formula's derivative at z is the power times z raised to one less, whatever folds it, so its size has a logarithm of ln(d) + (d - 1) ln|z|
|
||||
(*record).log_derivative_sum += log(power) + (power - 1.) * 0.5 * log(max(length_squared, 1.175494e-38));
|
||||
}
|
||||
|
||||
// How close the orbit came to the origin relative to its first value, which is full brightness for an orbit escaping before it recorded any value
|
||||
fn closest_approach(record: OrbitRecord) -> f32 {
|
||||
if record.closest_iteration == 0u {
|
||||
return 1.;
|
||||
}
|
||||
return select(0., sqrt(record.closest / record.first), record.first > 0.);
|
||||
}
|
||||
|
||||
// The iteration that came closest to the origin, as a brightness that rises toward 1 with later iterations
|
||||
fn closest_iteration_brightness(record: OrbitRecord) -> f32 {
|
||||
return 1. - 1. / f32(max(record.closest_iteration, 1u));
|
||||
}
|
||||
|
||||
fn follows_reference() -> bool {
|
||||
return parameters.mandelbrot.reference_length != 0u;
|
||||
}
|
||||
|
||||
fn orbit_value(orbit: Orbit) -> vec2<f32> {
|
||||
if follows_reference() {
|
||||
return orbit.reference.xy + orbit.offset;
|
||||
}
|
||||
return orbit.z;
|
||||
}
|
||||
|
||||
fn orbit_step(orbit: ptr<function, Orbit>) {
|
||||
let settings = parameters.mandelbrot;
|
||||
if !follows_reference() {
|
||||
(*orbit).z = complex_power(formula_input((*orbit).z), settings.power) + (*orbit).c;
|
||||
return;
|
||||
}
|
||||
|
||||
// Following the reference orbit from its start again wherever that shrinks the offset, or once the reference orbit escapes, keeps the offset small (Zhuoran's rebasing)
|
||||
let z = (*orbit).reference.xy + (*orbit).offset;
|
||||
let rebased = z - (*orbit).reference_start.xy;
|
||||
let shrinks = (*orbit).index > 0u && dot(rebased, rebased) < dot((*orbit).offset, (*orbit).offset);
|
||||
if shrinks || (*orbit).index + 1u == settings.reference_length {
|
||||
(*orbit).offset = rebased;
|
||||
(*orbit).index = 0u;
|
||||
(*orbit).reference = (*orbit).reference_start;
|
||||
}
|
||||
|
||||
(*orbit).offset = perturbed_step((*orbit).reference.xy, (*orbit).reference.zw, (*orbit).offset) + (*orbit).added_offset;
|
||||
(*orbit).index += 1u;
|
||||
(*orbit).reference = reference_value((*orbit).index);
|
||||
}
|
||||
|
||||
fn reference_value(index: u32) -> vec4<f32> {
|
||||
return textureLoad(reference_orbit, vec2<i32>(i32(index % REFERENCE_ROW_LENGTH), i32(index / REFERENCE_ROW_LENGTH)), 0);
|
||||
}
|
||||
|
||||
// What the formula does to the value before raising it to the power
|
||||
fn formula_input(z: vec2<f32>) -> vec2<f32> {
|
||||
let fractal = parameters.mandelbrot.fractal;
|
||||
if fractal == FRACTAL_BURNING_SHIP {
|
||||
return abs(z);
|
||||
}
|
||||
if fractal == FRACTAL_TRICORN {
|
||||
return vec2<f32>(z.x, -z.y);
|
||||
}
|
||||
return z;
|
||||
}
|
||||
|
||||
// How far the formula's next value, before the point is added, moves from the reference value's with an offset from it, given the reference value as the formula raises it.
|
||||
// It's worked out from the offset itself, which keeps a small offset precise rather than subtracting two nearly equal values.
|
||||
fn perturbed_step(orbit_reference: vec2<f32>, raised_reference: vec2<f32>, orbit_offset: vec2<f32>) -> vec2<f32> {
|
||||
let settings = parameters.mandelbrot;
|
||||
var reference = orbit_reference;
|
||||
var offset = orbit_offset;
|
||||
if settings.fractal == FRACTAL_BURNING_SHIP {
|
||||
offset = vec2<f32>(absolute_difference(reference.x, offset.x), absolute_difference(reference.y, offset.y));
|
||||
reference = abs(reference);
|
||||
}
|
||||
if settings.fractal == FRACTAL_TRICORN {
|
||||
offset = vec2<f32>(offset.x, -offset.y);
|
||||
reference = vec2<f32>(reference.x, -reference.y);
|
||||
}
|
||||
|
||||
if settings.integer_power == 0u {
|
||||
return raised_step(reference, raised_reference, offset);
|
||||
}
|
||||
|
||||
// (Z + δ)^d - Z^d = δ × Σ (Z + δ)^(d - 1 - k) Z^k
|
||||
let value = reference + offset;
|
||||
var sum = vec2<f32>(0.);
|
||||
var reference_power = vec2<f32>(1., 0.);
|
||||
for (var k = 0u; k < settings.integer_power; k++) {
|
||||
sum = complex_multiply(sum, value) + reference_power;
|
||||
reference_power = complex_multiply(reference_power, reference);
|
||||
}
|
||||
return complex_multiply(offset, sum);
|
||||
}
|
||||
|
||||
// How far Z^d moves, for a power `d` other than an integer, when Z moves by δ, given Z^d. It's Z^d × (exp(d × ln(1 + δ/Z)) - 1), keeping to the principal branch that raising
|
||||
// Z + δ directly takes, so the logarithm turns back a whole turn where δ carries Z across the negative real axis.
|
||||
fn raised_step(reference: vec2<f32>, raised_reference: vec2<f32>, offset: vec2<f32>) -> vec2<f32> {
|
||||
let power = parameters.mandelbrot.power;
|
||||
|
||||
// Far offsets, and zero reference values like the start of the Mandelbrot set's orbits, raise the value directly
|
||||
if dot(offset, offset) >= OFFSET_STEP_REACH * OFFSET_STEP_REACH * dot(reference, reference) {
|
||||
return complex_power(reference + offset, power) - raised_reference;
|
||||
}
|
||||
|
||||
var logarithm = complex_logarithm_of_one_plus(complex_divide(offset, reference));
|
||||
let crosses = reference.x < 0. && (reference.y >= 0.) != (reference.y + offset.y >= 0.);
|
||||
if crosses {
|
||||
logarithm.y += select(TAU, -TAU, reference.y >= 0.);
|
||||
}
|
||||
return complex_multiply(raised_reference, complex_exponential_less_one(logarithm * power));
|
||||
}
|
||||
|
||||
// ln(1 + u), summed as a series for small `u`
|
||||
fn complex_logarithm_of_one_plus(u: vec2<f32>) -> vec2<f32> {
|
||||
if dot(u, u) >= SERIES_REACH * SERIES_REACH {
|
||||
let value = u + vec2<f32>(1., 0.);
|
||||
return vec2<f32>(0.5 * log(dot(value, value)), atan2(value.y, value.x));
|
||||
}
|
||||
|
||||
// u - u²/2 + u³/3 - ..., by Horner's method
|
||||
var sum = vec2<f32>(0.);
|
||||
for (var term = LOGARITHM_TERMS; term >= 1u; term--) {
|
||||
let sign = select(-1., 1., term % 2u == 1u);
|
||||
sum = vec2<f32>(sign / f32(term), 0.) + complex_multiply(u, sum);
|
||||
}
|
||||
return complex_multiply(u, sum);
|
||||
}
|
||||
|
||||
// exp(w) - 1, summed as a series for small `w`
|
||||
fn complex_exponential_less_one(w: vec2<f32>) -> vec2<f32> {
|
||||
if dot(w, w) >= SERIES_REACH * SERIES_REACH {
|
||||
let magnitude = exp(w.x);
|
||||
return vec2<f32>(magnitude * cos(w.y) - 1., magnitude * sin(w.y));
|
||||
}
|
||||
|
||||
// w + w²/2! + w³/3! + ..., by Horner's method
|
||||
var sum = vec2<f32>(1., 0.);
|
||||
for (var term = EXPONENTIAL_TERMS; term >= 2u; term--) {
|
||||
sum = vec2<f32>(1., 0.) + complex_multiply(w, sum) / f32(term);
|
||||
}
|
||||
return complex_multiply(w, sum);
|
||||
}
|
||||
|
||||
// |x + δ| - |x|, worked out without subtracting two nearly equal values
|
||||
fn absolute_difference(x: f32, offset: f32) -> f32 {
|
||||
if x >= 0. {
|
||||
return select(-2. * x - offset, offset, x + offset >= 0.);
|
||||
}
|
||||
return select(-offset, 2. * x + offset, x + offset >= 0.);
|
||||
}
|
||||
|
||||
// The derivative of the orbit's next value with respect to the point, given its current value `z` and derivative
|
||||
fn derivative_step(z: vec2<f32>, derivative: vec2<f32>) -> vec2<f32> {
|
||||
return chain_step(z, derivative) + vec2<f32>(parameters.mandelbrot.added_slope, 0.);
|
||||
}
|
||||
|
||||
// The formula's derivative at the value `z` times `derivative`, chaining the derivative of the value before it through one iteration
|
||||
fn chain_step(orbit_z: vec2<f32>, orbit_derivative: vec2<f32>) -> vec2<f32> {
|
||||
let settings = parameters.mandelbrot;
|
||||
var z = orbit_z;
|
||||
var derivative = orbit_derivative;
|
||||
switch settings.fractal {
|
||||
case FRACTAL_BURNING_SHIP: {
|
||||
derivative *= vec2<f32>(select(-1., 1., z.x >= 0.), select(-1., 1., z.y >= 0.));
|
||||
z = abs(z);
|
||||
}
|
||||
case FRACTAL_TRICORN: {
|
||||
z = vec2<f32>(z.x, -z.y);
|
||||
derivative = vec2<f32>(derivative.x, -derivative.y);
|
||||
}
|
||||
default: {}
|
||||
}
|
||||
return complex_multiply(complex_power(z, settings.power - 1.) * settings.power, derivative);
|
||||
}
|
||||
|
||||
// The brightness of a point that escaped on `iteration` with the value `z`
|
||||
fn exterior(iteration: u32, z: vec2<f32>, derivative: vec2<f32>, stripe_sum: f32, last_stripe: f32, escape_angle: EscapeAngle, record: OrbitRecord) -> f32 {
|
||||
let settings = parameters.mandelbrot;
|
||||
|
||||
// How far past the bailout radius the value landed, from 0 just past it to 1 at the bailout radius raised to the power
|
||||
let log_magnitude = 0.5 * log(dot(z, z));
|
||||
let overshoot = clamp(log(log_magnitude / settings.log_bailout) / log(settings.power), 0., 1.);
|
||||
let escape = max(f32(iteration) - overshoot, 0.);
|
||||
|
||||
var value: f32;
|
||||
switch settings.exterior {
|
||||
case EXTERIOR_FLAT: {
|
||||
value = 0.;
|
||||
}
|
||||
case EXTERIOR_ANGLE: {
|
||||
value = fract(escape_angle.radians / TAU + 0.5);
|
||||
}
|
||||
case EXTERIOR_SMOOTH_ESCAPE: {
|
||||
value = log(escape + 1.) / log(f32(settings.iterations) + 1.);
|
||||
}
|
||||
// The smooth escape at the start of its band, where the value lands farthest past the bailout radius
|
||||
case EXTERIOR_DISCRETE_ESCAPE: {
|
||||
value = log(f32(iteration)) / log(f32(settings.iterations) + 1.);
|
||||
}
|
||||
case EXTERIOR_PROXIMITY: {
|
||||
let distance = 2. * exp(log_magnitude) * log_magnitude / length_without_overflow(derivative);
|
||||
value = select(1., max(-log2(distance) / DISTANCE_DOUBLINGS, 0.), distance > 0. && distance < 3.4e38);
|
||||
}
|
||||
case EXTERIOR_CLOSEST_APPROACH: {
|
||||
value = closest_approach(record);
|
||||
}
|
||||
case EXTERIOR_CLOSEST_ITERATION: {
|
||||
value = closest_iteration_brightness(record);
|
||||
}
|
||||
// Blended between the averages with and without the last value, so the stripes run on unbroken where points escape one iteration later
|
||||
case EXTERIOR_TENDRILS: {
|
||||
let average = stripe_sum / f32(iteration);
|
||||
let previous = select(average, (stripe_sum - last_stripe) / f32(iteration - 1u), iteration > 1u);
|
||||
value = previous + (average - previous) * (1. - overshoot);
|
||||
}
|
||||
// The angle scales by the power across the overshoot, so the lines run on unbroken where points escape one iteration later.
|
||||
// The Burning Ship folds the value into a quarter turn before raising it to the power, so its lines take that angle at twice the frequency to join up the same way.
|
||||
default: {
|
||||
var angle = atan2(z.y, z.x);
|
||||
var frequency = settings.frequency;
|
||||
if settings.fractal == FRACTAL_BURNING_SHIP {
|
||||
angle = atan2(abs(z.y), abs(z.x));
|
||||
frequency = 2. * settings.frequency;
|
||||
}
|
||||
value = 0.5 * cos(frequency * pow(settings.power, 1. - overshoot) * angle) + 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// The brightness of a point inside the set at the pixel `position`, given its orbit after all its iterations and what it recorded along the way
|
||||
fn interior_brightness(orbit: ptr<function, Orbit>, record: OrbitRecord, position: vec2<f32>) -> f32 {
|
||||
let settings = parameters.mandelbrot;
|
||||
let interior = settings.interior;
|
||||
if interior == INTERIOR_FLAT {
|
||||
return 1.;
|
||||
}
|
||||
// Finding the cycle once for every interior drawn from it, since the shader compiler copies each call's loops in again
|
||||
if shows_cycle(interior) || interior == INTERIOR_DISCRETE_SETTLING || interior == INTERIOR_PROXIMITY {
|
||||
let cycle = settled_cycle(orbit);
|
||||
if !cycle.found {
|
||||
return 1.;
|
||||
}
|
||||
if interior == INTERIOR_DISCRETE_SETTLING {
|
||||
return discrete_settling(cycle.period, position);
|
||||
}
|
||||
if interior == INTERIOR_PROXIMITY {
|
||||
return select(0., clamp(-log2(cycle.edge_distance) / DISTANCE_DOUBLINGS, 0., 1.), cycle.edge_distance < 3.4e38);
|
||||
}
|
||||
return cycle_brightness(cycle.found, cycle.period, cycle.multiplier);
|
||||
}
|
||||
|
||||
let z = orbit_value(*orbit);
|
||||
var value: f32;
|
||||
if interior == INTERIOR_FINAL_DISTANCE {
|
||||
value = length(z) / 2.;
|
||||
} else if interior == INTERIOR_CLOSEST_APPROACH {
|
||||
value = closest_approach(record);
|
||||
} else if interior == INTERIOR_CLOSEST_ITERATION {
|
||||
value = closest_iteration_brightness(record);
|
||||
} else if interior == INTERIOR_FINAL_ANGLE {
|
||||
value = atan2(z.y, z.x) / TAU + 0.5;
|
||||
} else {
|
||||
// The geometric mean of how much each iteration scales distances, which is the exponential of the Lyapunov exponent
|
||||
value = exp(record.log_derivative_sum / f32(settings.iterations));
|
||||
}
|
||||
return min(value, 1.);
|
||||
}
|
||||
|
||||
// The cycle an orbit has settled into after all its iterations, if it's `found`: its length, its multiplier, and for the Proximity interior, the distance to its bulb's edge
|
||||
struct Cycle {
|
||||
found: bool,
|
||||
period: u32,
|
||||
multiplier: vec2<f32>,
|
||||
edge_distance: f32,
|
||||
}
|
||||
|
||||
// The cycle the orbit has settled into after all its iterations, which leaves the orbit a turn of the cycle on.
|
||||
// The length is the first number of iterations bringing the value back about as close as any does, and the multiplier is the derivative of that many iterations.
|
||||
fn settled_cycle(orbit: ptr<function, Orbit>) -> Cycle {
|
||||
let settings = parameters.mandelbrot;
|
||||
|
||||
let settled = orbit_value(*orbit);
|
||||
var found = false;
|
||||
var period = 0u;
|
||||
var multiplier = vec2<f32>(1., 0.);
|
||||
|
||||
// For the Proximity interior, the derivatives around the cycle of its iterations by the value and by the point added each iteration,
|
||||
// and the second derivatives by the value twice and by both
|
||||
let edge = settings.interior == INTERIOR_PROXIMITY;
|
||||
var by_value = vec2<f32>(1., 0.);
|
||||
var by_added = vec2<f32>(0.);
|
||||
var by_value_twice = vec2<f32>(0.);
|
||||
var by_both = vec2<f32>(0.);
|
||||
|
||||
// First a copy of the orbit steps through all its iterations to find its closest return, which finds the cycles of orbits still settling near a bulb's edge,
|
||||
// as no fixed tolerance would. Then the orbit steps until it comes back about that close. Both step through one call, since the shader compiler
|
||||
// copies a call's whole step in again, which slowed its first compile.
|
||||
var returning = *orbit;
|
||||
var closest = 3.4e38;
|
||||
for (var step = 0u; step < 2u * settings.iterations; step++) {
|
||||
let finding_period = step >= settings.iterations;
|
||||
if step == settings.iterations && closest >= SETTLED_TOLERANCE * SETTLED_TOLERANCE {
|
||||
break;
|
||||
}
|
||||
|
||||
if finding_period && edge {
|
||||
let z = formula_input(orbit_value(*orbit));
|
||||
let first = complex_power(z, settings.power - 1.) * settings.power;
|
||||
let second = complex_power(z, settings.power - 2.) * (settings.power * (settings.power - 1.));
|
||||
by_both = complex_multiply(second, complex_multiply(by_value, by_added)) + complex_multiply(first, by_both);
|
||||
by_value_twice = complex_multiply(second, complex_multiply(by_value, by_value)) + complex_multiply(first, by_value_twice);
|
||||
by_added = complex_multiply(first, by_added) + vec2<f32>(1., 0.);
|
||||
by_value = complex_multiply(first, by_value);
|
||||
}
|
||||
if finding_period {
|
||||
multiplier = chain_step(orbit_value(*orbit), multiplier);
|
||||
}
|
||||
|
||||
var stepping = returning;
|
||||
if finding_period {
|
||||
stepping = *orbit;
|
||||
}
|
||||
orbit_step(&stepping);
|
||||
let difference = orbit_value(stepping) - settled;
|
||||
|
||||
if !finding_period {
|
||||
returning = stepping;
|
||||
closest = min(closest, dot(difference, difference));
|
||||
} else {
|
||||
*orbit = stepping;
|
||||
if dot(difference, difference) <= 4. * closest + PERIOD_TOLERANCE * PERIOD_TOLERANCE {
|
||||
found = true;
|
||||
period = step - settings.iterations + 1u;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The multiplier changes with the point by the mixed derivative plus the second derivative times how far the cycle shifts,
|
||||
// and the edge lies about as far away as the multiplier's size has left to reach 1, divided by that rate (the interior distance estimate)
|
||||
var edge_distance = 0.;
|
||||
if edge {
|
||||
let shift = complex_divide(by_added, vec2<f32>(1., 0.) - by_value);
|
||||
let rate = length_without_overflow(by_both + complex_multiply(by_value_twice, shift)) * settings.added_slope;
|
||||
edge_distance = max((1. - dot(by_value, by_value)) / rate, 0.);
|
||||
}
|
||||
return Cycle(found, period, multiplier, edge_distance);
|
||||
}
|
||||
|
||||
// The first iteration from which the orbit of the point at the pixel `position` repeats itself each turn of its `period`-long cycle to within the settling tolerance,
|
||||
// brightest for the orbits that settle last, at the start of the band they settle in, like the discrete escape outside
|
||||
fn discrete_settling(period: u32, position: vec2<f32>) -> f32 {
|
||||
let settings = parameters.mandelbrot;
|
||||
|
||||
// The orbit again from its start, against itself a turn of the cycle ahead. Once the leading orbit is a turn ahead, they take turns stepping
|
||||
// through one call, since the shader compiler copies a call's whole step in again, which slowed its first compile.
|
||||
var following = start_orbit(position);
|
||||
var leading = following;
|
||||
var settling = settings.iterations;
|
||||
for (var step = 0u; step < period + 2u * settings.iterations; step++) {
|
||||
let following_turn = step >= period && (step - period) % 2u == 0u;
|
||||
if following_turn {
|
||||
let difference = orbit_value(leading) - orbit_value(following);
|
||||
if dot(difference, difference) < SETTLING_TOLERANCE * SETTLING_TOLERANCE {
|
||||
settling = (step - period) / 2u;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var stepping = leading;
|
||||
if following_turn {
|
||||
stepping = following;
|
||||
}
|
||||
orbit_step(&stepping);
|
||||
if following_turn {
|
||||
following = stepping;
|
||||
} else {
|
||||
leading = stepping;
|
||||
}
|
||||
}
|
||||
return min(log(f32(settling) + 1.) / log(f32(settings.iterations) + 1.), 1.);
|
||||
}
|
||||
|
||||
// The brightness inside the set from the length and multiplier of the cycle a point's orbit settles into, if one was `found`
|
||||
fn cycle_brightness(found: bool, period: u32, multiplier: vec2<f32>) -> f32 {
|
||||
let interior = parameters.mandelbrot.interior;
|
||||
if interior == INTERIOR_FLAT {
|
||||
return 1.;
|
||||
}
|
||||
|
||||
var value = 1.;
|
||||
if found && interior == INTERIOR_RADIUS {
|
||||
value = min(length(multiplier), 1.);
|
||||
} else if found && interior == INTERIOR_ANGLE {
|
||||
value = atan2(multiplier.y, multiplier.x) / TAU + 0.5;
|
||||
} else if found && interior == INTERIOR_RAYS {
|
||||
value = 0.5 * cos(parameters.mandelbrot.frequency * atan2(multiplier.y, multiplier.x)) + 0.5;
|
||||
} else if found {
|
||||
value = 1. - 1. / f32(period);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Whether the interior shows the cycle a point's orbit settles into
|
||||
fn shows_cycle(interior: u32) -> bool {
|
||||
return interior == INTERIOR_PERIOD || interior == INTERIOR_RADIUS || interior == INTERIOR_ANGLE || interior == INTERIOR_RAYS;
|
||||
}
|
||||
|
||||
// The period of the main cardioid or the bulb on its left if the point lies in one, or 0, worked out from its position alone
|
||||
fn cardioid_or_bulb_period(point: vec2<f32>) -> u32 {
|
||||
let shifted = point.x - 0.25;
|
||||
let squared = shifted * shifted + point.y * point.y;
|
||||
if squared * (squared + shifted) <= 0.25 * point.y * point.y {
|
||||
return 1u;
|
||||
}
|
||||
if (point.x + 1.) * (point.x + 1.) + point.y * point.y <= 1. / 16. {
|
||||
return 2u;
|
||||
}
|
||||
return 0u;
|
||||
}
|
||||
|
||||
// The length of `v`, without its squared length overflowing
|
||||
fn length_without_overflow(v: vec2<f32>) -> f32 {
|
||||
let largest = max(abs(v.x), abs(v.y));
|
||||
if largest == 0. || largest > 3.4e38 {
|
||||
return largest;
|
||||
}
|
||||
return largest * length(v / largest);
|
||||
}
|
||||
|
||||
fn complex_multiply(a: vec2<f32>, b: vec2<f32>) -> vec2<f32> {
|
||||
return vec2<f32>(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
|
||||
}
|
||||
|
||||
// The principal square root of `z`
|
||||
fn complex_square_root(z: vec2<f32>) -> vec2<f32> {
|
||||
let magnitude = length(z);
|
||||
let imaginary = sqrt(max(0.5 * (magnitude - z.x), 0.));
|
||||
return vec2<f32>(sqrt(max(0.5 * (magnitude + z.x), 0.)), select(imaginary, -imaginary, z.y < 0.));
|
||||
}
|
||||
|
||||
fn complex_divide(a: vec2<f32>, b: vec2<f32>) -> vec2<f32> {
|
||||
return complex_multiply(a, vec2<f32>(b.x, -b.y)) / dot(b, b);
|
||||
}
|
||||
|
||||
// `z` raised to `power`, by repeated multiplication for integer powers and in polar form for others
|
||||
fn complex_power(z: vec2<f32>, power: f32) -> vec2<f32> {
|
||||
if fract(power) == 0. && power >= 0. {
|
||||
var product = vec2<f32>(1., 0.);
|
||||
for (var k = 0u; k < u32(power); k++) {
|
||||
product = complex_multiply(product, z);
|
||||
}
|
||||
return product;
|
||||
}
|
||||
let squared = dot(z, z);
|
||||
if squared == 0. {
|
||||
return vec2<f32>(0.);
|
||||
}
|
||||
let magnitude = exp2(0.5 * power * log2(squared));
|
||||
let angle = atan2(z.y, z.x) * power;
|
||||
return vec2<f32>(cos(angle), sin(angle)) * magnitude;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
struct Parameters {
|
||||
corner: vec2<f32>,
|
||||
texel: vec2<f32>,
|
||||
// Whether the noise warps its domain before it's sampled
|
||||
domain_warp: u32,
|
||||
@align(16) noise: fnl_state,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> parameters: Parameters;
|
||||
|
||||
@fragment
|
||||
fn generate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let point = parameters.corner + position.xy * parameters.texel;
|
||||
|
||||
var x = point.x;
|
||||
var y = point.y;
|
||||
if parameters.domain_warp != 0u {
|
||||
fnlDomainWarp2D(parameters.noise, &x, &y);
|
||||
}
|
||||
let luminance = (fnlGetNoise2D(parameters.noise, x, y) + 1.) * 0.5;
|
||||
|
||||
return vec4<f32>(vec3<f32>(linear_to_srgb(luminance)), 1.);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// The start of the noise shader's noise state, laid out the same way in every backend's shading language as a struct of its own
|
||||
struct NoiseState {
|
||||
seed: i32,
|
||||
}
|
||||
|
||||
struct Parameters {
|
||||
corner: vec2<f32>,
|
||||
texel: vec2<f32>,
|
||||
_domain_warp: u32,
|
||||
@align(16) noise: NoiseState,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> parameters: Parameters;
|
||||
|
||||
// A random value for each square of one unit, matching the CPU's
|
||||
@fragment
|
||||
fn generate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let point = parameters.corner + position.xy * parameters.texel;
|
||||
|
||||
let cell = vec2<i32>(floor(point));
|
||||
let hash = pcg3d(vec3<u32>(bitcast<vec2<u32>>(cell), bitcast<u32>(parameters.noise.seed)));
|
||||
|
||||
// The top 24 bits, which an f32 holds exactly
|
||||
let luminance = f32(hash.x >> 8u) / 16777216.;
|
||||
|
||||
return vec4<f32>(vec3<f32>(linear_to_srgb(luminance)), 1.);
|
||||
}
|
||||
|
||||
// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result
|
||||
fn pcg3d(input: vec3<u32>) -> vec3<u32> {
|
||||
var v = input * 1664525u + 1013904223u;
|
||||
v.x += v.y * v.z;
|
||||
v.y += v.z * v.x;
|
||||
v.z += v.x * v.y;
|
||||
v ^= v >> vec3<u32>(16u);
|
||||
v.x += v.y * v.z;
|
||||
v.y += v.z * v.x;
|
||||
v.z += v.x * v.y;
|
||||
return v;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use glam::{DAffine2, UVec2};
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::raster_types::{CPU, Image, Raster, WeakCPU};
|
||||
use graphic_types::{Adjustment, Effects};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, GlyphResources, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use vello_gpu::kurbo::Affine;
|
||||
@@ -38,7 +38,7 @@ pub const MAX_LAYER_RENDER_SIZE: u32 = 4096;
|
||||
|
||||
/// Vello GPU's renderer and GPU resources, shared by every [`VelloCanvas`] so their memory and pipelines exist once.
|
||||
pub(crate) struct VelloRenderer {
|
||||
/// Locked only while a scene is rendered and submitted, so one canvas drawing its scene on the CPU doesn't hold up another's render.
|
||||
/// Locked only while a scene is rendered and submitted or a glyph run is drawn, so one canvas drawing its scene on the CPU doesn't hold up another's render.
|
||||
gpu: Mutex<(Renderer, Resources)>,
|
||||
alpha_conversion: AlphaConversion,
|
||||
effect_passes: EffectPasses,
|
||||
@@ -258,7 +258,10 @@ impl RenderContext<'_> {
|
||||
// Draw the scene for this render's size and placement, which renders its effects groups as they're drawn
|
||||
let mut scene = self.canvas.spare_scenes.pop().unwrap_or_else(|| vello_gpu::Scene::new(width, height));
|
||||
scene.reset_and_resize(width, height);
|
||||
let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size).with_effects_renderer(self);
|
||||
let glyph_resources: &VelloRenderer = self.renderer;
|
||||
let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size)
|
||||
.with_glyph_resources(glyph_resources)
|
||||
.with_effects_renderer(self);
|
||||
draw(&mut builder);
|
||||
let (scene, images) = builder.finish();
|
||||
|
||||
@@ -356,6 +359,14 @@ impl RenderContext<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl GlyphResources for VelloRenderer {
|
||||
fn with_resources(&self, draw: &mut dyn FnMut(&mut Resources)) {
|
||||
// Glyph runs are drawn without the atlas cache, so they only touch the CPU-side outline caches the lock guards
|
||||
let mut gpu = self.gpu.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
draw(&mut gpu.1);
|
||||
}
|
||||
}
|
||||
|
||||
impl EffectsRenderer for RenderContext<'_> {
|
||||
fn renders_effects(&self) -> bool {
|
||||
self.renderer.effect_passes.renders_working_formats
|
||||
@@ -423,6 +434,8 @@ struct AdjustedTexture {
|
||||
#[derive(Default)]
|
||||
struct ImageTextures {
|
||||
textures: HashMap<ImageKey, ImageTexture>,
|
||||
/// The textures of the generator tiles the last render freed, for its next render's new tiles to take over, as when changing a generator's settings replaces every tile.
|
||||
spare_generator_tiles: Vec<wgpu::Texture>,
|
||||
render_count: u64,
|
||||
}
|
||||
|
||||
@@ -462,18 +475,11 @@ impl ImageTextures {
|
||||
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
SceneImage::GeneratorTile { pattern, tile } => {
|
||||
// Rendered on the GPU, or on the CPU where 32-bit floats can't place its pixels
|
||||
let texture = (self.spare_generator_tiles.pop()).unwrap_or_else(|| GeneratorPasses::tile_texture(device, GeneratorTile::SAMPLES));
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
match renderer.generator_passes.render_tile(device, encoder, pattern, corner, texel, GeneratorTile::SAMPLES) {
|
||||
Some(texture) => {
|
||||
renderer.effect_passes.record_mipmaps(device, encoder, &texture);
|
||||
texture
|
||||
}
|
||||
None => {
|
||||
let (pixels, width, height) = tile.render(pattern).ok()?.to_flat_u8();
|
||||
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
}
|
||||
renderer.generator_passes.render_tile(device, queue, encoder, &texture, pattern, corner, texel);
|
||||
renderer.effect_passes.record_mipmaps(device, encoder, &texture);
|
||||
texture
|
||||
}
|
||||
SceneImage::Rendered(_) => return None,
|
||||
SceneImage::Texture(texture) => create_texture(
|
||||
@@ -590,12 +596,19 @@ impl ImageTextures {
|
||||
let render_count = self.render_count;
|
||||
let in_use = |last_used: u64| render_count - last_used < UNUSED_IMAGE_RENDER_LIMIT;
|
||||
|
||||
self.textures.retain(|key, image_texture| match key {
|
||||
let kept = |key: &ImageKey, image_texture: &ImageTexture| match key {
|
||||
// CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return
|
||||
ImageKey::Blob(_) => image_texture.last_used == render_count,
|
||||
ImageKey::Raster(_) => image_texture.last_used == render_count || (in_use(image_texture.last_used) && image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive)),
|
||||
ImageKey::Texture(_) | ImageKey::GeneratorTile(_) => in_use(image_texture.last_used),
|
||||
});
|
||||
};
|
||||
|
||||
// Spares this render didn't take over are freed, and the tiles it freed become the next render's spares
|
||||
self.spare_generator_tiles.clear();
|
||||
let unused = self.textures.extract_if(|key, image_texture| !kept(key, image_texture));
|
||||
let unused_tiles = unused.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_))).map(|(_, image_texture)| image_texture.texture);
|
||||
self.spare_generator_tiles.extend(unused_tiles);
|
||||
|
||||
self.textures.values_mut().for_each(|image_texture| {
|
||||
image_texture.adjusted.retain(|copy| in_use(copy.last_used));
|
||||
if image_texture.adjusted.is_empty() {
|
||||
@@ -611,8 +624,8 @@ impl ImageTextures {
|
||||
if tile_ages.len() > MAX_CACHED_GENERATOR_TILES {
|
||||
let excess = tile_ages.len() - MAX_CACHED_GENERATOR_TILES;
|
||||
let (_, &mut oldest_kept, _) = tile_ages.select_nth_unstable(excess);
|
||||
self.textures
|
||||
.retain(|key, image_texture| !matches!(key, ImageKey::GeneratorTile(_)) || image_texture.last_used >= oldest_kept);
|
||||
let least_recent = (self.textures).extract_if(|key, image_texture| matches!(key, ImageKey::GeneratorTile(_)) && image_texture.last_used < oldest_kept);
|
||||
self.spare_generator_tiles.extend(least_recent.map(|(_, image_texture)| image_texture.texture));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use crate::WgpuExecutor;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use vello_gpu::kurbo::{Affine, BezPath, Line, Rect, Stroke};
|
||||
use vello_gpu::kurbo::{Affine, BezPath, Line, ParamCurve, PathSeg, Point, Rect, Stroke, Vec2};
|
||||
use vello_gpu::peniko::{self, Color, Fill};
|
||||
|
||||
/// The executor every test shares, or `None` without a GPU.
|
||||
@@ -159,6 +159,79 @@ fn infinite_line_renders() {
|
||||
assert_eq!(pixel(&pixels, size, 128, 128)[3], 255);
|
||||
}
|
||||
|
||||
/// A view at `zoom` and `tilt` that places the document point `target` at the pixel `pixel`.
|
||||
fn deep_view(zoom: f64, tilt: f64, target: Point, pixel: Point) -> Affine {
|
||||
Affine::translate(pixel.to_vec2()) * Affine::rotate(tilt) * Affine::scale(zoom) * Affine::translate(-target.to_vec2())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_zoomed_edges_land_on_the_right_pixel() {
|
||||
let size = UVec2::new(256, 256);
|
||||
let middle = Point::new(128., 128.);
|
||||
let (center, radius) = ((1234.5678, -987.6543), 100.);
|
||||
let path = circle(center, radius);
|
||||
|
||||
// The middle of a segment, where a stroke's fitted outline strays furthest, and outward from the circle by the segment's symmetry
|
||||
let Some(PathSeg::Cubic(segment)) = path.get_seg(2) else {
|
||||
panic!("The circle's second segment is a cubic")
|
||||
};
|
||||
let on_curve = segment.eval(0.5);
|
||||
let outward = (on_curve - Point::from(center)).normalize();
|
||||
|
||||
for zoom in [1e4, 1e7, 1e10] {
|
||||
for tilt in [0., 0.3, std::f64::consts::FRAC_PI_2, 2.4] {
|
||||
// The edge belongs at the middle pixel, with the shape covering what's inward of it
|
||||
for (label, target, stroke) in [("fill", on_curve, None), ("stroke", on_curve + outward, Some(Stroke::new(2.)))] {
|
||||
let view = deep_view(zoom, tilt, target, middle);
|
||||
let Some(pixels) = render(size, |scene| match &stroke {
|
||||
Some(stroke) => scene.stroke(stroke, view, RED, None, &path),
|
||||
None => scene.fill(Fill::NonZero, view, RED, None, &path),
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Walking inward from outside to the first mostly covered pixel
|
||||
let screen_outward = (view * (target + outward / zoom)) - middle;
|
||||
let covered_at = (-40..=40_i32).rev().find(|&distance| {
|
||||
let point = middle + screen_outward * distance as f64;
|
||||
pixel(&pixels, size, point.x as u32, point.y as u32)[3] >= 128
|
||||
});
|
||||
assert!(
|
||||
covered_at.is_some_and(|distance| distance.abs() <= 2),
|
||||
"the {label} edge at zoom {zoom} and tilt {tilt} lands {covered_at:?} pixels outward"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_zoomed_images_blend_their_texels_precisely() {
|
||||
let size = UVec2::new(256, 256);
|
||||
|
||||
// A red texel beside a blue one, sampled as Graphite draws images, viewed a quarter texel past the edge between them
|
||||
let image = peniko::ImageBrush::new(peniko::ImageData {
|
||||
data: [255, 0, 0, 255, 0, 0, 255, 255].to_vec().into(),
|
||||
format: peniko::ImageFormat::Rgba8,
|
||||
alpha_type: peniko::ImageAlphaType::Alpha,
|
||||
width: 2,
|
||||
height: 1,
|
||||
})
|
||||
.with_extend(peniko::Extend::Pad);
|
||||
let origin = Point::new(1234.5678, -987.6543);
|
||||
let target = origin + Vec2::new(1.25, 0.5);
|
||||
|
||||
for zoom in [1e6, 1e8, 1e10] {
|
||||
let view = deep_view(zoom, 0., target, Point::new(128., 128.)) * Affine::translate(origin.to_vec2());
|
||||
let Some(pixels) = render(size, |scene| scene.draw_image(&image, view)) else { return };
|
||||
|
||||
for x in [0, 128, 255] {
|
||||
let red = pixel(&pixels, size, x, 128)[0];
|
||||
assert!(red.abs_diff(64) <= 2, "the image at zoom {zoom} blends to red {red} rather than 64 at pixel {x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nan_points_render_nothing_wrong() {
|
||||
let size = UVec2::new(256, 256);
|
||||
@@ -2119,7 +2192,7 @@ fn svgs_draw_content_with_effects_svg_cannot_express_as_images_the_gpu_renders()
|
||||
resolution: UVec2::splat(32),
|
||||
..Default::default()
|
||||
};
|
||||
let rendered = executor.render_deferred_svg_images(&render.deferred_images, footprint);
|
||||
let rendered = executor.render_deferred_images(&render.deferred_images, footprint);
|
||||
|
||||
// The square comes out gray, with the shadow beside it
|
||||
let [(_, texture)] = &rendered[..] else { panic!("expected one image, got {}", rendered.len()) };
|
||||
@@ -2281,22 +2354,132 @@ fn every_noise_setting_renders_on_the_gpu_like_on_the_cpu() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mandelbrot_set_renders_on_the_gpu_like_on_the_cpu() {
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
fn every_mandelbrot_setting_renders_on_the_gpu_like_on_the_cpu() {
|
||||
use core_types::choice_type::ChoiceTypeStatic;
|
||||
use graphic_types::generator::*;
|
||||
|
||||
// Its whole unit square across the pixels compared, where the GPU's 32-bit floats may escape a few points on the set's edge at another iteration
|
||||
let Some((mismatched, _)) = drawing_differences(&GeneratorPattern::Mandelbrot, 64., glam::DVec2::ZERO) else {
|
||||
return;
|
||||
fn every<T: ChoiceTypeStatic + 'static>() -> impl Iterator<Item = T> {
|
||||
T::list().iter().flat_map(|section| section.iter().map(|(variant, _)| *variant))
|
||||
}
|
||||
|
||||
let GeneratorPattern::Mandelbrot(defaults) = GeneratorPattern::decode(Generator::Mandelbrot, &|_| None) else {
|
||||
unreachable!()
|
||||
};
|
||||
assert!(mismatched <= 40, "{mismatched} pixels differ from the CPU's samples");
|
||||
|
||||
// Pixels a billionth of a unit across, too fine for 32-bit floats, on the edge of the set's second largest bulb
|
||||
let Some((_, worst)) = drawing_differences(&GeneratorPattern::Mandelbrot, 2_f64.powi(30), glam::DVec2::new(0.25, 0.5)) else {
|
||||
// A power-of-two scale, so the tiles' pixels line up with the pixels compared at the power-of-two zooms below
|
||||
let scale = 1024.;
|
||||
|
||||
// Each fractal, interior, and exterior, and every other setting away from its default
|
||||
let base = || MandelbrotSettings { scale, ..defaults.clone() };
|
||||
let variations = (every::<MandelbrotFractal>().map(|fractal| MandelbrotSettings { fractal, ..base() }))
|
||||
.chain(every::<MandelbrotExterior>().map(|exterior| MandelbrotSettings { exterior, ..base() }))
|
||||
.chain(every::<MandelbrotInterior>().map(|interior| MandelbrotSettings { interior, ..base() }))
|
||||
.chain([50., 100.].map(|mandelbrot_to_julia| MandelbrotSettings { mandelbrot_to_julia, ..base() }))
|
||||
.chain([3., 2.5].map(|power| MandelbrotSettings { power, ..base() }))
|
||||
.chain([32, 1000].map(|iterations| MandelbrotSettings { iterations, ..base() }))
|
||||
.chain([MandelbrotSettings {
|
||||
mandelbrot_to_julia: 100.,
|
||||
julia_slice: glam::DVec2::new(0.285, 0.01),
|
||||
..base()
|
||||
}])
|
||||
.chain([0., 50.].map(|mandelbrot_to_julia| MandelbrotSettings {
|
||||
mandelbrot_slice: glam::DVec2::new(0.3, -0.2),
|
||||
mandelbrot_to_julia,
|
||||
..base()
|
||||
}))
|
||||
.chain([MandelbrotExterior::Tendrils, MandelbrotExterior::Rays].map(|exterior| MandelbrotSettings { exterior, frequency: 2, ..base() }));
|
||||
|
||||
// The plane from -2 to 2 across the pixels compared, where 32-bit rounding, and the CPU and each GPU tile following reference orbits of their own, may tip points
|
||||
// on the set's ragged edge into escaping at another iteration
|
||||
for settings in variations {
|
||||
let Some((mismatched, _)) = drawing_differences(&GeneratorPattern::Mandelbrot(settings.clone()), 64. / (4. * scale), glam::DVec2::splat(-2. * scale)) else {
|
||||
return;
|
||||
};
|
||||
assert!(mismatched <= 120, "{mismatched} pixels differ from the CPU's samples with {settings:?}");
|
||||
}
|
||||
|
||||
// Pixels 2^-28 of a unit of the plane across, too fine for 32-bit floats without a reference orbit, on the edge of the set's second largest bulb
|
||||
let Some((_, worst)) = drawing_differences(&GeneratorPattern::Mandelbrot(base()), 2_f64.powi(28) / scale, glam::DVec2::new(-1.25 * scale, 0.)) else {
|
||||
return;
|
||||
};
|
||||
assert!(worst <= 2, "deep zooms differ from the CPU's samples by up to {worst} levels");
|
||||
}
|
||||
|
||||
/// Renders the tile of `pattern`, `pixels` across with its top left corner at `corner` of its space and pixels `texel` units across, into straight-alpha RGBA8 pixels, or `None` without a GPU.
|
||||
fn generator_tile_pixels(pattern: &graphic_types::generator::GeneratorPattern, corner: glam::DVec2, texel: f64, pixels: u32) -> Option<Vec<[u8; 4]>> {
|
||||
let executor = executor()?;
|
||||
let device = &executor.context().device;
|
||||
let _turn = take_turn();
|
||||
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("generator_tile_test"),
|
||||
size: wgpu::Extent3d {
|
||||
width: pixels,
|
||||
height: pixels,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: crate::vello_render::TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
});
|
||||
|
||||
let queue = executor.context().queue.lock();
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("generator_tile_test") });
|
||||
(executor.inner.vello_renderer.generator_passes).render_tile(device, &queue, &mut encoder, &texture, pattern, corner, texel);
|
||||
queue.submit([encoder.finish()]);
|
||||
drop(queue);
|
||||
|
||||
let bytes = executor.read_texture_pixels(&texture).expect("Failed to read back the tile");
|
||||
Some(bytes.as_chunks::<4>().0.to_vec())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_mandelbrot_tiles_follow_their_reference_orbits_like_the_cpu() {
|
||||
use graphic_types::generator::*;
|
||||
use raster_kernels::mandelbrot::MandelbrotSetup;
|
||||
|
||||
let GeneratorPattern::Mandelbrot(defaults) = GeneratorPattern::decode(Generator::Mandelbrot, &|_| None) else {
|
||||
unreachable!()
|
||||
};
|
||||
|
||||
// Pixels 2^-32 of a unit of the plane across, on the edges of the sets with powers of 2 and 2.5 at 256 iterations, and across the seam of the Tricorn's with a power of 2.5
|
||||
// on the negative real axis. Rounding, especially by Direct3D's transcendental functions, may tip a few points on the edges into escaping at another iteration.
|
||||
let views = [
|
||||
(MandelbrotFractal::ClassicMandelbrot, 2., glam::DVec2::new(0.139_355_853_002_853_52, 0.613_550_669_256_420_2)),
|
||||
(MandelbrotFractal::ClassicMandelbrot, 2.5, glam::DVec2::new(0.172_648_565_655_390_94, 0.688_459_272_724_629_5)),
|
||||
(MandelbrotFractal::Tricorn, 2.5, glam::DVec2::new(-0.863_244_635_611_779_1, 0.)),
|
||||
];
|
||||
for (fractal, power, center) in views {
|
||||
let settings = MandelbrotSettings {
|
||||
fractal,
|
||||
power,
|
||||
scale: 1.,
|
||||
..defaults.clone()
|
||||
};
|
||||
let (pixels, texel) = (64, 2_f64.powi(-32));
|
||||
let corner = center - texel * (pixels / 2) as f64;
|
||||
let Some(drawn) = generator_tile_pixels(&GeneratorPattern::Mandelbrot(settings.clone()), corner, texel, pixels) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// The CPU follows the same reference orbit as the tile
|
||||
let setup = MandelbrotSetup::new(&settings);
|
||||
let reference = setup.reference_orbit([corner, corner + texel * pixels as f64], texel).filter(|reference| reference.values.len() >= 2);
|
||||
assert!(reference.is_some(), "{fractal:?} with a power of {power} has no reference orbit");
|
||||
let mismatched = (0..pixels * pixels)
|
||||
.filter(|index| {
|
||||
let point = corner + (glam::DVec2::new((index % pixels) as f64, (index / pixels) as f64) + 0.5) * texel;
|
||||
let sampled = (setup.sample(point, reference.as_ref(), false).clamp(0., 1.) * 255.).round() as u8;
|
||||
drawn[*index as usize][0].abs_diff(sampled) > 2
|
||||
})
|
||||
.count();
|
||||
assert!(mismatched <= 128, "{mismatched} pixels differ from the CPU's samples for {fractal:?} with a power of {power}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_tiles_are_reused_across_a_pan() {
|
||||
let Some(executor) = executor() else { return };
|
||||
@@ -2320,3 +2503,136 @@ fn generator_tiles_are_reused_across_a_pan() {
|
||||
let panned = tiles(&canvas) - first;
|
||||
assert!(panned < first, "panning renders only the tiles newly in view, not all {first} again (rendered {panned})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_generator_tiles_take_over_the_textures_of_freed_ones() {
|
||||
use graphic_types::generator::{GeneratorPattern, NoiseSettings};
|
||||
|
||||
let Some(executor) = executor() else { return };
|
||||
let _turn = take_turn();
|
||||
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
|
||||
let tile_textures = |canvas: &crate::VelloCanvas| -> Vec<wgpu::Texture> {
|
||||
(canvas.images.textures.iter())
|
||||
.filter(|(key, _)| matches!(key, super::ImageKey::GeneratorTile(_)))
|
||||
.map(|(_, image_texture)| image_texture.texture.clone())
|
||||
.collect()
|
||||
};
|
||||
|
||||
let mut canvas = crate::VelloCanvas::default();
|
||||
let draw = |canvas: &mut crate::VelloCanvas, seed: i64| {
|
||||
let mut scene = VelloSceneBuilder::new(512, 512, Affine::IDENTITY, max_texture_size);
|
||||
scene.draw_generator(&GeneratorPattern::Noise(NoiseSettings { seed, ..noise_settings() }), Affine::scale(2.));
|
||||
executor.render_vello_scene_on_canvas(canvas, scene).unwrap();
|
||||
};
|
||||
|
||||
// The first pattern's tiles, freed once another is drawn for long enough
|
||||
draw(&mut canvas, 1);
|
||||
let freed = tile_textures(&canvas);
|
||||
for _ in 0..super::UNUSED_IMAGE_RENDER_LIMIT {
|
||||
draw(&mut canvas, 2);
|
||||
}
|
||||
|
||||
// The textures in use since the first pattern was freed are the second's and the third's, which takes over the first's
|
||||
let second = tile_textures(&canvas);
|
||||
draw(&mut canvas, 3);
|
||||
let third: Vec<_> = tile_textures(&canvas).into_iter().filter(|texture| !second.contains(texture)).collect();
|
||||
assert!(
|
||||
third.len() == freed.len() && third.iter().all(|texture| freed.contains(texture)),
|
||||
"the third pattern's tiles render into the textures of the first's"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_glyph_runs_match_outlined_text() {
|
||||
use core_types::list::{ATTR_APPEARANCE, Item, List};
|
||||
use core_types::{ATTR_FONT_SIZE, ATTR_LETTER_TILT, ATTR_MAX_WIDTH, ATTR_TEXT_ALIGN, ATTR_TRANSFORM};
|
||||
use graphic_types::{Appearance, Coverage, Graphic};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(320, 120);
|
||||
|
||||
// Tilted, and wrapped into a justified last line so blank glyphs take the extra spacing
|
||||
let text = Item::new_from_element("Glyph runs\nspace out".to_string())
|
||||
.with_attribute(ATTR_FONT_SIZE, 36.)
|
||||
.with_attribute(ATTR_LETTER_TILT, 12.)
|
||||
.with_attribute(ATTR_MAX_WIDTH, 300.)
|
||||
.with_attribute(ATTR_TEXT_ALIGN, text_nodes::TextAlign::JustifyAll)
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(glam::DVec2::new(10., 10.)));
|
||||
|
||||
let mut outlined = text_nodes::shape_text_item(&text, false).expect("the fallback font shapes the text");
|
||||
let black_fill = Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(core_types::Color::BLACK)));
|
||||
for index in 0..outlined.len() {
|
||||
outlined.set_attribute(ATTR_APPEARANCE, index, black_fill.clone());
|
||||
}
|
||||
let text = List::new_from_item(text);
|
||||
|
||||
let render_params = RenderParams::default();
|
||||
let Some(native) = render(size, |scene| {
|
||||
assert!(scene.can_draw_glyphs(), "renders through the executor draw glyph runs natively");
|
||||
text.render_to_vello(scene, DAffine2::IDENTITY, &render_params);
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let Some(reference) = render(size, |scene| outlined.render_to_vello(scene, DAffine2::IDENTITY, &render_params)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let coverage = |pixels: &[[u8; 4]]| pixels.iter().filter(|pixel| pixel[3] > 127).count();
|
||||
assert!(coverage(&reference) > 500, "the reference draws the text");
|
||||
|
||||
// Both fill the same outlines, so only antialiasing along their edges may differ
|
||||
let differing = native.iter().zip(&reference).filter(|(a, b)| a[3].abs_diff(b[3]) > 64).count();
|
||||
assert!(differing * 50 < coverage(&reference), "{differing} pixels differ out of {} covered", coverage(&reference));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_glyph_runs_paint_like_outlined_text() {
|
||||
use core_types::list::{ATTR_APPEARANCE, Item, List};
|
||||
use core_types::{ATTR_FONT_SIZE, ATTR_TRANSFORM};
|
||||
use graphic_types::appearance::{CoverPlacement, stamp_coverage};
|
||||
use graphic_types::vector_types::gradient::Gradient;
|
||||
use graphic_types::vector_types::vector::style::Stroke as VectorStroke;
|
||||
use graphic_types::{Appearance, Coverage, Graphic};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(320, 120);
|
||||
|
||||
// Scaled evenly, so the stroke's width is measured in a space the glyphs reach by a uniform scale
|
||||
let mut text = Item::new_from_element("Painted".to_string())
|
||||
.with_attribute(ATTR_FONT_SIZE, 40.)
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale_angle_translation(glam::DVec2::splat(1.5), 0.1, glam::DVec2::new(10., 5.)));
|
||||
|
||||
let gradient_placement = DAffine2::from_scale_angle_translation(glam::DVec2::new(160., 50.), 0., glam::DVec2::ZERO);
|
||||
let gradient = Item::new_from_element(Gradient::from(vec![
|
||||
core_types::Color::from_rgbaf32_unchecked(1., 0., 0., 1.),
|
||||
core_types::Color::from_rgbaf32_unchecked(0., 0., 1., 1.),
|
||||
]))
|
||||
.with_attribute(ATTR_TRANSFORM, gradient_placement);
|
||||
stamp_coverage(&mut text, Coverage::new_fill(), Graphic::Gradient(gradient), CoverPlacement::Above);
|
||||
|
||||
let stroke = VectorStroke { weight: 3., ..Default::default() };
|
||||
let stroke_paint = Graphic::ColorList(List::new_from_element(core_types::Color::from_rgbaf32_unchecked(0., 0.6, 0., 1.)));
|
||||
stamp_coverage(&mut text, Coverage::new_stroke(&stroke), stroke_paint, CoverPlacement::Above);
|
||||
|
||||
let appearance: Appearance = text.attribute_cloned_or_default(ATTR_APPEARANCE);
|
||||
let mut outlined = text_nodes::shape_text_item(&text, false).expect("the fallback font shapes the text");
|
||||
for index in 0..outlined.len() {
|
||||
outlined.set_attribute(ATTR_APPEARANCE, index, appearance.clone());
|
||||
}
|
||||
let text = List::new_from_item(text);
|
||||
|
||||
let render_params = RenderParams::default();
|
||||
let Some(native) = render(size, |scene| text.render_to_vello(scene, DAffine2::IDENTITY, &render_params)) else {
|
||||
return;
|
||||
};
|
||||
let Some(reference) = render(size, |scene| outlined.render_to_vello(scene, DAffine2::IDENTITY, &render_params)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let covered = reference.iter().filter(|pixel| pixel[3] > 127).count();
|
||||
assert!(covered > 500, "the reference draws the text");
|
||||
|
||||
// Strokes expand per glyph rather than along the compound outline, so only antialiasing along their edges may differ
|
||||
let differing = (native.iter().zip(&reference)).filter(|(a, b)| a.iter().zip(b.iter()).any(|(a, b)| a.abs_diff(*b) > 64)).count();
|
||||
assert!(differing * 50 < covered, "{differing} pixels differ out of {covered} covered");
|
||||
}
|
||||
@@ -601,7 +601,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
Some(path) => quote!(Some(#path(#(&#declared_field_names),*))),
|
||||
None => quote!(None),
|
||||
};
|
||||
let keep_previous = attributes.flags.keep_previous;
|
||||
let data_clones = data_field_names.iter().map(|name| quote!(let #name = self.#name.clone();));
|
||||
let landed_call = landed(quote!(self::#fn_name(__context #(, &#data_field_names)* #(, #regular_field_names)*).await));
|
||||
quote! {
|
||||
@@ -633,7 +632,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let __runtime = _runtime.element().clone();
|
||||
let __context = __input.clone();
|
||||
#(#data_clones)*
|
||||
let __state = self.slots.resolve(__key, &__runtime, __source, __placeholder, #keep_previous, move || async move { #landed_call });
|
||||
let __state = self.slots.resolve(__key, &__runtime, __source, __placeholder, move || async move { #landed_call });
|
||||
__cell.merge(__state)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,8 +52,6 @@ pub(crate) struct NodeFlags {
|
||||
pub(crate) skip_impl: bool,
|
||||
/// Whether the node refuses placeholder data.
|
||||
pub(crate) no_partial: bool,
|
||||
/// Whether a pending evaluation returns the latest landed output instead of the placeholder.
|
||||
pub(crate) keep_previous: bool,
|
||||
/// Set on the `Destructure` derive's generated extractor nodes, which take the struct rather than an `Item` or `List`. Not parsed from source.
|
||||
pub(crate) destructure_extractor: bool,
|
||||
}
|
||||
@@ -600,18 +598,13 @@ impl Parse for NodeFnAttributes {
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., no_partial, ...)]
|
||||
"no_partial" => set_flag(&mut flags.no_partial, meta, "no_partial")?,
|
||||
// Makes a pending evaluation return the latest landed output instead of the placeholder
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., keep_previous, ...)]
|
||||
"keep_previous" => set_flag(&mut flags.keep_previous, meta, "keep_previous")?,
|
||||
_ => {
|
||||
return Err(Error::new_spanned(
|
||||
meta,
|
||||
indoc!(
|
||||
r#"
|
||||
Unsupported attribute in `node`.
|
||||
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', 'keep_previous', and 'version'.
|
||||
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
|
||||
Example usage:
|
||||
#[node_macro::node(..., name("Test Node"), ...)]
|
||||
"#
|
||||
|
||||
@@ -459,9 +459,6 @@ fn validate_async(parsed: &ParsedNodeFn) {
|
||||
if parsed.attributes.placeholder.is_some() && !parsed.is_async {
|
||||
emit_error!(parsed.fn_name.span(), "Only an async node can have a `placeholder`");
|
||||
}
|
||||
if parsed.attributes.flags.keep_previous && !parsed.is_async {
|
||||
emit_error!(parsed.fn_name.span(), "Only an async node can have `keep_previous`");
|
||||
}
|
||||
}
|
||||
|
||||
/// The arguments that aren't parameters, which are `#[data]` state and the inputs the compiler fills in, go after the parameters.
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{ATTR_EDITOR_FOOTPRINT_AREAS, ATTR_TRANSFORM, CloneVarArgs, Color, Context, ExtractAll, ExtractVarArgs, InjectFootprint, Interrupt, OwnedContextImpl};
|
||||
use core_types::list::Item;
|
||||
use core_types::{Color, ExtractVarArgs};
|
||||
use core_types::{Ctx, ExtractIndex, ExtractPosition};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
use graphic_types::{Artboard, Generator, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Graphic, Vector};
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ReadContextError {
|
||||
@@ -97,96 +96,6 @@ fn read_index(
|
||||
Ok(Item::new_from_element(at_loop_level(indices, *loop_level.element())? as f64))
|
||||
}
|
||||
|
||||
/// Evaluates the content with a fixed footprint in place of the one requested by the renderer, so the result no longer depends on the view.
|
||||
#[node_macro::node(category("Data: Context"))]
|
||||
fn bake_footprint<T>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + InjectFootprint,
|
||||
#[implementations(
|
||||
Context -> Item<bool>,
|
||||
Context -> Item<i64>,
|
||||
Context -> Item<f64>,
|
||||
Context -> Item<String>,
|
||||
Context -> Item<DAffine2>,
|
||||
Context -> Item<Footprint>,
|
||||
Context -> Item<DVec2>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> List<String>,
|
||||
Context -> List<f64>,
|
||||
Context -> List<DVec2>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
value: impl Node<Context<'static>, Output = T>,
|
||||
/// The area of the document and the resolution the content is evaluated at.
|
||||
#[default(0., 0., 1000., 1000.)]
|
||||
footprint: Item<Footprint>,
|
||||
#[node_path] node_path: Item<NodeIdPath>,
|
||||
) -> Result<T, Interrupt>
|
||||
where
|
||||
T: RecordFootprintArea,
|
||||
{
|
||||
let area = footprint.into_element();
|
||||
let unit_square_to_pixels = DAffine2::from_scale(area.resolution.as_dvec2());
|
||||
let footprint = Footprint {
|
||||
transform: unit_square_to_pixels * area.transform.inverse(),
|
||||
..area
|
||||
};
|
||||
|
||||
let new_context = OwnedContextImpl::from(ctx).with_footprint(footprint);
|
||||
let mut content = value.eval(Some(new_context.into()))?;
|
||||
|
||||
content.record_footprint_area(node_path.element(), area.transform);
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
/// Content whose items can record the footprint areas they were evaluated in.
|
||||
pub trait RecordFootprintArea {
|
||||
/// Appends the area of the node at `node_path` to each item. `area` maps the unit square into the space the items are placed in.
|
||||
fn record_footprint_area(&mut self, node_path: &NodeIdPath, area: DAffine2);
|
||||
}
|
||||
|
||||
impl<T> RecordFootprintArea for Item<T> {
|
||||
fn record_footprint_area(&mut self, node_path: &NodeIdPath, area: DAffine2) {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let Some(footprint_area) = footprint_area_row(node_path, item_transform, area) else { return };
|
||||
|
||||
self.attribute_mut_or_insert_default::<List<NodeIdPath>>(ATTR_EDITOR_FOOTPRINT_AREAS).push(footprint_area);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> RecordFootprintArea for List<T> {
|
||||
fn record_footprint_area(&mut self, node_path: &NodeIdPath, area: DAffine2) {
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let Some(footprint_area) = footprint_area_row(node_path, item_transform, area) else { continue };
|
||||
|
||||
self.with_attribute_mut_or_default::<List<NodeIdPath>, _, _>(ATTR_EDITOR_FOOTPRINT_AREAS, index, |footprint_areas| footprint_areas.push(footprint_area));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The row recording the area relative to the item, so it follows the transforms later applied to the item.
|
||||
fn footprint_area_row(node_path: &NodeIdPath, item_transform: DAffine2, area: DAffine2) -> Option<Item<NodeIdPath>> {
|
||||
if item_transform.matrix2.determinant() == 0. {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Item::new_from_element(node_path.clone()).with_attribute(ATTR_TRANSFORM, item_transform.inverse() * area))
|
||||
}
|
||||
|
||||
/// The value of the loop `level` loops out from the innermost one, given the loops' values from the innermost outwards.
|
||||
fn at_loop_level<T>(levels: impl Iterator<Item = T>, level: i64) -> Result<T, ReadContextError> {
|
||||
let levels: Vec<T> = levels.collect();
|
||||
|
||||
@@ -46,6 +46,7 @@ core-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
svg-convert = { workspace = true }
|
||||
blending-nodes = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
transform-nodes = { workspace = true }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use core_types::Ctx;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::ops::ConvertAsync;
|
||||
use core_types::transform::Footprint;
|
||||
@@ -11,7 +11,6 @@ pub use graph_craft::application_io::*;
|
||||
pub use graph_craft::document::value::RenderOutputType;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub use graphene_canvas_utils as canvas_utils;
|
||||
use graphene_core::context::RecordFootprintArea;
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
use graphic_types::raster_types::{Image, ImageError};
|
||||
@@ -219,8 +218,19 @@ fn bytes_to_image(_: impl Ctx, data: Item<Resource>) -> Result<Item<Raster<CPU>>
|
||||
Ok(Item::new_from_element(Raster::new_cpu(image)))
|
||||
}
|
||||
|
||||
/// Converts SVG to graphics.
|
||||
#[node_macro::node(category("Graphic"), icon("NodeBytesToImage"), name("SVG to Graphic"))]
|
||||
fn svg_to_graphic(_: impl Ctx, #[name("SVG")] svg: Item<String>) -> Result<List<Graphic>, svg_convert::Error> {
|
||||
let svg = svg.into_element();
|
||||
if svg.trim().is_empty() {
|
||||
return Ok(List::new());
|
||||
}
|
||||
|
||||
svg_convert::convert(&svg, &svg_convert::Options::default())
|
||||
}
|
||||
|
||||
/// Renders a view of the input graphics within an area defined by the *Footprint*, producing a raster image.
|
||||
#[node_macro::node(category("Raster"), icon("NodeRasterize"), placeholder = pending_raster, keep_previous, version(2))]
|
||||
#[node_macro::node(category("Raster"), icon("NodeRasterize"), placeholder = pending_raster)]
|
||||
async fn rasterize(
|
||||
_: impl Ctx,
|
||||
/// The graphics to render as an image.
|
||||
@@ -229,13 +239,8 @@ async fn rasterize(
|
||||
#[default(0., 0., 1000., 1000.)]
|
||||
footprint: Item<Footprint>,
|
||||
#[scope(wgpu_executor::IDENTIFIER)] executor: Item<::wgpu_executor::WgpuExecutor>,
|
||||
#[node_path] node_path: Item<NodeIdPath>,
|
||||
) -> Result<List<Raster<CPU>>, NodeError> {
|
||||
let footprint = footprint.into_element();
|
||||
let mut raster = rasterize_with_vello(data, footprint, executor.into_element()).await?;
|
||||
|
||||
raster.record_footprint_area(node_path.element(), footprint.transform);
|
||||
Ok(raster)
|
||||
rasterize_with_vello(data, footprint.into_element(), executor.into_element()).await
|
||||
}
|
||||
|
||||
async fn rasterize_with_vello(data: List<Graphic>, footprint: Footprint, executor: ::wgpu_executor::WgpuExecutor) -> Result<List<Raster<CPU>>, NodeError> {
|
||||
@@ -265,7 +270,7 @@ async fn rasterize_with_vello(data: List<Graphic>, footprint: Footprint, executo
|
||||
))
|
||||
}
|
||||
|
||||
fn pending_raster(_data: &List<Graphic>, _footprint: &Item<Footprint>, _executor: &Item<::wgpu_executor::WgpuExecutor>, _node_path: &Item<NodeIdPath>) -> List<Raster<CPU>> {
|
||||
fn pending_raster(_data: &List<Graphic>, _footprint: &Item<Footprint>, _executor: &Item<::wgpu_executor::WgpuExecutor>) -> List<Raster<CPU>> {
|
||||
List::new()
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ use core_types::list::Item;
|
||||
use core_types::math::bbox::AxisAlignedBbox;
|
||||
use core_types::transform::{Footprint, RenderQuality, Transform};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Generations, NodeError, OwnedContextImpl, Poll};
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use glam::{DAffine2, DVec2, I64Vec2, UVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -17,10 +17,11 @@ pub const TILE_SIZE: u32 = 256;
|
||||
pub const MAX_CACHE_MEMORY_BYTES: usize = 512 * 1024 * 1024;
|
||||
const BYTES_PER_PIXEL: usize = 4;
|
||||
|
||||
/// A tile in the grid laid out in device pixels from the document's origin, which deep zoom puts too far away to count in 32 bits.
|
||||
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
|
||||
pub struct TileCoord {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub x: i64,
|
||||
pub y: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -126,10 +127,10 @@ pub struct CacheQuery {
|
||||
|
||||
fn bounds_to_tiles(bounds: &AxisAlignedBbox) -> Vec<TileCoord> {
|
||||
let tile_size = TILE_SIZE as f64;
|
||||
let tile_start_x = (bounds.start.x / tile_size).floor() as i32;
|
||||
let tile_start_y = (bounds.start.y / tile_size).floor() as i32;
|
||||
let tile_end_x = (bounds.end.x / tile_size).ceil() as i32;
|
||||
let tile_end_y = (bounds.end.y / tile_size).ceil() as i32;
|
||||
let tile_start_x = (bounds.start.x / tile_size).floor() as i64;
|
||||
let tile_start_y = (bounds.start.y / tile_size).floor() as i64;
|
||||
let tile_end_x = (bounds.end.x / tile_size).ceil() as i64;
|
||||
let tile_end_y = (bounds.end.y / tile_size).ceil() as i64;
|
||||
|
||||
let mut tiles = Vec::new();
|
||||
for y in tile_start_y..tile_end_y {
|
||||
@@ -227,7 +228,7 @@ fn tile_rectangles(tiles: &[TileCoord]) -> Vec<RenderRegion> {
|
||||
sorted.dedup();
|
||||
|
||||
// Each row's runs of adjacent tiles, as their row and first and last columns
|
||||
let mut runs: Vec<(i32, i32, i32)> = Vec::new();
|
||||
let mut runs: Vec<(i64, i64, i64)> = Vec::new();
|
||||
for tile in sorted {
|
||||
match runs.last_mut() {
|
||||
Some((row, _, last)) if *row == tile.y && *last + 1 == tile.x => *last = tile.x,
|
||||
@@ -236,7 +237,7 @@ fn tile_rectangles(tiles: &[TileCoord]) -> Vec<RenderRegion> {
|
||||
}
|
||||
|
||||
// The top and bottom rows of the rectangle each run of columns extends, which closes once a row lacks that run
|
||||
let mut open: HashMap<(i32, i32), (i32, i32)> = HashMap::new();
|
||||
let mut open: HashMap<(i64, i64), (i64, i64)> = HashMap::new();
|
||||
let mut rectangles = Vec::new();
|
||||
for (row, first, last) in runs {
|
||||
match open.get_mut(&(first, last)) {
|
||||
@@ -463,11 +464,11 @@ fn render_missing_region<F>(
|
||||
where
|
||||
F: Fn(Context<'static>) -> Poll<Item<RenderOutput>>,
|
||||
{
|
||||
let min_tile = region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
|
||||
let max_tile = region.tiles.iter().fold(IVec2::new(i32::MIN, i32::MIN), |acc, t| acc.max(IVec2::new(t.x, t.y)));
|
||||
let min_tile = region.tiles.iter().fold(I64Vec2::MAX, |acc, t| acc.min(I64Vec2::new(t.x, t.y)));
|
||||
let max_tile = region.tiles.iter().fold(I64Vec2::MIN, |acc, t| acc.max(I64Vec2::new(t.x, t.y)));
|
||||
|
||||
let tile_count = (max_tile - min_tile) + IVec2::ONE;
|
||||
let region_pixel_size = (tile_count * TILE_SIZE as i32).as_uvec2();
|
||||
let tile_count = (max_tile - min_tile) + I64Vec2::ONE;
|
||||
let region_pixel_size = (tile_count * TILE_SIZE as i64).as_uvec2();
|
||||
|
||||
let tile_global_offset = min_tile.as_dvec2() * TILE_SIZE as f64 + *viewport_origin_offset;
|
||||
let region_transform = DAffine2::from_translation(-tile_global_offset) * *viewport_transform;
|
||||
@@ -567,24 +568,13 @@ struct RegionPlacement {
|
||||
}
|
||||
|
||||
fn region_placement(region: &CachedRegion, device_origin_offset: &DVec2, output_resolution: UVec2) -> Option<RegionPlacement> {
|
||||
let min_tile = region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
|
||||
let min_tile = region.tiles.iter().fold(I64Vec2::MAX, |acc, t| acc.min(I64Vec2::new(t.x, t.y)));
|
||||
|
||||
// Convert global tile position to physical pixel offset in the output texture
|
||||
let offset_pixels = min_tile * TILE_SIZE as i32 + device_origin_offset.round().as_ivec2();
|
||||
let offset_pixels = min_tile * TILE_SIZE as i64 + device_origin_offset.round().as_i64vec2();
|
||||
|
||||
let (source_x, destination_x, width) = if offset_pixels.x >= 0 {
|
||||
(0, offset_pixels.x as u32, region.size.x.min(output_resolution.x.saturating_sub(offset_pixels.x as u32)))
|
||||
} else {
|
||||
let skip = (-offset_pixels.x) as u32;
|
||||
(skip, 0, region.size.x.saturating_sub(skip).min(output_resolution.x))
|
||||
};
|
||||
|
||||
let (source_y, destination_y, height) = if offset_pixels.y >= 0 {
|
||||
(0, offset_pixels.y as u32, region.size.y.min(output_resolution.y.saturating_sub(offset_pixels.y as u32)))
|
||||
} else {
|
||||
let skip = (-offset_pixels.y) as u32;
|
||||
(skip, 0, region.size.y.saturating_sub(skip).min(output_resolution.y))
|
||||
};
|
||||
let (source_x, destination_x, width) = span_placement(offset_pixels.x, region.size.x, output_resolution.x);
|
||||
let (source_y, destination_y, height) = span_placement(offset_pixels.y, region.size.y, output_resolution.y);
|
||||
|
||||
(width > 0 && height > 0).then_some(RegionPlacement {
|
||||
source: UVec2::new(source_x, source_y),
|
||||
@@ -593,6 +583,16 @@ fn region_placement(region: &CachedRegion, device_origin_offset: &DVec2, output_
|
||||
})
|
||||
}
|
||||
|
||||
/// Along one axis, where the part of a region starting `offset` pixels into the output lands: its start within the region, its start within the output, and its length.
|
||||
fn span_placement(offset: i64, region_length: u32, output_length: u32) -> (u32, u32, u32) {
|
||||
let (region_length, output_length) = (region_length as i64, output_length as i64);
|
||||
|
||||
let start = offset.clamp(0, output_length);
|
||||
let end = (offset + region_length).clamp(start, output_length);
|
||||
|
||||
((start - offset).clamp(0, region_length) as u32, start as u32, (end - start) as u32)
|
||||
}
|
||||
|
||||
/// Renders an output too large for one texture into RGBA8 pixels on the CPU, rendering one region at a time and copying it in, so only one region's texture is in use at a time.
|
||||
fn render_regions_to_buffer<F>(
|
||||
viewport_bounds_device: &AxisAlignedBbox,
|
||||
@@ -698,4 +698,33 @@ mod tests {
|
||||
assert_eq!(region.tiles.len(), (size.x * size.y) as usize);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regions_far_from_the_document_origin_fill_the_output() {
|
||||
let resolution = UVec2::new(1000, 800);
|
||||
|
||||
// The document's origin billions, then trillions, of pixels from the view, as deep zoom places it
|
||||
for device_origin_offset in [DVec2::new(-3e9 + 0.25, 5e9), DVec2::new(1e13, -7e12 - 0.5)] {
|
||||
let viewport_bounds = AxisAlignedBbox {
|
||||
start: -device_origin_offset,
|
||||
end: resolution.as_dvec2() - device_origin_offset,
|
||||
};
|
||||
|
||||
// The regions' placements don't overlap, so they fill the output exactly when their areas add up to its own
|
||||
let mut covered = 0;
|
||||
for region in group_into_regions(&bounds_to_tiles(&viewport_bounds), 4096) {
|
||||
let region = CachedRegion {
|
||||
output: Poll::Pending,
|
||||
size: tiles_bounds(®ion.tiles).size().as_uvec2(),
|
||||
tiles: region.tiles,
|
||||
last_access: 0,
|
||||
memory_size: 0,
|
||||
};
|
||||
if let Some(placement) = region_placement(®ion, &device_origin_offset, resolution) {
|
||||
covered += placement.size.x as u64 * placement.size.y as u64;
|
||||
}
|
||||
}
|
||||
assert_eq!(covered, resolution.x as u64 * resolution.y as u64, "with the document's origin offset by {device_origin_offset}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
mod svg_readback;
|
||||
mod readback;
|
||||
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
@@ -9,10 +9,10 @@ use graphene_application_io::{ExportFormat, RenderConfig};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use readback::ReadbackSlot;
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
|
||||
use std::sync::Arc;
|
||||
use svg_readback::SvgReadbackSlot;
|
||||
use vector_types::Gradient;
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
@@ -23,6 +23,8 @@ pub enum RenderIntermediateType {
|
||||
Svg(Arc<SvgRenderOutput>),
|
||||
/// The content itself, for content that draws only the part of it in view, drawn as SVG at each render for its view
|
||||
SvgInView(Arc<dyn Render + Send + Sync>),
|
||||
/// The content itself, drawn onto a PDF page sized at each render
|
||||
Pdf(Arc<dyn Render + Send + Sync>),
|
||||
}
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
pub struct RenderIntermediate {
|
||||
@@ -62,6 +64,10 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
ty: RenderIntermediateType::Vello(Arc::new(data)),
|
||||
metadata,
|
||||
},
|
||||
RenderOutputTypeRequest::Pdf => RenderIntermediate {
|
||||
ty: RenderIntermediateType::Pdf(Arc::new(data)),
|
||||
metadata,
|
||||
},
|
||||
RenderOutputTypeRequest::Svg => {
|
||||
let render_params = RenderParams {
|
||||
view_wanted: Default::default(),
|
||||
@@ -90,7 +96,7 @@ fn render(
|
||||
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: impl Node<Context<'static>, Output = Item<WgpuExecutor>>,
|
||||
#[scope("runtime")] runtime: Item<RuntimeHandle>,
|
||||
#[source_id] source: Item<SourceId>,
|
||||
#[data] svg_readback: SvgReadbackSlot,
|
||||
#[data] readback: ReadbackSlot,
|
||||
) -> Poll<Item<RenderOutput>> {
|
||||
let footprint = ctx.footprint();
|
||||
let render_params = ctx
|
||||
@@ -131,11 +137,11 @@ fn render(
|
||||
assert!(output.svg_defs.is_empty());
|
||||
|
||||
let executor = executor.eval(&Context::default()).value().map(Item::into_element);
|
||||
svg_readback.poll(output, *footprint, executor, runtime.element(), *source.element())
|
||||
readback.poll(output, *footprint, executor, runtime.element(), *source.element())
|
||||
}
|
||||
(RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => {
|
||||
// The latest SVG render isn't needed anymore, and a finished one holds a whole SVG export
|
||||
svg_readback.clear();
|
||||
readback.clear();
|
||||
|
||||
let (executor, executor_partial, executor_error) = match executor.eval(&Context::default()) {
|
||||
Poll::Final(executor) => (executor.into_element(), false, None),
|
||||
@@ -169,6 +175,14 @@ fn render(
|
||||
(false, None) => Poll::Final(texture),
|
||||
}
|
||||
}
|
||||
(RenderOutputTypeRequest::Pdf, RenderIntermediateType::Pdf(content)) => {
|
||||
let logical_transform = glam::DAffine2::from_scale(glam::DVec2::splat(1.0 / render_params.scale)) * footprint.transform;
|
||||
let logical_resolution = footprint.resolution.as_dvec2() / render_params.scale;
|
||||
let page = rendering::pdf::PdfPage::new(logical_resolution, logical_transform, render_params.scale);
|
||||
|
||||
let executor = executor.eval(&Context::default()).value().map(Item::into_element);
|
||||
readback.poll_pdf(content, page, render_params.clone(), executor, runtime.element(), *source.element())
|
||||
}
|
||||
_ => unreachable!("Render node did not receive its requested data type"),
|
||||
};
|
||||
|
||||
@@ -181,7 +195,7 @@ fn create_context(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync,
|
||||
data: impl Node<Context<'static>, Output = Item<RenderOutput>>,
|
||||
) -> Result<Item<RenderOutput>, Interrupt> {
|
||||
let render_config = ctx.vararg(0).ok().and_then(|config| config.downcast_ref::<RenderConfig>()).copied().unwrap_or_else(|| {
|
||||
let render_config = ctx.vararg(0).ok().and_then(|config| config.downcast_ref::<RenderConfig>()).cloned().unwrap_or_else(|| {
|
||||
log::error!("The boundary context is missing its render config vararg");
|
||||
RenderConfig::default()
|
||||
});
|
||||
@@ -189,6 +203,7 @@ fn create_context(
|
||||
let render_output_type = match render_config.export_format {
|
||||
ExportFormat::Svg => RenderOutputTypeRequest::Svg,
|
||||
ExportFormat::Raster => RenderOutputTypeRequest::Vello,
|
||||
ExportFormat::Pdf { .. } => RenderOutputTypeRequest::Pdf,
|
||||
};
|
||||
|
||||
let logical_viewport = render_config.viewport;
|
||||
@@ -200,12 +215,16 @@ fn create_context(
|
||||
// Rounded up so no image is sent below its on-screen resolution, with a tolerance for float noise at exact powers of two
|
||||
let canvas_image_scale = match render_output_type {
|
||||
RenderOutputTypeRequest::Svg => (footprint.scale_magnitudes().max_element().log2() - 1e-9).ceil().exp2(),
|
||||
RenderOutputTypeRequest::Vello => 0.,
|
||||
RenderOutputTypeRequest::Vello | RenderOutputTypeRequest::Pdf => 0.,
|
||||
};
|
||||
|
||||
let render_params = RenderParams {
|
||||
render_mode: render_config.render_mode,
|
||||
for_export: render_config.for_export,
|
||||
// Exported SVG files keep their text as text, while the canvas and other SVG renders draw it as outlines
|
||||
embed_fonts: render_config.for_export && matches!(render_output_type, RenderOutputTypeRequest::Svg),
|
||||
artboards_as_pages: matches!(render_config.export_format, ExportFormat::Pdf { artboards_as_pages: true }),
|
||||
export_metadata: render_config.metadata.clone().map(Arc::new),
|
||||
render_output_type,
|
||||
scale: render_config.scale,
|
||||
viewport_zoom: Some(logical_viewport.scale_magnitudes().x),
|
||||
|
||||
+139
-24
@@ -1,33 +1,35 @@
|
||||
use core_types::WasmNotSend;
|
||||
use core_types::runtime::Runtime;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{CacheHash, Poll, RuntimeHandle, SourceId};
|
||||
use futures::future::{AbortHandle, Abortable};
|
||||
use graph_craft::document::value::RenderOutputType;
|
||||
use rendering::SvgRenderOutput;
|
||||
use rendering::pdf::{PdfPage, PdfRasters, render_pdf_document};
|
||||
use rendering::{Render, RenderParams, SvgRenderOutput};
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
/// The latest SVG render that needs maps and images from the GPU, kept across the render node's evaluations while a task reads them back.
|
||||
/// The latest SVG or PDF render that needs maps and images from the GPU, kept across the render node's evaluations while a task reads them back.
|
||||
/// A render of other content or for another view replaces it, cancelling the readback still underway for the one it replaced.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct SvgReadbackSlot(Arc<Mutex<Option<SvgReadback>>>);
|
||||
pub struct ReadbackSlot(Arc<Mutex<Option<Readback>>>);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SvgReadback {
|
||||
struct Readback {
|
||||
key: u64,
|
||||
finished: Option<RenderOutputType>,
|
||||
task: AbortHandle,
|
||||
}
|
||||
|
||||
impl Drop for SvgReadback {
|
||||
impl Drop for Readback {
|
||||
fn drop(&mut self) {
|
||||
self.task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
impl SvgReadbackSlot {
|
||||
fn lock(&self) -> MutexGuard<'_, Option<SvgReadback>> {
|
||||
impl ReadbackSlot {
|
||||
fn lock(&self) -> MutexGuard<'_, Option<Readback>> {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
@@ -53,33 +55,105 @@ impl SvgReadbackSlot {
|
||||
footprint.cache_hash(&mut hasher);
|
||||
let key = hasher.finish();
|
||||
|
||||
if self.lock().as_ref().is_none_or(|readback| readback.key != key) {
|
||||
let Some(executor) = executor else {
|
||||
return Poll::Final(RenderOutputType::Svg { svg, image_data });
|
||||
};
|
||||
let partial = RenderOutputType::Svg {
|
||||
svg: svg.clone(),
|
||||
image_data: image_data.clone(),
|
||||
};
|
||||
self.poll_readback(key, partial, runtime, source, || {
|
||||
let executor = executor?;
|
||||
let effect_maps = executor.render_effect_maps(&output.effect_maps, footprint);
|
||||
let deferred_images = executor.render_deferred_svg_images(&output.deferred_images, footprint);
|
||||
let deferred_images = executor.render_deferred_images(&output.deferred_images, footprint);
|
||||
if effect_maps.is_empty() && deferred_images.is_empty() {
|
||||
self.clear();
|
||||
return Poll::Final(RenderOutputType::Svg { svg, image_data });
|
||||
return None;
|
||||
}
|
||||
|
||||
let (task, registration) = AbortHandle::new_pair();
|
||||
*self.lock() = Some(SvgReadback { key, finished: None, task });
|
||||
|
||||
let (mut svg, mut image_data) = (svg.clone(), image_data.clone());
|
||||
let readback = async move {
|
||||
let (mut svg, mut image_data) = (svg, image_data);
|
||||
Some(async move {
|
||||
executor.resolve_effect_maps(&mut svg, effect_maps).await;
|
||||
executor.resolve_deferred_svg_images(&mut svg, &mut image_data, deferred_images).await;
|
||||
RenderOutputType::Svg { svg, image_data }
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The PDF of `content` with the images the GPU renders of what the PDF can't draw itself, partial without them while a task reads them back.
|
||||
/// The task landing evaluates the render node again through its `source`.
|
||||
pub fn poll_pdf(
|
||||
&self,
|
||||
content: Arc<dyn Render + Send + Sync>,
|
||||
page: PdfPage,
|
||||
render_params: RenderParams,
|
||||
executor: Option<WgpuExecutor>,
|
||||
runtime: &RuntimeHandle,
|
||||
source: SourceId,
|
||||
) -> Poll<RenderOutputType> {
|
||||
let (pdf, deferred) = match render_pdf_document(content.as_ref(), &page, &render_params, PdfRasters::new()) {
|
||||
Ok(rendered) => rendered,
|
||||
Err(error) => return Poll::error(error),
|
||||
};
|
||||
if deferred.is_empty() {
|
||||
self.clear();
|
||||
return Poll::Final(RenderOutputType::Pdf { data: pdf });
|
||||
}
|
||||
|
||||
// The document without its images stands for its content, which sets the key apart from other renders
|
||||
let mut hasher = DefaultHasher::new();
|
||||
pdf.hash(&mut hasher);
|
||||
page.size.to_array().map(f64::to_bits).hash(&mut hasher);
|
||||
page.transform.to_cols_array().map(f64::to_bits).hash(&mut hasher);
|
||||
page.raster_scale.to_bits().hash(&mut hasher);
|
||||
let key = hasher.finish();
|
||||
|
||||
let partial = RenderOutputType::Pdf { data: pdf.clone() };
|
||||
self.poll_readback(key, partial, runtime, source, || {
|
||||
let executor = executor?;
|
||||
// Each image is rendered in the view of the page it's on
|
||||
let images: Vec<_> = (deferred.iter())
|
||||
.flat_map(|deferred| executor.render_deferred_images(std::slice::from_ref(&deferred.image), deferred.view))
|
||||
.collect();
|
||||
if images.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(async move {
|
||||
let rasters: PdfRasters = (executor.read_back_deferred_images(images).await.into_iter())
|
||||
.map(|(placement, raster)| (placement.id, (placement, raster)))
|
||||
.collect();
|
||||
|
||||
match render_pdf_document(content.as_ref(), &page, &render_params, rasters) {
|
||||
Ok((data, _)) => RenderOutputType::Pdf { data },
|
||||
// The document without the images is the most there is to export
|
||||
Err(error) => {
|
||||
log::error!("{error}");
|
||||
RenderOutputType::Pdf { data: pdf }
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The finished output of the render `key` names, starting its readback with `start` the first time it's polled, and `partial` until the readback lands.
|
||||
/// Without a readback to start, `partial` is all there is to the render.
|
||||
fn poll_readback<F>(&self, key: u64, partial: RenderOutputType, runtime: &RuntimeHandle, source: SourceId, start: impl FnOnce() -> Option<F>) -> Poll<RenderOutputType>
|
||||
where
|
||||
F: Future<Output = RenderOutputType> + WasmNotSend + 'static,
|
||||
{
|
||||
if self.lock().as_ref().is_none_or(|readback| readback.key != key) {
|
||||
let Some(readback) = start() else {
|
||||
self.clear();
|
||||
return Poll::Final(partial);
|
||||
};
|
||||
|
||||
let (task, registration) = AbortHandle::new_pair();
|
||||
*self.lock() = Some(Readback { key, finished: None, task });
|
||||
|
||||
// Held weakly, the slot is dropped along with the render node, which cancels the readback
|
||||
let slot = Arc::downgrade(&self.0);
|
||||
runtime.spawn(
|
||||
source,
|
||||
Box::pin(async move {
|
||||
if let Ok(finished) = Abortable::new(readback, registration).await
|
||||
&& let Some(slot) = slot.upgrade().map(SvgReadbackSlot)
|
||||
&& let Some(slot) = slot.upgrade().map(ReadbackSlot)
|
||||
&& let Some(readback) = slot.lock().as_mut().filter(|readback| readback.key == key)
|
||||
{
|
||||
readback.finished = Some(finished);
|
||||
@@ -91,7 +165,7 @@ impl SvgReadbackSlot {
|
||||
let finished = self.lock().as_ref().filter(|readback| readback.key == key).and_then(|readback| readback.finished.clone());
|
||||
match finished {
|
||||
Some(finished) => Poll::Final(finished),
|
||||
None => Poll::Partial(RenderOutputType::Svg { svg, image_data }),
|
||||
None => Poll::Partial(partial),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,7 +247,7 @@ mod tests {
|
||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
||||
let tasks = Arc::new(HeldTasks::default());
|
||||
let runtime = AsyncRuntime::new(tasks.clone());
|
||||
let slot = SvgReadbackSlot::default();
|
||||
let slot = ReadbackSlot::default();
|
||||
let output = deferred_svg();
|
||||
let poll = || slot.poll(again(&output), view(32), Some(executor.clone()), &runtime.handle(), SourceId(1));
|
||||
|
||||
@@ -194,12 +268,53 @@ mod tests {
|
||||
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "{svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pdf_render_embeds_images_of_effects_once_its_readback_lands() {
|
||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
||||
let tasks = Arc::new(HeldTasks::default());
|
||||
let runtime = AsyncRuntime::new(tasks.clone());
|
||||
let slot = ReadbackSlot::default();
|
||||
|
||||
// The orange square casting a shadow, which no PDF can draw itself
|
||||
let shadow = EffectOperation::DropShadow {
|
||||
color: Color::BLACK,
|
||||
angle: 180.,
|
||||
distance: 4.,
|
||||
spread: 0.,
|
||||
size: 0.,
|
||||
contour: Default::default(),
|
||||
knockout: true,
|
||||
};
|
||||
let mut item =
|
||||
Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::from_gamma_srgb_channels(1., 0.5, 0., 1.)))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(10.)));
|
||||
stamp_effect(&mut item, Effect::new(&shadow));
|
||||
let content: Arc<dyn Render + Send + Sync> = Arc::new(List::new_from_item(item));
|
||||
|
||||
let page = PdfPage::new(DVec2::splat(32.), DAffine2::IDENTITY, 1.);
|
||||
let poll = || slot.poll_pdf(content.clone(), page, RenderParams::default(), Some(executor.clone()), &runtime.handle(), SourceId(1));
|
||||
let embeds_image = |pdf: &[u8]| pdf.windows(b"/Subtype/Image".len()).any(|window| window == b"/Subtype/Image");
|
||||
|
||||
// Until the readback lands, the PDF lacks the image, and evaluating the same render again doesn't read it back again
|
||||
for _ in 0..2 {
|
||||
let Poll::Partial(RenderOutputType::Pdf { data }) = poll() else {
|
||||
panic!("expected a partial PDF")
|
||||
};
|
||||
assert!(!embeds_image(&data), "the partial PDF shouldn't have the image yet");
|
||||
}
|
||||
let spawned = tasks.take();
|
||||
assert_eq!(spawned.len(), 1, "the readback should be spawned once");
|
||||
|
||||
spawned.into_iter().for_each(futures::executor::block_on);
|
||||
let Poll::Final(RenderOutputType::Pdf { data }) = poll() else { panic!("expected a finished PDF") };
|
||||
assert!(embeds_image(&data), "the finished PDF should embed the image of the square and its shadow");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_render_for_another_view_cancels_the_readback_of_the_one_it_replaces() {
|
||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
||||
let tasks = Arc::new(HeldTasks::default());
|
||||
let runtime = AsyncRuntime::new(tasks.clone());
|
||||
let slot = SvgReadbackSlot::default();
|
||||
let slot = ReadbackSlot::default();
|
||||
let output = deferred_svg();
|
||||
let poll = |size| slot.poll(again(&output), view(size), Some(executor.clone()), &runtime.handle(), SourceId(1));
|
||||
|
||||
@@ -224,7 +339,7 @@ mod tests {
|
||||
let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return };
|
||||
let tasks = Arc::new(HeldTasks::default());
|
||||
let runtime = AsyncRuntime::new(tasks.clone());
|
||||
let slot = SvgReadbackSlot::default();
|
||||
let slot = ReadbackSlot::default();
|
||||
|
||||
let render = slot.poll(deferred_svg(), view(32), Some(executor), &runtime.handle(), SourceId(1));
|
||||
assert!(matches!(render, Poll::Partial(_)));
|
||||
@@ -12,7 +12,7 @@ use graphic_types::adjustment::{
|
||||
LevelsRecord, LevelsSettings, SelectiveColorInks, SelectiveColorSettings,
|
||||
};
|
||||
pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute};
|
||||
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
||||
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||
use raster_kernels::{evaluate_color_effects, evaluate_gradient_effects};
|
||||
use raster_types::{CPU, GPU, Image, Raster};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::color::Color;
|
||||
use core_types::color::{Alpha, AlphaMut, LinearChannel, Luminance, RGBMut};
|
||||
@@ -9,7 +9,7 @@ use core_types::transform::Transform;
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::generator::{Generator, NoiseSettings};
|
||||
use graphic_types::generator::{Generator, MandelbrotSettings, NoiseSettings};
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{Bitmap, BitmapMut};
|
||||
@@ -307,9 +307,66 @@ fn noise_pattern(
|
||||
generator
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"), version(2))]
|
||||
fn mandelbrot(_: impl Ctx, _primary: ()) -> Item<Generator> {
|
||||
Item::new_from_element(Generator::Mandelbrot)
|
||||
/// Generates a Mandelbrot-style fractal filling the plane, as brightness for a 'Gradient Map' node to color. The origin is the complex plane's, where the Mandelbrot set's main body lies just left of it.
|
||||
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"), version(3))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn mandelbrot(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
/// Which fractal is iterated, the Mandelbrot set or one of its variations.
|
||||
fractal: Item<MandelbrotFractal>,
|
||||
/// What the brightness outside the set comes from.
|
||||
exterior: Item<MandelbrotExterior>,
|
||||
/// What the brightness inside the set comes from.
|
||||
interior: Item<MandelbrotInterior>,
|
||||
/// How many tendrils or rays appear for each turn around the set with the Tendrils or Rays exterior, or around each bulb's center with the Rays interior.
|
||||
#[widget(ParsedWidgetOverride::Custom = "mandelbrot_inspector_frequency")]
|
||||
#[default(1)]
|
||||
#[hard(1..64)]
|
||||
frequency: Item<i64>,
|
||||
/// How many units span one unit of the complex plane. The Mandelbrot set is about 2.5 of the plane's units across.
|
||||
#[default(100.)]
|
||||
#[hard(0..)]
|
||||
scale: Item<f64>,
|
||||
/// The most iterations before a point counts as inside the set. Higher values resolve finer detail along its edge, especially when zoomed in, but take longer to render.
|
||||
#[default(256)]
|
||||
#[hard(1..10000)]
|
||||
iterations: Item<i64>,
|
||||
/// The exponent each iteration raises a point's value to, which changes the fractal's shape. Powers that aren't integers tear the set along a seam, and render more slowly when zoomed in far.
|
||||
#[default(2.)]
|
||||
#[hard(1..32)]
|
||||
#[soft(2..8)]
|
||||
power: Item<f64>,
|
||||
/// How far the slice through the fractal turns from the Mandelbrot end, the selected fractal's own set at 0%, to the Julia end, the Julia set chosen by the Julia Slice at 100%, passing through hybrid shapes between them.
|
||||
#[name("Mandelbrot-to-Julia")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
mandelbrot_to_julia: Item<f64>,
|
||||
/// Which slice of the fractal the Mandelbrot end shows, chosen by where each point's orbit starts. Moved off the origin, it bends the selected fractal's set away from its classic shape. Its effect fades out as Mandelbrot-to-Julia rises.
|
||||
#[widget(ParsedWidgetOverride::Custom = "mandelbrot_inspector_mandelbrot_slice")]
|
||||
mandelbrot_slice: Item<DVec2>,
|
||||
/// Which slice of the fractal the Julia end shows, chosen by the point added each iteration. A point of the selected fractal's set gives that point's Julia set, and points near the set's edge often give intricate ones. Its effect fades in as Mandelbrot-to-Julia rises.
|
||||
#[widget(ParsedWidgetOverride::Custom = "mandelbrot_inspector_julia_slice")]
|
||||
#[default(-0.8, 0.156)]
|
||||
julia_slice: Item<DVec2>,
|
||||
) -> Item<Generator> {
|
||||
let settings = MandelbrotSettings {
|
||||
fractal: fractal.into_element(),
|
||||
exterior: exterior.into_element(),
|
||||
interior: interior.into_element(),
|
||||
frequency: frequency.into_element(),
|
||||
scale: scale.into_element(),
|
||||
iterations: iterations.into_element(),
|
||||
power: power.into_element(),
|
||||
mandelbrot_to_julia: mandelbrot_to_julia.into_element(),
|
||||
mandelbrot_slice: mandelbrot_slice.into_element(),
|
||||
julia_slice: julia_slice.into_element(),
|
||||
};
|
||||
|
||||
let mut generator = Item::new_from_element(Generator::Mandelbrot);
|
||||
settings.stamp(&mut generator);
|
||||
generator
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -150,7 +150,7 @@ fn centered_cell_window(first_cell: DVec2, last_cell: DVec2, max_count: f64) ->
|
||||
}
|
||||
|
||||
/// Repeats the content on a grid that covers the visible viewport.
|
||||
#[node_macro::node(category("Graphic"), icon("NodeRepeatArray"))]
|
||||
#[node_macro::node(category(""), icon("NodeRepeatArray"))]
|
||||
fn tile<T: Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx + ExtractFootprint + InjectFootprint,
|
||||
#[implementations(
|
||||
|
||||
@@ -28,16 +28,8 @@ fn typography_attribute<T: Clone + 'static>(item: &Item<String>, key: &'static s
|
||||
value.downcast_ref::<T>().cloned().map(Some).ok_or(TextToVectorError::MistypedAttribute(key))
|
||||
}
|
||||
|
||||
/// Shapes a single styled string item into vector geometry, reading its font and typesetting from the item's
|
||||
/// attributes (as set by the 'Text' node) and re-applying its transform and blending attributes onto the produced
|
||||
/// paths. With `separate_glyphs`, each glyph becomes its own item; otherwise a single compound path is produced.
|
||||
pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> Result<List<Vector>, TextToVectorError> {
|
||||
let text = item.element();
|
||||
if text.is_empty() {
|
||||
return Ok(List::new());
|
||||
}
|
||||
|
||||
// Use fallback font when none is explicitly attached.
|
||||
/// The font and typesetting a styled string item's attributes set, falling back to the default font when none is attached.
|
||||
fn item_font_and_typesetting(item: &Item<String>) -> Result<(Resource, TypesettingConfig), TextToVectorError> {
|
||||
let font = typography_attribute::<Resource>(item, ATTR_FONT)?.filter(|font| !font.is_empty());
|
||||
let font = font.unwrap_or_else(|| super::FALLBACK_FONT_RESOURCE.clone());
|
||||
|
||||
@@ -52,6 +44,30 @@ pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> Result<Lis
|
||||
align: typography_attribute(item, ATTR_TEXT_ALIGN)?.unwrap_or(defaults.align),
|
||||
};
|
||||
|
||||
Ok((font, typesetting))
|
||||
}
|
||||
|
||||
/// The box a styled string item lays out in, in its own space before its transform, or `None` for empty or unreadable text.
|
||||
pub fn text_item_layout_bounds(item: &Item<String>) -> Option<[DVec2; 2]> {
|
||||
if item.element().is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (font, typesetting) = item_font_and_typesetting(item).ok()?;
|
||||
let size = bounding_box(item.element(), &font, typesetting, false);
|
||||
(size != DVec2::ZERO).then_some([DVec2::ZERO, size])
|
||||
}
|
||||
|
||||
/// Shapes a single styled string item into vector geometry, reading its font and typesetting from the item's
|
||||
/// attributes (as set by the 'Text' node) and re-applying its transform and blending attributes onto the produced
|
||||
/// paths. With `separate_glyphs`, each glyph becomes its own item; otherwise a single compound path is produced.
|
||||
pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> Result<List<Vector>, TextToVectorError> {
|
||||
let text = item.element();
|
||||
if text.is_empty() {
|
||||
return Ok(List::new());
|
||||
}
|
||||
|
||||
let (font, typesetting) = item_font_and_typesetting(item)?;
|
||||
let vectors = to_path(text, &font, typesetting, separate_glyphs)?;
|
||||
let transform = item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
let layer_path = item.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).cloned();
|
||||
|
||||
@@ -29,6 +29,7 @@ graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
repeat-nodes = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
dyn-any = { workspace = true }
|
||||
|
||||
@@ -28,7 +28,8 @@ use vector_types::GradientForm;
|
||||
use vector_types::gradient::{build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box};
|
||||
use vector_types::vector::SetVectorPaths;
|
||||
use vector_types::vector::algorithms::bezpath_algorithms::{
|
||||
self, SampleCountError, TValue, bezpath_area_centroid_and_area, bezpath_length_centroid_and_length, eval_pathseg_euclidean, evaluate_bezpath, split_bezpath, tangent_on_bezpath,
|
||||
self, PoissonDiskError, PoissonDiskSampler, SampleCountError, TValue, bezpath_area_centroid_and_area, bezpath_length_centroid_and_length, eval_pathseg_euclidean, evaluate_bezpath, split_bezpath,
|
||||
tangent_on_bezpath,
|
||||
};
|
||||
use vector_types::vector::algorithms::concave_hull::concave_hull_of_geometry;
|
||||
use vector_types::vector::algorithms::offset_bezpath::{OffsetPathError, offset_bezpath};
|
||||
@@ -162,6 +163,48 @@ impl VectorItemMut for Item<Graphic> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Content a paint can cover, which a gradient without its own placement spans the bounds of.
|
||||
trait PaintTarget {
|
||||
/// The union of the content's bounds in its own space, before its transform.
|
||||
fn content_bounds(&mut self) -> Option<[DVec2; 2]>;
|
||||
}
|
||||
|
||||
/// The union of the bounds of the vector content `content` reaches, or `None` without any measurable geometry.
|
||||
fn vector_content_bounds(content: &mut impl VectorItemMut) -> Option<[DVec2; 2]> {
|
||||
let mut bounds: Option<[DVec2; 2]> = None;
|
||||
content.for_each_vector_mut(|vector, vector_paths, _| {
|
||||
if let Some([min, max]) = vector.bounding_box(vector_paths) {
|
||||
bounds = Some(match bounds {
|
||||
Some([bounds_min, bounds_max]) => [bounds_min.min(min), bounds_max.max(max)],
|
||||
None => [min, max],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
bounds
|
||||
}
|
||||
|
||||
impl PaintTarget for Item<Vector> {
|
||||
fn content_bounds(&mut self) -> Option<[DVec2; 2]> {
|
||||
vector_content_bounds(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl PaintTarget for Item<Graphic> {
|
||||
fn content_bounds(&mut self) -> Option<[DVec2; 2]> {
|
||||
match self.element() {
|
||||
Graphic::Text(text) => text_nodes::text_item_layout_bounds(text),
|
||||
_ => vector_content_bounds(self),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PaintTarget for Item<String> {
|
||||
fn content_bounds(&mut self) -> Option<[DVec2; 2]> {
|
||||
text_nodes::text_item_layout_bounds(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Geometry counterpart to [`VectorItemMut`] for the element-wise modifier nodes, running a per-item transformation over
|
||||
/// every vector reachable from the content. Geometry is never inherited, so this recurses into nested groups.
|
||||
trait MapVectorItems: Sized {
|
||||
@@ -407,12 +450,12 @@ fn vary_cover_colors<T: VectorListIterMut>(
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
|
||||
/// Applies a fill style to the vector or text content, giving an appearance to the area within the interior of the geometry.
|
||||
#[node_macro::node(category("Vector: Style"), icon("NodeFill"), path(graphene_core::vector), inspector("fill_inspector"))]
|
||||
fn fill<V>(
|
||||
_: impl Ctx,
|
||||
/// The content with vector paths to apply the fill style to.
|
||||
#[implementations(Vector, Graphic)]
|
||||
/// The vector paths or text to apply the fill style to.
|
||||
#[implementations(Vector, Graphic, String)]
|
||||
content: Item<V>,
|
||||
#[default(Color::BLACK)] paint: Item<Graphic>,
|
||||
_backup_color: Item<Color>,
|
||||
@@ -422,7 +465,7 @@ fn fill<V>(
|
||||
_transform: Item<DAffine2>,
|
||||
) -> Item<V>
|
||||
where
|
||||
Item<V>: VectorItemMut + Send,
|
||||
Item<V>: PaintTarget + Send,
|
||||
{
|
||||
let _gradient_form = _gradient_form.into_element();
|
||||
let (_has_transform, _transform) = (_has_transform.into_element(), *_transform.element());
|
||||
@@ -447,18 +490,8 @@ where
|
||||
return _transform;
|
||||
}
|
||||
|
||||
let mut bounds: Option<[DVec2; 2]> = None;
|
||||
content.for_each_vector_mut(|vector, vector_paths, _| {
|
||||
if let Some([min, max]) = vector.bounding_box(vector_paths) {
|
||||
bounds = Some(match bounds {
|
||||
Some([bmin, bmax]) => [bmin.min(min), bmax.max(max)],
|
||||
None => [min, max],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Nudge a degenerate axis so the gradient transform stays invertible, matching the editor's `nonzero_bounding_box`
|
||||
let [min, mut max] = bounds.unwrap_or([DVec2::ZERO, DVec2::ONE]);
|
||||
let [min, mut max] = content.content_bounds().unwrap_or([DVec2::ZERO, DVec2::ONE]);
|
||||
if max.x - min.x < 1e-10 {
|
||||
max.x = min.x + 1.;
|
||||
}
|
||||
@@ -497,12 +530,12 @@ where
|
||||
content
|
||||
}
|
||||
|
||||
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
|
||||
/// Applies a stroke style to the vector or text content, giving an appearance to the area within the outline of the geometry.
|
||||
#[node_macro::node(category("Vector: Style"), icon("NodeStroke"), path(graphene_core::vector), inspector("stroke_inspector"))]
|
||||
fn stroke<V>(
|
||||
_: impl Ctx,
|
||||
/// The content with vector paths to apply the stroke style to.
|
||||
#[implementations(Vector, Graphic)]
|
||||
/// The vector paths or text to apply the stroke style to.
|
||||
#[implementations(Vector, Graphic, String)]
|
||||
content: Item<V>,
|
||||
/// The stroke paint.
|
||||
#[default(Color::BLACK)]
|
||||
@@ -529,7 +562,7 @@ fn stroke<V>(
|
||||
dash_offset: Item<f64>,
|
||||
) -> Item<V>
|
||||
where
|
||||
Item<V>: VectorItemMut + Send,
|
||||
Item<V>: PaintTarget + Send,
|
||||
{
|
||||
let mut content = content;
|
||||
let (weight, align, cap, join, miter_limit, dash_offset) = (
|
||||
@@ -2553,7 +2586,7 @@ fn evaluate_path(
|
||||
})
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Point"), icon("NodeScatterPoints"), path(core_types::vector), memoize)]
|
||||
#[node_macro::node(category("Vector: Point"), icon("NodeScatterPoints"), path(core_types::vector), version(2), memoize)]
|
||||
fn scatter_points<V: MapVectorItems + Send>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Graphic, Vector)] content: Item<V>,
|
||||
@@ -2564,37 +2597,24 @@ fn scatter_points<V: MapVectorItems + Send>(
|
||||
#[soft(1..100)]
|
||||
separation: Item<f64>,
|
||||
#[hard(0..)] seed: Item<i64>,
|
||||
) -> Item<V> {
|
||||
V::map_vector_items(content, |content| {
|
||||
) -> Result<Item<V>, PoissonDiskError> {
|
||||
// One sampler for every vector in the content holds them all together to its limits on work
|
||||
let mut sampler = PoissonDiskSampler::default();
|
||||
|
||||
V::try_map_vector_items(content, |content| {
|
||||
let mut content = content;
|
||||
let (separation, seed) = (*separation.element(), *seed.element());
|
||||
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
|
||||
|
||||
let mut cloud = List::new();
|
||||
|
||||
let content_paths = shared_paths_from_item_attributes(&content);
|
||||
let path_with_bounding_boxes: Vec<_> = content
|
||||
.element()
|
||||
.stroke_bezpath_iter(&content_paths)
|
||||
.map(|mut bezpath| {
|
||||
// TODO: apply transform to points instead of modifying the paths
|
||||
bezpath.close_path();
|
||||
let bbox = bezpath.bounding_box();
|
||||
(bezpath, bbox)
|
||||
})
|
||||
let bezpaths: Vec<_> = content.element().stroke_bezpath_iter(&content_paths).collect();
|
||||
|
||||
// Each point's ID comes from the dart that placed it, so a point keeps its ID while edits elsewhere in the shape leave it in place
|
||||
let cloud = sampler
|
||||
.points(&bezpaths, separation, seed as u64)?
|
||||
.into_iter()
|
||||
.map(|(point, hash)| Item::new_from_element(point).with_attribute(ATTR_ID, PointId::ZERO.generate_from_hash(hash)))
|
||||
.collect();
|
||||
|
||||
for (i, (subpath, _)) in path_with_bounding_boxes.iter().enumerate() {
|
||||
if subpath.segments().count() < 2 {
|
||||
continue;
|
||||
}
|
||||
|
||||
for point in bezpath_algorithms::poisson_disk_points(i, &path_with_bounding_boxes, separation, || rng.random::<f64>()) {
|
||||
cloud.push(Item::new_from_element(point).with_attribute(ATTR_ID, PointId::generate()));
|
||||
}
|
||||
}
|
||||
|
||||
// The scattered points replace the source shape entirely, leaving no paths
|
||||
drop(content_paths);
|
||||
edit_item_geometry(&mut content, |vector, paths| {
|
||||
@@ -2602,7 +2622,7 @@ fn scatter_points<V: MapVectorItems + Send>(
|
||||
*paths = List::new();
|
||||
});
|
||||
|
||||
content
|
||||
Ok(content)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4498,7 +4518,8 @@ mod test {
|
||||
vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.))),
|
||||
Item::new_from_element(10. * std::f64::consts::SQRT_2),
|
||||
Item::new_from_element(0),
|
||||
);
|
||||
)
|
||||
.expect("the separation should fit the circle");
|
||||
let positions = poisson_points.element().anchor_positions(item_paths(&poisson_points));
|
||||
assert!((20..=40).contains(&positions.len()), "actual len {}", positions.len());
|
||||
for point in positions {
|
||||
@@ -5198,14 +5219,128 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn scatter_points_skips_an_infinite_subpath() {
|
||||
let mut bezpath = ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.));
|
||||
let ellipse = || ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.));
|
||||
let mut bezpath = ellipse();
|
||||
bezpath.move_to((0., 0.));
|
||||
bezpath.line_to((f64::INFINITY, 0.));
|
||||
bezpath.line_to((0., 10.));
|
||||
bezpath.close_path();
|
||||
|
||||
let scattered = super::scatter_points((), vector_item_from_bezpath(bezpath), item(10.), item(0));
|
||||
assert!(scattered.element().point_count() > 0);
|
||||
let points = scattered_points(bezpath, 10., 0);
|
||||
assert!(!points.is_empty());
|
||||
assert_eq!(points, scattered_points(ellipse(), 10., 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_points_samples_each_vector_in_graphic_content() {
|
||||
let shapes = [ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.)), ellipse_bezpath(DVec2::new(200., -40.), DVec2::new(300., 40.))];
|
||||
let vectors: List<Vector> = shapes.iter().cloned().map(vector_item_from_bezpath).collect();
|
||||
let scattered = super::scatter_points((), Item::new_from_element(Graphic::VectorList(vectors)), item(10.), item(0)).expect("the shapes should scatter");
|
||||
|
||||
let Graphic::VectorList(vectors) = scattered.element() else {
|
||||
panic!("the content should stay a vector list")
|
||||
};
|
||||
assert_eq!(vectors.len(), shapes.len());
|
||||
for (vector, shape) in vectors.iter_element_values().zip(shapes) {
|
||||
let alone: Vec<_> = scattered_points(shape, 10., 0).into_iter().map(|(position, _)| position).collect();
|
||||
assert_eq!(vector.0.iter_element_values().copied().collect::<Vec<_>>(), alone);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_points_on_empty_content_gives_no_points() {
|
||||
let scattered = super::scatter_points((), vector_item_from_bezpath(BezPath::new()), item(10.), item(0)).expect("empty content should scatter nothing");
|
||||
assert_eq!(scattered.element().point_count(), 0);
|
||||
}
|
||||
|
||||
fn scattered_points(bezpath: BezPath, separation: f64, seed: i64) -> Vec<(DVec2, PointId)> {
|
||||
let scattered = super::scatter_points((), vector_item_from_bezpath(bezpath), item(separation), item(seed)).expect("the separation should fit the shape");
|
||||
let points = &scattered.element().0;
|
||||
points.iter_element_values().copied().zip(points.iter_attribute_values::<PointId>(ATTR_ID).unwrap().copied()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_points_changes_only_points_near_an_edit() {
|
||||
// A square with a vertex partway down its right side, which the edit pushes outward
|
||||
let pentagon = |bulge: f64| {
|
||||
let mut bezpath = BezPath::new();
|
||||
bezpath.move_to((0., 0.));
|
||||
bezpath.line_to((400., 0.));
|
||||
bezpath.line_to((400. + bulge, 200.));
|
||||
bezpath.line_to((400., 400.));
|
||||
bezpath.line_to((0., 400.));
|
||||
bezpath.close_path();
|
||||
scattered_points(bezpath, 10., 0)
|
||||
};
|
||||
let (before, after) = (pentagon(0.), pentagon(40.));
|
||||
|
||||
// Points over ten separations from the edit keep their positions and IDs, while the bulge gains points of its own
|
||||
let far_from_edit = |points: &[(DVec2, PointId)]| points.iter().copied().filter(|(position, _)| position.x < 300.).collect::<Vec<_>>();
|
||||
assert_eq!(far_from_edit(&before), far_from_edit(&after));
|
||||
assert!(after.iter().any(|(position, _)| position.x > 405.));
|
||||
|
||||
let unchanged = before.iter().filter(|point| after.contains(point)).count();
|
||||
assert!(unchanged as f64 > before.len() as f64 * 0.95, "only {unchanged} of {} points are unchanged", before.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_points_ignores_distant_geometry() {
|
||||
let circle = || ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.));
|
||||
let alone = scattered_points(circle(), 7., 3);
|
||||
|
||||
// Distant shapes on opposite sides, plus a frame around the circle that shares its grid while staying too far away to affect its points
|
||||
let mut with_distant_shapes = circle();
|
||||
with_distant_shapes.extend(ellipse_bezpath(DVec2::new(500., -900.), DVec2::new(700., -600.)));
|
||||
with_distant_shapes.extend(ellipse_bezpath(DVec2::new(-800., 300.), DVec2::new(-600., 700.)));
|
||||
with_distant_shapes.extend(Rect::new(-400., -400., 400., 400.).to_path(DEFAULT_ACCURACY));
|
||||
with_distant_shapes.extend(Rect::new(-200., -200., 200., 200.).to_path(DEFAULT_ACCURACY).reverse_subpaths());
|
||||
let with_distant_shapes = scattered_points(with_distant_shapes, 7., 3);
|
||||
let near_first_circle: Vec<_> = with_distant_shapes.iter().copied().filter(|(position, _)| position.length() < 60.).collect();
|
||||
|
||||
assert_eq!(alone, near_first_circle);
|
||||
assert!(with_distant_shapes.len() > alone.len() * 2, "the distant shapes should get points of their own");
|
||||
assert!(
|
||||
with_distant_shapes.iter().any(|(position, _)| position.x.abs().max(position.y.abs()) > 200.),
|
||||
"the frame should get points of its own"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_points_keeps_its_separation_across_overlapping_subpaths() {
|
||||
let mut bezpath = ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.));
|
||||
bezpath.extend(ellipse_bezpath(DVec2::new(-20., -50.), DVec2::new(80., 50.)));
|
||||
let points = scattered_points(bezpath, 10., 0);
|
||||
assert!(points.iter().any(|(position, _)| position.x > 55.), "the second ellipse should get points of its own");
|
||||
|
||||
for (i, (a, _)) in points.iter().enumerate() {
|
||||
for (b, _) in &points[i + 1..] {
|
||||
assert!(a.distance(*b) > 10. * (1. - 1e-9), "{a} and {b} are closer than the separation");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_points_reports_a_separation_too_small_for_the_shape() {
|
||||
let circle = |center: DVec2, radius: f64| vector_item_from_bezpath(ellipse_bezpath(center - radius, center + radius));
|
||||
let scatter = |content, separation| super::scatter_points((), content, item(separation), item(0));
|
||||
|
||||
assert!(matches!(scatter(circle(DVec2::ZERO, 100.), 0.15), Err(PoissonDiskError::SeparationTooSmall { .. })));
|
||||
assert!(matches!(scatter(circle(DVec2::ZERO, 100.), 0.01), Err(PoissonDiskError::ExtentTooLarge)));
|
||||
assert!(matches!(scatter(circle(DVec2::new(1e10, 0.), 10.), 1.), Err(PoissonDiskError::TooFarFromOrigin)));
|
||||
|
||||
let scattered = scatter(circle(DVec2::ZERO, 100.), 1.).expect("a 1 px separation should fit a 200 px circle");
|
||||
assert!(scattered.element().point_count() > 10_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scatter_points_samples_small_shapes_spread_far_apart() {
|
||||
// The empty space between the shapes doesn't count toward the limit on points
|
||||
let mut bezpath = ellipse_bezpath(DVec2::splat(-10.), DVec2::splat(10.));
|
||||
bezpath.extend(ellipse_bezpath(DVec2::splat(4990.), DVec2::splat(5010.)));
|
||||
let points = scattered_points(bezpath, 1., 0);
|
||||
|
||||
assert!(points.iter().any(|(position, _)| position.length() < 10.));
|
||||
assert!(points.iter().any(|(position, _)| position.distance(DVec2::splat(5000.)) < 10.));
|
||||
}
|
||||
|
||||
// The axis a collapsed transform keeps is too long to square, but still gives the perpendicular one a direction
|
||||
|
||||
@@ -38,7 +38,7 @@ const BROWSER_MAX_MEGABYTES: f64 = 1000.;
|
||||
/// Traces an image into a stack of filled and stroked shapes, drawn bottom to top as an artist would layer them.
|
||||
///
|
||||
/// The trace runs in slices, one per evaluation, showing the shapes traced so far until it is done.
|
||||
#[node_macro::node(category("Raster"), icon("NodeVectorize"), memoize, footprint_invariant)]
|
||||
#[node_macro::node(category("Raster"), icon("NodeVectorize"), memoize)]
|
||||
fn vectorize(
|
||||
_: impl Ctx,
|
||||
/// The image to trace.
|
||||
|
||||
Reference in new issue
Block a user