mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1db3026a2 | ||
|
|
91c7236e10 | ||
|
|
fa686d5063 | ||
|
|
7d8f124539 | ||
|
|
78a1be4059 | ||
|
|
a7ed5fcf0f | ||
|
|
48fe21ebe3 | ||
|
|
0ab2f21e47 | ||
|
|
d73bd34750 | ||
|
|
4f999ea73b | ||
|
|
80f9dbb992 | ||
|
|
9fd1011e1e | ||
|
|
3d4d7d1058 | ||
|
|
401cf1419a | ||
|
|
369671dc41 | ||
|
|
fe505edeff | ||
|
|
63a8befe4b |
No files matched your search
Generated
+160
-10
@@ -1239,7 +1239,7 @@ dependencies = [
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"tinyvec",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
@@ -2136,6 +2136,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"
|
||||
@@ -2155,6 +2158,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"
|
||||
@@ -2196,7 +2208,7 @@ dependencies = [
|
||||
"linebender_resource_handle",
|
||||
"memmap2",
|
||||
"parlance",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -3040,7 +3052,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -3075,6 +3087,40 @@ dependencies = [
|
||||
"foldhash 0.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-ccitt"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "adbed896e99325bc312778bb9c9c289d795d51c12775c44dd5e4352f679c7e46"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb5c7f3a4eb551c2bb7fa16e268f728d4bc2a5c9b090554b8dc0ee2503fb5840"
|
||||
dependencies = [
|
||||
"hayro-ccitt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-jpeg2000"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e5e5f2b3de970707fc22fd956d8f44211602939d5e4588603afa919cb7b3740"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-syntax"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6ced8279487b029813f6cc05399099fa34df6fa23d8f7b0d41d972c49d5b30d"
|
||||
dependencies = [
|
||||
"hayro-jbig2",
|
||||
"hayro-jpeg2000",
|
||||
"rustc-hash 2.1.3",
|
||||
"smallvec",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
@@ -3428,6 +3474,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"
|
||||
@@ -3800,6 +3852,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"
|
||||
@@ -5033,7 +5112,7 @@ dependencies = [
|
||||
"parlance",
|
||||
"parley_data",
|
||||
"parley_emoji",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5064,6 +5143,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"
|
||||
@@ -5866,6 +5957,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"
|
||||
@@ -5873,7 +5974,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
@@ -6019,13 +6120,15 @@ dependencies = [
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"hayro-syntax",
|
||||
"krilla",
|
||||
"kurbo",
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
@@ -6603,6 +6706,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"
|
||||
@@ -6964,6 +7073,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"
|
||||
@@ -6971,7 +7090,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7150,6 +7269,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"
|
||||
@@ -7332,7 +7463,7 @@ dependencies = [
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"thiserror 2.0.21",
|
||||
"titlecase",
|
||||
"tsify",
|
||||
@@ -7932,14 +8063,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",
|
||||
@@ -9282,6 +9413,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"
|
||||
@@ -9422,6 +9566,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"
|
||||
|
||||
@@ -223,6 +223,8 @@ skrifa = "0.44"
|
||||
polycool = "0.4"
|
||||
color = "0.3"
|
||||
# Linebender ecosystem (END)
|
||||
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
|
||||
hayro-syntax = { version = "0.9", default-features = false, features = ["std"] }
|
||||
rand = { version = "0.10", default-features = false, features = ["std_rng"] }
|
||||
rand_chacha = "0.10"
|
||||
glam = { version = "0.34", default-features = false, features = [
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("blending_nodes::effects::BlurNode"@2 => @3)]
|
||||
pub fn blur_v2(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
RADIUS as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BlurV2, &contract());
|
||||
check_undo(&BlurV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&BlurV2);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), vec![literal(Tagged::None), number(10.), number(0.), number(0.)]);
|
||||
let migrated = fixture.migrate(&BlurV2).unwrap();
|
||||
|
||||
let radius = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, blur), [literal(Tagged::None), radius, number(0.), number(0.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod bevel_and_emboss_v1;
|
||||
mod blur_v2;
|
||||
mod drop_shadow_v1;
|
||||
mod inner_glow_v1;
|
||||
mod inner_shadow_v1;
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DIAMETER: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The diameter is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("brush_nodes::BrushStrokesNode"@1 => @2)]
|
||||
pub fn brush_strokes_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DIAMETER) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
DIAMETER as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BrushStrokesV1, &contract());
|
||||
check_undo(&BrushStrokesV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&BrushStrokesV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let brush_strokes = fixture.add(decl!("brush_nodes::BrushStrokesNode"@1), vec![literal(Tagged::None), number(0.), number(40.), number(0.), number(100.)]);
|
||||
let migrated = fixture.migrate(&BrushStrokesV1).unwrap();
|
||||
|
||||
let diameter = literal(Tagged::Length(TypedLength { value: 40., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, brush_strokes), [literal(Tagged::None), number(0.), diameter, number(0.), number(100.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
//! Migrations of the nodes in `brush_nodes`.
|
||||
|
||||
mod brush_strokes_v1;
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DISTANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::BevelNode"@1 => @2)]
|
||||
pub fn bevel_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
DISTANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BevelV1, &contract());
|
||||
check_undo(&BevelV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&BevelV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let bevel = fixture.add(decl!("core_types::vector::BevelNode"@1), vec![literal(Tagged::None), number(10.)]);
|
||||
let migrated = fixture.migrate(&BevelV1).unwrap();
|
||||
|
||||
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, bevel), [literal(Tagged::None), distance]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const TOLERANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The tolerance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::DecimateNode"@1 => @2)]
|
||||
pub fn decimate_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(TOLERANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
TOLERANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&DecimateV1, &contract());
|
||||
check_undo(&DecimateV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&DecimateV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let decimate = fixture.add(decl!("core_types::vector::DecimateNode"@1), vec![literal(Tagged::None), number(5.)]);
|
||||
let migrated = fixture.migrate(&DecimateV1).unwrap();
|
||||
|
||||
let tolerance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, decimate), [literal(Tagged::None), tolerance]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DIRECTION: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
DVec2([f64; 2]),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The direction is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::ExtrudeNode"@1 => @2)]
|
||||
pub fn extrude_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DIRECTION) else { return };
|
||||
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(DIRECTION as u32, lengths(pixels));
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| match slot {
|
||||
DIRECTION => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::None),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ExtrudeV1, &contract());
|
||||
check_undo(&ExtrudeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&ExtrudeV1);
|
||||
let node = fixture.add(
|
||||
decl!("core_types::vector::ExtrudeNode"@1),
|
||||
vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.])), literal(Tagged::None)],
|
||||
);
|
||||
let migrated = fixture.migrate(&ExtrudeV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.]), literal(Tagged::None)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const MAX_DISTANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The max distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::JitterPointsNode"@1 => @2)]
|
||||
pub fn jitter_points_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(MAX_DISTANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
MAX_DISTANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&JitterPointsV1, &contract());
|
||||
check_undo(&JitterPointsV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&JitterPointsV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let jitter_points = fixture.add(decl!("core_types::vector::JitterPointsNode"@1), vec![literal(Tagged::None), number(5.), number(0.), number(1.)]);
|
||||
let migrated = fixture.migrate(&JitterPointsV1).unwrap();
|
||||
|
||||
let max_distance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, jitter_points), [literal(Tagged::None), max_distance, number(0.), number(1.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! Migrations of the nodes in `core_types`.
|
||||
|
||||
mod bevel_v1;
|
||||
mod decimate_v1;
|
||||
mod extrude_v1;
|
||||
mod jitter_points_v1;
|
||||
mod offset_path_v1;
|
||||
mod offset_points_v1;
|
||||
mod point_inside_v1;
|
||||
mod round_corners_v1;
|
||||
mod sample_polyline_v1;
|
||||
mod scatter_points_v2;
|
||||
mod simplify_v1;
|
||||
mod weld_v1;
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DISTANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::OffsetPathNode"@1 => @2)]
|
||||
pub fn offset_path_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
DISTANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OffsetPathV1, &contract());
|
||||
check_undo(&OffsetPathV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&OffsetPathV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let offset_path = fixture.add(decl!("core_types::vector::OffsetPathNode"@1), vec![literal(Tagged::None), number(10.), number(0.), number(4.)]);
|
||||
let migrated = fixture.migrate(&OffsetPathV1).unwrap();
|
||||
|
||||
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, offset_path), [literal(Tagged::None), distance, number(0.), number(4.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DISTANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::OffsetPointsNode"@1 => @2)]
|
||||
pub fn offset_points_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
DISTANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OffsetPointsV1, &contract());
|
||||
check_undo(&OffsetPointsV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&OffsetPointsV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let offset_points = fixture.add(decl!("core_types::vector::OffsetPointsNode"@1), vec![literal(Tagged::None), number(10.)]);
|
||||
let migrated = fixture.migrate(&OffsetPointsV1).unwrap();
|
||||
|
||||
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, offset_points), [literal(Tagged::None), distance]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const POINT: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
DVec2([f64; 2]),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The point is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::PointInsideNode"@1 => @2)]
|
||||
pub fn point_inside_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(POINT) else { return };
|
||||
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(POINT as u32, lengths(pixels));
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| match slot {
|
||||
POINT => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::None),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PointInsideV1, &contract());
|
||||
check_undo(&PointInsideV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&PointInsideV1);
|
||||
let node = fixture.add(decl!("core_types::vector::PointInsideNode"@1), vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.]))]);
|
||||
let migrated = fixture.migrate(&PointInsideV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.])]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 1;
|
||||
const MIN_ANGLE_THRESHOLD: usize = 4;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The radius is a length and the minimum angle threshold is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||
#[migration("core_types::vector::RoundCornersNode"@1 => @2)]
|
||||
pub fn round_corners_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(pixels) = number_at(RADIUS) {
|
||||
inputs.set(RADIUS as u32, length(pixels));
|
||||
}
|
||||
if let Some(degrees) = number_at(MIN_ANGLE_THRESHOLD) {
|
||||
inputs.set(MIN_ANGLE_THRESHOLD as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RoundCornersV1, &contract());
|
||||
check_undo(&RoundCornersV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_and_degrees_become_a_length_and_an_angle() {
|
||||
let mut fixture = Fixture::new(&RoundCornersV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let round_corners = fixture.add(
|
||||
decl!("core_types::vector::RoundCornersNode"@1),
|
||||
vec![literal(Tagged::None), number(10.), number(0.5), number(100.), number(5.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&RoundCornersV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, round_corners), [literal(Tagged::None), length(10.), number(0.5), number(100.), angle(5.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SEPARATION: usize = 2;
|
||||
const START_OFFSET: usize = 4;
|
||||
const STOP_OFFSET: usize = 5;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The separation and start and stop offsets are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("core_types::vector::SamplePolylineNode"@1 => @2)]
|
||||
pub fn sample_polyline_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [SEPARATION, START_OFFSET, STOP_OFFSET] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&SamplePolylineV1, &contract());
|
||||
check_undo(&SamplePolylineV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&SamplePolylineV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let sample_polyline = fixture.add(
|
||||
decl!("core_types::vector::SamplePolylineNode"@1),
|
||||
vec![literal(Tagged::None), number(0.), number(100.), number(100.), number(10.), number(20.), number(0.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&SamplePolylineV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, sample_polyline),
|
||||
[literal(Tagged::None), number(0.), length(100.), number(100.), length(10.), length(20.), number(0.)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SEPARATION: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The separation is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::ScatterPointsNode"@2 => @3)]
|
||||
pub fn scatter_points_v2(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(SEPARATION) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
SEPARATION as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ScatterPointsV2, &contract());
|
||||
check_undo(&ScatterPointsV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&ScatterPointsV2);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let scatter_points = fixture.add(decl!("core_types::vector::ScatterPointsNode"@2), vec![literal(Tagged::None), number(10.), number(0.)]);
|
||||
let migrated = fixture.migrate(&ScatterPointsV2).unwrap();
|
||||
|
||||
let separation = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, scatter_points), [literal(Tagged::None), separation, number(0.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const TOLERANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The tolerance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::SimplifyNode"@1 => @2)]
|
||||
pub fn simplify_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(TOLERANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
TOLERANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&SimplifyV1, &contract());
|
||||
check_undo(&SimplifyV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&SimplifyV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let simplify = fixture.add(decl!("core_types::vector::SimplifyNode"@1), vec![literal(Tagged::None), number(5.)]);
|
||||
let migrated = fixture.migrate(&SimplifyV1).unwrap();
|
||||
|
||||
let tolerance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, simplify), [literal(Tagged::None), tolerance]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DISTANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::WeldNode"@1 => @2)]
|
||||
pub fn weld_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
DISTANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&WeldV1, &contract());
|
||||
check_undo(&WeldV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&WeldV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let weld = fixture.add(decl!("core_types::vector::WeldNode"@1), vec![literal(Tagged::None), number(0.1), number(0.)]);
|
||||
let migrated = fixture.migrate(&WeldV1).unwrap();
|
||||
|
||||
let distance = literal(Tagged::Length(TypedLength { value: 0.1, unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, weld), [literal(Tagged::None), distance, number(0.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Migrations of the nodes in `graphene_core`.
|
||||
|
||||
mod pack_strips_v1;
|
||||
mod passthrough_from_upload_texture_node;
|
||||
mod renames;
|
||||
mod stroke_v1;
|
||||
mod vary_colors_from_assign_colors;
|
||||
@@ -0,0 +1,73 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SEPARATION: usize = 1;
|
||||
const STRIP_MAX_LENGTH: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The separation and strip max length are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("graphene_core::vector::PackStripsNode"@1 => @2)]
|
||||
pub fn pack_strips_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [SEPARATION, STRIP_MAX_LENGTH] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PackStripsV1, &contract());
|
||||
check_undo(&PackStripsV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&PackStripsV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let pack_strips = fixture.add(decl!("graphene_core::vector::PackStripsNode"@1), vec![literal(Tagged::None), number(10.), number(1000.), number(0.)]);
|
||||
let migrated = fixture.migrate(&PackStripsV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, pack_strips), [literal(Tagged::None), length(10.), length(1000.), number(0.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const WEIGHT: usize = 2;
|
||||
const DASH_OFFSET: usize = 8;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The weight and dash offset are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("graphene_core::vector::StrokeNode"@1 => @2)]
|
||||
pub fn stroke_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [WEIGHT, DASH_OFFSET] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(9, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&StrokeV1, &contract());
|
||||
check_undo(&StrokeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&StrokeV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let stroke = fixture.add(
|
||||
decl!("graphene_core::vector::StrokeNode"@1),
|
||||
vec![literal(Tagged::None), number(0.), number(2.), number(0.), number(0.), number(0.), number(4.), number(0.), number(5.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&StrokeV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, stroke),
|
||||
[literal(Tagged::None), number(0.), length(2.), number(0.), number(0.), number(0.), number(4.), number(0.), length(5.)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
//! Migrations of the nodes in `graphene_std`.
|
||||
|
||||
mod renames;
|
||||
mod text_v1;
|
||||
@@ -0,0 +1,130 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SIZE: usize = 3;
|
||||
const LETTER_SPACING: usize = 5;
|
||||
const LETTER_TILT: usize = 6;
|
||||
const MAX_WIDTH: usize = 8;
|
||||
const MAX_HEIGHT: usize = 10;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The size, letter spacing, and max sizes are lengths and the letter tilt is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||
#[migration("graphene_std::text::TextNode"@1 => @2)]
|
||||
pub fn text_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [SIZE, LETTER_SPACING, MAX_WIDTH, MAX_HEIGHT] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
if let Some(degrees) = number_at(LETTER_TILT) {
|
||||
inputs.set(LETTER_TILT as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(12, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&TextV1, &contract());
|
||||
check_undo(&TextV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_and_degrees_become_lengths_and_an_angle() {
|
||||
let mut fixture = Fixture::new(&TextV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let text = fixture.add(
|
||||
decl!("graphene_std::text::TextNode"@1),
|
||||
vec![
|
||||
literal(Tagged::None),
|
||||
number(0.),
|
||||
number(0.),
|
||||
number(24.),
|
||||
number(1.2),
|
||||
number(2.),
|
||||
number(10.),
|
||||
number(0.),
|
||||
number(100.),
|
||||
number(0.),
|
||||
number(100.),
|
||||
number(0.),
|
||||
],
|
||||
);
|
||||
let migrated = fixture.migrate(&TextV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, text),
|
||||
[
|
||||
literal(Tagged::None),
|
||||
number(0.),
|
||||
number(0.),
|
||||
length(24.),
|
||||
number(1.2),
|
||||
length(2.),
|
||||
angle(10.),
|
||||
number(0.),
|
||||
length(100.),
|
||||
number(0.),
|
||||
length(100.),
|
||||
number(0.)
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const LOCATION: usize = 1;
|
||||
const DIMENSIONS: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
DVec2([f64; 2]),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The location and dimensions are pairs of lengths, which keep the pixels they held. Wired Vec2s still feed them, read as pixels.
|
||||
#[migration("graphic_nodes::artboard::CreateArtboardNode"@1 => @2)]
|
||||
pub fn create_artboard_v1(node: &Node, inputs: &mut Inputs) {
|
||||
for slot in [LOCATION, DIMENSIONS] {
|
||||
if let Some(Tagged::DVec2(pixels)) = node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
inputs.set(slot as u32, lengths(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| match slot {
|
||||
LOCATION | DIMENSIONS => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::None),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&CreateArtboardV1, &contract());
|
||||
check_undo(&CreateArtboardV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec2s_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&CreateArtboardV1);
|
||||
let none = || literal(Tagged::None);
|
||||
let artboard = fixture.add(
|
||||
decl!("graphic_nodes::artboard::CreateArtboardNode"@1),
|
||||
vec![none(), literal(Tagged::DVec2([10., 20.])), literal(Tagged::DVec2([1920., 1080.])), none(), none()],
|
||||
);
|
||||
let migrated = fixture.migrate(&CreateArtboardV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, artboard), [none(), lengths([10., 20.]), lengths([1920., 1080.]), none(), none()]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const OFFSET: usize = 2;
|
||||
const ANGLE: usize = 3;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The offset is a length and the angle is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||
#[migration("graphic_nodes::graphic::MirrorNode"@1 => @2)]
|
||||
pub fn mirror_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(pixels) = number_at(OFFSET) {
|
||||
inputs.set(OFFSET as u32, length(pixels));
|
||||
}
|
||||
if let Some(degrees) = number_at(ANGLE) {
|
||||
inputs.set(ANGLE as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MirrorV1, &contract());
|
||||
check_undo(&MirrorV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_and_degrees_become_a_length_and_an_angle() {
|
||||
let mut fixture = Fixture::new(&MirrorV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let mirror = fixture.add(
|
||||
decl!("graphic_nodes::graphic::MirrorNode"@1),
|
||||
vec![literal(Tagged::None), number(0.), number(20.), number(45.), number(1.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&MirrorV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, mirror), [literal(Tagged::None), number(0.), length(20.), angle(45.), number(1.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `graphic_nodes`.
|
||||
|
||||
mod create_artboard_v1;
|
||||
mod mirror_v1;
|
||||
@@ -2,8 +2,13 @@
|
||||
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
|
||||
|
||||
mod blending_nodes;
|
||||
mod brush_nodes;
|
||||
mod core_types;
|
||||
mod graphene_core;
|
||||
mod graphene_std;
|
||||
mod graphic_nodes;
|
||||
mod math_nodes;
|
||||
mod raster_nodes;
|
||||
mod repeat_nodes;
|
||||
mod transform_nodes;
|
||||
mod vector_nodes;
|
||||
@@ -0,0 +1,47 @@
|
||||
use migration_core::{Inputs, NodeInput, migration};
|
||||
|
||||
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
|
||||
#[migration("math_nodes::MathFormulaNode"@2 => @3)]
|
||||
pub fn math_formula_v2(inputs: &mut Inputs) {
|
||||
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
String(String),
|
||||
}
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| match slot {
|
||||
1 => literal(Tagged::String("a + b".to_string())),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MathFormulaV2, &contract());
|
||||
check_undo(&MathFormulaV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_resolution_is_read_from_the_scope() {
|
||||
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("a * 2".to_string())), literal(Tagged::Number(0.))];
|
||||
|
||||
let mut fixture = Fixture::new(&MathFormulaV2);
|
||||
let formula = fixture.add(decl!("math_nodes::MathFormulaNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&MathFormulaV2).unwrap();
|
||||
|
||||
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
|
||||
assert_eq!(fixture.inputs(&migrated, formula), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod math_formula_from_math_f;
|
||||
mod math_formula_v2;
|
||||
mod math_function_v2;
|
||||
mod renames;
|
||||
@@ -3,3 +3,21 @@
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2);
|
||||
|
||||
// Version 2 takes lengths and angles too, with its output type following them, and stored nodes already have its layout
|
||||
rename!("math_nodes::SineNode"@1 => @2);
|
||||
rename!("math_nodes::CosineNode"@1 => @2);
|
||||
rename!("math_nodes::TangentNode"@1 => @2);
|
||||
rename!("math_nodes::SignNode"@1 => @2);
|
||||
rename!("math_nodes::SumNode"@1 => @2);
|
||||
rename!("math_nodes::AverageNode"@1 => @2);
|
||||
rename!("math_nodes::MinimumNode"@1 => @2);
|
||||
rename!("math_nodes::MaximumNode"@1 => @2);
|
||||
|
||||
// Version 2 reads a number beside a length or angle in pixels or degrees, and stored nodes already have its layout
|
||||
rename!("math_nodes::LerpNode"@1 => @2);
|
||||
rename!("math_nodes::ClampNode"@1 => @2);
|
||||
rename!("math_nodes::LessThanNode"@1 => @2);
|
||||
rename!("math_nodes::GreaterThanNode"@1 => @2);
|
||||
rename!("math_nodes::EqualsNode"@1 => @2);
|
||||
rename!("math_nodes::NotEqualsNode"@1 => @2);
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("raster_nodes::filter::MedianFilterNode"@1 => @2)]
|
||||
pub fn median_filter_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
RADIUS as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MedianFilterV1, &contract());
|
||||
check_undo(&MedianFilterV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&MedianFilterV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let median_filter = fixture.add(decl!("raster_nodes::filter::MedianFilterNode"@1), vec![literal(Tagged::None), number(5.)]);
|
||||
let migrated = fixture.migrate(&MedianFilterV1).unwrap();
|
||||
|
||||
let radius = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, median_filter), [literal(Tagged::None), radius]);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod mandelbrot_v1;
|
||||
mod mandelbrot_v2;
|
||||
mod median_filter_v1;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod pattern_square;
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `repeat_nodes`.
|
||||
|
||||
mod repeat_array_v1;
|
||||
mod repeat_radial_v1;
|
||||
@@ -0,0 +1,98 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DIRECTION: usize = 1;
|
||||
const ANGLE: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
DVec2([f64; 2]),
|
||||
Angle(TypedAngle),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The direction is a pair of lengths and the angle is an angle, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
|
||||
#[migration("repeat_nodes::repeat_nodes::RepeatArrayNode"@1 => @2)]
|
||||
pub fn repeat_array_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
|
||||
|
||||
if let Some(Tagged::DVec2(pixels)) = literal_at(DIRECTION) {
|
||||
inputs.set(DIRECTION as u32, direction(pixels));
|
||||
}
|
||||
if let Some(Tagged::Number(degrees)) = literal_at(ANGLE) {
|
||||
inputs.set(ANGLE as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn direction(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| match slot {
|
||||
0 => literal(Tagged::None),
|
||||
DIRECTION => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::Number(random.below(100) as f64)),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RepeatArrayV1, &contract());
|
||||
check_undo(&RepeatArrayV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_degrees_becomes_an_angle_in_degrees() {
|
||||
let mut fixture = Fixture::new(&RepeatArrayV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let repeat_array = fixture.add(
|
||||
decl!("repeat_nodes::repeat_nodes::RepeatArrayNode"@1),
|
||||
vec![literal(Tagged::None), literal(Tagged::DVec2([100., 50.])), number(90.), number(5.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&RepeatArrayV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, repeat_array), [literal(Tagged::None), direction([100., 50.]), angle(90.), number(5.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const START_ANGLE: usize = 1;
|
||||
const RADIUS: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The start angle is an angle and the radius is a length, which keep the numbers of degrees and pixels they held. Wired numbers still feed them, read as degrees and pixels.
|
||||
#[migration("repeat_nodes::repeat_nodes::RepeatRadialNode"@1 => @2)]
|
||||
pub fn repeat_radial_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(pixels) = number_at(RADIUS) {
|
||||
inputs.set(RADIUS as u32, length(pixels));
|
||||
}
|
||||
if let Some(degrees) = number_at(START_ANGLE) {
|
||||
inputs.set(START_ANGLE as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RepeatRadialV1, &contract());
|
||||
check_undo(&RepeatRadialV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_degrees_and_pixels_become_an_angle_and_a_length() {
|
||||
let mut fixture = Fixture::new(&RepeatRadialV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let repeat_radial = fixture.add(
|
||||
decl!("repeat_nodes::repeat_nodes::RepeatRadialNode"@1),
|
||||
vec![literal(Tagged::None), number(45.), number(5.), number(5.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&RepeatRadialV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, repeat_radial), [literal(Tagged::None), angle(45.), length(5.), number(5.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `transform_nodes`.
|
||||
|
||||
mod transform_v1;
|
||||
mod vary_rotations_v2;
|
||||
@@ -0,0 +1,125 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const TRANSLATION: usize = 1;
|
||||
const ROTATION: usize = 2;
|
||||
const SKEW: usize = 4;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
DVec2([f64; 2]),
|
||||
Angle(TypedAngle),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
AngleVec2(TypedAngleVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngleVec2 {
|
||||
value: [f64; 2],
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The translation is a pair of lengths and the rotation and skew are angles, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
|
||||
#[migration("transform_nodes::transform_nodes::TransformNode"@1 => @2)]
|
||||
pub fn transform_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
|
||||
|
||||
if let Some(Tagged::DVec2(pixels)) = literal_at(TRANSLATION) {
|
||||
inputs.set(TRANSLATION as u32, translation(pixels));
|
||||
}
|
||||
if let Some(Tagged::Number(degrees)) = literal_at(ROTATION) {
|
||||
inputs.set(ROTATION as u32, rotation(degrees));
|
||||
}
|
||||
if let Some(Tagged::DVec2(degrees)) = literal_at(SKEW) {
|
||||
inputs.set(SKEW as u32, skew(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole-list counterpart of the Transform node, with parameters that migrate the same way.
|
||||
#[migration("transform_nodes::transform_nodes::TransformListNode"@1 => @2)]
|
||||
pub fn transform_list_v1(node: &Node, inputs: &mut Inputs) {
|
||||
transform_v1(node, inputs);
|
||||
}
|
||||
|
||||
fn translation(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn rotation(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
fn skew(degrees: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::AngleVec2(TypedAngleVec2 {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| match slot {
|
||||
0 => literal(Tagged::None),
|
||||
ROTATION => literal(Tagged::Number(random.below(360) as f64)),
|
||||
_ => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&TransformV1, &contract());
|
||||
check_undo(&TransformV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixels_and_degrees_become_typed_lengths_and_angles() {
|
||||
let mut fixture = Fixture::new(&TransformV1);
|
||||
let vec2 = |x: f64, y: f64| literal(Tagged::DVec2([x, y]));
|
||||
let transform = fixture.add(
|
||||
decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
vec![literal(Tagged::None), vec2(10., 20.), literal(Tagged::Number(45.)), vec2(2., 3.), vec2(15., 0.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&TransformV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, transform),
|
||||
[literal(Tagged::None), translation([10., 20.]), rotation(45.), vec2(2., 3.), skew([15., 0.])]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const MIN: usize = 1;
|
||||
const MAX: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The ends of the range are angles, which keep the numbers of degrees they held. Wired numbers still feed them, read as degrees.
|
||||
#[migration("transform_nodes::transform_nodes::VaryRotationsNode"@2 => @3)]
|
||||
pub fn vary_rotations_v2(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [MIN, MAX] {
|
||||
if let Some(degrees) = number_at(slot) {
|
||||
inputs.set(slot as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&VaryRotationsV2, &contract());
|
||||
check_undo(&VaryRotationsV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_degrees_become_angles_in_degrees() {
|
||||
let mut fixture = Fixture::new(&VaryRotationsV2);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let vary_rotations = fixture.add(
|
||||
decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2),
|
||||
vec![literal(Tagged::None), number(-180.), number(180.), number(0.5), number(0.), number(1.), number(0.), number(0.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&VaryRotationsV2).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, vary_rotations),
|
||||
[literal(Tagged::None), angle(-180.), angle(180.), number(0.5), number(0.), number(1.), number(0.), number(0.)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 1;
|
||||
const START_ANGLE: usize = 2;
|
||||
const SWEEP_ANGLE: usize = 3;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The radius is a length and the start and sweep angles are angles, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||
#[migration("vector_nodes::generator_nodes::ArcNode"@1 => @2)]
|
||||
pub fn arc_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(pixels) = number_at(RADIUS) {
|
||||
inputs.set(RADIUS as u32, length(pixels));
|
||||
}
|
||||
for slot in [START_ANGLE, SWEEP_ANGLE] {
|
||||
if let Some(degrees) = number_at(slot) {
|
||||
inputs.set(slot as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ArcV1, &contract());
|
||||
check_undo(&ArcV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_and_degrees_become_a_length_and_angles() {
|
||||
let mut fixture = Fixture::new(&ArcV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let arc = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::ArcNode"@1),
|
||||
vec![literal(Tagged::None), number(50.), number(0.), number(270.), number(1.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&ArcV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, arc), [literal(Tagged::None), length(50.), angle(0.), angle(270.), number(1.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const ARROW_TO: usize = 1;
|
||||
const SHAFT_WIDTH: usize = 2;
|
||||
const HEAD_WIDTH: usize = 3;
|
||||
const HEAD_LENGTH: usize = 4;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
DVec2([f64; 2]),
|
||||
Length(TypedLength),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The end point is a pair of lengths and the shaft and head sizes are lengths, which keep the pixels they held. Wired values still feed them, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::ArrowNode"@1 => @2)]
|
||||
pub fn arrow_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(Tagged::DVec2(pixels)) = node.inputs().get(ARROW_TO).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
inputs.set(ARROW_TO as u32, lengths(pixels));
|
||||
}
|
||||
for slot in [SHAFT_WIDTH, HEAD_WIDTH, HEAD_LENGTH] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| match slot {
|
||||
0 => literal(Tagged::None),
|
||||
ARROW_TO => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::Number(random.below(100) as f64)),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ArrowV1, &contract());
|
||||
check_undo(&ArrowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&ArrowV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let arrow = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::ArrowNode"@1),
|
||||
vec![literal(Tagged::None), literal(Tagged::DVec2([100., 0.])), number(10.), number(30.), number(20.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&ArrowV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, arrow), [literal(Tagged::None), lengths([100., 0.]), length(10.), length(30.), length(20.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS_X: usize = 1;
|
||||
const RADIUS_Y: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radii are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::EllipseNode"@1 => @2)]
|
||||
pub fn ellipse_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [RADIUS_X, RADIUS_Y] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&EllipseV1, &contract());
|
||||
check_undo(&EllipseV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&EllipseV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let ellipse = fixture.add(decl!("vector_nodes::generator_nodes::EllipseNode"@1), vec![literal(Tagged::None), number(50.), number(25.)]);
|
||||
let migrated = fixture.migrate(&EllipseV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, ellipse), [literal(Tagged::None), length(50.), length(25.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SPACING: usize = 6;
|
||||
const ANGLES: usize = 7;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
DVec2([f64; 2]),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
AngleVec2(TypedAngleVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngleVec2 {
|
||||
value: [f64; 2],
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The spacing is a pair of lengths, filled from one number in both axes, and the isometric angles are a pair of angles, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
|
||||
#[migration("vector_nodes::generator_nodes::GridNode"@1 => @2)]
|
||||
pub fn grid_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
|
||||
|
||||
match literal_at(SPACING) {
|
||||
Some(Tagged::Number(pixels)) => inputs.set(SPACING as u32, lengths([pixels, pixels])),
|
||||
Some(Tagged::DVec2(pixels)) => inputs.set(SPACING as u32, lengths(pixels)),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(Tagged::DVec2(degrees)) = literal_at(ANGLES) {
|
||||
inputs.set(ANGLES as u32, angles(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angles(degrees: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::AngleVec2(TypedAngleVec2 {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, slot| match slot {
|
||||
SPACING if random.below(2) == 0 => literal(Tagged::Number(random.below(100) as f64)),
|
||||
SPACING | ANGLES => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::None),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&GridV1, &contract());
|
||||
check_undo(&GridV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixels_and_degrees_become_typed_lengths_and_angles() {
|
||||
let mut fixture = Fixture::new(&GridV1);
|
||||
let none = || literal(Tagged::None);
|
||||
let square = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::GridNode"@1),
|
||||
vec![none(), none(), none(), none(), none(), none(), literal(Tagged::Number(10.)), literal(Tagged::DVec2([30., 30.]))],
|
||||
);
|
||||
let rectangular = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::GridNode"@1),
|
||||
vec![none(), none(), none(), none(), none(), none(), literal(Tagged::DVec2([10., 20.])), literal(Tagged::DVec2([30., 60.]))],
|
||||
);
|
||||
let migrated = fixture.migrate(&GridV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, square),
|
||||
[none(), none(), none(), none(), none(), none(), lengths([10., 10.]), angles([30., 30.])]
|
||||
);
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, rectangular),
|
||||
[none(), none(), none(), none(), none(), none(), lengths([10., 20.]), angles([30., 60.])]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const TIP_ANGLE: usize = 6;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The tip angle is an angle, which keeps the number of degrees it held. A wired number still feeds it, read as degrees.
|
||||
#[migration("vector_nodes::generator_nodes::HeartNode"@1 => @2)]
|
||||
pub fn heart_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(TIP_ANGLE) else { return };
|
||||
let Some(Tagged::Number(degrees)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
TIP_ANGLE as u32,
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&HeartV1, &contract());
|
||||
check_undo(&HeartV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_degrees_becomes_an_angle_in_degrees() {
|
||||
let mut fixture = Fixture::new(&HeartV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let heart = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::HeartNode"@1),
|
||||
vec![literal(Tagged::None), number(70.), number(0.), number(0.), number(70.), number(50.), number(75.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&HeartV1).unwrap();
|
||||
|
||||
let tip_angle = literal(Tagged::Angle(TypedAngle { value: 75., unit: AngleUnit::Degree }));
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, heart),
|
||||
[literal(Tagged::None), number(70.), number(0.), number(0.), number(70.), number(50.), tip_angle]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const LINE_TO: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
DVec2([f64; 2]),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The end point is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::LineNode"@1 => @2)]
|
||||
pub fn line_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(LINE_TO) else { return };
|
||||
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(LINE_TO as u32, lengths(pixels));
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| match slot {
|
||||
LINE_TO => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::None),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&LineV1, &contract());
|
||||
check_undo(&LineV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&LineV1);
|
||||
let node = fixture.add(decl!("vector_nodes::generator_nodes::LineNode"@1), vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.]))]);
|
||||
let migrated = fixture.migrate(&LineV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.])]);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,16 @@
|
||||
//! Migrations of the nodes in `vector_nodes`.
|
||||
|
||||
mod arc_v1;
|
||||
mod arrow_v1;
|
||||
mod circle_v1;
|
||||
mod ellipse_v1;
|
||||
mod grid_v1;
|
||||
mod heart_v1;
|
||||
mod line_v1;
|
||||
mod path_from_path_network;
|
||||
mod qr_code_v1;
|
||||
mod rectangle_v1;
|
||||
mod regular_polygon_v1;
|
||||
mod renames;
|
||||
mod spiral_v1;
|
||||
mod star_v1;
|
||||
@@ -0,0 +1,69 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SIZE: usize = 3;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The size is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::QrCodeNode"@1 => @2)]
|
||||
pub fn qr_code_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(SIZE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(SIZE as u32, length(pixels));
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(6, |random, slot| if slot == SIZE { literal(Tagged::Number(random.below(100) as f64)) } else { literal(Tagged::None) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&QrCodeV1, &contract());
|
||||
check_undo(&QrCodeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&QrCodeV1);
|
||||
let none = || literal(Tagged::None);
|
||||
let qr_code = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::QrCodeNode"@1),
|
||||
vec![none(), none(), none(), literal(Tagged::Number(200.)), none(), none()],
|
||||
);
|
||||
let migrated = fixture.migrate(&QrCodeV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, qr_code), [none(), none(), none(), length(200.), none(), none()]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const WIDTH: usize = 1;
|
||||
const HEIGHT: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The width and height are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::RectangleNode"@1 => @2)]
|
||||
pub fn rectangle_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [WIDTH, HEIGHT] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(6, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RectangleV1, &contract());
|
||||
check_undo(&RectangleV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&RectangleV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let rectangle = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::RectangleNode"@1),
|
||||
vec![literal(Tagged::None), number(100.), number(80.), number(0.), number(1.), number(0.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&RectangleV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, rectangle),
|
||||
[literal(Tagged::None), length(100.), length(80.), number(0.), number(1.), number(0.)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::RegularPolygonNode"@1 => @2)]
|
||||
pub fn regular_polygon_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
RADIUS as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RegularPolygonV1, &contract());
|
||||
check_undo(&RegularPolygonV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&RegularPolygonV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let polygon = fixture.add(decl!("vector_nodes::generator_nodes::RegularPolygonNode"@1), vec![literal(Tagged::None), number(6.), number(50.)]);
|
||||
let migrated = fixture.migrate(&RegularPolygonV1).unwrap();
|
||||
|
||||
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, polygon), [literal(Tagged::None), number(6.), radius]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const START_ANGLE: usize = 3;
|
||||
const INNER_RADIUS: usize = 4;
|
||||
const OUTER_RADIUS: usize = 5;
|
||||
const ANGULAR_RESOLUTION: usize = 6;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The radii are lengths and the start angle and angular resolution are angles, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||
#[migration("vector_nodes::generator_nodes::SpiralNode"@1 => @2)]
|
||||
pub fn spiral_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [INNER_RADIUS, OUTER_RADIUS] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
for slot in [START_ANGLE, ANGULAR_RESOLUTION] {
|
||||
if let Some(degrees) = number_at(slot) {
|
||||
inputs.set(slot as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&SpiralV1, &contract());
|
||||
check_undo(&SpiralV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_and_degrees_become_lengths_and_angles() {
|
||||
let mut fixture = Fixture::new(&SpiralV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let spiral = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::SpiralNode"@1),
|
||||
vec![literal(Tagged::None), number(0.), number(5.), number(0.), number(0.), number(25.), number(90.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&SpiralV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, spiral),
|
||||
[literal(Tagged::None), number(0.), number(5.), angle(0.), length(0.), length(25.), angle(90.)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS_1: usize = 2;
|
||||
const RADIUS_2: usize = 3;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radii are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::StarNode"@1 => @2)]
|
||||
pub fn star_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [RADIUS_1, RADIUS_2] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&StarV1, &contract());
|
||||
check_undo(&StarV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&StarV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let star = fixture.add(decl!("vector_nodes::generator_nodes::StarNode"@1), vec![literal(Tagged::None), number(5.), number(50.), number(25.)]);
|
||||
let migrated = fixture.migrate(&StarV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, star), [literal(Tagged::None), number(5.), length(50.), length(25.)]);
|
||||
}
|
||||
}
|
||||
@@ -115,27 +115,13 @@ 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();
|
||||
|
||||
if let ExportBounds::Artboard(layer) = self.export_dialog.bounds
|
||||
&& !self.export_dialog.artboards.contains_key(&layer)
|
||||
&& !self.export_dialog.artboards.iter().any(|(artboard, _)| *artboard == layer)
|
||||
{
|
||||
self.export_dialog.bounds = ExportBounds::AllArtwork;
|
||||
self.export_dialog.bounds = self.export_dialog.default_bounds();
|
||||
self.export_dialog.bounds_chosen = false;
|
||||
}
|
||||
|
||||
self.export_dialog.has_selection = document.network_interface.selected_nodes().selected_layers(document.metadata()).next().is_some();
|
||||
|
||||
@@ -14,7 +14,10 @@ pub struct ExportDialogMessageHandler {
|
||||
pub file_type: FileType,
|
||||
pub scale_factor: f64,
|
||||
pub bounds: ExportBounds,
|
||||
pub artboards: HashMap<LayerNodeIdentifier, String>,
|
||||
/// Whether the bounds were picked in the dialog, rather than left at the default of the file type, which a change of file type replaces.
|
||||
pub bounds_chosen: bool,
|
||||
/// Each artboard with its name, from the top of the Layers panel down.
|
||||
pub artboards: Vec<(LayerNodeIdentifier, String)>,
|
||||
pub has_selection: bool,
|
||||
}
|
||||
|
||||
@@ -24,6 +27,7 @@ impl Default for ExportDialogMessageHandler {
|
||||
file_type: Default::default(),
|
||||
scale_factor: 1.,
|
||||
bounds: Default::default(),
|
||||
bounds_chosen: false,
|
||||
artboards: Default::default(),
|
||||
has_selection: false,
|
||||
}
|
||||
@@ -36,20 +40,23 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
let ExportDialogMessageContext { portfolio } = context;
|
||||
|
||||
match message {
|
||||
ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
|
||||
ExportDialogMessage::FileType { file_type } => {
|
||||
self.file_type = file_type;
|
||||
if !self.bounds_chosen {
|
||||
self.bounds = self.default_bounds();
|
||||
}
|
||||
}
|
||||
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
|
||||
ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
|
||||
ExportDialogMessage::ExportBounds { bounds } => {
|
||||
self.bounds = bounds;
|
||||
self.bounds_chosen = true;
|
||||
}
|
||||
|
||||
ExportDialogMessage::Submit => {
|
||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
||||
let bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
|
||||
ExportBounds::AllArtwork
|
||||
} else {
|
||||
self.bounds
|
||||
};
|
||||
let bounds = self.current_bounds();
|
||||
|
||||
let artboard_name = match bounds {
|
||||
ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
|
||||
ExportBounds::Artboard(layer) => self.artboards.iter().find(|(artboard, _)| *artboard == layer).map(|(_, name)| name.clone()),
|
||||
_ => None,
|
||||
};
|
||||
responses.add_front(PortfolioMessage::SubmitDocumentExport {
|
||||
@@ -70,6 +77,23 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
);
|
||||
}
|
||||
|
||||
impl ExportDialogMessageHandler {
|
||||
/// The bounds a file type starts with: each artboard as its own page for a PDF, or otherwise all the artwork.
|
||||
pub fn default_bounds(&self) -> ExportBounds {
|
||||
if self.file_type == FileType::Pdf { ExportBounds::AllArtboards } else { ExportBounds::AllArtwork }
|
||||
}
|
||||
|
||||
/// The chosen bounds, falling back to the default and then "All Artwork" in place of a choice that isn't currently available.
|
||||
fn current_bounds(&self) -> ExportBounds {
|
||||
let available = |bounds: &ExportBounds| match bounds {
|
||||
ExportBounds::Selection => self.has_selection,
|
||||
ExportBounds::AllArtboards => self.file_type == FileType::Pdf && !self.artboards.is_empty(),
|
||||
ExportBounds::AllArtwork | ExportBounds::Artboard(_) => true,
|
||||
};
|
||||
[self.bounds, self.default_bounds()].into_iter().find(available).unwrap_or(ExportBounds::AllArtwork)
|
||||
}
|
||||
}
|
||||
|
||||
impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||
const ICON: &'static str = "File";
|
||||
const TITLE: &'static str = "Export";
|
||||
@@ -94,9 +118,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"),
|
||||
@@ -139,7 +163,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.increment_step(0.5)
|
||||
.disabled(self.file_type == FileType::Svg)
|
||||
.disabled(matches!(self.file_type, FileType::Svg | FileType::Pdf))
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
||||
.sizing(WidgetSizing::default().min_width(200))
|
||||
.widget_instance(),
|
||||
@@ -149,15 +173,12 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
(ExportBounds::AllArtwork, "All Artwork".to_string(), false),
|
||||
(ExportBounds::Selection, "Selection".to_string(), !self.has_selection),
|
||||
];
|
||||
let artboards = self.artboards.iter().map(|(&layer, name)| (ExportBounds::Artboard(layer), name.to_string(), false)).collect();
|
||||
let choices = [standard_bounds, artboards];
|
||||
// Only a PDF can hold every artboard, each as its own page
|
||||
let all_artboards = (!self.artboards.is_empty()).then(|| (ExportBounds::AllArtboards, "All Artboards".to_string(), self.file_type != FileType::Pdf));
|
||||
let artboards = self.artboards.iter().map(|(layer, name)| (ExportBounds::Artboard(*layer), name.to_string(), false));
|
||||
let choices = [standard_bounds, all_artboards.into_iter().chain(artboards).collect()];
|
||||
|
||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
||||
let current_bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
|
||||
ExportBounds::AllArtwork
|
||||
} else {
|
||||
self.bounds
|
||||
};
|
||||
let current_bounds = self.current_bounds();
|
||||
let index = choices.iter().flatten().position(|(bounds, _, _)| *bounds == current_bounds).unwrap_or(0);
|
||||
|
||||
let mut entries = choices
|
||||
@@ -188,3 +209,44 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
Layout(vec![LayoutGroup::row(export_type), LayoutGroup::row(resolution), LayoutGroup::row(export_area)])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::EditorTestUtils;
|
||||
use graphene_std::uuid::NodeId;
|
||||
|
||||
#[test]
|
||||
fn a_pdf_defaults_to_every_artboard_as_a_page() {
|
||||
let editor = EditorTestUtils::create();
|
||||
let portfolio = editor.portfolio_message_handler();
|
||||
let mut dialog = ExportDialogMessageHandler {
|
||||
artboards: vec![(LayerNodeIdentifier::new_unchecked(NodeId(1)), "Artboard".to_string())],
|
||||
has_selection: true,
|
||||
..Default::default()
|
||||
};
|
||||
let send = |dialog: &mut ExportDialogMessageHandler, message: ExportDialogMessage| dialog.process_message(message, &mut VecDeque::new(), ExportDialogMessageContext { portfolio });
|
||||
|
||||
// Bounds left at the default follow the file type between PDF and a single image
|
||||
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Pdf });
|
||||
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtboards);
|
||||
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Png });
|
||||
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtwork);
|
||||
|
||||
// A choice of other bounds stays through a change of file type
|
||||
send(&mut dialog, ExportDialogMessage::ExportBounds { bounds: ExportBounds::Selection });
|
||||
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Pdf });
|
||||
assert_eq!(dialog.current_bounds(), ExportBounds::Selection);
|
||||
|
||||
// Even a choice of the bounds another file type defaults to
|
||||
send(&mut dialog, ExportDialogMessage::ExportBounds { bounds: ExportBounds::AllArtwork });
|
||||
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Png });
|
||||
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Pdf });
|
||||
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtwork);
|
||||
|
||||
// Without artboards, a PDF falls back to one page of all the artwork
|
||||
send(&mut dialog, ExportDialogMessage::ExportBounds { bounds: ExportBounds::AllArtboards });
|
||||
dialog.artboards.clear();
|
||||
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtwork);
|
||||
}
|
||||
}
|
||||
+59
-16
@@ -1,12 +1,13 @@
|
||||
use crate::messages::dialog::document_setup_dialog::resolution_row;
|
||||
use crate::messages::layout::layout_message_handler::unit_suffix;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::node_inspector::length_decimal_places;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, LengthUnit, TypedLength};
|
||||
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, LengthUnit, TypedLength, TypedLengthVec2};
|
||||
|
||||
/// A dialog to allow users to set some initial options about a new document.
|
||||
#[derive(Debug, Clone, ExtractField)]
|
||||
@@ -54,10 +55,11 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
});
|
||||
|
||||
let dimensions = self.artboard_dimensions();
|
||||
let pixels = dimensions.to_length_vec2(self.pixels_per_inch).pixels();
|
||||
if self.infinite {
|
||||
// Infinite canvas: add a locked white background layer
|
||||
graph_modification_utils::new_background_layer(0, responses);
|
||||
} else if dimensions.x > 0. && dimensions.y > 0. {
|
||||
} else if pixels.x > 0. && pixels.y > 0. {
|
||||
// Finite canvas: create an artboard with the specified dimensions
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
@@ -66,7 +68,7 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
background: Color::WHITE,
|
||||
clip: true,
|
||||
});
|
||||
responses.add(NavigationMessage::CanvasPan { delta: dimensions });
|
||||
responses.add(NavigationMessage::CanvasPan { delta: pixels });
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
@@ -142,6 +144,7 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
||||
NumberInput::new(Some(length.value))
|
||||
.label(label)
|
||||
.unit(unit_suffix(length.unit.symbol()))
|
||||
.display_decimal_places(length_decimal_places(length.unit, self.pixels_per_inch))
|
||||
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||
.pixels_per_inch(self.pixels_per_inch)
|
||||
.min(0.)
|
||||
@@ -176,10 +179,12 @@ impl NewDocumentDialogMessageHandler {
|
||||
})
|
||||
}
|
||||
|
||||
/// The artboard's size in whole pixels, converting a dimension typed in a physical unit at the chosen resolution.
|
||||
pub fn artboard_dimensions(&self) -> DVec2 {
|
||||
let pixels = |length: TypedLength| length.to_length(self.pixels_per_inch).pixels().round();
|
||||
DVec2::new(pixels(self.width), pixels(self.height))
|
||||
/// The artboard's size in the unit both dimensions share, like an A4 page in millimeters.
|
||||
pub fn artboard_dimensions(&self) -> TypedLengthVec2 {
|
||||
TypedLengthVec2 {
|
||||
value: DVec2::new(self.width.value, self.height.value),
|
||||
unit: self.width.unit,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,6 +209,7 @@ mod tests {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_DIMENSIONS_INPUT_INDEX;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::{LengthUnit, TypedLengthVec2};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Commits text into the dialog's number field with this label or tooltip label, as the frontend sends a typed entry.
|
||||
@@ -234,15 +240,17 @@ mod tests {
|
||||
.await;
|
||||
}
|
||||
|
||||
fn artboard_dimensions(editor: &EditorTestUtils) -> Option<DVec2> {
|
||||
fn artboard_dimensions(editor: &EditorTestUtils) -> Option<TaggedValue> {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let artboard = network_interface.all_artboards().into_iter().next()?;
|
||||
let node = network_interface.document_network().nodes.get(&artboard.to_node())?;
|
||||
|
||||
match node.inputs.get(ARTBOARD_DIMENSIONS_INPUT_INDEX)?.as_value()? {
|
||||
TaggedValue::DVec2(dimensions) => Some(*dimensions),
|
||||
_ => None,
|
||||
}
|
||||
node.inputs.get(ARTBOARD_DIMENSIONS_INPUT_INDEX)?.as_value().cloned()
|
||||
}
|
||||
|
||||
fn artboard_pixels(editor: &EditorTestUtils) -> Option<DVec2> {
|
||||
let pixels_per_inch = editor.active_document().network_interface.pixels_per_inch();
|
||||
artboard_dimensions(editor)?.as_length_vec2_pixels(pixels_per_inch).map(DVec2::round)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -252,11 +260,11 @@ mod tests {
|
||||
type_into_field(&mut editor, "Resolution", "300");
|
||||
create_document(&mut editor).await;
|
||||
assert_eq!(editor.active_document().network_interface.pixels_per_inch(), 300.);
|
||||
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(1920., 1080.)));
|
||||
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(1920., 1080.)));
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().network_interface.pixels_per_inch(), 300.);
|
||||
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(1920., 1080.)));
|
||||
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(1920., 1080.)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -268,7 +276,7 @@ mod tests {
|
||||
// The height of 1080 px at 96 PPI became 285.75 mm, so it grows with the resolution like the width
|
||||
type_into_field(&mut editor, "Resolution", "300");
|
||||
create_document(&mut editor).await;
|
||||
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(2480., 3375.)));
|
||||
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(2480., 3375.)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -281,6 +289,41 @@ mod tests {
|
||||
// The lengths stay in millimeters, so their size in pixels follows a resolution chosen after them
|
||||
type_into_field(&mut editor, "Resolution", "300");
|
||||
create_document(&mut editor).await;
|
||||
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(2480., 3508.)));
|
||||
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(2480., 3508.)));
|
||||
|
||||
// The artboard keeps the millimeters, so changing the resolution later keeps the page's physical size
|
||||
let a4 = TaggedValue::LengthVec2(TypedLengthVec2 {
|
||||
value: DVec2::new(210., 297.),
|
||||
unit: LengthUnit::Millimeter,
|
||||
});
|
||||
assert_eq!(artboard_dimensions(&editor), Some(a4));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moving_an_artboard_sized_in_millimeters_keeps_its_millimeters() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||
type_into_field(&mut editor, "W", "210mm");
|
||||
type_into_field(&mut editor, "H", "297mm");
|
||||
create_document(&mut editor).await;
|
||||
let a4 = artboard_dimensions(&editor);
|
||||
|
||||
// Tools move and nudge an artboard by resizing it to its own size in whole pixels, which 793.7 x 1122.5 px rounds to
|
||||
let layer = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.all_artboards()
|
||||
.into_iter()
|
||||
.next()
|
||||
.expect("the document should have an artboard");
|
||||
let dimensions = artboard_pixels(&editor).expect("the artboard should have dimensions");
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::ResizeArtboard {
|
||||
layer,
|
||||
location: DVec2::new(10., 0.),
|
||||
dimensions,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(artboard_dimensions(&editor), a4);
|
||||
}
|
||||
}
|
||||
@@ -78,6 +78,7 @@ pub enum FileType {
|
||||
Tga,
|
||||
Ico,
|
||||
Svg,
|
||||
Pdf,
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
@@ -91,6 +92,7 @@ impl FileType {
|
||||
FileType::Tga => "tga",
|
||||
FileType::Ico => "ico",
|
||||
FileType::Svg => "svg",
|
||||
FileType::Pdf => "pdf",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +106,7 @@ impl FileType {
|
||||
FileType::Tga => "TGA Image",
|
||||
FileType::Ico => "ICO Image",
|
||||
FileType::Svg => "SVG Image",
|
||||
FileType::Pdf => "PDF Document",
|
||||
};
|
||||
FileFilter {
|
||||
name: name.into(),
|
||||
@@ -130,6 +133,7 @@ impl FileType {
|
||||
FileType::Tga => ImageFormat::Tga,
|
||||
FileType::Ico => ImageFormat::Ico,
|
||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||
FileType::Pdf => return Err("PDF cannot be exported from an image buffer".to_string()),
|
||||
};
|
||||
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());
|
||||
@@ -164,6 +168,8 @@ pub enum ExportBounds {
|
||||
#[default]
|
||||
AllArtwork,
|
||||
Selection,
|
||||
/// Each artboard as its own page, for a file type that holds pages.
|
||||
AllArtboards,
|
||||
Artboard(LayerNodeIdentifier),
|
||||
}
|
||||
|
||||
@@ -228,6 +234,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();
|
||||
|
||||
@@ -25,7 +25,7 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||
use graphene_std::units::{Angle, Length};
|
||||
use graphene_std::units::{Angle, AngleVec2, Length, LengthVec2};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||
WeldMethod,
|
||||
@@ -404,6 +404,8 @@ macro_rules! inspectable_types {
|
||||
List<f64>,
|
||||
List<Length>,
|
||||
List<Angle>,
|
||||
List<LengthVec2>,
|
||||
List<AngleVec2>,
|
||||
List<i64>,
|
||||
List<bool>,
|
||||
List<DVec2>,
|
||||
@@ -466,6 +468,8 @@ macro_rules! inspectable_types {
|
||||
Item<f64>,
|
||||
Item<Length>,
|
||||
Item<Angle>,
|
||||
Item<LengthVec2>,
|
||||
Item<AngleVec2>,
|
||||
Item<i64>,
|
||||
Item<bool>,
|
||||
Item<DVec2>,
|
||||
@@ -1129,6 +1133,31 @@ impl TableItemLayout for Angle {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for LengthVec2 {
|
||||
fn type_name() -> &'static str {
|
||||
"Length Vec2"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format_dvec2(self.pixels())
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for AngleVec2 {
|
||||
fn type_name() -> &'static str {
|
||||
"Angle Vec2"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
let degrees = self.degrees();
|
||||
format!("({}°, {}°)", format_rounded(degrees.x, 3), format_rounded(degrees.y, 3))
|
||||
}
|
||||
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for u8 {
|
||||
fn type_name() -> &'static str {
|
||||
"Byte"
|
||||
|
||||
@@ -2456,6 +2456,23 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
/// Each artboard with its name, from the top of the Layers panel down.
|
||||
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
|
||||
}
|
||||
@@ -5299,7 +5316,7 @@ mod document_message_handler_tests {
|
||||
.handle_message(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
location: DVec2::ZERO,
|
||||
dimensions: DVec2::splat(200.),
|
||||
dimensions: graphene_std::units::TypedLengthVec2::pixels(DVec2::splat(200.)),
|
||||
background: Color::WHITE,
|
||||
clip: true,
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::units::TypedLengthVec2;
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, VectorModificationType};
|
||||
use std::sync::Arc;
|
||||
@@ -136,7 +137,7 @@ pub enum GraphOperationMessage {
|
||||
NewArtboard {
|
||||
id: NodeId,
|
||||
location: DVec2,
|
||||
dimensions: DVec2,
|
||||
dimensions: TypedLengthVec2,
|
||||
background: Color,
|
||||
clip: bool,
|
||||
},
|
||||
|
||||
+2
-1
@@ -14,6 +14,7 @@ use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::list;
|
||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::units::TypedLength;
|
||||
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::{Artboard, Color};
|
||||
|
||||
@@ -886,7 +887,7 @@ fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, laye
|
||||
let strokes_node = strokes_node_type.node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(color), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(diameter), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(diameter)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(flow), false)),
|
||||
]);
|
||||
|
||||
@@ -4,34 +4,40 @@ use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::transform::Transform;
|
||||
|
||||
/// Update the inputs of the transform node to match a new transform
|
||||
/// Update the inputs of the transform node to match a new transform, keeping each in the unit it was typed in.
|
||||
pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &NodeId, transform: DAffine2) {
|
||||
use graphene_std::transform_nodes::transform::*;
|
||||
|
||||
let (rotation, scale, skew) = transform.decompose_rotation_scale_skew();
|
||||
let translation = transform.translation;
|
||||
|
||||
let rotation = rotation.to_degrees();
|
||||
let skew = DVec2::new(skew.atan().to_degrees(), 0.);
|
||||
|
||||
network_interface.set_input(
|
||||
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::TranslationInput),
|
||||
NodeInput::value(TaggedValue::DVec2(translation), false),
|
||||
&[],
|
||||
);
|
||||
network_interface.set_input(
|
||||
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::RotationInput),
|
||||
NodeInput::value(TaggedValue::Number(rotation), false),
|
||||
&[],
|
||||
);
|
||||
network_interface.set_input(
|
||||
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::ScaleInput),
|
||||
NodeInput::value(TaggedValue::DVec2(scale), false),
|
||||
&[],
|
||||
);
|
||||
network_interface.set_input(
|
||||
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::SkewInput),
|
||||
NodeInput::value(TaggedValue::DVec2(skew), false),
|
||||
&[],
|
||||
);
|
||||
let pixels_per_inch = network_interface.pixels_per_inch();
|
||||
let [translation_input, rotation_input, scale_input, skew_input] = [
|
||||
InputConnector::node(*node_id, TranslationInput),
|
||||
InputConnector::node(*node_id, RotationInput),
|
||||
InputConnector::node(*node_id, ScaleInput),
|
||||
InputConnector::node(*node_id, SkewInput),
|
||||
];
|
||||
let existing = |input: &InputConnector| network_interface.input_from_connector(input, &[]).and_then(NodeInput::as_value).cloned().unwrap_or(TaggedValue::None);
|
||||
let (existing_translation, existing_rotation, existing_skew) = (existing(&translation_input), existing(&rotation_input), existing(&skew_input));
|
||||
|
||||
// An input already holding the value is left as typed, so rotating a layer doesn't rewrite a translation typed in millimeters with float noise
|
||||
let unchanged = |existing: Option<DVec2>, value: DVec2| existing.is_some_and(|existing| existing.abs_diff_eq(value, 1e-9));
|
||||
|
||||
if !unchanged(existing_translation.as_length_vec2_pixels(pixels_per_inch), translation) {
|
||||
let translation = existing_translation.length_vec2_in_same_unit(translation, pixels_per_inch);
|
||||
network_interface.set_input(&translation_input, NodeInput::value(translation, false), &[]);
|
||||
}
|
||||
if !unchanged(existing_rotation.as_angle_degrees().map(DVec2::splat), DVec2::splat(rotation)) {
|
||||
network_interface.set_input(&rotation_input, NodeInput::value(existing_rotation.angle_in_same_unit(rotation), false), &[]);
|
||||
}
|
||||
network_interface.set_input(&scale_input, NodeInput::value(TaggedValue::DVec2(scale), false), &[]);
|
||||
if !unchanged(existing_skew.as_angle_vec2_degrees(), skew) {
|
||||
network_interface.set_input(&skew_input, NodeInput::value(existing_skew.angle_vec2_in_same_unit(skew), false), &[]);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: This should be extracted from the graph at the location of the transform node.
|
||||
@@ -63,16 +69,14 @@ impl LayerBounds {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the current affine transform from the transform node's inputs
|
||||
pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
|
||||
let translation = if let Some(&TaggedValue::DVec2(translation)) = inputs[1].as_value() {
|
||||
translation
|
||||
} else {
|
||||
DVec2::ZERO
|
||||
};
|
||||
let rotation = if let Some(&TaggedValue::Number(rotation)) = inputs[2].as_value() { rotation } else { 0. };
|
||||
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
|
||||
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
|
||||
/// Get the current affine transform from the transform node's inputs, sizing a translation in a physical unit by the document's resolution.
|
||||
pub fn get_current_transform(inputs: &[NodeInput], pixels_per_inch: f64) -> DAffine2 {
|
||||
let value = |index: usize| inputs.get(index).and_then(NodeInput::as_value);
|
||||
|
||||
let translation = value(1).and_then(|value| value.as_length_vec2_pixels(pixels_per_inch)).unwrap_or(DVec2::ZERO);
|
||||
let rotation = value(2).and_then(TaggedValue::as_angle_degrees).unwrap_or(0.);
|
||||
let scale = if let Some(&TaggedValue::DVec2(scale)) = value(3) { scale } else { DVec2::ONE };
|
||||
let skew = value(4).and_then(TaggedValue::as_angle_vec2_degrees).unwrap_or(DVec2::ZERO);
|
||||
|
||||
let rotation = rotation.to_radians();
|
||||
let skew = DVec2::new(skew.x.to_radians().tan(), skew.y.to_radians().tan());
|
||||
|
||||
@@ -15,6 +15,7 @@ use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, list};
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::units::{TypedAngle, TypedLength, TypedLengthVec2};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic};
|
||||
@@ -68,12 +69,12 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
/// Creates an artboard as the primary export for the document network.
|
||||
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: DVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
|
||||
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: TypedLengthVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
|
||||
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
|
||||
Some(NodeInput::type_default(list!(Artboard), true)),
|
||||
Some(NodeInput::type_default(list!(Graphic), true)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(location), false)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
|
||||
Some(NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(location)), false)),
|
||||
Some(NodeInput::value(TaggedValue::LengthVec2(dimensions), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(background), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
|
||||
]);
|
||||
@@ -196,14 +197,14 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::None, false)),
|
||||
Some(NodeInput::value(TaggedValue::String(text), false)),
|
||||
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.font_size), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.font_size)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_spacing), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.letter_spacing)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Angle(TypedAngle::degrees(typesetting.letter_tilt)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.max_width.unwrap_or(100.))), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(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)
|
||||
@@ -729,13 +730,14 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
};
|
||||
|
||||
// `composed_old` = T_n * T_{n-1} * ... * T_1, `prior_combined` = same product without T_n
|
||||
let pixels_per_inch = self.network_interface.pixels_per_inch();
|
||||
let compose = |ids: &[_]| {
|
||||
ids.iter().fold(DAffine2::IDENTITY, |acc, transform_id| {
|
||||
self.network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.get(transform_id)
|
||||
.map_or(acc, |document_node| acc * transform_utils::get_current_transform(&document_node.inputs))
|
||||
.map_or(acc, |document_node| acc * transform_utils::get_current_transform(&document_node.inputs, pixels_per_inch))
|
||||
})
|
||||
};
|
||||
let prior_combined = compose(prior_transforms);
|
||||
@@ -871,7 +873,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.weight), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Length(TypedLength::pixels(stroke.weight)), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
|
||||
@@ -883,7 +885,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Length(TypedLength::pixels(stroke.dash_offset)), false), true);
|
||||
}
|
||||
|
||||
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
|
||||
@@ -894,7 +896,10 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false)
|
||||
.and_then(|transform_node_id| {
|
||||
let document_node = self.network_interface.document_network().nodes.get(&transform_node_id)?;
|
||||
Some((transform_utils::get_current_transform(&document_node.inputs), transform_node_id))
|
||||
Some((
|
||||
transform_utils::get_current_transform(&document_node.inputs, self.network_interface.pixels_per_inch()),
|
||||
transform_node_id,
|
||||
))
|
||||
})
|
||||
.unzip();
|
||||
let layer_transform = layer_transform.unwrap_or_default();
|
||||
@@ -932,7 +937,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let local_transform = metadata.local_transforms.get(&layer.to_node()).copied().unwrap_or(DAffine2::IDENTITY);
|
||||
let current_transform_node_value = transform_node_id
|
||||
.and_then(|id| self.network_interface.document_network().nodes.get(&id))
|
||||
.map(|node| transform_utils::get_current_transform(&node.inputs))
|
||||
.map(|node| transform_utils::get_current_transform(&node.inputs, self.network_interface.pixels_per_inch()))
|
||||
.unwrap_or(DAffine2::IDENTITY);
|
||||
parent_inverse * transform * local_transform.inverse() * current_transform_node_value
|
||||
} else {
|
||||
@@ -1020,16 +1025,37 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
dimensions.y = -dimensions.y;
|
||||
location.y -= dimensions.y;
|
||||
}
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node_at_index(artboard_node_id, ARTBOARD_LOCATION_INPUT_INDEX),
|
||||
NodeInput::value(TaggedValue::DVec2(location), false),
|
||||
false,
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node_at_index(artboard_node_id, ARTBOARD_DIMENSIONS_INPUT_INDEX),
|
||||
NodeInput::value(TaggedValue::DVec2(dimensions), false),
|
||||
false,
|
||||
);
|
||||
|
||||
// Each stays in the unit it was typed in, and a component that already rounds to the requested whole pixels stays as typed, so moving an artboard sized in millimeters keeps them
|
||||
let pixels_per_inch = self.network_interface.pixels_per_inch();
|
||||
for (index, pixels) in [(ARTBOARD_LOCATION_INPUT_INDEX, location), (ARTBOARD_DIMENSIONS_INPUT_INDEX, dimensions)] {
|
||||
let input_connector = InputConnector::node_at_index(artboard_node_id, index);
|
||||
let existing = self
|
||||
.network_interface
|
||||
.input_from_connector(&input_connector, &[])
|
||||
.and_then(NodeInput::as_value)
|
||||
.cloned()
|
||||
.unwrap_or(TaggedValue::None);
|
||||
let existing_lengths = match existing {
|
||||
TaggedValue::LengthVec2(lengths) => Some(lengths),
|
||||
TaggedValue::DVec2(pixels) => Some(TypedLengthVec2::pixels(pixels)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let mut value = existing.length_vec2_in_same_unit(pixels, pixels_per_inch);
|
||||
if let (Some(existing_lengths), TaggedValue::LengthVec2(lengths)) = (existing_lengths, &mut value) {
|
||||
let existing_pixels = existing_lengths.to_length_vec2(pixels_per_inch).pixels();
|
||||
for axis in 0..2 {
|
||||
if existing_pixels[axis].round() == pixels[axis] {
|
||||
lengths.value[axis] = existing_lengths.value[axis];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if value != existing {
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(value, false), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the input, refresh the Inspector, and run the document graph if skip_rerender is false
|
||||
|
||||
@@ -17,6 +17,7 @@ use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::units::TypedLengthVec2;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
@@ -242,8 +243,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Artboard), true),
|
||||
NodeInput::type_default(list!(Graphic), true),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
|
||||
NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(DVec2::ZERO)), false),
|
||||
NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(DVec2::new(1920., 1080.))), false),
|
||||
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
],
|
||||
@@ -709,6 +710,41 @@ type InputInspector = HashMap<String, Box<dyn Fn(NodeId, usize, &mut NodeInspect
|
||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector);
|
||||
|
||||
/// A number field set up from the proto node parameter's metadata, which only proto nodes have.
|
||||
fn proto_parameter_number_input(node_id: NodeId, index: usize, context: &mut NodeInspectorContext) -> NumberInput {
|
||||
let mut number_input = NumberInput::default();
|
||||
// The field is cloned so the lock is released before the caller builds the row, which locks the node metadata again
|
||||
if let Some(field) = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
{
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
// Typing is clamped only by the hard bounds; the slider extent prefers the soft bounds (see `inspector_row_from_type`)
|
||||
if let Some(hard_min) = field.number_hard_min {
|
||||
number_input = number_input.min(hard_min);
|
||||
}
|
||||
if let Some(hard_max) = field.number_hard_max {
|
||||
number_input = number_input.max(hard_max);
|
||||
}
|
||||
if field.number_mode_range {
|
||||
number_input = number_input
|
||||
.mode_range()
|
||||
.range_min(field.number_soft_min.or(field.number_hard_min))
|
||||
.range_max(field.number_soft_max.or(field.number_hard_max));
|
||||
}
|
||||
number_input = number_input.is_integer(false);
|
||||
if let Some(number_step) = field.number_step {
|
||||
number_input = number_input.step(number_step);
|
||||
}
|
||||
};
|
||||
|
||||
number_input
|
||||
}
|
||||
|
||||
/// Defines the logic for inputs to display a custom Inspector widget.
|
||||
fn static_input_inspector() -> InputInspector {
|
||||
let mut map: InputInspector = HashMap::new();
|
||||
@@ -812,50 +848,21 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// The custom number input settings are only available on proto nodes
|
||||
"optional_f64".to_string(),
|
||||
// A length row gated by the bool input before it. Its field keeps any length unit typed into it and gives its bounds in pixels.
|
||||
"optional_length".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
if let Some(field) = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
{
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
// Typing is clamped only by the hard bounds; the slider extent prefers the soft bounds (see `inspector_row_from_type`)
|
||||
if let Some(hard_min) = field.number_hard_min {
|
||||
number_input = number_input.min(hard_min);
|
||||
}
|
||||
if let Some(hard_max) = field.number_hard_max {
|
||||
number_input = number_input.max(hard_max);
|
||||
}
|
||||
if field.number_mode_range {
|
||||
number_input = number_input
|
||||
.mode_range()
|
||||
.range_min(field.number_soft_min.or(field.number_hard_min))
|
||||
.range_max(field.number_soft_max.or(field.number_hard_max));
|
||||
}
|
||||
number_input = number_input.is_integer(false);
|
||||
if let Some(number_step) = field.number_step {
|
||||
number_input = number_input.step(number_step);
|
||||
}
|
||||
};
|
||||
// NOTE: The bool input MUST be at the input index directly before the f64 input!
|
||||
Ok(vec![LayoutGroup::row(node_inspector::optional_f64_widget(
|
||||
let number_input = proto_parameter_number_input(node_id, index, context);
|
||||
// NOTE: The bool input MUST be at the input index directly before the length input!
|
||||
Ok(vec![LayoutGroup::row(node_inspector::optional_length_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, false, context),
|
||||
index - 1,
|
||||
number_input,
|
||||
None,
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// Like `optional_f64`, but with a 0-100% range slider beside the number input, double-click restoring the full 100%.
|
||||
// As with `optional_f64`, the bool input must be at the input index directly before the f64 input.
|
||||
// A number row gated by the bool input before it, with a 0-100% range slider beside the number input, double-click restoring the full 100%.
|
||||
// The bool input must be at the input index directly before the f64 input.
|
||||
"optional_percentage".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let number_input = NumberInput::default().mode_increment().unit("%").min(0.).max(100.);
|
||||
@@ -957,15 +964,15 @@ fn static_input_inspector() -> InputInspector {
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
&x,
|
||||
&y,
|
||||
&unit,
|
||||
min,
|
||||
is_integer,
|
||||
false,
|
||||
)])
|
||||
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
|
||||
// A pair measured in pixels is a pair of lengths, which keeps any length unit typed into it
|
||||
if unit.trim() == "px" {
|
||||
let number_props = NumberInput::default().min(min.unwrap_or(f64::NEG_INFINITY)).is_integer(is_integer);
|
||||
return Ok(vec![node_inspector::length_vec2_widget(info, &x, &y, number_props)]);
|
||||
}
|
||||
|
||||
Ok(vec![node_inspector::vec2_widget(info, &x, &y, &unit, min, is_integer, false)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
@@ -1225,46 +1232,16 @@ fn static_input_inspector() -> InputInspector {
|
||||
map.insert(
|
||||
"transform_rotation".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut widgets = node_inspector::start_widgets(&ParameterWidgetsInfo::at_index(node_id, index, true, context));
|
||||
|
||||
let document_node = node_inspector::get_document_node(node_id, context)?;
|
||||
let Some(input) = document_node.inputs.get(index) else {
|
||||
return Err("Input not found in transform rotation input override".to_string());
|
||||
};
|
||||
if let Some(&TaggedValue::Number(val)) = input.as_non_exposed_value() {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(val))
|
||||
.unit("°")
|
||||
.mode(NumberInputMode::Range)
|
||||
.range_min(Some(-180.))
|
||||
.range_max(Some(180.))
|
||||
.on_update(node_inspector::update_value_at_index(
|
||||
|number_input: &NumberInput| TaggedValue::Number(number_input.value.unwrap()),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(node_inspector::commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
|
||||
Ok(vec![LayoutGroup::row(widgets)])
|
||||
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
let number_props = NumberInput::default().mode(NumberInputMode::Range).range_min(Some(-180.)).range_max(Some(180.));
|
||||
Ok(vec![LayoutGroup::row(node_inspector::angle_widget(info, number_props))])
|
||||
}),
|
||||
);
|
||||
// Translation uses a Vec2 widget with X/Y labels and a "px" unit suffix
|
||||
map.insert(
|
||||
"transform_translation".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
"X",
|
||||
"Y",
|
||||
" px",
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::length_vec2_widget(info, "X", "Y", NumberInput::default())])
|
||||
}),
|
||||
);
|
||||
// Scale uses a Vec2 widget with W/H labels and an "x" unit suffix
|
||||
@@ -1282,48 +1259,11 @@ fn static_input_inspector() -> InputInspector {
|
||||
)])
|
||||
}),
|
||||
);
|
||||
// Skew has a custom override that maps to degrees
|
||||
map.insert(
|
||||
"transform_skew".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut widgets = node_inspector::start_widgets(&ParameterWidgetsInfo::at_index(node_id, index, true, context));
|
||||
|
||||
let document_node = node_inspector::get_document_node(node_id, context)?;
|
||||
let Some(input) = document_node.inputs.get(index) else {
|
||||
return Err("Input not found in transform skew input override".to_string());
|
||||
};
|
||||
if let Some(&TaggedValue::DVec2(val)) = input.as_non_exposed_value() {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(val.x))
|
||||
.label("X")
|
||||
.unit("°")
|
||||
.min(-89.9)
|
||||
.max(89.9)
|
||||
.on_update(node_inspector::update_value_at_index(
|
||||
move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), val.y)),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(node_inspector::commit_value)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(val.y))
|
||||
.label("Y")
|
||||
.unit("°")
|
||||
.min(-89.9)
|
||||
.max(89.9)
|
||||
.on_update(node_inspector::update_value_at_index(
|
||||
move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(val.x, input.value.unwrap())),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(node_inspector::commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
|
||||
Ok(vec![LayoutGroup::row(widgets)])
|
||||
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::angle_vec2_widget(info, "X", "Y", NumberInput::default().min(-89.9).max(89.9))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
@@ -1717,9 +1657,9 @@ mod test {
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
}
|
||||
|
||||
// Guards the `optional_f64` widget override against holding the node metadata lock while building rows that lock it again
|
||||
// Guards the `optional_length` widget override against holding the node metadata lock while building rows that lock it again
|
||||
#[tokio::test]
|
||||
async fn optional_f64_inspector_row_builds() {
|
||||
async fn optional_length_inspector_row_builds() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::data_panel::node_reference_button;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, LAYER_SECONDARY_INPUT_INDEX, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, LAYER_SECONDARY_INPUT_INDEX, NodeNetworkInterface, OutputConnector, wire_feeds_proto_input};
|
||||
use crate::messages::portfolio::fonts::utility_types::FontCatalogStyle;
|
||||
use crate::messages::portfolio::ingest::utility_types::{DataTransferItem, IngestAction, TypeFilter};
|
||||
use crate::messages::prelude::*;
|
||||
@@ -32,7 +32,7 @@ use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::units::{Angle, AngleUnit, Length, LengthUnit, TypedAngle, TypedLength};
|
||||
use graphene_std::units::{Angle, AngleUnit, AngleVec2, Length, LengthUnit, LengthVec2, TypedAngle, TypedAngleVec2, TypedLength, TypedLengthVec2};
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||
@@ -280,6 +280,11 @@ impl SliderRange {
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a parameter's number field.
|
||||
type FieldWidget = fn(ParameterWidgetsInfo<'_>, NumberInput) -> Vec<WidgetInstance>;
|
||||
/// Builds a parameter's range slider beside its number field.
|
||||
type SliderWidget = fn(ParameterWidgetsInfo<'_>, NumberInput, SliderRange) -> Vec<WidgetInstance>;
|
||||
|
||||
/// The number a parameter's definition gives it by default, which a slider's double-click restores.
|
||||
pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
|
||||
let identifier = parameter_widgets_info
|
||||
@@ -289,6 +294,7 @@ pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidget
|
||||
|
||||
match input.as_value()? {
|
||||
TaggedValue::Number(value) => Some(*value),
|
||||
TaggedValue::Angle(angle) => Some(angle.to_degrees()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -339,16 +345,17 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
|
||||
let no_soft_bounds = soft_min.is_none() && soft_max.is_none();
|
||||
let hard_both_ends = hard_min.is_some() && hard_max.is_some();
|
||||
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| -> LayoutGroup {
|
||||
let field_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput, field: FieldWidget, slider: SliderWidget| -> LayoutGroup {
|
||||
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
|
||||
match (number_input.min, number_input.max) {
|
||||
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
|
||||
let default = definition_default_number(&default_info);
|
||||
range_slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
|
||||
slider(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
|
||||
}
|
||||
_ => number_widget(default_info, number_input).into(),
|
||||
_ => field(default_info, number_input).into(),
|
||||
}
|
||||
};
|
||||
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| field_or_slider(default_info, number_input, number_widget, range_slider_widget);
|
||||
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
|
||||
@@ -390,13 +397,15 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
},
|
||||
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<Length>(x) => length_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<Angle>(x) => angle_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<Angle>(x) => field_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), angle_widget, angle_slider_widget),
|
||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if id_is::<String>(x) => match multiline {
|
||||
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, false),
|
||||
Some(x) if id_is::<LengthVec2>(x) => length_vec2_widget(default_info, "X", "Y", bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
||||
Some(x) if id_is::<AngleVec2>(x) => angle_vec2_widget(default_info, "X", "Y", bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
||||
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)),
|
||||
@@ -1210,6 +1219,24 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
|
||||
/// A number row gated by the bool input at `bool_input_index`, drawn as a checkbox in the assist slot after the label like the
|
||||
/// Opacity node's toggles, so the caller passes `blank_assist = false`. Given a `slider`, a range slider spanning it sits between them.
|
||||
pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_input_index: usize, number_props: NumberInput, slider: Option<SliderRange>) -> Vec<WidgetInstance> {
|
||||
optional_number_widget(parameter_widgets_info, bool_input_index, number_props, |parameter_widgets_info, number_props| match slider {
|
||||
Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider),
|
||||
None => number_widget(parameter_widgets_info, number_props),
|
||||
})
|
||||
}
|
||||
|
||||
/// Like [`optional_f64_widget`], for a length parameter. Its field keeps any length unit typed into it.
|
||||
pub fn optional_length_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_input_index: usize, number_props: NumberInput) -> Vec<WidgetInstance> {
|
||||
optional_number_widget(parameter_widgets_info, bool_input_index, number_props, length_widget)
|
||||
}
|
||||
|
||||
/// The row of an optional parameter, with its `field` built by the caller.
|
||||
fn optional_number_widget(
|
||||
parameter_widgets_info: ParameterWidgetsInfo,
|
||||
bool_input_index: usize,
|
||||
number_props: NumberInput,
|
||||
field: impl FnOnce(ParameterWidgetsInfo, NumberInput) -> Vec<WidgetInstance>,
|
||||
) -> Vec<WidgetInstance> {
|
||||
let node_id = parameter_widgets_info.node_id;
|
||||
let enabled = parameter_widgets_info
|
||||
.document_node
|
||||
@@ -1220,10 +1247,7 @@ pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_in
|
||||
let exposed = parameter_widgets_info.is_exposed();
|
||||
|
||||
let number_props = number_props.disabled(enabled == Some(false));
|
||||
let mut widgets = match slider {
|
||||
Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider),
|
||||
None => number_widget(parameter_widgets_info, number_props),
|
||||
};
|
||||
let mut widgets = field(parameter_widgets_info, number_props);
|
||||
|
||||
if !exposed {
|
||||
widgets.splice(label_count..label_count, optional_parameter_assist(enabled, node_id, bool_input_index));
|
||||
@@ -1320,6 +1344,20 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
// A length or angle left over from rows that took one reads as the number its field showed, pixels or degrees
|
||||
Some(TaggedValue::Length(_) | TaggedValue::Angle(_)) => {
|
||||
let number = input
|
||||
.as_non_exposed_value()
|
||||
.and_then(|value| value.as_length_pixels(parameter_widgets_info.network_interface.pixels_per_inch()).or_else(|| value.as_angle_degrees()));
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(number)
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -1350,6 +1388,12 @@ pub fn length_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
let length = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::Length(length)) => length,
|
||||
Some(&TaggedValue::Number(pixels)) => TypedLength::pixels(pixels),
|
||||
// A pair shows its `y`, which the "Grid" node's isometric spacing keeps from its rectangular height
|
||||
Some(&TaggedValue::LengthVec2(lengths)) => TypedLength {
|
||||
value: lengths.value.y,
|
||||
unit: lengths.unit,
|
||||
},
|
||||
Some(&TaggedValue::DVec2(pixels)) => TypedLength::pixels(pixels.y),
|
||||
_ => return widgets,
|
||||
};
|
||||
|
||||
@@ -1360,6 +1404,7 @@ pub fn length_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
number_props
|
||||
.value(Some(length.value))
|
||||
.unit(unit_suffix(length.unit.symbol()))
|
||||
.display_decimal_places(length_decimal_places(length.unit, pixels_per_inch))
|
||||
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||
.pixels_per_inch(pixels_per_inch)
|
||||
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
|
||||
@@ -1391,27 +1436,210 @@ pub fn angle_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
_ => return widgets,
|
||||
};
|
||||
|
||||
let number_props = bounds_in_unit(number_props, |degrees| angle.unit.from_angle(Angle::from_degrees(degrees)));
|
||||
let number_props = bounds_in_unit(number_props, |degrees| angle.unit.from_degrees(degrees));
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(angle.value))
|
||||
.unit(unit_suffix(angle.unit.symbol()))
|
||||
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
|
||||
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
|
||||
TaggedValue::Angle(TypedAngle {
|
||||
value: input.value.unwrap_or_default(),
|
||||
unit,
|
||||
})
|
||||
}))
|
||||
.on_commit(commit_value)
|
||||
angle_field(number_props, angle).on_update(parameter_widgets_info.update_value(typed_angle)).widget_instance(),
|
||||
]);
|
||||
|
||||
widgets
|
||||
}
|
||||
|
||||
/// An angle's range slider beside its number field, which keeps the unit the angle was typed in, with the slider's bounds given in degrees.
|
||||
pub fn angle_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
let angle = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::Angle(angle)) => angle,
|
||||
Some(&TaggedValue::Number(degrees)) => TypedAngle::degrees(degrees),
|
||||
_ => return widgets,
|
||||
};
|
||||
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
|
||||
|
||||
let unit = angle.unit;
|
||||
let slid_to = move |position| {
|
||||
let value = unit.from_degrees(slider.value(position));
|
||||
TaggedValue::Angle(TypedAngle { value, unit })
|
||||
};
|
||||
let default_position = slider.default.map(|default| slider.position(default));
|
||||
|
||||
let number_props = bounds_in_unit(number_props, |degrees| unit.from_degrees(degrees));
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
value_slider(node_id, index, GradientStops::default(), Color::WHITE, slider.position(angle.to_degrees()), default_position, slid_to)
|
||||
.range_slider(true)
|
||||
.disabled(number_props.disabled)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
// A unit spelled out, like `0.25 turn`, needs more room than a degree sign
|
||||
angle_field(number_props, angle)
|
||||
.sizing(WidgetSizing::fixed(if unit == AngleUnit::Degree { 60 } else { 90 }))
|
||||
.on_update(update_value_at_index(typed_angle, node_id, index))
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
widgets
|
||||
}
|
||||
|
||||
/// The decimal places a field shows a length in, resolving about a hundredth of a pixel in any unit, so `0.125 in` doesn't display as `0.13 in`.
|
||||
pub(crate) fn length_decimal_places(unit: LengthUnit, pixels_per_inch: f64) -> u32 {
|
||||
decimal_places_for_size(unit.convert(1., LengthUnit::Pixel, pixels_per_inch))
|
||||
}
|
||||
|
||||
/// The decimal places a field shows an angle in, resolving about a hundredth of a degree in any unit.
|
||||
fn angle_decimal_places(unit: AngleUnit) -> u32 {
|
||||
decimal_places_for_size(unit.to_angle(1.).degrees())
|
||||
}
|
||||
|
||||
/// Two decimal places for a unit the size of the field's base unit (a pixel or a degree), and one more for each power of ten larger it is.
|
||||
fn decimal_places_for_size(base_units_per_unit: f64) -> u32 {
|
||||
let extra = base_units_per_unit.log10().ceil();
|
||||
if extra.is_finite() { (2. + extra.clamp(0., 7.)) as u32 } else { 2 }
|
||||
}
|
||||
|
||||
/// The number field showing an angle in the unit it was typed in, which keeps any angle unit typed into it.
|
||||
fn angle_field(number_props: NumberInput, angle: TypedAngle) -> NumberInput {
|
||||
number_props
|
||||
.value(Some(angle.value))
|
||||
.unit(unit_suffix(angle.unit.symbol()))
|
||||
.display_decimal_places(angle_decimal_places(angle.unit))
|
||||
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||
.on_commit(commit_value)
|
||||
}
|
||||
|
||||
/// The angle in an angle field, in the unit typed into it.
|
||||
fn typed_angle(input: &NumberInput) -> TaggedValue {
|
||||
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
|
||||
TaggedValue::Angle(TypedAngle {
|
||||
value: input.value.unwrap_or_default(),
|
||||
unit,
|
||||
})
|
||||
}
|
||||
|
||||
/// A pair of lengths' X and Y number fields, which share the unit the pair was typed in, with the fields' bounds given in pixels.
|
||||
/// Typing another length unit into either field moves both into it, converting the other component so its length stays the same.
|
||||
pub fn length_vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, number_props: NumberInput) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return LayoutGroup::row(vec![]);
|
||||
};
|
||||
let lengths = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::LengthVec2(lengths)) => lengths,
|
||||
Some(&TaggedValue::DVec2(pixels)) => TypedLengthVec2::pixels(pixels),
|
||||
// One length stands for both components, like the "Grid" node's isometric spacing
|
||||
Some(&TaggedValue::Length(length)) => TypedLengthVec2 {
|
||||
value: DVec2::splat(length.value),
|
||||
unit: length.unit,
|
||||
},
|
||||
Some(&TaggedValue::Number(pixels)) => TypedLengthVec2::pixels(DVec2::splat(pixels)),
|
||||
_ => return LayoutGroup::row(widgets),
|
||||
};
|
||||
|
||||
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
|
||||
// A field limited to integers would convert a typed physical length into its pixels, so whole pixels are enforced only on a pair in pixels
|
||||
let whole_pixels = number_props.is_integer;
|
||||
let number_props = bounds_in_unit(number_props, |pixels| LengthUnit::Pixel.convert(pixels, lengths.unit, pixels_per_inch));
|
||||
let field = |component: f64, label: &str| {
|
||||
number_props
|
||||
.clone()
|
||||
.is_integer(false)
|
||||
.label(label)
|
||||
.value(Some(component))
|
||||
.unit(unit_suffix(lengths.unit.symbol()))
|
||||
.display_decimal_places(length_decimal_places(lengths.unit, pixels_per_inch))
|
||||
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||
.pixels_per_inch(pixels_per_inch)
|
||||
.on_commit(commit_value)
|
||||
};
|
||||
|
||||
// The edited component takes the typed unit, and the other converts into it
|
||||
let typed = move |input: &NumberInput, edited_axis: usize| {
|
||||
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
|
||||
let mut value = DVec2::new(
|
||||
lengths.unit.convert(lengths.value.x, unit, pixels_per_inch),
|
||||
lengths.unit.convert(lengths.value.y, unit, pixels_per_inch),
|
||||
);
|
||||
value[edited_axis] = input.value.unwrap_or_default();
|
||||
if whole_pixels && unit == LengthUnit::Pixel {
|
||||
value = value.round();
|
||||
}
|
||||
TaggedValue::LengthVec2(TypedLengthVec2 { value, unit })
|
||||
};
|
||||
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
field(lengths.value.x, x)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 0)))
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
field(lengths.value.y, y)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 1)))
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
LayoutGroup::row(widgets)
|
||||
}
|
||||
|
||||
/// A pair of angles' X and Y number fields, which share the unit the pair was typed in, with the fields' bounds given in degrees.
|
||||
/// Typing another angle unit into either field moves both into it, converting the other component so its angle stays the same.
|
||||
pub fn angle_vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, number_props: NumberInput) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return LayoutGroup::row(vec![]);
|
||||
};
|
||||
let angles = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::AngleVec2(angles)) => angles,
|
||||
Some(&TaggedValue::DVec2(degrees)) => TypedAngleVec2::degrees(degrees),
|
||||
_ => return LayoutGroup::row(widgets),
|
||||
};
|
||||
|
||||
let number_props = bounds_in_unit(number_props, |degrees| angles.unit.from_degrees(degrees));
|
||||
let field = |component: f64, label: &str| {
|
||||
number_props
|
||||
.clone()
|
||||
.label(label)
|
||||
.value(Some(component))
|
||||
.unit(unit_suffix(angles.unit.symbol()))
|
||||
.display_decimal_places(angle_decimal_places(angles.unit))
|
||||
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||
.on_commit(commit_value)
|
||||
};
|
||||
|
||||
// The edited component takes the typed unit, and the other converts into it
|
||||
let typed = move |input: &NumberInput, edited_axis: usize| {
|
||||
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
|
||||
let degrees = angles.to_degrees();
|
||||
let mut value = if unit == angles.unit {
|
||||
angles.value
|
||||
} else {
|
||||
DVec2::new(unit.from_degrees(degrees.x), unit.from_degrees(degrees.y))
|
||||
};
|
||||
value[edited_axis] = input.value.unwrap_or_default();
|
||||
TaggedValue::AngleVec2(TypedAngleVec2 { value, unit })
|
||||
};
|
||||
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
field(angles.value.x, x)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 0)))
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
field(angles.value.y, y)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 1)))
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
LayoutGroup::row(widgets)
|
||||
}
|
||||
|
||||
// TODO: Auto-generate this enum dropdown menu widget
|
||||
pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
@@ -1507,6 +1735,74 @@ fn wire_element(ty: &Type) -> Type {
|
||||
}
|
||||
}
|
||||
|
||||
/// The length or angle type of the field an unwired input shows, where the node's rows take one there among other types.
|
||||
/// The rows fitting the node's other known inputs decide it when they all need one type there. Otherwise a length or angle the input holds keeps its field.
|
||||
fn measurement_input_type(node_id: NodeId, input_index: usize, identifier: &graph_craft::ProtoNodeIdentifier, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option<Type> {
|
||||
let rows = interpreted_executor::node_registry::NODE_REGISTRY.get(identifier)?;
|
||||
let measurements = [concrete!(Length), concrete!(Angle)];
|
||||
let element_at = |inputs: &[Type], index: usize| inputs.get(index).map(wire_element);
|
||||
|
||||
let offered: Vec<Type> = rows.keys().filter_map(|row| element_at(&row.inputs, input_index)).collect();
|
||||
if !offered.iter().any(|element| measurements.contains(element)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Only an unwired input shows a field
|
||||
let held_measurement = |index: usize| match network_interface.input_from_connector(&InputConnector::node_at_index(node_id, index), network_path) {
|
||||
Some(NodeInput::Value { tagged_value, .. }) => Some(wire_element(&tagged_value.ty())).filter(|element| measurements.contains(element)),
|
||||
_ => None,
|
||||
};
|
||||
let Some(NodeInput::Value { .. }) = network_interface.input_from_connector(&InputConnector::node_at_index(node_id, input_index), network_path) else {
|
||||
return None;
|
||||
};
|
||||
let held = held_measurement(input_index).filter(|held| offered.contains(held));
|
||||
|
||||
// Wired inputs, through the conversions ahead of them, and inputs holding a length or angle decide which rows fit, unlike a plain number, which may be the one to change
|
||||
enum Known {
|
||||
Wired(Type),
|
||||
Held(Type),
|
||||
}
|
||||
let known_inputs: Vec<(usize, Known)> = (0..network_interface.number_of_inputs(&node_id, network_path))
|
||||
.filter(|&index| index != input_index)
|
||||
.filter_map(|index| match network_interface.input_from_connector(&InputConnector::node_at_index(node_id, index), network_path)? {
|
||||
NodeInput::Node { .. } | NodeInput::Import { .. } => {
|
||||
let wired = network_interface.input_type_not_invalid(&InputConnector::node_at_index(node_id, index), network_path);
|
||||
Some((index, Known::Wired(wired.compiled_nested_type()?.clone())))
|
||||
}
|
||||
NodeInput::Value { .. } => Some((index, Known::Held(held_measurement(index)?))),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if known_inputs.is_empty() {
|
||||
return held;
|
||||
}
|
||||
|
||||
let fits = |row: &graphene_std::NodeIOTypes, exactly: bool| {
|
||||
known_inputs.iter().all(|(index, known)| match known {
|
||||
Known::Wired(source) if exactly => element_at(&row.inputs, *index) == Some(wire_element(source)),
|
||||
Known::Wired(source) => row.inputs.get(*index).is_some_and(|connector| wire_feeds_proto_input(identifier, *index, source, connector)),
|
||||
Known::Held(element) => element_at(&row.inputs, *index).as_ref() == Some(element),
|
||||
})
|
||||
};
|
||||
|
||||
// The compiler takes a row the wires feed as they are over one they would be converted into
|
||||
let exact: Vec<&graphene_std::NodeIOTypes> = rows.keys().filter(|row| fits(row, true)).collect();
|
||||
let fitting = if exact.is_empty() { rows.keys().filter(|row| fits(row, false)).collect() } else { exact };
|
||||
let needed: Vec<(Type, Type)> = fitting
|
||||
.iter()
|
||||
.filter_map(|row| Some((element_at(&row.inputs, input_index)?, wire_element(&row.return_value))))
|
||||
.collect();
|
||||
let Some((first, _)) = needed.first() else { return held };
|
||||
|
||||
// A number reads in pixels or degrees where it gives what a length or angle would, so rows taking either call for the length or angle
|
||||
let plain = concrete!(f64);
|
||||
match needed.iter().find(|(element, _)| measurements.contains(element)) {
|
||||
Some((measurement, output)) if needed.iter().all(|(element, result)| element == measurement || (*element == plain && result == output)) => Some(measurement.clone()),
|
||||
None if needed.iter().all(|(element, _)| element == first) => None,
|
||||
_ => held,
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical order and grouping of the graph's types, which a type choice renders as dropdown sections divided by separators.
|
||||
/// Enums stay unlisted on purpose, joining any other unnamed type in a trailing alphabetical section.
|
||||
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
|
||||
@@ -2880,14 +3176,14 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
|
||||
if let Some(grid_type) = grid_type {
|
||||
if grid_type.is_isometric() {
|
||||
let spacing = LayoutGroup::row(number_widget(
|
||||
let spacing = LayoutGroup::row(length_widget(
|
||||
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
||||
NumberInput::default().label("H").min(0.).unit(" px"),
|
||||
NumberInput::default().label("H").min(0.),
|
||||
));
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false);
|
||||
let angles = angle_vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", NumberInput::default());
|
||||
widgets.extend([spacing, angles]);
|
||||
} else {
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false);
|
||||
let spacing = length_vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", NumberInput::default().min(0.));
|
||||
widgets.push(spacing);
|
||||
}
|
||||
}
|
||||
@@ -2902,7 +3198,7 @@ pub(crate) fn spiral_inspector(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, SpiralTypeInput, true, context))
|
||||
.inspector_row();
|
||||
let turns = number_widget(ParameterWidgetsInfo::new(node_id, TurnsInput, true, context), NumberInput::default().min(0.1));
|
||||
let start_angle = number_widget(ParameterWidgetsInfo::new(node_id, StartAngleInput, true, context), NumberInput::default().unit("°"));
|
||||
let start_angle = angle_widget(ParameterWidgetsInfo::new(node_id, StartAngleInput, true, context), NumberInput::default());
|
||||
|
||||
let mut widgets = vec![spiral_type, LayoutGroup::row(turns), LayoutGroup::row(start_angle)];
|
||||
|
||||
@@ -2921,35 +3217,23 @@ pub(crate) fn spiral_inspector(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
if let Some(&TaggedValue::SpiralType(spiral_type)) = spiral_type_input.as_non_exposed_value() {
|
||||
match spiral_type {
|
||||
SpiralType::Archimedean => {
|
||||
let inner_radius = LayoutGroup::row(number_widget(
|
||||
ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context),
|
||||
NumberInput::default().min(0.).unit(" px"),
|
||||
));
|
||||
let inner_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context), NumberInput::default().min(0.)));
|
||||
|
||||
let outer_radius = LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context), NumberInput::default().unit(" px")));
|
||||
let outer_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context), NumberInput::default()));
|
||||
|
||||
widgets.extend([inner_radius, outer_radius]);
|
||||
}
|
||||
SpiralType::Logarithmic => {
|
||||
let inner_radius = LayoutGroup::row(number_widget(
|
||||
ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context),
|
||||
NumberInput::default().min(0.).unit(" px"),
|
||||
));
|
||||
let inner_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context), NumberInput::default().min(0.)));
|
||||
|
||||
let outer_radius = LayoutGroup::row(number_widget(
|
||||
ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context),
|
||||
NumberInput::default().min(0.1).unit(" px"),
|
||||
));
|
||||
let outer_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context), NumberInput::default().min(0.1)));
|
||||
|
||||
widgets.extend([inner_radius, outer_radius]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let angular_resolution = number_widget(
|
||||
ParameterWidgetsInfo::new(node_id, AngularResolutionInput, true, context),
|
||||
NumberInput::default().min(1.).max(180.).unit("°"),
|
||||
);
|
||||
let angular_resolution = angle_widget(ParameterWidgetsInfo::new(node_id, AngularResolutionInput, true, context), NumberInput::default().min(1.).max(180.));
|
||||
|
||||
widgets.push(LayoutGroup::row(angular_resolution));
|
||||
|
||||
@@ -2980,10 +3264,10 @@ pub(crate) fn sample_polyline_inspector(node_id: NodeId, context: &mut NodeInspe
|
||||
let spacing = enum_choice::<PointSpacingType>()
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context))
|
||||
.inspector_row();
|
||||
let separation = number_widget(ParameterWidgetsInfo::new(node_id, SeparationInput, true, context), NumberInput::default().min(0.).unit(" px"));
|
||||
let separation = length_widget(ParameterWidgetsInfo::new(node_id, SeparationInput, true, context), NumberInput::default().min(0.));
|
||||
let quantity = number_widget(ParameterWidgetsInfo::new(node_id, QuantityInput, true, context), NumberInput::default().min(2.).int());
|
||||
let start_offset = number_widget(ParameterWidgetsInfo::new(node_id, StartOffsetInput, true, context), NumberInput::default().min(0.).unit(" px"));
|
||||
let stop_offset = number_widget(ParameterWidgetsInfo::new(node_id, StopOffsetInput, true, context), NumberInput::default().min(0.).unit(" px"));
|
||||
let start_offset = length_widget(ParameterWidgetsInfo::new(node_id, StartOffsetInput, true, context), NumberInput::default().min(0.));
|
||||
let stop_offset = length_widget(ParameterWidgetsInfo::new(node_id, StopOffsetInput, true, context), NumberInput::default().min(0.));
|
||||
let adaptive_spacing = bool_widget(ParameterWidgetsInfo::new(node_id, AdaptiveSpacingInput, true, context), CheckboxInput::default().disabled(is_quantity));
|
||||
|
||||
vec![
|
||||
@@ -3309,10 +3593,10 @@ pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorCo
|
||||
}
|
||||
|
||||
// Size X
|
||||
let size_x = number_widget(ParameterWidgetsInfo::new(node_id, WidthInput, true, context), NumberInput::default());
|
||||
let size_x = length_widget(ParameterWidgetsInfo::new(node_id, WidthInput, true, context), NumberInput::default());
|
||||
|
||||
// Size Y
|
||||
let size_y = number_widget(ParameterWidgetsInfo::new(node_id, HeightInput, true, context), NumberInput::default());
|
||||
let size_y = length_widget(ParameterWidgetsInfo::new(node_id, HeightInput, true, context), NumberInput::default());
|
||||
|
||||
// Clamped
|
||||
let clamped = bool_widget(ParameterWidgetsInfo::new(node_id, ClampedInput, true, context), CheckboxInput::default());
|
||||
@@ -3383,6 +3667,10 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
if let Some(measurement) = measurement_input_type(node_id, input_index, &proto_node_identifier, context.network_interface, context.selection_network_path) {
|
||||
break 'early_return measurement;
|
||||
}
|
||||
|
||||
if let Some(default) = default_type {
|
||||
break 'early_return default;
|
||||
}
|
||||
@@ -3811,7 +4099,7 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
|
||||
ParameterWidgetsInfo::new(node_id, PaintInput, true, context),
|
||||
crate::messages::layout::utility_types::widgets::button_widgets::ColorInput::default(),
|
||||
);
|
||||
let weight = number_widget(ParameterWidgetsInfo::new(node_id, WeightInput, true, context), NumberInput::default().unit(" px").min(0.));
|
||||
let weight = length_widget(ParameterWidgetsInfo::new(node_id, WeightInput, true, context), NumberInput::default().min(0.));
|
||||
let align = enum_choice::<StrokeAlign>().for_socket(ParameterWidgetsInfo::new(node_id, AlignInput, true, context)).inspector_row();
|
||||
let cap = enum_choice::<StrokeCap>().for_socket(ParameterWidgetsInfo::new(node_id, CapInput, true, context)).inspector_row();
|
||||
let join = enum_choice::<StrokeJoin>().for_socket(ParameterWidgetsInfo::new(node_id, JoinInput, true, context)).inspector_row();
|
||||
@@ -3820,10 +4108,10 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
|
||||
ParameterWidgetsInfo::new(node_id, MiterLimitInput, true, context),
|
||||
NumberInput::default().min(0.).disabled(miter_limit_disabled),
|
||||
);
|
||||
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
|
||||
let disabled_number_input = NumberInput::default().disabled(has_dash_lengths);
|
||||
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
|
||||
let number_input = disabled_number_input;
|
||||
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
|
||||
let dash_offset = length_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
|
||||
|
||||
vec![
|
||||
color,
|
||||
@@ -3840,8 +4128,7 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
|
||||
pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::vector::offset_path::*;
|
||||
|
||||
let number_input = NumberInput::default().unit(" px");
|
||||
let distance = number_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), number_input);
|
||||
let distance = length_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), NumberInput::default());
|
||||
|
||||
let join = enum_choice::<StrokeJoin>().for_socket(ParameterWidgetsInfo::new(node_id, JoinInput, true, context)).inspector_row();
|
||||
|
||||
@@ -4127,6 +4414,46 @@ mod tests {
|
||||
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
|
||||
}
|
||||
|
||||
/// The field the second input of a node shows with a length wired into its first, which feeds a circle's radius so it compiles.
|
||||
async fn second_input_field_beside_a_wired_length(target: graph_craft::ProtoNodeIdentifier) -> Option<Type> {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
|
||||
let mut editor = crate::test_utils::EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
// The length comes from an Add of two lengths
|
||||
let add = graphene_std::math_nodes::add::IDENTIFIER;
|
||||
let source = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(add), 0, 0).await;
|
||||
for input_index in 0..2 {
|
||||
let value = Box::new(TaggedValue::Length(graphene_std::units::TypedLength::pixels(1.)));
|
||||
editor.handle_message(NodeGraphMessage::SetInputValue { node_id: source, input_index, value }).await;
|
||||
}
|
||||
|
||||
// Only the nodes feeding the document's output are compiled, which resolves the types of their wires
|
||||
let node = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(target.clone()), 10, 0).await;
|
||||
let circle = editor
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::circle::IDENTIFIER), 20, 0)
|
||||
.await;
|
||||
for (output_connector, input_connector) in [
|
||||
(OutputConnector::node(source, 0), InputConnector::primary_input(node)),
|
||||
(OutputConnector::node(node, 0), InputConnector::node_at_index(circle, 1)),
|
||||
(OutputConnector::node(circle, 0), InputConnector::Export(0)),
|
||||
] {
|
||||
editor.handle_message(NodeGraphMessage::CreateWire { output_connector, input_connector }).await;
|
||||
}
|
||||
|
||||
measurement_input_type(node, 1, &target, &editor.active_document().network_interface, &[])
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_number_beside_a_wired_length_shows_as_a_length_where_it_reads_in_pixels() {
|
||||
assert_eq!(second_input_field_beside_a_wired_length(graphene_std::math_nodes::add::IDENTIFIER).await, Some(concrete!(Length)));
|
||||
assert_eq!(second_input_field_beside_a_wired_length(graphene_std::math_nodes::clamp::IDENTIFIER).await, Some(concrete!(Length)));
|
||||
|
||||
// A divisor of a length is a plain number, which a length would turn into a ratio
|
||||
assert_eq!(second_input_field_beside_a_wired_length(graphene_std::math_nodes::divide::IDENTIFIER).await, None);
|
||||
}
|
||||
|
||||
fn description(expression: &str) -> Option<String> {
|
||||
math_expression_error(expression, false).map(|error| math_expression_error_description(&error))
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ impl FrontendGraphDataType {
|
||||
"Color" => Self::Color,
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" | "Length" | "Angle" => Self::Number,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" | "Length" | "Angle" | "LengthVec2" | "AngleVec2" => Self::Number,
|
||||
// A generator draws pixels like an image, at whatever resolution is needed
|
||||
"Generator" => Self::Raster,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
|
||||
@@ -19,6 +19,7 @@ use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::renderer::RenderMetadata;
|
||||
use graphene_std::renderer::scene_builder::SceneBuilder;
|
||||
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
|
||||
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
|
||||
@@ -190,7 +190,9 @@ impl DocumentMetadata {
|
||||
let transform = local_transform.unwrap_or_else(|| {
|
||||
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER), layer, network_interface);
|
||||
let transform_node = transform_node_id.and_then(|id| network_interface.document_node(&id, &[]));
|
||||
transform_node.map(|node| transform_utils::get_current_transform(node.inputs.as_slice())).unwrap_or_default()
|
||||
transform_node
|
||||
.map(|node| transform_utils::get_current_transform(node.inputs.as_slice(), network_interface.pixels_per_inch()))
|
||||
.unwrap_or_default()
|
||||
});
|
||||
|
||||
footprint * transform
|
||||
|
||||
@@ -37,6 +37,7 @@ mod view;
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use layout_pass::NetworkLayout;
|
||||
pub use reconcile::{ReconcileError, Reconciled};
|
||||
pub(crate) use resolved_types::wire_feeds_proto_input;
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
pub use structure::vector_outline_targets;
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ fn new_artboard_message(id: NodeId) -> GraphOperationMessage {
|
||||
GraphOperationMessage::NewArtboard {
|
||||
id,
|
||||
location: DVec2::ZERO,
|
||||
dimensions: DVec2::new(400., 300.),
|
||||
dimensions: graphene_std::units::TypedLengthVec2::pixels(DVec2::new(400., 300.)),
|
||||
background: Color::WHITE,
|
||||
clip: false,
|
||||
}
|
||||
|
||||
+6
@@ -95,6 +95,12 @@ fn type_feeds_input(source: &Type, connector: &Type, conversions: Option<&Adapte
|
||||
.any(|adapted| adapted == connector || Promotion::exists_between(adapted, connector))
|
||||
}
|
||||
|
||||
/// Whether a wire of the `source` type can feed the proto node's input at `input_index`, registered as `connector`, through the conversions
|
||||
/// the compiler places ahead of that input.
|
||||
pub(crate) fn wire_feeds_proto_input(proto_node_identifier: &ProtoNodeIdentifier, input_index: usize, source: &Type, connector: &Type) -> bool {
|
||||
type_feeds_input(source, connector, input_conversions(proto_node_identifier).get(input_index).copied().flatten())
|
||||
}
|
||||
|
||||
// This file contains utility methods for interfacing with the resolved types returned from the compiler
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ResolvedDocumentNodeTypes {
|
||||
|
||||
@@ -57,7 +57,7 @@ impl OriginalTransforms {
|
||||
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER), layer, network_interface)?;
|
||||
|
||||
let document_node = network_interface.document_network().nodes.get(&transform_node_id)?;
|
||||
Some(transform_utils::get_current_transform(&document_node.inputs))
|
||||
Some(transform_utils::get_current_transform(&document_node.inputs, network_interface.pixels_per_inch()))
|
||||
}
|
||||
|
||||
pub fn update<'a>(&mut self, selected: &'a [LayerNodeIdentifier], network_interface: &NodeNetworkInterface, shape_editor: Option<&'a ShapeState>) {
|
||||
|
||||
@@ -3536,9 +3536,11 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
// Preserve primary input connection
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
// Set arrow_to = end - start
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::DVec2(end - start), false), network_path);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 1),
|
||||
NodeInput::value(TaggedValue::LengthVec2(graphene_std::units::TypedLengthVec2::pixels(end - start)), false),
|
||||
network_path,
|
||||
);
|
||||
// Preserve shaft_width, head_width, head_length (shifted from indices 3,4,5 to 2,3,4)
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), old_inputs[3].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), old_inputs[4].clone(), network_path);
|
||||
@@ -3558,7 +3560,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
return None;
|
||||
};
|
||||
let mut transform_template = transform_node_type.default_node_template();
|
||||
transform_template.inputs[1] = NodeInput::value(TaggedValue::DVec2(start), false);
|
||||
transform_template.inputs[1] = NodeInput::value(TaggedValue::LengthVec2(graphene_std::units::TypedLengthVec2::pixels(start)), false);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
|
||||
@@ -3601,9 +3603,11 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
// Preserve primary input connection
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
// Set line_to = end - start
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::DVec2(end - start), false), network_path);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*node_id, 1),
|
||||
NodeInput::value(TaggedValue::LengthVec2(graphene_std::units::TypedLengthVec2::pixels(end - start)), false),
|
||||
network_path,
|
||||
);
|
||||
|
||||
// Find downstream connection to insert Transform node
|
||||
let downstream = document
|
||||
@@ -3619,7 +3623,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
return None;
|
||||
};
|
||||
let mut transform_template = transform_node_type.default_node_template();
|
||||
transform_template.inputs[1] = NodeInput::value(TaggedValue::DVec2(start), false);
|
||||
transform_template.inputs[1] = NodeInput::value(TaggedValue::LengthVec2(graphene_std::units::TypedLengthVec2::pixels(start)), false);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
|
||||
@@ -5004,11 +5008,18 @@ mod tests {
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
assert_eq!(node.inputs.len(), 3, "the output type is kept, or added to a node from before it");
|
||||
match &node.implementation {
|
||||
let identifier = match &node.implementation {
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => identifier.clone(),
|
||||
other => panic!("expected a proto node implementation, got {other:?}"),
|
||||
};
|
||||
|
||||
// The output type is kept, or added to a node from before it, and Math Formula reads the resolution after it
|
||||
let expected_inputs = if identifier == math_formula::IDENTIFIER { 4 } else { 3 };
|
||||
assert_eq!(node.inputs.len(), expected_inputs);
|
||||
if identifier == math_formula::IDENTIFIER {
|
||||
assert_eq!(node.inputs.get(3), Some(&NodeInput::scope(graphene_std::units::PIXELS_PER_INCH_SCOPE)));
|
||||
}
|
||||
identifier
|
||||
};
|
||||
let items = || NodeInput::value(TaggedValue::None, false);
|
||||
let expression = |text: &str| NodeInput::value(TaggedValue::String(text.into()), false);
|
||||
|
||||
+1
-6
@@ -11,7 +11,6 @@ use crate::messages::tool::common_functionality::shapes::shape_utility::{extract
|
||||
use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::ParameterRef;
|
||||
use graphene_std::core_types::FallibleVec2Operations;
|
||||
use std::collections::VecDeque;
|
||||
@@ -194,12 +193,8 @@ impl RadiusHandle {
|
||||
// The size is snapped, which keeps whichever sign the radius has come to
|
||||
let snapped_radius = snap_session.snap_value(view, position_of, self.free_radius.abs(), on_screen_per_unit, equal_radii) * self.free_radius.signum();
|
||||
|
||||
// A radius typed in a unit like millimeters stays in it
|
||||
let input_connector = InputConnector::node(node_id, radius_parameter);
|
||||
let radius = match document.network_interface.input_from_connector(&input_connector, &[]).and_then(|input| input.as_value()) {
|
||||
Some(existing @ TaggedValue::Length(_)) => existing.length_in_same_unit(snapped_radius, document.network_interface.pixels_per_inch()),
|
||||
_ => TaggedValue::Number(snapped_radius),
|
||||
};
|
||||
let radius = graph_modification_utils::length_in_unit_of_input(&document.network_interface, &input_connector, snapped_radius);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector,
|
||||
input: NodeInput::value(radius, false),
|
||||
|
||||
@@ -374,9 +374,15 @@ impl HeartHandles {
|
||||
return;
|
||||
}
|
||||
|
||||
let input_connector = InputConnector::node(node_id, parameter.input());
|
||||
let input_value = parameter.input_value(value.clamp(min, max));
|
||||
let input_value = match parameter {
|
||||
HeartParameter::TipAngle => graph_modification_utils::angle_in_unit_of_input(&document.network_interface, &input_connector, input_value),
|
||||
_ => TaggedValue::Number(input_value),
|
||||
};
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, parameter.input()),
|
||||
input: NodeInput::value(TaggedValue::Number(parameter.input_value(value.clamp(min, max))), false),
|
||||
input_connector,
|
||||
input: NodeInput::value(input_value, false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
+7
-20
@@ -8,13 +8,12 @@ use crate::messages::portfolio::document::{overlays::utility_types::OverlayConte
|
||||
use crate::messages::prelude::FrontendMessage;
|
||||
use crate::messages::prelude::Responses;
|
||||
use crate::messages::prelude::{DocumentMessageHandler, NodeGraphMessage};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer};
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::{draw_snapping_ticks, extract_polygon_parameters, polygon_outline, polygon_vertex_position, star_outline};
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::{extract_star_parameters, star_vertex_position};
|
||||
use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::ParameterRef;
|
||||
use graphene_std::vector::generator_nodes::{regular_polygon, star};
|
||||
use std::collections::VecDeque;
|
||||
@@ -340,20 +339,12 @@ impl PointRadiusHandle {
|
||||
fn calculate_snap_radii(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, radius_parameter: &ParameterRef) -> Vec<f64> {
|
||||
let mut snap_radii = Vec::new();
|
||||
|
||||
let Some(parameters) = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(star::IDENTIFIER) else {
|
||||
return snap_radii;
|
||||
};
|
||||
|
||||
let (Some(&TaggedValue::Number(radius_1)), Some(&TaggedValue::Number(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
|
||||
let Some((sides, radius_1, radius_2)) = extract_star_parameters(Some(layer), document) else {
|
||||
return snap_radii;
|
||||
};
|
||||
|
||||
let other_radius = if *radius_parameter == ParameterRef::from(star::Radius2Input) { radius_1 } else { radius_2 };
|
||||
|
||||
let Some(&TaggedValue::Integer(sides)) = parameters.value(star::SidesInput) else {
|
||||
return snap_radii;
|
||||
};
|
||||
|
||||
let both_radii_negative = radius_1.is_sign_negative() && radius_2.is_sign_negative();
|
||||
let both_radii_same_sign = (radius_1.signum() * radius_2.signum()).is_sign_positive();
|
||||
|
||||
@@ -465,21 +456,17 @@ impl PointRadiusHandle {
|
||||
self.update_state(PointRadiusHandleState::Snapped(candidate.key.identity[0] as usize));
|
||||
}
|
||||
|
||||
let input_connector = InputConnector::node(node_id, radius_parameter);
|
||||
let radius = graph_modification_utils::length_in_unit_of_input(&document.network_interface, &input_connector, snapped_radius);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, radius_parameter),
|
||||
input: NodeInput::value(TaggedValue::Number(snapped_radius), false),
|
||||
input_connector,
|
||||
input: NodeInput::value(radius, false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
fn check_if_radius_flipped(&mut self, original_radius: f64, new_radius: f64, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, radius_parameter: &ParameterRef) {
|
||||
let Some(parameters) = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(star::IDENTIFIER) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (Some(&TaggedValue::Number(radius_1)), Some(&TaggedValue::Number(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
|
||||
return;
|
||||
};
|
||||
let Some((_, radius_1, radius_2)) = extract_star_parameters(Some(layer), document) else { return };
|
||||
|
||||
let other_radius = if *radius_parameter == ParameterRef::from(star::Radius2Input) { radius_1 } else { radius_2 };
|
||||
|
||||
|
||||
+11
-6
@@ -249,22 +249,26 @@ impl SpiralTurns {
|
||||
let Some(node_id) = graph_modification_utils::get_spiral_id(layer, &document.network_interface) else {
|
||||
return;
|
||||
};
|
||||
let outer_radius_input = InputConnector::node(node_id, OuterRadiusInput);
|
||||
|
||||
match self.gizmo_type {
|
||||
GizmoType::Start => {
|
||||
let (new_start_angle, new_turns, new_outer_radius) = self.start_dragged_to(self.initial_turns - turns_delta);
|
||||
|
||||
let start_angle_input = InputConnector::node(node_id, StartAngleInput);
|
||||
let start_angle = graph_modification_utils::angle_in_unit_of_input(&document.network_interface, &start_angle_input, new_start_angle);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, StartAngleInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_start_angle), false),
|
||||
input_connector: start_angle_input,
|
||||
input: NodeInput::value(start_angle, false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, TurnsInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_turns), false),
|
||||
});
|
||||
let outer_radius = graph_modification_utils::length_in_unit_of_input(&document.network_interface, &outer_radius_input, new_outer_radius);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, OuterRadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_outer_radius), false),
|
||||
input_connector: outer_radius_input,
|
||||
input: NodeInput::value(outer_radius, false),
|
||||
});
|
||||
}
|
||||
GizmoType::End => {
|
||||
@@ -275,9 +279,10 @@ impl SpiralTurns {
|
||||
input_connector: InputConnector::node(node_id, TurnsInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_turns), false),
|
||||
});
|
||||
let outer_radius = graph_modification_utils::length_in_unit_of_input(&document.network_interface, &outer_radius_input, new_outer_radius);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, OuterRadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_outer_radius), false),
|
||||
input_connector: outer_radius_input,
|
||||
input: NodeInput::value(outer_radius, false),
|
||||
});
|
||||
}
|
||||
GizmoType::None => {
|
||||
|
||||
+22
-18
@@ -10,8 +10,8 @@ use crate::messages::tool::common_functionality::shapes::shape_utility::{arc_end
|
||||
use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate};
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::ParameterRef;
|
||||
use std::collections::VecDeque;
|
||||
use std::f64::consts::PI;
|
||||
|
||||
@@ -235,7 +235,7 @@ impl SweepAngleGizmo {
|
||||
self.initial_start_angle = current_start_angle;
|
||||
self.update_state(SweepAngleGizmoState::Snapped);
|
||||
|
||||
self.apply_arc_update(node_id, self.initial_start_angle, self.initial_sweep_angle - wrapped, input, responses);
|
||||
self.apply_arc_update(node_id, self.initial_start_angle, self.initial_sweep_angle - wrapped, view, responses);
|
||||
}
|
||||
() if new_sweep_angle < 0. => {
|
||||
let rest_angle = angle_delta + new_sweep_angle;
|
||||
@@ -246,7 +246,7 @@ impl SweepAngleGizmo {
|
||||
self.initial_sweep_angle = 0.;
|
||||
self.initial_start_angle = current_start_angle + rest_angle;
|
||||
|
||||
self.apply_arc_update(node_id, self.initial_start_angle, new_sweep_angle.abs(), input, responses);
|
||||
self.apply_arc_update(node_id, self.initial_start_angle, new_sweep_angle.abs(), view, responses);
|
||||
}
|
||||
// Wrap start angle > 180° back into [-180°, 180°] and adjust sweep
|
||||
() if new_start_angle > 180. => {
|
||||
@@ -260,7 +260,7 @@ impl SweepAngleGizmo {
|
||||
self.initial_start_angle = -180.;
|
||||
self.initial_sweep_angle = current_sweep_angle - rest_angle;
|
||||
|
||||
self.apply_arc_update(node_id, self.initial_start_angle + overflow, self.initial_sweep_angle - overflow, input, responses);
|
||||
self.apply_arc_update(node_id, self.initial_start_angle + overflow, self.initial_sweep_angle - overflow, view, responses);
|
||||
}
|
||||
// Wrap start angle < -180° back into [-180°, 180°] and adjust sweep
|
||||
() if new_start_angle < -180. => {
|
||||
@@ -274,7 +274,7 @@ impl SweepAngleGizmo {
|
||||
self.initial_start_angle = 180.;
|
||||
self.initial_sweep_angle = current_sweep_angle + rest_angle.abs();
|
||||
|
||||
self.apply_arc_update(node_id, self.initial_start_angle + underflow, self.initial_sweep_angle + underflow.abs(), input, responses);
|
||||
self.apply_arc_update(node_id, self.initial_start_angle + underflow, self.initial_sweep_angle + underflow.abs(), view, responses);
|
||||
}
|
||||
_ => {
|
||||
let free_sweep_angle = self.initial_sweep_angle - total;
|
||||
@@ -284,7 +284,7 @@ impl SweepAngleGizmo {
|
||||
}
|
||||
|
||||
self.total_angle_delta = angle;
|
||||
self.apply_arc_update(node_id, self.initial_start_angle + total, self.initial_sweep_angle - total, input, responses);
|
||||
self.apply_arc_update(node_id, self.initial_start_angle + total, self.initial_sweep_angle - total, view, responses);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -304,7 +304,7 @@ impl SweepAngleGizmo {
|
||||
self.total_angle_delta = delta;
|
||||
self.endpoint = EndpointType::Start;
|
||||
|
||||
self.apply_arc_update(node_id, self.initial_start_angle + delta, self.initial_sweep_angle + delta.abs() * sign, input, responses);
|
||||
self.apply_arc_update(node_id, self.initial_start_angle + delta, self.initial_sweep_angle + delta.abs() * sign, view, responses);
|
||||
}
|
||||
// Clamp sweep angle above 360°, switch to start
|
||||
() if new_sweep_angle > 360. => {
|
||||
@@ -316,7 +316,7 @@ impl SweepAngleGizmo {
|
||||
self.endpoint = EndpointType::Start;
|
||||
self.update_state(SweepAngleGizmoState::Snapped);
|
||||
|
||||
self.apply_arc_update(node_id, self.initial_start_angle + angle_delta, self.initial_sweep_angle + angle_delta.abs() * sign, input, responses);
|
||||
self.apply_arc_update(node_id, self.initial_start_angle + angle_delta, self.initial_sweep_angle + angle_delta.abs() * sign, view, responses);
|
||||
}
|
||||
_ => {
|
||||
let free_sweep_angle = self.initial_sweep_angle + angle;
|
||||
@@ -326,7 +326,7 @@ impl SweepAngleGizmo {
|
||||
}
|
||||
|
||||
self.total_angle_delta = angle;
|
||||
self.apply_arc_update(node_id, self.initial_start_angle, self.initial_sweep_angle + total, input, responses);
|
||||
self.apply_arc_update(node_id, self.initial_start_angle, self.initial_sweep_angle + total, view, responses);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -335,17 +335,21 @@ impl SweepAngleGizmo {
|
||||
}
|
||||
|
||||
/// Applies the updated start and sweep angles to the arc.
|
||||
fn apply_arc_update(&mut self, node_id: NodeId, start_angle: f64, sweep_angle: f64, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fn apply_arc_update(&mut self, node_id: NodeId, start_angle: f64, sweep_angle: f64, view: SnapView, responses: &mut VecDeque<Message>) {
|
||||
let SnapView { document, input, .. } = view;
|
||||
self.snap_angles = Self::calculate_snap_angles();
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arc::StartAngleInput),
|
||||
input: NodeInput::value(TaggedValue::Number(start_angle), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arc::SweepAngleInput),
|
||||
input: NodeInput::value(TaggedValue::Number(sweep_angle), false),
|
||||
});
|
||||
for (parameter, degrees) in [
|
||||
(ParameterRef::from(graphene_std::vector::generator_nodes::arc::StartAngleInput), start_angle),
|
||||
(ParameterRef::from(graphene_std::vector::generator_nodes::arc::SweepAngleInput), sweep_angle),
|
||||
] {
|
||||
let input_connector = InputConnector::node(node_id, parameter);
|
||||
let angle = graph_modification_utils::angle_in_unit_of_input(&document.network_interface, &input_connector, degrees);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector,
|
||||
input: NodeInput::value(angle, false),
|
||||
});
|
||||
}
|
||||
|
||||
self.previous_mouse_position = input.mouse.position;
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
|
||||
@@ -274,11 +274,9 @@ pub fn new_custom(id: NodeId, nodes: Vec<(NodeId, NodeTemplate)>, parent: LayerN
|
||||
pub fn get_origin(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<DVec2> {
|
||||
use graphene_std::transform_nodes::transform::*;
|
||||
|
||||
if let TaggedValue::DVec2(origin) = NodeGraphLayer::new(layer, network_interface).parameter_value(TranslationInput)? {
|
||||
Some(*origin)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
NodeGraphLayer::new(layer, network_interface)
|
||||
.parameter_value(TranslationInput)?
|
||||
.as_length_vec2_pixels(network_interface.pixels_per_inch())
|
||||
}
|
||||
|
||||
pub fn get_viewport_origin(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> DVec2 {
|
||||
@@ -646,28 +644,21 @@ pub fn get_text<'a>(
|
||||
Some(TaggedValue::Resource(resource_id)) => fonts.id_font(resources, *resource_id).unwrap_or_default(),
|
||||
_ => Font::default(),
|
||||
};
|
||||
let Some(&TaggedValue::Number(font_size)) = parameters.value(text::SizeInput) else { return None };
|
||||
let pixels_per_inch = network_interface.pixels_per_inch();
|
||||
let font_size = parameters.value(text::SizeInput)?.as_length_pixels(pixels_per_inch)?;
|
||||
let Some(&TaggedValue::Number(line_height_ratio)) = parameters.value(text::LineHeightInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Number(letter_spacing)) = parameters.value(text::LetterSpacingInput) else {
|
||||
return None;
|
||||
};
|
||||
let letter_spacing = parameters.value(text::LetterSpacingInput)?.as_length_pixels(pixels_per_inch)?;
|
||||
let Some(&TaggedValue::Bool(has_max_width)) = parameters.value(text::HasMaxWidthInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Number(max_width)) = parameters.value(text::MaxWidthInput) else {
|
||||
return None;
|
||||
};
|
||||
let max_width = parameters.value(text::MaxWidthInput)?.as_length_pixels(pixels_per_inch)?;
|
||||
let Some(&TaggedValue::Bool(has_max_height)) = parameters.value(text::HasMaxHeightInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Number(max_height)) = parameters.value(text::MaxHeightInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Number(letter_tilt)) = parameters.value(text::LetterTiltInput) else {
|
||||
return None;
|
||||
};
|
||||
let max_height = parameters.value(text::MaxHeightInput)?.as_length_pixels(pixels_per_inch)?;
|
||||
let letter_tilt = parameters.value(text::LetterTiltInput)?.as_angle_degrees()?;
|
||||
let Some(&TaggedValue::TextAlign(align)) = parameters.value(text::AlignInput) else { return None };
|
||||
|
||||
let typesetting = TypesettingConfig {
|
||||
@@ -683,11 +674,8 @@ pub fn get_text<'a>(
|
||||
}
|
||||
|
||||
pub fn get_stroke_width(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<f64> {
|
||||
if let TaggedValue::Number(width) = NodeGraphLayer::new(layer, network_interface).parameter_value(graphene_std::vector::stroke::WeightInput)? {
|
||||
Some(*width)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let weight = NodeGraphLayer::new(layer, network_interface).parameter_value(graphene_std::vector::stroke::WeightInput)?;
|
||||
weight.as_length_pixels(network_interface.pixels_per_inch())
|
||||
}
|
||||
|
||||
/// Subset of Stroke node inputs read for the control bar's stroke options popover.
|
||||
@@ -729,10 +717,10 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
Some(TaggedValue::DashPattern(lengths)) => lengths.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let dash_offset = match parameters.value(stroke::DashOffsetInput) {
|
||||
Some(TaggedValue::Number(value)) => *value,
|
||||
_ => 0.,
|
||||
};
|
||||
let dash_offset = parameters
|
||||
.value(stroke::DashOffsetInput)
|
||||
.and_then(|value| value.as_length_pixels(network_interface.pixels_per_inch()))
|
||||
.unwrap_or_default();
|
||||
|
||||
Some(StrokeOptionsState {
|
||||
align,
|
||||
@@ -817,10 +805,11 @@ pub fn get_stroke_paint_order(layer: LayerNodeIdentifier, network_interface: &No
|
||||
pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
for layer in paintable_selected_layers(document) {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::vector::stroke::WeightInput);
|
||||
responses.add(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: graphene_std::vector::stroke::WeightInput::INDEX,
|
||||
value: TaggedValue::Number(weight).into(),
|
||||
value: length_in_unit_of_input(&document.network_interface, &input_connector, weight).into(),
|
||||
});
|
||||
} else if weight > 0. {
|
||||
let color = Some(Color::BLACK);
|
||||
@@ -1109,6 +1098,30 @@ pub fn set_parameter_for_selected_layers(document: &DocumentMessageHandler, para
|
||||
}
|
||||
}
|
||||
|
||||
/// A length in pixels as a value for the length input at `input_connector`, kept in the unit its current value was typed in, like a dragged radius that stays in millimeters.
|
||||
pub fn length_in_unit_of_input(network_interface: &NodeNetworkInterface, input_connector: &InputConnector, pixels: f64) -> TaggedValue {
|
||||
let existing = network_interface.input_from_connector(input_connector, &[]).and_then(NodeInput::as_value);
|
||||
existing.unwrap_or(&TaggedValue::None).length_in_same_unit(pixels, network_interface.pixels_per_inch())
|
||||
}
|
||||
|
||||
/// An angle in degrees as a value for the angle input at `input_connector`, kept in the unit its current value was typed in.
|
||||
pub fn angle_in_unit_of_input(network_interface: &NodeNetworkInterface, input_connector: &InputConnector, degrees: f64) -> TaggedValue {
|
||||
let existing = network_interface.input_from_connector(input_connector, &[]).and_then(NodeInput::as_value);
|
||||
existing.unwrap_or(&TaggedValue::None).angle_in_same_unit(degrees)
|
||||
}
|
||||
|
||||
/// A pair of lengths in pixels as a value for the input at `input_connector`, kept in the unit its current value was typed in.
|
||||
pub fn length_vec2_in_unit_of_input(network_interface: &NodeNetworkInterface, input_connector: &InputConnector, pixels: DVec2) -> TaggedValue {
|
||||
let existing = network_interface.input_from_connector(input_connector, &[]).and_then(NodeInput::as_value);
|
||||
existing.unwrap_or(&TaggedValue::None).length_vec2_in_same_unit(pixels, network_interface.pixels_per_inch())
|
||||
}
|
||||
|
||||
/// A pair of angles in degrees as a value for the input at `input_connector`, kept in the unit its current value was typed in.
|
||||
pub fn angle_vec2_in_unit_of_input(network_interface: &NodeNetworkInterface, input_connector: &InputConnector, degrees: DVec2) -> TaggedValue {
|
||||
let existing = network_interface.input_from_connector(input_connector, &[]).and_then(NodeInput::as_value);
|
||||
existing.unwrap_or(&TaggedValue::None).angle_vec2_in_same_unit(degrees)
|
||||
}
|
||||
|
||||
/// Checks if a specified layer uses an upstream node matching the given name.
|
||||
pub fn is_layer_fed_by_node_of_name(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface, identifier: &DefinitionIdentifier) -> bool {
|
||||
NodeGraphLayer::new(layer, network_interface).find_node_inputs(identifier).is_some()
|
||||
|
||||
@@ -11,6 +11,7 @@ use crate::messages::tool::common_functionality::snap_session::{SnapSession, Sna
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::{TypedAngle, TypedLength};
|
||||
use graphene_std::vector::misc::ArcType;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -135,9 +136,9 @@ impl Arc {
|
||||
let node_type = resolve_proto_node_type(graphene_std::vector::generator_nodes::arc::IDENTIFIER).expect("Ellipse node does not exist");
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::Number(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(270.), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(0.5)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Angle(TypedAngle::degrees(0.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Angle(TypedAngle::degrees(270.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::ArcType(arc_type), false)),
|
||||
])
|
||||
}
|
||||
@@ -179,7 +180,7 @@ impl Arc {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arc::RadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(radius), false),
|
||||
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius)), false),
|
||||
});
|
||||
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), aspect));
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::messages::tool::common_functionality::snap_session::{SnapSession, Sna
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::{TypedLength, TypedLengthVec2};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -25,10 +26,10 @@ impl Arrow {
|
||||
let node_type = resolve_document_node_type(&identifier).expect("Arrow node can't be found");
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false)), // arrow_to
|
||||
Some(NodeInput::value(TaggedValue::Number(shaft_width), false)), // shaft_width
|
||||
Some(NodeInput::value(TaggedValue::Number(head_width), false)), // head_width
|
||||
Some(NodeInput::value(TaggedValue::Number(head_length), false)), // head_length
|
||||
Some(NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(DVec2::ZERO)), false)), // arrow_to
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(shaft_width)), false)), // shaft_width
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(head_width)), false)), // head_width
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(head_length)), false)), // head_length
|
||||
])
|
||||
}
|
||||
|
||||
@@ -57,9 +58,11 @@ impl Arrow {
|
||||
|
||||
let document_to_viewport = document.metadata().document_to_viewport;
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::vector::generator_nodes::arrow::ArrowToInput);
|
||||
let arrow_to = graph_modification_utils::length_vec2_in_unit_of_input(&document.network_interface, &input_connector, arrow_to);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arrow::ArrowToInput),
|
||||
input: NodeInput::value(TaggedValue::DVec2(arrow_to), false),
|
||||
input_connector,
|
||||
input: NodeInput::value(arrow_to, false),
|
||||
});
|
||||
let downstream = document.metadata().downstream_transform_to_viewport(layer);
|
||||
let scope = downstream.inverse() * document_to_viewport;
|
||||
@@ -80,7 +83,7 @@ impl Arrow {
|
||||
.selected_visible_and_unlocked_layers(&document.network_interface)
|
||||
.filter_map(|layer| {
|
||||
let node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::arrow::IDENTIFIER))?;
|
||||
let Some(&TaggedValue::DVec2(arrow_to)) = node_inputs[1].as_value() else { return None };
|
||||
let arrow_to = node_inputs[1].as_value()?.as_length_vec2_pixels(document.network_interface.pixels_per_inch())?;
|
||||
|
||||
let transform = document.metadata().transform_to_viewport(layer);
|
||||
let viewport_start = transform.transform_point2(DVec2::ZERO);
|
||||
|
||||
@@ -84,7 +84,7 @@ pub struct Circle;
|
||||
impl Circle {
|
||||
pub fn create_node() -> NodeTemplate {
|
||||
let node_type = resolve_proto_node_type(graphene_std::vector::generator_nodes::circle::IDENTIFIER).expect("Circle can't be found");
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(0.), false))])
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(0.)), false))])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::messages::tool::common_functionality::snap_session::{SnapSession, Sna
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::TypedLength;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -16,7 +17,8 @@ pub struct Ellipse;
|
||||
impl Ellipse {
|
||||
pub fn create_node() -> NodeTemplate {
|
||||
let node_type = resolve_proto_node_type(graphene_std::vector::generator_nodes::ellipse::IDENTIFIER).expect("Ellipse node can't be found");
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(0.5), false)), Some(NodeInput::value(TaggedValue::Number(0.5), false))])
|
||||
let radius = || Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(0.5)), false));
|
||||
node_type.node_template_input_override([None, radius(), radius()])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
@@ -39,11 +41,11 @@ impl Ellipse {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::ellipse::RadiusXInput),
|
||||
input: NodeInput::value(TaggedValue::Number(radius.x), false),
|
||||
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius.x)), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::ellipse::RadiusYInput),
|
||||
input: NodeInput::value(TaggedValue::Number(radius.y), false),
|
||||
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius.y)), false),
|
||||
});
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
|
||||
}
|
||||
@@ -54,6 +56,7 @@ impl Ellipse {
|
||||
mod test_ellipse {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graphene_std::units::Length;
|
||||
use graphene_std::vector::generator_nodes::ellipse;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
@@ -76,8 +79,8 @@ mod test_ellipse {
|
||||
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
let ellipse_node = node_graph_layer.upstream_node_id_from_protonode(ellipse::IDENTIFIER)?;
|
||||
Some(ResolvedEllipse {
|
||||
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput, f64>(&[ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput, f64>(&[ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput, Length>(&[ellipse_node], &editor.runtime).unwrap().pixels(),
|
||||
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput, Length>(&[ellipse_node], &editor.runtime).unwrap().pixels(),
|
||||
transform: document.metadata().transform_to_document(layer),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -12,6 +12,7 @@ use crate::messages::tool::common_functionality::snap_session::{PointOptions, Sn
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::TypedLengthVec2;
|
||||
use graphene_std::vector::misc::GridType;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -92,7 +93,7 @@ impl Grid {
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false)),
|
||||
Some(NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(DVec2::ZERO)), false)),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -133,16 +134,20 @@ impl Grid {
|
||||
let dimensions = dimensions / viewport_zoom(document);
|
||||
|
||||
// Set dimensions/spacing
|
||||
let spacing_input = InputConnector::node(node_id, SpacingInput);
|
||||
let spacing = graph_modification_utils::length_vec2_in_unit_of_input(&document.network_interface, &spacing_input, dimensions);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, SpacingInput),
|
||||
input: NodeInput::value(TaggedValue::DVec2(dimensions), false),
|
||||
input_connector: spacing_input,
|
||||
input: NodeInput::value(spacing, false),
|
||||
});
|
||||
|
||||
// Set angle for isometric grids
|
||||
if let Some(angle_deg) = angle {
|
||||
let angles_input = InputConnector::node(node_id, AnglesInput);
|
||||
let angles = graph_modification_utils::angle_vec2_in_unit_of_input(&document.network_interface, &angles_input, DVec2::splat(angle_deg));
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, AnglesInput),
|
||||
input: NodeInput::value(TaggedValue::DVec2(DVec2::splat(angle_deg)), false),
|
||||
input_connector: angles_input,
|
||||
input: NodeInput::value(angles, false),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::TypedLengthVec2;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Clone, PartialEq, Debug, Default)]
|
||||
@@ -40,7 +41,7 @@ impl Line {
|
||||
pub fn create_node() -> NodeTemplate {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::line::IDENTIFIER);
|
||||
let node_type = resolve_document_node_type(&identifier).expect("Line node can't be found");
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false))])
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(DVec2::ZERO)), false))])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
@@ -70,9 +71,11 @@ impl Line {
|
||||
// Compute line_to in document space
|
||||
let line_to = document_points[1] - document_points[0];
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::vector::generator_nodes::line::LineToInput);
|
||||
let line_to = graph_modification_utils::length_vec2_in_unit_of_input(&document.network_interface, &input_connector, line_to);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::line::LineToInput),
|
||||
input: NodeInput::value(TaggedValue::DVec2(line_to), false),
|
||||
input_connector,
|
||||
input: NodeInput::value(line_to, false),
|
||||
});
|
||||
let document_to_viewport = document.metadata().document_to_viewport;
|
||||
let downstream = document.metadata().downstream_transform_to_viewport(layer);
|
||||
@@ -94,9 +97,7 @@ impl Line {
|
||||
let node_inputs =
|
||||
NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::line::IDENTIFIER))?;
|
||||
|
||||
let Some(&TaggedValue::DVec2(line_to)) = node_inputs[1].as_value() else {
|
||||
return None;
|
||||
};
|
||||
let line_to = node_inputs[1].as_value()?.as_length_vec2_pixels(document.network_interface.pixels_per_inch())?;
|
||||
|
||||
// Line goes from local origin (0,0) to line_to, positioned by the Transform node
|
||||
let transform = document.metadata().transform_to_viewport(layer);
|
||||
@@ -168,7 +169,6 @@ mod test_line_tool {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
/// Get the line's document-space start and end points by reading line_to from the node
|
||||
/// and computing the actual positions via the layer's transform.
|
||||
@@ -181,9 +181,7 @@ mod test_line_tool {
|
||||
.selected_visible_and_unlocked_layers(network_interface)
|
||||
.filter_map(|layer| {
|
||||
let node_inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::line::IDENTIFIER))?;
|
||||
let Some(&TaggedValue::DVec2(line_to)) = node_inputs[1].as_value() else {
|
||||
return None;
|
||||
};
|
||||
let line_to = node_inputs[1].as_value()?.as_length_vec2_pixels(network_interface.pixels_per_inch())?;
|
||||
|
||||
let transform_to_doc = document.metadata().transform_to_document(layer);
|
||||
let doc_start = transform_to_doc.transform_point2(DVec2::ZERO);
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::messages::tool::tool_messages::shape_tool::ShapeOptionsUpdate;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::TypedLength;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -113,7 +114,7 @@ impl Polygon {
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::Integer(vertices as i64), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(0.5)), false)),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -160,7 +161,7 @@ impl Polygon {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::regular_polygon::RadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(radius), false),
|
||||
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius)), false),
|
||||
});
|
||||
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), aspect));
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::messages::tool::common_functionality::snap_session::{SnapSession, Sna
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::TypedLength;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -16,7 +17,8 @@ pub struct Rectangle;
|
||||
impl Rectangle {
|
||||
pub fn create_node() -> NodeTemplate {
|
||||
let node_type = resolve_proto_node_type(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER).expect("Rectangle node can't be found");
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(1.), false)), Some(NodeInput::value(TaggedValue::Number(1.), false))])
|
||||
let side = || Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(1.)), false));
|
||||
node_type.node_template_input_override([None, side(), side()])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
@@ -39,11 +41,11 @@ impl Rectangle {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::rectangle::WidthInput),
|
||||
input: NodeInput::value(TaggedValue::Number(size.x), false),
|
||||
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(size.x)), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::rectangle::HeightInput),
|
||||
input: NodeInput::value(TaggedValue::Number(size.y), false),
|
||||
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(size.y)), false),
|
||||
});
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
|
||||
}
|
||||
|
||||
@@ -188,8 +188,7 @@ pub fn clicked_on_shape_endpoints(layer: LayerNodeIdentifier, document: &Documen
|
||||
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
let endpoint = line_like_shape_nodes.iter().find_map(|id| {
|
||||
let node_inputs = node_graph_layer.find_node_inputs(id)?;
|
||||
let &TaggedValue::DVec2(endpoint) = node_inputs[1].as_value()? else { return None };
|
||||
Some(endpoint)
|
||||
node_inputs[1].as_value()?.as_length_vec2_pixels(document.network_interface.pixels_per_inch())
|
||||
});
|
||||
let Some(endpoint) = endpoint else { return false };
|
||||
|
||||
@@ -276,12 +275,11 @@ pub fn anchor_overlays(document: &DocumentMessageHandler, overlay_context: &mut
|
||||
/// Returns an option of (sides, radius1, radius2).
|
||||
pub fn extract_star_parameters(layer: Option<LayerNodeIdentifier>, document: &DocumentMessageHandler) -> Option<(u32, f64, f64)> {
|
||||
let node_inputs = NodeGraphLayer::new(layer?, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::star::IDENTIFIER))?;
|
||||
let pixels_per_inch = document.network_interface.pixels_per_inch();
|
||||
|
||||
let (Some(&TaggedValue::Integer(sides)), Some(&TaggedValue::Number(radius_1)), Some(&TaggedValue::Number(radius_2))) =
|
||||
(node_inputs.get(1)?.as_value(), node_inputs.get(2)?.as_value(), node_inputs.get(3)?.as_value())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Integer(sides)) = node_inputs.get(1)?.as_value() else { return None };
|
||||
let radius_1 = node_inputs.get(2)?.as_value()?.as_length_pixels(pixels_per_inch)?;
|
||||
let radius_2 = node_inputs.get(3)?.as_value()?.as_length_pixels(pixels_per_inch)?;
|
||||
|
||||
Some((sides.max(0) as u32, radius_1, radius_2))
|
||||
}
|
||||
@@ -292,9 +290,8 @@ pub fn extract_polygon_parameters(layer: Option<LayerNodeIdentifier>, document:
|
||||
let node_inputs =
|
||||
NodeGraphLayer::new(layer?, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::regular_polygon::IDENTIFIER))?;
|
||||
|
||||
let (Some(&TaggedValue::Integer(n)), Some(&TaggedValue::Number(radius))) = (node_inputs.get(1)?.as_value(), node_inputs.get(2)?.as_value()) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Integer(n)) = node_inputs.get(1)?.as_value() else { return None };
|
||||
let radius = node_inputs.get(2)?.as_value()?.as_length_pixels(document.network_interface.pixels_per_inch())?;
|
||||
|
||||
Some((n.max(0) as u32, radius))
|
||||
}
|
||||
@@ -304,14 +301,10 @@ pub fn extract_polygon_parameters(layer: Option<LayerNodeIdentifier>, document:
|
||||
pub fn extract_arc_parameters(layer: Option<LayerNodeIdentifier>, document: &DocumentMessageHandler) -> Option<(f64, f64, f64, ArcType)> {
|
||||
let node_inputs = NodeGraphLayer::new(layer?, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::arc::IDENTIFIER))?;
|
||||
|
||||
let (Some(&TaggedValue::Number(radius)), Some(&TaggedValue::Number(start_angle)), Some(&TaggedValue::Number(sweep_angle)), Some(&TaggedValue::ArcType(arc_type))) = (
|
||||
node_inputs.get(1)?.as_value(),
|
||||
node_inputs.get(2)?.as_value(),
|
||||
node_inputs.get(3)?.as_value(),
|
||||
node_inputs.get(4)?.as_value(),
|
||||
) else {
|
||||
return None;
|
||||
};
|
||||
let radius = node_inputs.get(1)?.as_value()?.as_length_pixels(document.network_interface.pixels_per_inch())?;
|
||||
let start_angle = node_inputs.get(2)?.as_value()?.as_angle_degrees()?;
|
||||
let sweep_angle = node_inputs.get(3)?.as_value()?.as_angle_degrees()?;
|
||||
let Some(&TaggedValue::ArcType(arc_type)) = node_inputs.get(4)?.as_value() else { return None };
|
||||
|
||||
Some((radius, start_angle, sweep_angle, arc_type))
|
||||
}
|
||||
@@ -322,25 +315,15 @@ pub fn extract_spiral_parameters(layer: LayerNodeIdentifier, document: &Document
|
||||
use graphene_std::vector::generator_nodes::spiral::*;
|
||||
|
||||
let parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(IDENTIFIER)?;
|
||||
let pixels_per_inch = document.network_interface.pixels_per_inch();
|
||||
|
||||
let (
|
||||
Some(&TaggedValue::SpiralType(spiral_type)),
|
||||
Some(&TaggedValue::Number(start_angle)),
|
||||
Some(&TaggedValue::Number(inner_radius)),
|
||||
Some(&TaggedValue::Number(outer_radius)),
|
||||
Some(&TaggedValue::Number(turns)),
|
||||
Some(&TaggedValue::Number(angle_resolution)),
|
||||
) = (
|
||||
parameters.value(SpiralTypeInput),
|
||||
parameters.value(StartAngleInput),
|
||||
parameters.value(InnerRadiusInput),
|
||||
parameters.value(OuterRadiusInput),
|
||||
parameters.value(TurnsInput),
|
||||
parameters.value(AngularResolutionInput),
|
||||
)
|
||||
else {
|
||||
let (Some(&TaggedValue::SpiralType(spiral_type)), Some(&TaggedValue::Number(turns))) = (parameters.value(SpiralTypeInput), parameters.value(TurnsInput)) else {
|
||||
return None;
|
||||
};
|
||||
let start_angle = parameters.value(StartAngleInput)?.as_angle_degrees()?;
|
||||
let inner_radius = parameters.value(InnerRadiusInput)?.as_length_pixels(pixels_per_inch)?;
|
||||
let outer_radius = parameters.value(OuterRadiusInput)?.as_length_pixels(pixels_per_inch)?;
|
||||
let angle_resolution = parameters.value(AngularResolutionInput)?.as_angle_degrees()?;
|
||||
|
||||
Some((spiral_type, start_angle, inner_radius, outer_radius, turns, angle_resolution))
|
||||
}
|
||||
@@ -357,18 +340,17 @@ pub fn extract_heart_parameters(layer: LayerNodeIdentifier, document: &DocumentM
|
||||
Some(&TaggedValue::Number(lobe_lean)),
|
||||
Some(&TaggedValue::Number(widest_point)),
|
||||
Some(&TaggedValue::Number(side_fullness)),
|
||||
Some(&TaggedValue::Number(tip_angle)),
|
||||
) = (
|
||||
parameters.value(CleftDepthInput),
|
||||
parameters.value(CleftSharpnessInput),
|
||||
parameters.value(LobeLeanInput),
|
||||
parameters.value(WidestPointInput),
|
||||
parameters.value(SideFullnessInput),
|
||||
parameters.value(TipAngleInput),
|
||||
)
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let tip_angle = parameters.value(TipAngleInput)?.as_angle_degrees()?;
|
||||
|
||||
Some(HeartProportions {
|
||||
cleft_depth: cleft_depth / 100.,
|
||||
@@ -647,16 +629,18 @@ pub fn extract_grid_parameters(layer: LayerNodeIdentifier, document: &DocumentMe
|
||||
|
||||
let parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(IDENTIFIER)?;
|
||||
|
||||
let (Some(&TaggedValue::GridType(grid_type)), Some(&TaggedValue::DVec2(spacing)), Some(&TaggedValue::Integer(columns)), Some(&TaggedValue::Integer(rows)), Some(&TaggedValue::DVec2(angles))) = (
|
||||
parameters.value(LatticeInput),
|
||||
parameters.value(SpacingInput),
|
||||
parameters.value(ColumnsInput),
|
||||
parameters.value(RowsInput),
|
||||
parameters.value(AnglesInput),
|
||||
) else {
|
||||
let (Some(&TaggedValue::GridType(grid_type)), Some(&TaggedValue::Integer(columns)), Some(&TaggedValue::Integer(rows))) =
|
||||
(parameters.value(LatticeInput), parameters.value(ColumnsInput), parameters.value(RowsInput))
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
|
||||
// The spacing is a pair of lengths, or one length for both axes
|
||||
let pixels_per_inch = document.network_interface.pixels_per_inch();
|
||||
let spacing = parameters.value(SpacingInput)?;
|
||||
let spacing = spacing.as_length_vec2_pixels(pixels_per_inch).or_else(|| spacing.as_length_pixels(pixels_per_inch).map(DVec2::splat))?;
|
||||
let angles = parameters.value(AnglesInput)?.as_angle_vec2_degrees()?;
|
||||
|
||||
Some((grid_type, spacing, columns.max(0) as u32, rows.max(0) as u32, angles))
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::{TypedAngle, TypedLength};
|
||||
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
|
||||
use graphene_std::vector::misc::SpiralType;
|
||||
use std::collections::VecDeque;
|
||||
@@ -106,10 +107,10 @@ impl Spiral {
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::SpiralType(spiral_type), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(turns), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(inner_radius), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.1), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(90.), false)),
|
||||
Some(NodeInput::value(TaggedValue::Angle(TypedAngle::degrees(0.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(inner_radius)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(0.1)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Angle(TypedAngle::degrees(90.)), false)),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -146,7 +147,7 @@ impl Spiral {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, OuterRadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_radius), false),
|
||||
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(new_radius)), false),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use core::f64;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::TypedLength;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -116,8 +117,8 @@ impl Star {
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::Integer(vertices as i64), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.25), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(0.5)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(0.25)), false)),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -164,12 +165,12 @@ impl Star {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::star::Radius1Input),
|
||||
input: NodeInput::value(TaggedValue::Number(radius), false),
|
||||
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius)), false),
|
||||
});
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::star::Radius2Input),
|
||||
input: NodeInput::value(TaggedValue::Number(radius * INNER_RADIUS_WHILE_DRAWING), false),
|
||||
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius * INNER_RADIUS_WHILE_DRAWING)), false),
|
||||
});
|
||||
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), aspect));
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::choice_type::ChoiceTypeStatic;
|
||||
use graphene_std::core_types::misc::parse_f64;
|
||||
use graphene_std::units::TypedLength;
|
||||
use graphene_std::vector::style::{PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
|
||||
/// All non-color stroke-related options surfaced in the control bar popover.
|
||||
@@ -221,5 +222,5 @@ pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, doc
|
||||
|
||||
pub fn apply_dash_offset(drawing: &mut DrawingToolState, offset: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.dash_offset = Some(offset);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::DashOffsetInput, TaggedValue::Number(offset), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::DashOffsetInput, TaggedValue::Length(TypedLength::pixels(offset)), responses);
|
||||
}
|
||||
@@ -484,7 +484,7 @@ impl Fsm for ArtboardToolFsmState {
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
id,
|
||||
location: start.min(end).round(),
|
||||
dimensions: (start.round() - end.round()).abs(),
|
||||
dimensions: graphene_std::units::TypedLengthVec2::pixels((start.round() - end.round()).abs()),
|
||||
background: graphene_std::Color::WHITE,
|
||||
clip: true,
|
||||
})
|
||||
|
||||
@@ -276,8 +276,8 @@ impl BrushTool {
|
||||
return;
|
||||
};
|
||||
let value = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
|
||||
if let Some(TaggedValue::Number(diameter)) = value(brush_strokes::DiameterInput::INDEX) {
|
||||
self.options.diameter = if self.options.scale_with_viewport { *diameter * viewport_zoom(document) } else { *diameter };
|
||||
if let Some(diameter) = value(brush_strokes::DiameterInput::INDEX).and_then(|diameter| diameter.as_length_pixels(document.network_interface.pixels_per_inch())) {
|
||||
self.options.diameter = if self.options.scale_with_viewport { diameter * viewport_zoom(document) } else { diameter };
|
||||
}
|
||||
if let Some(TaggedValue::Number(hardness)) = value(brush_strokes::HardnessInput::INDEX) {
|
||||
self.options.hardness = *hardness;
|
||||
@@ -380,7 +380,7 @@ impl BrushToolData {
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER) {
|
||||
self.transform = get_current_transform(&node.inputs) * self.transform;
|
||||
self.transform = get_current_transform(&node.inputs, document.network_interface.pixels_per_inch()) * self.transform;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,10 +393,11 @@ impl BrushToolData {
|
||||
return false;
|
||||
};
|
||||
let value = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
|
||||
let diameter = value(brush_strokes::DiameterInput::INDEX).and_then(|diameter| diameter.as_length_pixels(document.network_interface.pixels_per_inch()));
|
||||
matches!(value(brush_strokes::ColorInput::INDEX), Some(TaggedValue::Color(color)) if *color == options.active_color())
|
||||
&& matches!(value(brush_strokes::DiameterInput::INDEX), Some(TaggedValue::Number(diameter)) if {
|
||||
&& diameter.is_some_and(|diameter| {
|
||||
let target = options.stroke_diameter(document);
|
||||
(*diameter - target).abs() <= diameter.abs().max(target.abs()) * (f64::EPSILON * 8.)
|
||||
(diameter - target).abs() <= diameter.abs().max(target.abs()) * (f64::EPSILON * 8.)
|
||||
})
|
||||
&& matches!(value(brush_strokes::HardnessInput::INDEX), Some(TaggedValue::Number(hardness)) if *hardness == options.hardness)
|
||||
&& matches!(value(brush_strokes::FlowInput::INDEX), Some(TaggedValue::Number(flow)) if *flow == options.flow)
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::consts::{
|
||||
COLOR_OVERLAY_BLUE, DRAG_THRESHOLD, GRADIENT_MIDPOINT_DIAMOND_RADIUS, GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN, GRADIENT_STOP_MIN_VIEWPORT_GAP, MANIPULATOR_GROUP_MARKER_SIZE,
|
||||
SEGMENT_INSERTION_DISTANCE, SEGMENT_OVERLAY_SIZE, SELECTION_THRESHOLD,
|
||||
};
|
||||
use crate::messages::portfolio::document::graph_operation::transform_utils;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{GizmoEmphasis, OverlayContext};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -429,7 +430,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
};
|
||||
|
||||
if reference == transform_reference {
|
||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||
transforms_downstream_to_upstream.push(transform_utils::get_current_transform(&document_node.inputs, network_interface.pixels_per_inch()));
|
||||
} else if reference == gradient_form_reference
|
||||
&& gradient_form.is_none()
|
||||
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||
@@ -448,34 +449,6 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconstruct the `DAffine2` produced by a 'Transform' node from its translation, rotation, scale, and skew inputs.
|
||||
fn read_transform_node_value(inputs: &[graph_craft::document::NodeInput]) -> DAffine2 {
|
||||
let translation = inputs
|
||||
.get(1)
|
||||
.and_then(|input| input.as_value())
|
||||
.and_then(|value| if let TaggedValue::DVec2(v) = value { Some(*v) } else { None })
|
||||
.unwrap_or(DVec2::ZERO);
|
||||
let rotation_degrees = inputs
|
||||
.get(2)
|
||||
.and_then(|input| input.as_value())
|
||||
.and_then(|value| if let TaggedValue::Number(v) = value { Some(*v) } else { None })
|
||||
.unwrap_or(0.);
|
||||
let scale = inputs
|
||||
.get(3)
|
||||
.and_then(|input| input.as_value())
|
||||
.and_then(|value| if let TaggedValue::DVec2(v) = value { Some(*v) } else { None })
|
||||
.unwrap_or(DVec2::ONE);
|
||||
let skew = inputs
|
||||
.get(4)
|
||||
.and_then(|input| input.as_value())
|
||||
.and_then(|value| if let TaggedValue::DVec2(v) = value { Some(*v) } else { None })
|
||||
.unwrap_or(DVec2::ZERO);
|
||||
|
||||
let trs = DAffine2::from_scale_angle_translation(scale, rotation_degrees.to_radians(), translation);
|
||||
let skew_matrix = DAffine2::from_cols_array(&[1., skew.y.to_radians().tan(), skew.x.to_radians().tan(), 1., 0., 0.]);
|
||||
trs * skew_matrix
|
||||
}
|
||||
|
||||
/// Whether two adjacent stops are too closely packed in viewport space for a midpoint diamond to be shown or interacted with.
|
||||
fn midpoint_hidden_by_proximity(left_stop_pos: f64, right_stop_pos: f64, viewport_line_length: f64) -> bool {
|
||||
(right_stop_pos - left_stop_pos) * viewport_line_length < GRADIENT_STOP_MIN_VIEWPORT_GAP * 2.
|
||||
|
||||
@@ -30,6 +30,7 @@ use crate::messages::tool::common_functionality::utility_functions::{closest_poi
|
||||
use crate::messages::tool::utility_types::DocumentToolData;
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::TypedLength;
|
||||
use graphene_std::vector::algorithms::shapes::HEART_SIZE;
|
||||
use graphene_std::vector::misc::{ArcType, GridType, SpiralType};
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
@@ -396,19 +397,22 @@ fn sync_shape_options_from_selection(options: &mut ShapeToolOptions, tool_data:
|
||||
}
|
||||
}
|
||||
ShapeType::Arrow => {
|
||||
if let Some(&TaggedValue::Number(shaft)) = layer_view.parameter_value(arrow::ShaftWidthInput)
|
||||
let pixels_per_inch = document.network_interface.pixels_per_inch();
|
||||
let pixels = |parameter: ParameterRef| layer_view.parameter_value(parameter).and_then(|value| value.as_length_pixels(pixels_per_inch));
|
||||
|
||||
if let Some(shaft) = pixels(arrow::ShaftWidthInput.into())
|
||||
&& options.arrow_shaft_width != shaft
|
||||
{
|
||||
options.arrow_shaft_width = shaft;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(&TaggedValue::Number(head_w)) = layer_view.parameter_value(arrow::HeadWidthInput)
|
||||
if let Some(head_w) = pixels(arrow::HeadWidthInput.into())
|
||||
&& options.arrow_head_width != head_w
|
||||
{
|
||||
options.arrow_head_width = head_w;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(&TaggedValue::Number(head_l)) = layer_view.parameter_value(arrow::HeadLengthInput)
|
||||
if let Some(head_l) = pixels(arrow::HeadLengthInput.into())
|
||||
&& options.arrow_head_length != head_l
|
||||
{
|
||||
options.arrow_head_length = head_l;
|
||||
@@ -677,15 +681,15 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Shap
|
||||
}
|
||||
ShapeOptionsUpdate::ArrowShaftWidth(shaft_width) => {
|
||||
self.options.arrow_shaft_width = shaft_width;
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::ShaftWidthInput, TaggedValue::Number(shaft_width), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::ShaftWidthInput, TaggedValue::Length(TypedLength::pixels(shaft_width)), responses);
|
||||
}
|
||||
ShapeOptionsUpdate::ArrowHeadWidth(head_width) => {
|
||||
self.options.arrow_head_width = head_width;
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::HeadWidthInput, TaggedValue::Number(head_width), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::HeadWidthInput, TaggedValue::Length(TypedLength::pixels(head_width)), responses);
|
||||
}
|
||||
ShapeOptionsUpdate::ArrowHeadLength(head_length) => {
|
||||
self.options.arrow_head_length = head_length;
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::HeadLengthInput, TaggedValue::Number(head_length), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::HeadLengthInput, TaggedValue::Length(TypedLength::pixels(head_length)), responses);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1654,6 +1658,7 @@ mod test_shape_tool {
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::units::TypedAngle;
|
||||
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, heart_bezpath};
|
||||
use graphene_std::vector::generator_nodes::arc;
|
||||
use graphene_std::vector::misc::{SpiralType, point_to_dvec2};
|
||||
@@ -2175,7 +2180,7 @@ mod test_shape_tool {
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, arc::SweepAngleInput),
|
||||
input: NodeInput::value(TaggedValue::Number(268.), false),
|
||||
input: NodeInput::value(TaggedValue::Angle(TypedAngle::degrees(268.)), false),
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::RunDocumentGraph).await;
|
||||
@@ -2478,9 +2483,9 @@ mod test_shape_tool {
|
||||
|
||||
let layer = editor.get_selected_layer().await.expect("the new line should be selected");
|
||||
let document = editor.active_document();
|
||||
let Some(&TaggedValue::DVec2(line_to)) = graph_modification_utils::NodeGraphLayer::new(layer, &document.network_interface)
|
||||
let Some(line_to) = graph_modification_utils::NodeGraphLayer::new(layer, &document.network_interface)
|
||||
.find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::line::IDENTIFIER))
|
||||
.and_then(|inputs| inputs[1].as_value())
|
||||
.and_then(|inputs| inputs[1].as_value()?.as_length_vec2_pixels(document.network_interface.pixels_per_inch()))
|
||||
else {
|
||||
panic!("the new layer should be a line")
|
||||
};
|
||||
|
||||
@@ -353,10 +353,11 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
|
||||
if let Some(layer) = can_edit_selected(context.document)
|
||||
&& let Some(node_id) = graph_modification_utils::get_text_id(layer, &context.document.network_interface)
|
||||
{
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::text::text::SizeInput);
|
||||
responses.add(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: graphene_std::text::text::SizeInput::INDEX,
|
||||
value: TaggedValue::Number(font_size).into(),
|
||||
value: graph_modification_utils::length_in_unit_of_input(&context.document.network_interface, &input_connector, font_size).into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -928,17 +929,21 @@ impl Fsm for TextToolFsmState {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::text::text::HasMaxWidthInput),
|
||||
input: NodeInput::value(TaggedValue::Bool(true), false),
|
||||
});
|
||||
let max_width_input = InputConnector::node(node_id, graphene_std::text::text::MaxWidthInput);
|
||||
let max_width = graph_modification_utils::length_in_unit_of_input(&document.network_interface, &max_width_input, size_layer.x);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::text::text::MaxWidthInput),
|
||||
input: NodeInput::value(TaggedValue::Number(size_layer.x), false),
|
||||
input_connector: max_width_input,
|
||||
input: NodeInput::value(max_width, false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::text::text::HasMaxHeightInput),
|
||||
input: NodeInput::value(TaggedValue::Bool(true), false),
|
||||
});
|
||||
let max_height_input = InputConnector::node(node_id, graphene_std::text::text::MaxHeightInput);
|
||||
let max_height = graph_modification_utils::length_in_unit_of_input(&document.network_interface, &max_height_input, size_layer.y);
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::text::text::MaxHeightInput),
|
||||
input: NodeInput::value(TaggedValue::Number(size_layer.y), false),
|
||||
input_connector: max_height_input,
|
||||
input: NodeInput::value(max_height, false),
|
||||
});
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer: dragging_layer.id,
|
||||
|
||||
@@ -1066,7 +1066,7 @@ mod test_transform_layer {
|
||||
let _responses: VecDeque<Message> = VecDeque::new();
|
||||
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER), layer, network_interface)?;
|
||||
let document_node = network_interface.document_network().nodes.get(&transform_node_id)?;
|
||||
Some(transform_utils::get_current_transform(&document_node.inputs))
|
||||
Some(transform_utils::get_current_transform(&document_node.inputs, network_interface.pixels_per_inch()))
|
||||
}
|
||||
|
||||
/// Draws a rectangle between two viewport positions, which leaves it selected, and returns its layer.
|
||||
|
||||
@@ -13,6 +13,8 @@ use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::encode_pdf_document;
|
||||
use graphene_std::renderer::pdf_scene_builder::{PdfPage, PdfScene};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
|
||||
@@ -125,6 +127,8 @@ pub struct NodeGraphExecutor {
|
||||
inspect_context_overrides: ContextOverrides,
|
||||
/// The canvas images the frontend holds, so a render sends only those it lacks.
|
||||
canvas_images_sent: HashSet<u64>,
|
||||
/// The scenes rendered so far for the pages of a PDF of every artboard, by page, until the last one completes the file.
|
||||
pdf_pages: Vec<Option<(PdfScene, PdfPage)>>,
|
||||
/// Evaluation errors of the last evaluation, used in tests
|
||||
#[cfg(test)]
|
||||
evaluation_errors: Option<EvaluationErrors>,
|
||||
@@ -137,6 +141,9 @@ pub struct NodeGraphExecutor {
|
||||
gradient_migration_attempted: HashSet<DocumentId>,
|
||||
}
|
||||
|
||||
/// The bounds an export renders, with its page among those of a PDF of every artboard.
|
||||
type ExportRender = ([DVec2; 2], Option<(usize, PdfPage)>);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ExecutionContext {
|
||||
export_config: Option<ExportConfig>,
|
||||
@@ -148,6 +155,8 @@ struct ExecutionContext {
|
||||
/// network path) and its original relative gradient. The evaluated geometry is read back from the inspect result to size the
|
||||
/// gradient; such runs never touch the visible artwork. Carrying the entry keeps a stale re-dispatched response paired with the fill it measured.
|
||||
measure_fill: Option<(Vec<NodeId>, NodeId, graphic_types::migrations::legacy::LegacyGradient)>,
|
||||
/// The page of a PDF of every artboard this execution renders, by its place among them.
|
||||
pdf_page: Option<(usize, PdfPage)>,
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
@@ -179,6 +188,7 @@ impl NodeGraphExecutor {
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
inspect_context_overrides: ContextOverrides::default(),
|
||||
canvas_images_sent: HashSet::new(),
|
||||
pdf_pages: Vec::new(),
|
||||
#[cfg(test)]
|
||||
evaluation_errors: None,
|
||||
gradient_migration: None,
|
||||
@@ -370,6 +380,7 @@ impl NodeGraphExecutor {
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
pdf_page: None,
|
||||
},
|
||||
));
|
||||
|
||||
@@ -438,6 +449,7 @@ impl NodeGraphExecutor {
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
pdf_page: None,
|
||||
},
|
||||
));
|
||||
|
||||
@@ -445,50 +457,55 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
/// Evaluates a node graph for export
|
||||
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, export_config: ExportConfig) -> Result<(), String> {
|
||||
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, mut export_config: ExportConfig) -> Result<(), String> {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
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
|
||||
};
|
||||
// A PDF's page is sized in physical units, so its dialog leaves the scale factor out
|
||||
if export_config.file_type == FileType::Pdf {
|
||||
export_config.scale_factor = 1.;
|
||||
}
|
||||
|
||||
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
|
||||
// Calculate the bounding box of each region to be exported (artboard bounds always contribute).
|
||||
// `AllArtwork` and `Selection` expand layer bounds by the rendered stroke width and effects reach so strokes
|
||||
// and shadows drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
let bounds = match export_config.bounds {
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke_and_effects(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke_and_effects(true, &[]),
|
||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
||||
// Every artboard with any area is a page of its own render, sized like an export of it alone.
|
||||
let renders: Vec<ExportRender> = match export_config.bounds {
|
||||
ExportBounds::AllArtboards => document
|
||||
.artboard_names()
|
||||
.into_iter()
|
||||
.filter_map(|(layer, name)| {
|
||||
let [min, max] = document.metadata().bounding_box_document(layer)?;
|
||||
let size = (max - min).round();
|
||||
let page = PdfPage {
|
||||
origin: kurbo::Point::ORIGIN,
|
||||
size: kurbo::Size::new(size.x, size.y),
|
||||
bookmark: Some(name),
|
||||
};
|
||||
(size.x > 0. && size.y > 0.).then_some(([min, min + size], page))
|
||||
})
|
||||
.enumerate()
|
||||
.map(|(index, (bounds, page))| (bounds, Some((index, page))))
|
||||
.collect(),
|
||||
ExportBounds::AllArtwork => document
|
||||
.network_interface
|
||||
.document_bounds_document_space_with_stroke_and_effects(true)
|
||||
.map(|bounds| (bounds, None))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
ExportBounds::Selection => document
|
||||
.network_interface
|
||||
.selected_bounds_document_space_with_stroke_and_effects(true, &[])
|
||||
.map(|bounds| (bounds, None))
|
||||
.into_iter()
|
||||
.collect(),
|
||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id).map(|bounds| (bounds, None)).into_iter().collect(),
|
||||
};
|
||||
if renders.is_empty() {
|
||||
return Err("No bounding box".to_string());
|
||||
}
|
||||
.ok_or_else(|| "No bounding box".to_string())?;
|
||||
|
||||
let resolution_in_document_space = bounds[1] - bounds[0];
|
||||
let export_resolution = resolution_in_document_space * export_config.scale_factor;
|
||||
let resolution = export_resolution.round().as_uvec2();
|
||||
let transform = DAffine2::from_translation(bounds[0]).inverse();
|
||||
let viewport = Footprint {
|
||||
resolution,
|
||||
transform,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let render_config = RenderConfig {
|
||||
viewport,
|
||||
scale: export_config.scale_factor,
|
||||
time: Default::default(),
|
||||
pointer: DVec2::ZERO,
|
||||
export_format,
|
||||
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
|
||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
// A document at CSS's 96 pixels per inch exports as it always has, in unitless pixels
|
||||
pixels_per_inch: Some(document.network_interface.pixels_per_inch()).filter(|pixels_per_inch| *pixels_per_inch != graphene_std::units::DEFAULT_PIXELS_PER_INCH),
|
||||
};
|
||||
self.pdf_pages = renders.iter().filter(|(_, page)| page.is_some()).map(|_| None).collect();
|
||||
|
||||
// Execute the node graph
|
||||
self.sender
|
||||
@@ -501,16 +518,49 @@ impl NodeGraphExecutor {
|
||||
pixels_per_inch: document.network_interface.pixels_per_inch(),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: Some(export_config),
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
},
|
||||
));
|
||||
|
||||
let export_format = match export_config.file_type {
|
||||
FileType::Svg => ExportFormat::Svg,
|
||||
FileType::Pdf => ExportFormat::Pdf,
|
||||
_ => ExportFormat::Raster,
|
||||
};
|
||||
for (bounds, pdf_page) in renders {
|
||||
let resolution_in_document_space = bounds[1] - bounds[0];
|
||||
let export_resolution = resolution_in_document_space * export_config.scale_factor;
|
||||
let resolution = export_resolution.round().as_uvec2();
|
||||
let transform = DAffine2::from_translation(bounds[0]).inverse();
|
||||
let viewport = Footprint {
|
||||
resolution,
|
||||
transform,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let render_config = RenderConfig {
|
||||
viewport,
|
||||
scale: export_config.scale_factor,
|
||||
time: Default::default(),
|
||||
pointer: DVec2::ZERO,
|
||||
export_format,
|
||||
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
|
||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
// A document at CSS's 96 pixels per inch exports as it always has, in unitless pixels
|
||||
pixels_per_inch: Some(document.network_interface.pixels_per_inch()).filter(|pixels_per_inch| *pixels_per_inch != graphene_std::units::DEFAULT_PIXELS_PER_INCH),
|
||||
};
|
||||
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: Some(export_config.clone()),
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
pdf_page,
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -675,7 +725,7 @@ impl NodeGraphExecutor {
|
||||
document.network_interface.update_vector_modify(path_contents(&observations));
|
||||
|
||||
match (node_graph_output, execution_context.export_config) {
|
||||
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
|
||||
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, execution_context.pdf_page, document, responses),
|
||||
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
|
||||
(None, _) => {}
|
||||
}
|
||||
@@ -934,6 +984,7 @@ impl NodeGraphExecutor {
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: Some((network_path, fill_node_id, gradient)),
|
||||
pdf_page: None,
|
||||
},
|
||||
));
|
||||
}
|
||||
@@ -1056,6 +1107,11 @@ impl NodeGraphExecutor {
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
return;
|
||||
}
|
||||
RenderOutputType::Pdf(_) => {
|
||||
log::error!("Invalid node graph output type: a PDF page");
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let RenderMetadata {
|
||||
@@ -1094,7 +1150,14 @@ impl NodeGraphExecutor {
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
|
||||
}
|
||||
|
||||
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fn process_export(
|
||||
&mut self,
|
||||
node_graph_output: TaggedValue,
|
||||
export_config: ExportConfig,
|
||||
pdf_page: Option<(usize, PdfPage)>,
|
||||
document: &DocumentMessageHandler,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
let ExportConfig {
|
||||
file_type,
|
||||
name,
|
||||
@@ -1126,7 +1189,7 @@ impl NodeGraphExecutor {
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Buffer { data, width, height },
|
||||
..
|
||||
}) if file_type != FileType::Svg => {
|
||||
}) if !matches!(file_type, FileType::Svg | FileType::Pdf) => {
|
||||
let content = match file_type.encode(width, height, data) {
|
||||
Ok(content) => content.into(),
|
||||
Err(description) => {
|
||||
@@ -1139,6 +1202,38 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
responses.add(FrontendMessage::TriggerSaveFile { name, folder, filters, content });
|
||||
}
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Pdf(scene), ..
|
||||
}) if file_type == FileType::Pdf => {
|
||||
let pixels_per_inch = document.network_interface.pixels_per_inch();
|
||||
let encoded = match pdf_page {
|
||||
None => scene.encode_pdf(pixels_per_inch),
|
||||
// A page waits for the others, and the last to finish encodes them all as one file
|
||||
Some((index, page)) => {
|
||||
let Some(slot) = self.pdf_pages.get_mut(index) else {
|
||||
log::error!("A PDF page finished rendering for an export no longer in progress");
|
||||
return;
|
||||
};
|
||||
*slot = Some((*scene, page));
|
||||
if self.pdf_pages.iter().any(Option::is_none) {
|
||||
return;
|
||||
}
|
||||
|
||||
let pages: Vec<(&PdfScene, &PdfPage)> = self.pdf_pages.iter().flatten().map(|(scene, page)| (scene, page)).collect();
|
||||
let encoded = encode_pdf_document(&pages, pixels_per_inch);
|
||||
self.pdf_pages.clear();
|
||||
encoded
|
||||
}
|
||||
};
|
||||
let content = match encoded {
|
||||
Ok(content) => content.into(),
|
||||
Err(error) => {
|
||||
log::error!("Failed to encode PDF: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
responses.add(FrontendMessage::TriggerSaveFile { name, folder, filters, content });
|
||||
}
|
||||
_ => {
|
||||
log::error!("Incorrect render type for exporting to {file_type:?}: {node_graph_output}");
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use graphene_std::ops::ConvertAsync;
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
|
||||
use graphene_std::raster_types::Raster;
|
||||
use graphene_std::renderer::scene_builder::SceneBuilder;
|
||||
use graphene_std::runtime::AsyncRuntime;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Context, NodeError, Poll};
|
||||
@@ -427,11 +428,21 @@ impl NodeRuntime {
|
||||
let Some(mut result) = result else { return };
|
||||
self.dirty.store(true, Ordering::Release);
|
||||
|
||||
if let Some(RenderOutput { data, .. }) = result.render_output()
|
||||
&& let RenderOutputType::Texture(texture) = data
|
||||
{
|
||||
let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8();
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
if let Some(RenderOutput { data, .. }) = result.render_output() {
|
||||
match data {
|
||||
RenderOutputType::Texture(texture) => {
|
||||
let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8();
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
}
|
||||
// The editor encodes the PDF away from the GPU, so the textures its page draws are read back here
|
||||
RenderOutputType::Pdf(scene) => {
|
||||
for (index, texture) in scene.textures() {
|
||||
let raster = self.read_back(texture).await;
|
||||
scene.resolve_texture(index, raster);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
@@ -658,6 +669,7 @@ mod tests {
|
||||
use crate::messages::frontend::utility_types::RenderStatus;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::test_utils::EditorTestUtils;
|
||||
use crate::test_utils::test_prelude::{ModifierKeys, ToolType};
|
||||
use glam::{DVec2, UVec2};
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graphene_std::SourceId;
|
||||
@@ -693,6 +705,10 @@ mod tests {
|
||||
|
||||
/// Sends a network update and a request to export it, as the editor does for an export.
|
||||
fn send_export(editor: &mut EditorTestUtils, file_type: FileType) {
|
||||
send_export_of(editor, file_type, ExportBounds::AllArtwork);
|
||||
}
|
||||
|
||||
fn send_export_of(editor: &mut EditorTestUtils, file_type: FileType, bounds: ExportBounds) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
@@ -701,12 +717,28 @@ mod tests {
|
||||
name: "export".to_string(),
|
||||
file_type,
|
||||
scale_factor: 1.,
|
||||
bounds: ExportBounds::AllArtwork,
|
||||
bounds,
|
||||
..Default::default()
|
||||
};
|
||||
executor.submit_document_export(document, document_id, export_config).unwrap();
|
||||
}
|
||||
|
||||
/// Runs the export sent last, over the evaluation of each page it renders, giving back the name and content of the file it saves.
|
||||
async fn saved_export(editor: &mut EditorTestUtils) -> (String, Vec<u8>) {
|
||||
for _ in 0..100 {
|
||||
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.to_vec())),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(saved) = saved {
|
||||
return saved;
|
||||
}
|
||||
}
|
||||
panic!("the export saved no file")
|
||||
}
|
||||
|
||||
/// Whether the runtime evaluated the graph since this was last called.
|
||||
fn evaluated(editor: &mut EditorTestUtils) -> bool {
|
||||
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::UpdateDocumentArtwork { .. }))
|
||||
@@ -1100,6 +1132,72 @@ mod tests {
|
||||
assert!(evaluated(&mut editor), "the request sent after the export was lost");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pdf_export_saves_a_pdf_document_of_the_artwork() {
|
||||
// The page spans the artwork at the document's resolution, so 96 pixels per inch is three quarters of a point per pixel
|
||||
for (pixels_per_inch, points_per_pixel) in [(96., 0.75), (192., 0.375)] {
|
||||
let mut editor = editor().await;
|
||||
editor.handle_message(DocumentMessage::SetPixelsPerInch { pixels_per_inch }).await;
|
||||
let [min, max] = editor.active_document().network_interface.document_bounds_document_space_with_stroke_and_effects(true).unwrap();
|
||||
send_export(&mut editor, FileType::Pdf);
|
||||
|
||||
let (name, content) = saved_export(&mut editor).await;
|
||||
assert_eq!(name, "export.pdf");
|
||||
assert!(content.starts_with(b"%PDF-") && content.trim_ascii_end().ends_with(b"%%EOF"));
|
||||
|
||||
let points = (max - min).round() * points_per_pixel;
|
||||
let content = String::from_utf8_lossy(&content);
|
||||
assert!(content.contains(&format!("/MediaBox[0 0 {} {}]", points.x, points.y)), "{content}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pdf_export_of_all_artboards_gives_each_artboard_its_own_page() {
|
||||
for (pixels_per_inch, points_per_pixel) in [(96., 0.75), (192., 0.375)] {
|
||||
let mut editor = editor().await;
|
||||
editor.handle_message(DocumentMessage::SetPixelsPerInch { pixels_per_inch }).await;
|
||||
|
||||
// Two differently sized artboards, named for their pages' bookmarks
|
||||
for (index, [left, top, right, bottom]) in [[200., 0., 400., 100.], [500., 50., 600., 300.]].into_iter().enumerate() {
|
||||
editor.drag_tool(ToolType::Artboard, left, top, right, bottom, ModifierKeys::empty()).await;
|
||||
let artboard = editor.get_selected_layer().await.expect("the drawn artboard should be selected");
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetDisplayName {
|
||||
node_id: artboard.to_node(),
|
||||
network_path: Vec::new(),
|
||||
alias: format!("Page {}", index + 1),
|
||||
skip_adding_history_step: false,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
// Pages follow the artboards from the top of the Layers panel down, so the last one drawn comes first
|
||||
let document = editor.active_document();
|
||||
let pages: Vec<_> = document
|
||||
.artboard_names()
|
||||
.into_iter()
|
||||
.map(|(layer, name)| {
|
||||
let [min, max] = document.metadata().bounding_box_document(layer).unwrap();
|
||||
(name, (max - min) * points_per_pixel)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(pages.iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), ["Page 2", "Page 1"]);
|
||||
|
||||
send_export_of(&mut editor, FileType::Pdf, ExportBounds::AllArtboards);
|
||||
let (name, content) = saved_export(&mut editor).await;
|
||||
assert_eq!(name, "export.pdf");
|
||||
|
||||
let content = String::from_utf8_lossy(&content);
|
||||
let media_boxes: Vec<&str> = content.split("/MediaBox[").skip(1).map(|rest| rest.split(']').next().unwrap_or_default()).collect();
|
||||
let expected_media_boxes: Vec<String> = pages.iter().map(|(_, size)| format!("0 0 {} {}", size.x, size.y)).collect();
|
||||
assert_eq!(media_boxes, expected_media_boxes, "{content}");
|
||||
|
||||
for (name, _) in &pages {
|
||||
assert!(content.contains(&format!("/Title({name})")), "{content}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_graph_settles_while_network_updates_keep_arriving() {
|
||||
let mut editor = editor().await;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::{ThumbnailContent, cell_size};
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::renderer::scene_builder::SceneBuilder;
|
||||
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
|
||||
use graphene_std::renderer::{RenderOutputType, RenderParams};
|
||||
use graphene_std::transform::Footprint;
|
||||
|
||||
@@ -121,7 +121,7 @@
|
||||
let sliderAbortTimeout1: ReturnType<typeof setTimeout> | undefined;
|
||||
let sliderAbortTimeout2: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
$: watchValue(value, unit, min, max);
|
||||
$: watchValue(value, unit, min, max, displayDecimalPlaces);
|
||||
$: if (exact !== undefined && !editing) text = exact;
|
||||
$: present = exact !== undefined || value !== undefined;
|
||||
// A number of only one digit, like `0` or `-1`, has no other digit to move the underline to, so it isn't shown
|
||||
@@ -179,8 +179,8 @@
|
||||
// TRACKING AND UPDATING THE VALUE
|
||||
// ===============================
|
||||
|
||||
// Called only when `value`, its unit, or its bounds are changed from outside this component.
|
||||
function watchValue(value: number | undefined, unit: string, min: number | undefined, max: number | undefined) {
|
||||
// Called only when `value`, its unit, its bounds, or its displayed precision are changed from outside this component.
|
||||
function watchValue(value: number | undefined, unit: string, min: number | undefined, max: number | undefined, decimalPlaces: number) {
|
||||
// Don't update if the slider is currently being dragged (we don't want the backend fighting with the user's drag)
|
||||
if (rangeSliderClickDragState === "Dragging") return;
|
||||
|
||||
@@ -202,7 +202,7 @@
|
||||
if (typeof min === "number") sanitized = Math.max(sanitized, min);
|
||||
if (typeof max === "number") sanitized = Math.min(sanitized, max);
|
||||
|
||||
text = displayText(sanitized, unit);
|
||||
text = displayText(sanitized, unit, decimalPlaces);
|
||||
}
|
||||
|
||||
// Rounds half away from zero, the graph's one Number to Integer rule, where `Math.round` would carry -1.5 up to -1
|
||||
@@ -359,10 +359,10 @@
|
||||
// ================
|
||||
|
||||
// Calculates the string to display when the field is not being edited.
|
||||
function displayText(displayValue: number | undefined, unit: string): string {
|
||||
function displayText(displayValue: number | undefined, unit: string, precision = displayDecimalPlaces): string {
|
||||
if (displayValue === undefined) return "-";
|
||||
|
||||
const decimalPlaces = Math.max(displayDecimalPlaces, 0);
|
||||
const decimalPlaces = Math.max(precision, 0);
|
||||
const roundingPower = 10 ** decimalPlaces;
|
||||
|
||||
// Values within floating point noise of zero (including -0) display as unsigned zero, unless the field's decimal precision is fine enough to display them
|
||||
|
||||
@@ -6,7 +6,7 @@ use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::units::{Angle, AngleUnit, DEFAULT_PIXELS_PER_INCH, Length, LengthUnit, TypedAngle, TypedLength};
|
||||
use core_types::units::{Angle, AngleUnit, AngleVec2, DEFAULT_PIXELS_PER_INCH, Length, LengthUnit, LengthVec2, TypedAngle, TypedAngleVec2, TypedLength, TypedLengthVec2};
|
||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor};
|
||||
pub use dyn_any::StaticType;
|
||||
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
@@ -19,6 +19,7 @@ use graphic_types::vector_types::vector::style::DashPattern;
|
||||
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
|
||||
use graphic_types::vector_types::vector::{self, ReferencePoint};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use rendering::pdf_scene_builder::PdfScene;
|
||||
use rendering::{CanvasImage, RenderMetadata};
|
||||
use std::fmt::Display;
|
||||
use std::hash::Hash;
|
||||
@@ -89,6 +90,10 @@ macro_rules! tagged_value {
|
||||
Length(TypedLength),
|
||||
/// An angle in the unit it was typed in, materializing as an `Item<Angle>`.
|
||||
Angle(TypedAngle),
|
||||
/// A pair of lengths sharing the unit they were typed in, materializing as an `Item<LengthVec2>` in pixels, converted like a `Length`.
|
||||
LengthVec2(TypedLengthVec2),
|
||||
/// A pair of angles sharing the unit they were typed in, materializing as an `Item<AngleVec2>`.
|
||||
AngleVec2(TypedAngleVec2),
|
||||
/// Stored as the `GradientRamp` exchange struct (nested `{ stops: { color, position?, midpoint? } }`), materializing as an `Item<Gradient>` at runtime. Aliases recover legacy on-disk shapes.
|
||||
/// (Old documents stored flat stops, a tuple list, or the ancient full `Gradient` struct under the legacy `"Gradient"` tag, all routed by `deserialize_tagged_value_with_legacy_migration`.)
|
||||
#[serde(alias = "Gradient", alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")]
|
||||
@@ -140,6 +145,8 @@ macro_rules! tagged_value {
|
||||
Self::TransferCurve(points) => points.cache_hash(state),
|
||||
Self::Length(length) => length.cache_hash(state),
|
||||
Self::Angle(angle) => angle.cache_hash(state),
|
||||
Self::LengthVec2(lengths) => lengths.cache_hash(state),
|
||||
Self::AngleVec2(angles) => angles.cache_hash(state),
|
||||
Self::GradientRamp(ramp) => ramp.cache_hash(state),
|
||||
Self::Strokes(strokes) => strokes.cache_hash(state),
|
||||
Self::BrushCache(cache) => cache.cache_hash(state),
|
||||
@@ -199,6 +206,8 @@ macro_rules! tagged_value {
|
||||
Self::TransferCurve(points) => Box::new(Item::new_from_element(TransferCurve::from(points))),
|
||||
Self::Length(length) => Box::new(Item::new_from_element(length.to_length(DEFAULT_PIXELS_PER_INCH))),
|
||||
Self::Angle(angle) => Box::new(Item::new_from_element(angle.to_angle())),
|
||||
Self::LengthVec2(lengths) => Box::new(Item::new_from_element(lengths.to_length_vec2(DEFAULT_PIXELS_PER_INCH))),
|
||||
Self::AngleVec2(angles) => Box::new(Item::new_from_element(angles.to_angle_vec2())),
|
||||
Self::GradientRamp(ramp) => Box::new(Item::<Gradient>::from(ramp)),
|
||||
Self::Strokes(strokes) => {
|
||||
let list: List<Stroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
@@ -261,6 +270,8 @@ macro_rules! tagged_value {
|
||||
Self::TransferCurve(points) => Arc::new(Item::new_from_element(TransferCurve::from(points))),
|
||||
Self::Length(length) => Arc::new(Item::new_from_element(length.to_length(DEFAULT_PIXELS_PER_INCH))),
|
||||
Self::Angle(angle) => Arc::new(Item::new_from_element(angle.to_angle())),
|
||||
Self::LengthVec2(lengths) => Arc::new(Item::new_from_element(lengths.to_length_vec2(DEFAULT_PIXELS_PER_INCH))),
|
||||
Self::AngleVec2(angles) => Arc::new(Item::new_from_element(angles.to_angle_vec2())),
|
||||
Self::GradientRamp(ramp) => Arc::new(Item::<Gradient>::from(ramp)),
|
||||
Self::Strokes(strokes) => {
|
||||
let list: List<Stroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
@@ -298,6 +309,8 @@ macro_rules! tagged_value {
|
||||
Self::TransferCurve(_) => item!(TransferCurve),
|
||||
Self::Length(_) => item!(Length),
|
||||
Self::Angle(_) => item!(Angle),
|
||||
Self::LengthVec2(_) => item!(LengthVec2),
|
||||
Self::AngleVec2(_) => item!(AngleVec2),
|
||||
Self::GradientRamp(_) => item!(Gradient),
|
||||
Self::Strokes(_) => list!(Stroke),
|
||||
Self::BrushCache(_) => item!(BrushCache),
|
||||
@@ -343,6 +356,10 @@ macro_rules! tagged_value {
|
||||
x if x == TypeId::of::<Item<Length>>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast::<Item<Length>>().unwrap().into_element().pixels()))),
|
||||
x if x == TypeId::of::<Angle>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast::<Angle>().unwrap().degrees()))),
|
||||
x if x == TypeId::of::<Item<Angle>>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast::<Item<Angle>>().unwrap().into_element().degrees()))),
|
||||
x if x == TypeId::of::<LengthVec2>() => Ok(TaggedValue::LengthVec2(TypedLengthVec2::pixels(input.downcast::<LengthVec2>().unwrap().pixels()))),
|
||||
x if x == TypeId::of::<Item<LengthVec2>>() => Ok(TaggedValue::LengthVec2(TypedLengthVec2::pixels(input.downcast::<Item<LengthVec2>>().unwrap().into_element().pixels()))),
|
||||
x if x == TypeId::of::<AngleVec2>() => Ok(TaggedValue::AngleVec2(TypedAngleVec2::degrees(input.downcast::<AngleVec2>().unwrap().degrees()))),
|
||||
x if x == TypeId::of::<Item<AngleVec2>>() => Ok(TaggedValue::AngleVec2(TypedAngleVec2::degrees(input.downcast::<Item<AngleVec2>>().unwrap().into_element().degrees()))),
|
||||
x if x == TypeId::of::<Gradient>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(*input.downcast::<Gradient>().unwrap()))),
|
||||
x if x == TypeId::of::<Item<Gradient>>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(&*input.downcast::<Item<Gradient>>().unwrap()))),
|
||||
x if x == TypeId::of::<List<Stroke>>() => Ok(TaggedValue::Strokes(input.downcast::<List<Stroke>>().unwrap().into_iter().map(Item::into_element).collect())),
|
||||
@@ -383,6 +400,10 @@ macro_rules! tagged_value {
|
||||
x if x == TypeId::of::<Item<Length>>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast_ref::<Item<Length>>().unwrap().element().pixels()))),
|
||||
x if x == TypeId::of::<Angle>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast_ref::<Angle>().unwrap().degrees()))),
|
||||
x if x == TypeId::of::<Item<Angle>>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast_ref::<Item<Angle>>().unwrap().element().degrees()))),
|
||||
x if x == TypeId::of::<LengthVec2>() => Ok(TaggedValue::LengthVec2(TypedLengthVec2::pixels(input.downcast_ref::<LengthVec2>().unwrap().pixels()))),
|
||||
x if x == TypeId::of::<Item<LengthVec2>>() => Ok(TaggedValue::LengthVec2(TypedLengthVec2::pixels(input.downcast_ref::<Item<LengthVec2>>().unwrap().element().pixels()))),
|
||||
x if x == TypeId::of::<AngleVec2>() => Ok(TaggedValue::AngleVec2(TypedAngleVec2::degrees(input.downcast_ref::<AngleVec2>().unwrap().degrees()))),
|
||||
x if x == TypeId::of::<Item<AngleVec2>>() => Ok(TaggedValue::AngleVec2(TypedAngleVec2::degrees(input.downcast_ref::<Item<AngleVec2>>().unwrap().element().degrees()))),
|
||||
x if x == TypeId::of::<Gradient>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(input.downcast_ref::<Gradient>().unwrap()))),
|
||||
x if x == TypeId::of::<Item<Gradient>>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(input.downcast_ref::<Item<Gradient>>().unwrap()))),
|
||||
x if x == TypeId::of::<List<Stroke>>() => Ok(TaggedValue::Strokes(input.downcast_ref::<List<Stroke>>().unwrap().iter_element_values().cloned().collect())),
|
||||
@@ -416,6 +437,8 @@ macro_rules! tagged_value {
|
||||
if name == std::any::type_name::<TransferCurve>() { return Some(TaggedValue::TransferCurve(TransferCurve::default().points().to_vec())) }
|
||||
if name == std::any::type_name::<Length>() { return Some(TaggedValue::Length(TypedLength::default())) }
|
||||
if name == std::any::type_name::<Angle>() { return Some(TaggedValue::Angle(TypedAngle::default())) }
|
||||
if name == std::any::type_name::<LengthVec2>() { return Some(TaggedValue::LengthVec2(TypedLengthVec2::default())) }
|
||||
if name == std::any::type_name::<AngleVec2>() { return Some(TaggedValue::AngleVec2(TypedAngleVec2::default())) }
|
||||
$( if name == std::any::type_name::<$ty>() { return Some(TaggedValue::$identifier(Default::default())) } )*
|
||||
if name == std::any::type_name::<List<Stroke>>() { return Some(TaggedValue::Strokes(Vec::new())) }
|
||||
if name == std::any::type_name::<BrushCache>() { return Some(TaggedValue::BrushCache(Default::default())) }
|
||||
@@ -468,6 +491,8 @@ macro_rules! tagged_value {
|
||||
Self::TransferCurve(points) => format!("TransferCurve({points:?})"),
|
||||
Self::Length(length) => format!("Length({} {})", length.value, length.unit.symbol()),
|
||||
Self::Angle(angle) => format!("Angle({} {})", angle.value, angle.unit.symbol()),
|
||||
Self::LengthVec2(lengths) => format!("LengthVec2({} {}, {} {})", lengths.value.x, lengths.unit.symbol(), lengths.value.y, lengths.unit.symbol()),
|
||||
Self::AngleVec2(angles) => format!("AngleVec2({} {}, {} {})", angles.value.x, angles.unit.symbol(), angles.value.y, angles.unit.symbol()),
|
||||
Self::GradientRamp(ramp) => format!("GradientRamp({ramp:?})"),
|
||||
Self::Strokes(strokes) => format!("Strokes({strokes:?})"),
|
||||
Self::BrushCache(cache) => format!("{cache:?}"),
|
||||
@@ -635,7 +660,7 @@ impl TaggedValue {
|
||||
/// An angle input's value in degrees, whether stored as a typed angle or as a plain number of degrees.
|
||||
pub fn as_angle_degrees(&self) -> Option<f64> {
|
||||
match self {
|
||||
Self::Angle(angle) => Some(angle.to_angle().degrees()),
|
||||
Self::Angle(angle) => Some(angle.to_degrees()),
|
||||
Self::Number(degrees) => Some(*degrees),
|
||||
_ => None,
|
||||
}
|
||||
@@ -648,7 +673,50 @@ impl TaggedValue {
|
||||
_ => AngleUnit::Degree,
|
||||
};
|
||||
Self::Angle(TypedAngle {
|
||||
value: unit.from_angle(Angle::from_degrees(degrees)),
|
||||
value: unit.from_degrees(degrees),
|
||||
unit,
|
||||
})
|
||||
}
|
||||
|
||||
/// A pair of lengths' value in pixels, whether stored as typed lengths or as a plain Vec2 of pixels.
|
||||
pub fn as_length_vec2_pixels(&self, pixels_per_inch: f64) -> Option<DVec2> {
|
||||
match self {
|
||||
Self::LengthVec2(lengths) => Some(lengths.to_length_vec2(pixels_per_inch).pixels()),
|
||||
Self::DVec2(pixels) => Some(*pixels),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A pair of lengths in pixels as a value for an input of them, kept in the unit `self` was typed in, like a dragged position that stays in millimeters.
|
||||
pub fn length_vec2_in_same_unit(&self, pixels: DVec2, pixels_per_inch: f64) -> Self {
|
||||
let unit = match self {
|
||||
Self::LengthVec2(lengths) => lengths.unit,
|
||||
Self::Length(length) => length.unit,
|
||||
_ => LengthUnit::Pixel,
|
||||
};
|
||||
Self::LengthVec2(TypedLengthVec2 {
|
||||
value: DVec2::new(LengthUnit::Pixel.convert(pixels.x, unit, pixels_per_inch), LengthUnit::Pixel.convert(pixels.y, unit, pixels_per_inch)),
|
||||
unit,
|
||||
})
|
||||
}
|
||||
|
||||
/// A pair of angles' value in degrees, whether stored as typed angles or as a plain Vec2 of degrees.
|
||||
pub fn as_angle_vec2_degrees(&self) -> Option<DVec2> {
|
||||
match self {
|
||||
Self::AngleVec2(angles) => Some(angles.to_degrees()),
|
||||
Self::DVec2(degrees) => Some(*degrees),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A pair of angles in degrees as a value for an input of them, kept in the unit `self` was typed in.
|
||||
pub fn angle_vec2_in_same_unit(&self, degrees: DVec2) -> Self {
|
||||
let unit = match self {
|
||||
Self::AngleVec2(angles) => angles.unit,
|
||||
_ => AngleUnit::Degree,
|
||||
};
|
||||
Self::AngleVec2(TypedAngleVec2 {
|
||||
value: DVec2::new(unit.from_degrees(degrees.x), unit.from_degrees(degrees.y)),
|
||||
unit,
|
||||
})
|
||||
}
|
||||
@@ -830,6 +898,8 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<Length>() => to_number(string).map(|pixels| TaggedValue::Length(TypedLength::pixels(pixels)))?,
|
||||
() if ty == TypeId::of::<Angle>() => to_number(string).map(|degrees| TaggedValue::Angle(TypedAngle::degrees(degrees)))?,
|
||||
() if ty == TypeId::of::<LengthVec2>() => to_dvec2(string).map(|pixels| TaggedValue::LengthVec2(TypedLengthVec2::pixels(pixels)))?,
|
||||
() if ty == TypeId::of::<AngleVec2>() => to_dvec2(string).map(|degrees| TaggedValue::AngleVec2(TypedAngleVec2::degrees(degrees)))?,
|
||||
_ => {
|
||||
log::error!("No parser for a default value of type `{}`: {string}", concrete_type.name);
|
||||
return None;
|
||||
@@ -1046,6 +1116,9 @@ pub enum RenderOutputType {
|
||||
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
|
||||
image_data: Vec<(u64, CanvasImage)>,
|
||||
},
|
||||
/// A PDF page's drawing, encoded into a file once any GPU textures it draws are read back.
|
||||
#[serde(skip)]
|
||||
Pdf(Box<PdfScene>),
|
||||
#[cfg(target_family = "wasm")]
|
||||
CanvasFrame { canvas_id: u64, resolution: DVec2 },
|
||||
}
|
||||
@@ -1064,6 +1137,8 @@ impl CacheHash for RenderOutputType {
|
||||
svg.cache_hash(state);
|
||||
image_data.cache_hash(state);
|
||||
}
|
||||
// Only an export makes one, and nothing hashes an export's output
|
||||
Self::Pdf(_) => {}
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::CanvasFrame { canvas_id, resolution } => {
|
||||
canvas_id.cache_hash(state);
|
||||
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user