mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc1c343bf3 | ||
|
|
9c9b393420 | ||
|
|
01c5455ecf | ||
|
|
41586d6967 | ||
|
|
7c37cc504b | ||
|
|
e30bf2e987 | ||
|
|
c8e8fbf8d1 | ||
|
|
9517b006fa | ||
|
|
cfb45f2d54 | ||
|
|
e27119b58b | ||
|
|
ebc49b40fc | ||
|
|
2cb8aed218 | ||
|
|
91b4072df6 | ||
|
|
bb2514d816 | ||
|
|
19df13ad1d | ||
|
|
a412979a7f | ||
|
|
738ea6ac20 | ||
|
|
d6ee55b86a | ||
|
|
33dd5e545a | ||
|
|
4f0d8c7f4c | ||
|
|
1335e9a0f8 | ||
|
|
89238b669a | ||
|
|
da2c5a2d13 | ||
|
|
c75ebbd143 | ||
|
|
addba860d3 | ||
|
|
9526711aa2 | ||
|
|
d8b9f67adb | ||
|
|
b149248db9 | ||
|
|
7b4dc4d8a7 | ||
|
|
feea64170a | ||
|
|
6541449a4a | ||
|
|
5e92356578 | ||
|
|
3ca1376f93 | ||
|
|
93d2738a23 | ||
|
|
9557c6adfc | ||
|
|
6c3232ee8c |
No files matched your search
@@ -150,20 +150,14 @@ jobs:
|
|||||||
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
|
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
|
||||||
|
|
||||||
- name: 📤 Publish to Cloudflare Pages
|
- name: 📤 Publish to Cloudflare Pages
|
||||||
if: inputs.merge_queue == false
|
if: inputs.merge_queue == false && !github.event.pull_request.head.repo.fork
|
||||||
id: cloudflare
|
id: cloudflare
|
||||||
continue-on-error: ${{ github.event_name != 'push' }}
|
|
||||||
env:
|
env:
|
||||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||||
# Passed through the environment so a branch name can't inject shell syntax
|
# Passed through the environment so a branch name can't inject shell syntax
|
||||||
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
|
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
|
||||||
run: |
|
run: |
|
||||||
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
|
|
||||||
echo "No Cloudflare API token available (fork PR), skipping deploy."
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ "${{ github.event_name }}" = "push" ]; then
|
if [ "${{ github.event_name }}" = "push" ]; then
|
||||||
DEPLOY_BRANCH="master"
|
DEPLOY_BRANCH="master"
|
||||||
else
|
else
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
|
# Runs the checks on a pushed branch that has no PR yet, such as each branch of a stack
|
||||||
|
workflow_dispatch: {}
|
||||||
|
|
||||||
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
|
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
|
||||||
concurrency:
|
concurrency:
|
||||||
@@ -245,7 +247,8 @@ jobs:
|
|||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
env:
|
env:
|
||||||
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
|
# A manual run has no base commit of its own, so it compares against master
|
||||||
|
BASE_REF: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || 'master' }}
|
||||||
steps:
|
steps:
|
||||||
- name: 📥 Clone repository
|
- name: 📥 Clone repository
|
||||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||||
@@ -259,7 +262,9 @@ jobs:
|
|||||||
rustflags: ""
|
rustflags: ""
|
||||||
|
|
||||||
- name: 📥 Fetch the base commit
|
- name: 📥 Fetch the base commit
|
||||||
run: git fetch --depth=1 origin "$BASE_SHA"
|
run: |
|
||||||
|
git fetch --depth=1 origin "$BASE_REF"
|
||||||
|
echo "BASE_SHA=$(git rev-parse FETCH_HEAD)" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
- name: 🔬 Check migrations against the base commit
|
- name: 🔬 Check migrations against the base commit
|
||||||
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
|
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
|
||||||
|
|||||||
@@ -51,6 +51,8 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
# Cache on Cargo.lock file
|
# Cache on Cargo.lock file
|
||||||
cache-on-failure: true
|
cache-on-failure: true
|
||||||
|
# Saved only by master pushes, since a PR's saved cache is readable only by that PR yet counts toward the repo's size limit
|
||||||
|
save-if: ${{ github.event_name == 'push' }}
|
||||||
|
|
||||||
- name: Install gungraun-runner and valgrind
|
- name: Install gungraun-runner and valgrind
|
||||||
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
|
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
|
||||||
|
|||||||
Generated
+3
@@ -590,6 +590,7 @@ dependencies = [
|
|||||||
"node-macro",
|
"node-macro",
|
||||||
"raster-kernels",
|
"raster-kernels",
|
||||||
"serde",
|
"serde",
|
||||||
|
"text-nodes",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -5745,6 +5746,7 @@ dependencies = [
|
|||||||
"glam",
|
"glam",
|
||||||
"graphene-resource",
|
"graphene-resource",
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
|
"half",
|
||||||
"log",
|
"log",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
@@ -6019,6 +6021,7 @@ dependencies = [
|
|||||||
"graphene-resource",
|
"graphene-resource",
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
"kurbo",
|
"kurbo",
|
||||||
|
"linesweeper",
|
||||||
"log",
|
"log",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
"parley",
|
"parley",
|
||||||
|
|||||||
@@ -406,9 +406,11 @@ fn set(registry: &mut Registry, ops: &mut Vec<RegistryDelta>, slot: Slot, input:
|
|||||||
match slot {
|
match slot {
|
||||||
Slot::Input(id, index) => {
|
Slot::Input(id, index) => {
|
||||||
let Some(input) = input else { return };
|
let Some(input) = input else { return };
|
||||||
if let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) {
|
// A chain the line no longer holds the slot for, as shrinking a node's inputs leaves, is not written back
|
||||||
slot.input = input.clone();
|
let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) else {
|
||||||
}
|
return;
|
||||||
|
};
|
||||||
|
slot.input = input.clone();
|
||||||
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
|
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
|
||||||
}
|
}
|
||||||
Slot::Export(id, index) => {
|
Slot::Export(id, index) => {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
//! operation mixed in. After every operation nothing may name a node the document no longer has.
|
//! operation mixed in. After every operation nothing may name a node the document no longer has.
|
||||||
|
|
||||||
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
||||||
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
|
use crate::{Implementation, InputSlot, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp};
|
||||||
|
|
||||||
/// A slot that can name a node.
|
/// A slot that can name a node.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
@@ -94,14 +94,16 @@ impl Scenario for Branching {
|
|||||||
node.inputs[1].input = second;
|
node.inputs[1].input = second;
|
||||||
node
|
node
|
||||||
};
|
};
|
||||||
|
// Nodes that still have an input past the primary one, the only ones an edit may write there
|
||||||
|
let wide: Vec<NodeId> = nodes.iter().copied().filter(|id| registry.node_instances[id].inputs.len() > 1).collect();
|
||||||
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
|
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
|
||||||
let plain: Vec<NodeId> = nodes
|
let plain: Vec<NodeId> = wide
|
||||||
.iter()
|
.iter()
|
||||||
.copied()
|
.copied()
|
||||||
.filter(|id| !matches!(place_value(®istry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
|
.filter(|id| !matches!(place_value(®istry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
match random.below(12) {
|
match random.below(14) {
|
||||||
// Draw a node on top of the chain off the export
|
// Draw a node on top of the chain off the export
|
||||||
0..=2 => {
|
0..=2 => {
|
||||||
let id = session.next_node_id();
|
let id = session.next_node_id();
|
||||||
@@ -122,7 +124,7 @@ impl Scenario for Branching {
|
|||||||
}
|
}
|
||||||
// Hang a node on an input past the primary one, over whatever is there already
|
// Hang a node on an input past the primary one, over whatever is there already
|
||||||
3..=5 => {
|
3..=5 => {
|
||||||
let Some(host) = random.pick(&nodes) else { return Vec::new() };
|
let Some(host) = random.pick(&wide) else { return Vec::new() };
|
||||||
let id = session.next_node_id();
|
let id = session.next_node_id();
|
||||||
let first = match place_value(®istry, Place::Input(host, 1)) {
|
let first = match place_value(®istry, Place::Input(host, 1)) {
|
||||||
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
|
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
|
||||||
@@ -179,6 +181,25 @@ impl Scenario for Branching {
|
|||||||
new_input: value(random.below(100)),
|
new_input: value(random.below(100)),
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
|
// Rewrite a node's whole input list, which an index-addressed write cannot express
|
||||||
|
11..=12 => {
|
||||||
|
let Some(node) = random.pick(&nodes) else { return Vec::new() };
|
||||||
|
let mut inputs = registry.node_instances[&node].inputs.clone();
|
||||||
|
match random.below(3) {
|
||||||
|
// Swap the first two, so what the node rested on moves past its primary input
|
||||||
|
0 if inputs.len() > 1 => inputs.swap(0, 1),
|
||||||
|
// One input more, holding a value
|
||||||
|
1 if inputs.len() < 4 => inputs.push(InputSlot {
|
||||||
|
input: value(random.below(100)),
|
||||||
|
timestamp: TimeStamp::ORIGIN,
|
||||||
|
attributes: Default::default(),
|
||||||
|
}),
|
||||||
|
// One input fewer, as removing a subgraph's import slot leaves the nodes wrapping it
|
||||||
|
_ if inputs.len() > 1 => _ = inputs.pop(),
|
||||||
|
_ => return Vec::new(),
|
||||||
|
}
|
||||||
|
vec![RegistryDelta::SetNodeInputs { id: node, inputs }]
|
||||||
|
}
|
||||||
// Cut the chain off an input past the primary one, taking its nodes with it
|
// Cut the chain off an input past the primary one, taking its nodes with it
|
||||||
_ => {
|
_ => {
|
||||||
let hosts: Vec<NodeId> = nodes
|
let hosts: Vec<NodeId> = nodes
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Bool(bool),
|
||||||
|
DAffine2([f64; 6]),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Bevel & Emboss' defaults to fitting gradient textures without a transform across the content.
|
||||||
|
#[migration("blending_nodes::effects::BevelAndEmbossNode"@2 => @3)]
|
||||||
|
pub fn bevel_and_emboss_v2(inputs: &mut Inputs) {
|
||||||
|
for input in added_inputs() {
|
||||||
|
inputs.push(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||||
|
fn added_inputs() -> [NodeInput; 2] {
|
||||||
|
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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(20, |random, _slot| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&BevelAndEmbossV2, &contract());
|
||||||
|
check_undo(&BevelAndEmbossV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_inputs_and_adds_an_unset_texture_placement() {
|
||||||
|
let inputs: Vec<_> = (0..20).map(|index| literal(index as f64)).collect();
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&BevelAndEmbossV2);
|
||||||
|
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@2), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&BevelAndEmbossV2).unwrap();
|
||||||
|
|
||||||
|
let mut expected = inputs;
|
||||||
|
expected.extend(added_inputs());
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@3)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, bevel), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
use migration_core::{Inputs, NodeInput, encode, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
TypeDefault(Type),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frozen mirror of the `Type` an empty list of graphics stores.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Type {
|
||||||
|
Concrete(TypeDescriptor),
|
||||||
|
List(Box<Type>),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypeDescriptor {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Blur' gained a radius mask after its radius, left empty to keep blurring the whole content by the radius.
|
||||||
|
#[migration("blending_nodes::effects::BlurNode"@2 => @3)]
|
||||||
|
pub fn blur_v2(inputs: &mut Inputs) {
|
||||||
|
inputs.insert(2, empty_radius_mask());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radius mask input with nothing connected and not exposed, as the node's definition gives it.
|
||||||
|
fn empty_radius_mask() -> NodeInput {
|
||||||
|
let no_graphics = Tagged::TypeDefault(Type::List(Box::new(Type::Concrete(TypeDescriptor {
|
||||||
|
name: "graphic_types::graphic::Graphic".to_string(),
|
||||||
|
}))));
|
||||||
|
NodeInput::Value {
|
||||||
|
value: encode(&no_graphics),
|
||||||
|
exposed: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::{decl, literal};
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&BlurV2, &contract());
|
||||||
|
check_undo(&BlurV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_inputs_and_inserts_an_empty_radius_mask_after_the_radius() {
|
||||||
|
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&BlurV2);
|
||||||
|
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&BlurV2).unwrap();
|
||||||
|
|
||||||
|
let mut expected = inputs;
|
||||||
|
expected.insert(2, empty_radius_mask());
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, blur), Some(decl!("blending_nodes::effects::BlurNode"@3)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, blur), expected);
|
||||||
|
assert!(matches!(expected[2], NodeInput::Value { exposed: false, .. }), "the radius mask is not exposed");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
use migration_core::{Inputs, literal, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Bool(bool),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Convolution Kernel' gained Apply to Alpha after its offset, left off to keep the content's coverage as it is.
|
||||||
|
#[migration("blending_nodes::filters::ConvolutionKernelNode"@1 => @2)]
|
||||||
|
pub fn convolution_kernel_v1(inputs: &mut Inputs) {
|
||||||
|
inputs.push(literal(Tagged::Bool(false)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&ConvolutionKernelV1, &contract());
|
||||||
|
check_undo(&ConvolutionKernelV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_inputs_and_appends_apply_to_alpha_turned_off() {
|
||||||
|
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&ConvolutionKernelV1);
|
||||||
|
let kernel = fixture.add(decl!("blending_nodes::filters::ConvolutionKernelNode"@1), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&ConvolutionKernelV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, kernel), Some(decl!("blending_nodes::filters::ConvolutionKernelNode"@2)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, kernel), [inputs, vec![literal(Tagged::Bool(false))]].concat());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
use migration_core::{Inputs, literal, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Number(f64),
|
||||||
|
Integer(i64),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Inner Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth.
|
||||||
|
#[migration("blending_nodes::effects::InnerGlowNode"@2 => @3)]
|
||||||
|
pub fn inner_glow_v2(inputs: &mut Inputs) {
|
||||||
|
inputs.insert(8, literal(Tagged::Number(0.)));
|
||||||
|
inputs.insert(9, literal(Tagged::Number(0.)));
|
||||||
|
inputs.insert(10, literal(Tagged::Integer(0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&InnerGlowV2, &contract());
|
||||||
|
check_undo(&InnerGlowV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
|
||||||
|
let inputs: Vec<_> = (0..9).map(|index| literal(index as f64)).collect();
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&InnerGlowV2);
|
||||||
|
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@2), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&InnerGlowV2).unwrap();
|
||||||
|
|
||||||
|
let mut expected = inputs;
|
||||||
|
expected.splice(8..8, [literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@3)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,21 @@
|
|||||||
//! Migrations of the nodes in `blending_nodes`.
|
//! Migrations of the nodes in `blending_nodes`.
|
||||||
|
|
||||||
mod bevel_and_emboss_v1;
|
mod bevel_and_emboss_v1;
|
||||||
|
mod bevel_and_emboss_v2;
|
||||||
|
mod blur_v2;
|
||||||
|
mod convolution_kernel_v1;
|
||||||
mod drop_shadow_v1;
|
mod drop_shadow_v1;
|
||||||
mod inner_glow_v1;
|
mod inner_glow_v1;
|
||||||
|
mod inner_glow_v2;
|
||||||
mod inner_shadow_v1;
|
mod inner_shadow_v1;
|
||||||
mod mask_by_any_graphic;
|
mod mask_by_any_graphic;
|
||||||
mod outer_glow_v1;
|
mod outer_glow_v1;
|
||||||
|
mod outer_glow_v2;
|
||||||
mod outline_v1;
|
mod outline_v1;
|
||||||
mod outline_v2;
|
mod outline_v2;
|
||||||
|
mod outline_v3;
|
||||||
mod paint_overlay_from_color_overlay;
|
mod paint_overlay_from_color_overlay;
|
||||||
|
mod paint_overlay_v2;
|
||||||
|
mod radial_blur_v1;
|
||||||
mod renames;
|
mod renames;
|
||||||
mod satin_v1;
|
mod satin_v1;
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
use migration_core::{Inputs, literal, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Number(f64),
|
||||||
|
Integer(i64),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Outer Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth.
|
||||||
|
#[migration("blending_nodes::effects::OuterGlowNode"@2 => @3)]
|
||||||
|
pub fn outer_glow_v2(inputs: &mut Inputs) {
|
||||||
|
inputs.insert(7, literal(Tagged::Number(0.)));
|
||||||
|
inputs.insert(8, literal(Tagged::Number(0.)));
|
||||||
|
inputs.insert(9, literal(Tagged::Integer(0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&OuterGlowV2, &contract());
|
||||||
|
check_undo(&OuterGlowV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
|
||||||
|
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&OuterGlowV2);
|
||||||
|
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@2), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&OuterGlowV2).unwrap();
|
||||||
|
|
||||||
|
let mut expected = inputs;
|
||||||
|
expected.splice(7..7, [literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@3)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Bool(bool),
|
||||||
|
DAffine2([f64; 6]),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Outline' defaults to fitting gradients without a transform across the content.
|
||||||
|
#[migration("blending_nodes::effects::OutlineNode"@3 => @4)]
|
||||||
|
pub fn outline_v3(inputs: &mut Inputs) {
|
||||||
|
for input in added_inputs() {
|
||||||
|
inputs.push(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||||
|
fn added_inputs() -> [NodeInput; 2] {
|
||||||
|
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&OutlineV3, &contract());
|
||||||
|
check_undo(&OutlineV3, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_inputs_and_adds_an_unset_placement() {
|
||||||
|
let inputs: Vec<_> = (0..6).map(|index| literal(index as f64)).collect();
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&OutlineV3);
|
||||||
|
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@3), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&OutlineV3).unwrap();
|
||||||
|
|
||||||
|
let mut expected = inputs;
|
||||||
|
expected.extend(added_inputs());
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@4)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Bool(bool),
|
||||||
|
DAffine2([f64; 6]),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Paint Overlay' defaults to fitting gradients without a transform across the content.
|
||||||
|
#[migration("blending_nodes::effects::PaintOverlayNode"@2 => @3)]
|
||||||
|
pub fn paint_overlay_v2(inputs: &mut Inputs) {
|
||||||
|
for input in added_inputs() {
|
||||||
|
inputs.push(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||||
|
fn added_inputs() -> [NodeInput; 2] {
|
||||||
|
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&PaintOverlayV2, &contract());
|
||||||
|
check_undo(&PaintOverlayV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_inputs_and_adds_an_unset_placement() {
|
||||||
|
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&PaintOverlayV2);
|
||||||
|
let overlay = fixture.add(decl!("blending_nodes::effects::PaintOverlayNode"@2), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&PaintOverlayV2).unwrap();
|
||||||
|
|
||||||
|
let mut expected = inputs;
|
||||||
|
expected.extend(added_inputs());
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@3)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, overlay), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const CENTER: u32 = 3;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
DVec2([f64; 2]),
|
||||||
|
DAffine2([f64; 6]),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Radial Blur' takes a transform placing a circle in place of its center, which the transform's translation keeps.
|
||||||
|
/// A wired center can't be read before it runs, so it becomes the identity, the circle at the content's origin.
|
||||||
|
#[migration("blending_nodes::distortions::RadialBlurNode"@1 => @2)]
|
||||||
|
pub fn radial_blur_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
|
||||||
|
let Some(center) = node.inputs().get(CENTER as usize) else {
|
||||||
|
return Err(MigrationError::invariant("Radial Blur has a Center input"));
|
||||||
|
};
|
||||||
|
|
||||||
|
inputs.set(CENTER, transform_input(¢er.input));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The transform input placing the circle at the old `center`, shown in the graph if it was exposed or wired.
|
||||||
|
fn transform_input(center: &NodeInput) -> NodeInput {
|
||||||
|
let ([x, y], exposed) = match center {
|
||||||
|
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(center) {
|
||||||
|
Some(Tagged::DVec2(center)) => (center, *exposed),
|
||||||
|
_ => ([0., 0.], *exposed),
|
||||||
|
},
|
||||||
|
_ => ([0., 0.], true),
|
||||||
|
};
|
||||||
|
|
||||||
|
NodeInput::Value {
|
||||||
|
value: encode(&Tagged::DAffine2([1., 0., 0., 1., x, y])),
|
||||||
|
exposed,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::{decl, literal};
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
const CENTER_SLOT: usize = CENTER as usize;
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(5, |random, slot| match slot {
|
||||||
|
CENTER_SLOT => literal(Tagged::DVec2([random.below(10) as f64, random.below(10) as f64])),
|
||||||
|
_ => literal(random.below(10) as f64),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn radial_blur_inputs(center: NodeInput) -> Vec<NodeInput> {
|
||||||
|
let mut inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
||||||
|
inputs[CENTER_SLOT] = center;
|
||||||
|
inputs
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&RadialBlurV1, &contract());
|
||||||
|
check_undo(&RadialBlurV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_center_becomes_the_translation_of_the_transform_in_its_place() {
|
||||||
|
let mut fixture = Fixture::new(&RadialBlurV1);
|
||||||
|
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(literal(Tagged::DVec2([12.5, -4.]))));
|
||||||
|
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
|
||||||
|
|
||||||
|
let expected = radial_blur_inputs(literal(Tagged::DAffine2([1., 0., 0., 1., 12.5, -4.])));
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, radial_blur), Some(decl!("blending_nodes::distortions::RadialBlurNode"@2)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, radial_blur), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wired_center_becomes_the_identity_shown_in_the_graph() {
|
||||||
|
let mut fixture = Fixture::new(&RadialBlurV1);
|
||||||
|
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||||
|
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(NodeInput::Node { id: source, index: 0 }));
|
||||||
|
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
|
||||||
|
|
||||||
|
let identity = NodeInput::Value {
|
||||||
|
value: encode(&Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
|
||||||
|
exposed: true,
|
||||||
|
};
|
||||||
|
assert_eq!(fixture.inputs(&migrated, radial_blur), radial_blur_inputs(identity));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,3 +3,4 @@
|
|||||||
use migration_core::rename;
|
use migration_core::rename;
|
||||||
|
|
||||||
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
|
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
|
||||||
|
rename!("blending_nodes::filters::AddNoiseNode"@1 => "blending_nodes::filters::SpeckleNode"@2);
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
use migration_core::{Inputs, literal, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Number(f64),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Make Opaque' gained a Strength percentage, set to 100% to keep making the content fully opaque.
|
||||||
|
#[migration("raster_nodes::adjustments::MakeOpaqueNode"@1 => @2)]
|
||||||
|
pub fn make_opaque_v1(inputs: &mut Inputs) {
|
||||||
|
inputs.push(literal(Tagged::Number(100.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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(1, |random, _slot| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&MakeOpaqueV1, &contract());
|
||||||
|
check_undo(&MakeOpaqueV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_content_and_adds_full_strength() {
|
||||||
|
let content = literal(1.);
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&MakeOpaqueV1);
|
||||||
|
let make_opaque = fixture.add(decl!("raster_nodes::adjustments::MakeOpaqueNode"@1), vec![content.clone()]);
|
||||||
|
let migrated = fixture.migrate(&MakeOpaqueV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, make_opaque), Some(decl!("raster_nodes::adjustments::MakeOpaqueNode"@2)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, make_opaque), [content, literal(Tagged::Number(100.))]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
//! Migrations of the nodes in `raster_nodes`.
|
//! Migrations of the nodes in `raster_nodes`.
|
||||||
|
|
||||||
|
mod make_opaque_v1;
|
||||||
mod mandelbrot_v1;
|
mod mandelbrot_v1;
|
||||||
mod mandelbrot_v2;
|
mod mandelbrot_v2;
|
||||||
mod mix_colors_from_mix_node;
|
mod mix_colors_from_mix_node;
|
||||||
mod noise_pattern_v1;
|
mod noise_pattern_v1;
|
||||||
|
mod noise_pattern_v2;
|
||||||
mod pattern_square;
|
mod pattern_square;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
use migration_core::attr::node::VISIBLE;
|
||||||
|
use migration_core::attr::node::ui::POSITION;
|
||||||
|
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Number(f64),
|
||||||
|
Bool(bool),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Noise Pattern' writes its value as the gray at that gamma-encoded level rather than as linear light, so whatever read it reads it through a
|
||||||
|
/// 'Gamma Correction' at its default gamma of 2.2, which turns the new gray back into about the old one.
|
||||||
|
#[migration("raster_nodes::std_nodes::NoisePatternNode"@2 => @3)]
|
||||||
|
pub fn noise_pattern_v2(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
|
||||||
|
let consumers = downstream.consumers(0);
|
||||||
|
if consumers.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let gamma_correction = downstream.add_node(NewNode {
|
||||||
|
declaration: decl!("raster_nodes::adjustments::GammaCorrectionNode"@1),
|
||||||
|
inputs: vec![NodeInput::Node { id: node.id(), index: 0 }, literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))],
|
||||||
|
});
|
||||||
|
for consumer in consumers {
|
||||||
|
downstream.connect(OutputConnector { node: gamma_correction, output: 0 }, consumer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
|
||||||
|
if !node.attributes().get_or(VISIBLE, true) {
|
||||||
|
attributes.set(gamma_correction, VISIBLE, &false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The Gamma Correction takes the pattern's place, with the pattern before it
|
||||||
|
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
|
||||||
|
attributes.set(gamma_correction, POSITION, &stored);
|
||||||
|
}
|
||||||
|
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use document_graph_storage::{Implementation, Network, NetworkId, NodeId, ROOT_NETWORK, TimeStamp};
|
||||||
|
use migration_core::Declaration;
|
||||||
|
use migration_core::attr::node::ui::IS_LAYER;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@2);
|
||||||
|
const GAMMA_CORRECTION: Declaration = decl!("raster_nodes::adjustments::GammaCorrectionNode"@1);
|
||||||
|
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(15, |random, _| literal(Tagged::Number(random.below(10) as f64)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn noise_inputs() -> Vec<NodeInput> {
|
||||||
|
(0..15).map(|slot| literal(Tagged::Number(slot as f64))).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wire(id: NodeId) -> NodeInput {
|
||||||
|
NodeInput::Node { id, index: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&NoisePatternV2, &contract());
|
||||||
|
check_undo(&NoisePatternV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_reader_reads_the_pattern_through_one_gamma_correction() {
|
||||||
|
let mut fixture = Fixture::new(&NoisePatternV2);
|
||||||
|
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
||||||
|
let both_slots = fixture.add(CONSUMER, vec![wire(noise), wire(noise)]);
|
||||||
|
let second_slot = fixture.add(CONSUMER, vec![literal(Tagged::Number(0.)), wire(noise)]);
|
||||||
|
fixture.export(wire(noise));
|
||||||
|
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, noise), noise_inputs());
|
||||||
|
|
||||||
|
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, second_slot)[1] else {
|
||||||
|
panic!("the consumer should read a node")
|
||||||
|
};
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, gamma_correction), [wire(noise), literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))]);
|
||||||
|
|
||||||
|
assert_eq!(fixture.inputs(&migrated, both_slots), [wire(gamma_correction), wire(gamma_correction)]);
|
||||||
|
assert_eq!(fixture.inputs(&migrated, second_slot)[0], literal(Tagged::Number(0.)));
|
||||||
|
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(gamma_correction)));
|
||||||
|
assert_eq!(migrated.node_instances.len(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_disabled_pattern_is_read_through_a_disabled_gamma_correction() {
|
||||||
|
let visibility_of_gamma_correction = |visible: bool| {
|
||||||
|
let mut fixture = Fixture::new(&NoisePatternV2);
|
||||||
|
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
||||||
|
if !visible {
|
||||||
|
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
|
||||||
|
attributes.set_serialized(VISIBLE, &false, TimeStamp::ORIGIN).unwrap();
|
||||||
|
}
|
||||||
|
let consumer = fixture.add(CONSUMER, vec![wire(noise)]);
|
||||||
|
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
||||||
|
|
||||||
|
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, consumer)[0] else {
|
||||||
|
panic!("the consumer should read a node")
|
||||||
|
};
|
||||||
|
migrated.node_instances[&gamma_correction].attributes().get_typed::<bool>(VISIBLE)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Visible is the default, so only a disabled pattern writes it
|
||||||
|
assert_eq!(visibility_of_gamma_correction(false), Some(false));
|
||||||
|
assert_eq!(visibility_of_gamma_correction(true), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unread_pattern_gains_no_gamma_correction() {
|
||||||
|
let mut fixture = Fixture::new(&NoisePatternV2);
|
||||||
|
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
||||||
|
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
|
||||||
|
assert_eq!(migrated.node_instances.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_pattern_in_a_subgraph_is_read_through_a_gamma_correction_inside_it() {
|
||||||
|
let mut fixture = Fixture::new(&NoisePatternV2);
|
||||||
|
|
||||||
|
// A custom subgraph exporting the pattern, read by the root network's export
|
||||||
|
let (subgraph, instance) = (NetworkId(100), NodeId(100));
|
||||||
|
fixture.registry.networks.insert(subgraph, Network::default());
|
||||||
|
let instance_node = document_graph_storage::Node::new(ROOT_NETWORK, Implementation::Network(subgraph), 0);
|
||||||
|
fixture.registry.node_instances.insert(instance, instance_node);
|
||||||
|
let noise = fixture.add_in(subgraph, NOISE_PATTERN, noise_inputs());
|
||||||
|
fixture.export_from(subgraph, wire(noise));
|
||||||
|
fixture.export(wire(instance));
|
||||||
|
|
||||||
|
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
||||||
|
|
||||||
|
let Some(NodeInput::Node { id: gamma_correction, .. }) = migrated.networks[&subgraph].exports[0].target else {
|
||||||
|
panic!("the subgraph's export should read a node")
|
||||||
|
};
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
|
||||||
|
assert_eq!(migrated.node_instances[&gamma_correction].network(), subgraph);
|
||||||
|
assert_eq!(fixture.inputs(&migrated, gamma_correction)[0], wire(noise));
|
||||||
|
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(instance)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The positions of the pattern and its Gamma Correction after migrating a pattern at `position`, read by a layer's chain or by another node.
|
||||||
|
fn placed_gamma_correction(position: Position, read_by_layer: bool) -> [Option<Position>; 2] {
|
||||||
|
let mut fixture = Fixture::new(&NoisePatternV2);
|
||||||
|
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
||||||
|
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
|
||||||
|
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
|
||||||
|
|
||||||
|
let (reader, slot) = if read_by_layer {
|
||||||
|
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::Number(0.)), wire(noise)]);
|
||||||
|
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
|
||||||
|
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
|
||||||
|
(layer, 1)
|
||||||
|
} else {
|
||||||
|
(fixture.add(CONSUMER, vec![wire(noise)]), 0)
|
||||||
|
};
|
||||||
|
|
||||||
|
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
||||||
|
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, reader)[slot] else {
|
||||||
|
panic!("slot {slot} of the reader should read a node")
|
||||||
|
};
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
|
||||||
|
|
||||||
|
[noise, gamma_correction].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_gamma_correction_takes_the_place_of_a_chained_or_placed_pattern() {
|
||||||
|
let chained = Position::Relative([-CHAIN_WIDTH, 0]);
|
||||||
|
for (position, read_by_layer) in [(chained, true), (Position::Absolute([5, 5]), false)] {
|
||||||
|
assert_eq!(placed_gamma_correction(position, read_by_layer), [Some(chained), Some(position)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
|||||||
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||||
};
|
};
|
||||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||||
@@ -196,10 +196,6 @@ pub enum FrontendMessage {
|
|||||||
#[serde(rename = "contextMenuInformation")]
|
#[serde(rename = "contextMenuInformation")]
|
||||||
context_menu_information: Option<ContextMenuInformation>,
|
context_menu_information: Option<ContextMenuInformation>,
|
||||||
},
|
},
|
||||||
UpdateClickTargets {
|
|
||||||
#[serde(rename = "clickTargets")]
|
|
||||||
click_targets: Option<FrontendClickTargets>,
|
|
||||||
},
|
|
||||||
UpdateGraphViewOverlay {
|
UpdateGraphViewOverlay {
|
||||||
open: bool,
|
open: bool,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -87,9 +87,7 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
|
|||||||
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
|
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
|
||||||
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
|
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
|
||||||
entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes),
|
entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes),
|
||||||
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets),
|
|
||||||
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
|
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
|
||||||
entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
|
|
||||||
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
|
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
|
||||||
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
|
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
|
||||||
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
|
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
|
||||||
|
|||||||
@@ -878,6 +878,22 @@ pub struct SliderMarker {
|
|||||||
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
|
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
|
||||||
#[serde(rename = "betweenNeighbors")]
|
#[serde(rename = "betweenNeighbors")]
|
||||||
between_neighbors: bool,
|
between_neighbors: bool,
|
||||||
|
/// How this marker and the next may pass each other.
|
||||||
|
#[serde(rename = "overlapNext")]
|
||||||
|
overlap_next: MarkerOverlap,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a slider marker and the next may pass each other, as split handles whose ranges may overlap.
|
||||||
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub enum MarkerOverlap {
|
||||||
|
/// Neither may pass the other.
|
||||||
|
#[default]
|
||||||
|
Never,
|
||||||
|
/// Each may pass the other but not the marker beyond it, so split handles' inner halves can overlap while the handles can't pass each other.
|
||||||
|
NextOnly,
|
||||||
|
/// The markers up to this one and those after it don't bound each other, so split handles can pass each other entirely.
|
||||||
|
Freely,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SliderMarker {
|
impl SliderMarker {
|
||||||
@@ -890,6 +906,7 @@ impl SliderMarker {
|
|||||||
paired_with_next: false,
|
paired_with_next: false,
|
||||||
dashed_to_next: false,
|
dashed_to_next: false,
|
||||||
between_neighbors: false,
|
between_neighbors: false,
|
||||||
|
overlap_next: MarkerOverlap::Never,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -907,6 +924,11 @@ impl SliderMarker {
|
|||||||
self.dashed_to_next = true;
|
self.dashed_to_next = true;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
||||||
|
self.overlap_next = overlap;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
|
|||||||
@@ -0,0 +1,262 @@
|
|||||||
|
//! Layers clipped to a base through the editor's own graph, where the base's filters shape what clips to it but the shadows it casts don't.
|
||||||
|
|
||||||
|
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||||
|
use crate::test_utils::gpu_executor;
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
use glam::{DAffine2, UVec2};
|
||||||
|
use graph_craft::document::value::TaggedValue;
|
||||||
|
use graphene_std::application_io::Texture;
|
||||||
|
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
|
||||||
|
use graphene_std::graphic::{IntoGraphicList, extend};
|
||||||
|
use graphene_std::list::{Item, List};
|
||||||
|
use graphene_std::math_nodes::{color_value, gradient_value};
|
||||||
|
use graphene_std::raster_nodes::std_nodes::noise_pattern;
|
||||||
|
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||||
|
use graphene_std::vector::style::RenderMode;
|
||||||
|
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
enum Base {
|
||||||
|
VectorLayer,
|
||||||
|
ImageLayer,
|
||||||
|
/// A group holding a vector layer, with the effect on the group.
|
||||||
|
Group,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn add_effect(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, effect: ProtoNodeIdentifier) {
|
||||||
|
let node_type = DefinitionIdentifier::ProtoNode(effect.clone());
|
||||||
|
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||||
|
|
||||||
|
if effect == blur::IDENTIFIER {
|
||||||
|
let node_id = NodeGraphLayer::new(layer, &editor.active_document().network_interface)
|
||||||
|
.upstream_node_id_from_protonode(effect)
|
||||||
|
.expect("the layer has its blur");
|
||||||
|
let value = Box::new(TaggedValue::Number(10.));
|
||||||
|
editor
|
||||||
|
.handle_message(NodeGraphMessage::SetInputValue {
|
||||||
|
node_id,
|
||||||
|
input_index: blur::RadiusInput::INDEX,
|
||||||
|
value,
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The root stack of a document with a blue base filling (50, 50) to (130, 130) and a larger red layer clipped to it, with `effect` on the base.
|
||||||
|
async fn clipped_stack(base: Base, effect: ProtoNodeIdentifier) -> List<Graphic> {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
|
||||||
|
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||||
|
let red = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
|
||||||
|
|
||||||
|
match base {
|
||||||
|
Base::ImageLayer => editor.create_raster_image(Image::new(80, 80, blue), Some((90., 90.))).await,
|
||||||
|
Base::VectorLayer | Base::Group => {
|
||||||
|
editor.select_primary_color(blue).await;
|
||||||
|
editor.select_secondary_color(blue).await;
|
||||||
|
editor.draw_rect(50., 50., 130., 130.).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let base_layer = editor.get_selected_layer().await.expect("the base is selected");
|
||||||
|
if !matches!(base, Base::Group) {
|
||||||
|
add_effect(&mut editor, base_layer, effect.clone()).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
editor.select_tool(ToolType::Select).await;
|
||||||
|
editor.select_primary_color(red).await;
|
||||||
|
editor.select_secondary_color(red).await;
|
||||||
|
editor.draw_rect(20., 20., 200., 200.).await;
|
||||||
|
let clipped_layer = editor.get_selected_layer().await.expect("the clipped layer is selected");
|
||||||
|
editor
|
||||||
|
.handle_message(GraphOperationMessage::FillColorSet {
|
||||||
|
layer: clipped_layer,
|
||||||
|
color: Some(red),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
editor.handle_message(DocumentMessage::ClipLayer { id: clipped_layer.to_node() }).await;
|
||||||
|
|
||||||
|
// Grouped once the red is clipped, the group takes the base's place beneath it
|
||||||
|
if let Base::Group = base {
|
||||||
|
let nodes = vec![base_layer.to_node()];
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
|
||||||
|
let group_folder_type = GroupFolderType::Layer;
|
||||||
|
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
|
||||||
|
let group = editor.get_selected_layer().await.expect("the group is selected");
|
||||||
|
add_effect(&mut editor, group, effect).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The stack is what the root's 'Extend' nodes put together: the base's layer extended by the clipped one
|
||||||
|
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
||||||
|
let mut news = instrumented.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime);
|
||||||
|
let clipped = news.find(|new| new.element().had_clip_enabled()).expect("the clipped layer is extended onto the base");
|
||||||
|
let mut bases = instrumented.grab_all_input::<extend::BaseInput, List<Graphic>>(&editor.runtime);
|
||||||
|
let mut stack = bases.find(|base| base.len() == 1).expect("the base's layer is extended");
|
||||||
|
stack.push(clipped);
|
||||||
|
stack
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks in SVG and in Vello that the red clipped to the base shows past the base's edges if `blurred`, and that a shadow the base casts doesn't widen the clip.
|
||||||
|
fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
|
||||||
|
// The clip's def in SVG carries out the blur but not the shadow
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
graphic.render_svg(
|
||||||
|
&mut render,
|
||||||
|
&RenderParams {
|
||||||
|
for_export: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let body = render.svg.to_svg_string();
|
||||||
|
let reference = body.rfind("url(#mask-").expect("the red is clipped");
|
||||||
|
let id: String = body[reference + "url(#".len()..].chars().take_while(|&character| character != ')').collect();
|
||||||
|
let defs = &render.svg_defs;
|
||||||
|
let def_start = defs.find(&format!(r#"id="{id}""#)).expect("the clip has a def");
|
||||||
|
let def_end = ["</mask>", "</clipPath>"]
|
||||||
|
.iter()
|
||||||
|
.filter_map(|closing| defs[def_start..].find(closing))
|
||||||
|
.min()
|
||||||
|
.expect("the clip's def is closed");
|
||||||
|
let clip = &defs[def_start..def_start + def_end];
|
||||||
|
assert_eq!(clip.contains("filter="), blurred, "{name}: the clip's def is {clip}");
|
||||||
|
|
||||||
|
// In Vello, the red past the base's edges shows where the blur reaches, but not where the shadow falls
|
||||||
|
let size = UVec2::new(256, 256);
|
||||||
|
let executor = gpu_executor();
|
||||||
|
let texture = executor
|
||||||
|
.render_vello(size, DAffine2::IDENTITY, &mut |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||||||
|
.expect("the clip renders");
|
||||||
|
let pixels = executor.read_texture_pixels(&texture).expect("the render reads back");
|
||||||
|
let pixel = |x: u32, y: u32| -> [u8; 4] {
|
||||||
|
let index = (y * size.x + x) as usize * 4;
|
||||||
|
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
|
||||||
|
};
|
||||||
|
|
||||||
|
let within = pixel(90, 90);
|
||||||
|
assert!(within[0] >= 250 && within[2] <= 5 && within[3] == 255, "{name}: within the base, the red is {within:?}");
|
||||||
|
assert_eq!(pixel(134, 90)[0] > 0, blurred, "{name}: past the base's right edge, the red is {:?}", pixel(134, 90));
|
||||||
|
assert_eq!(pixel(93, 135)[0] > 0, blurred, "{name}: past the base's bottom edge, the red is {:?}", pixel(93, 135));
|
||||||
|
assert!(blurred || pixel(93, 135)[3] > 0, "{name}: the base's shadow shows where it falls");
|
||||||
|
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Endless content a layer can hold, which fills the whole canvas unless something clips it.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
enum Endless {
|
||||||
|
Color,
|
||||||
|
Gradient,
|
||||||
|
NoisePattern,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A document viewed in the `render_mode` with a blue rectangle filling (50, 50) to (130, 130).
|
||||||
|
async fn document_with_a_rectangle(render_mode: RenderMode) -> EditorTestUtils {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
|
||||||
|
|
||||||
|
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||||
|
editor.select_primary_color(blue).await;
|
||||||
|
editor.select_secondary_color(blue).await;
|
||||||
|
editor.draw_rect(50., 50., 130., 130.).await;
|
||||||
|
|
||||||
|
editor
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds a new layer of `endless` content above the selected layer, clipped to it as by an Alt-click between them.
|
||||||
|
async fn add_clipped_endless_layer(editor: &mut EditorTestUtils, endless: Endless) {
|
||||||
|
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
|
||||||
|
let layer = editor.get_selected_layer().await.expect("the new layer is selected");
|
||||||
|
let node = match endless {
|
||||||
|
Endless::Color => color_value::IDENTIFIER,
|
||||||
|
Endless::Gradient => gradient_value::IDENTIFIER,
|
||||||
|
Endless::NoisePattern => noise_pattern::IDENTIFIER,
|
||||||
|
};
|
||||||
|
let node_type = DefinitionIdentifier::ProtoNode(node);
|
||||||
|
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||||
|
editor.handle_message(DocumentMessage::ClipLayer { id: layer.to_node() }).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluates the document for a viewport of `size` as the app does, returning what the frontend is sent and the frame the runtime presents.
|
||||||
|
async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<FrontendMessage>, Option<Texture>) {
|
||||||
|
let portfolio = editor.portfolio_message_handler_mut();
|
||||||
|
let document_id = portfolio.active_document_id.expect("a document is open");
|
||||||
|
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||||
|
let document = documents.get_mut(&document_id).expect("the active document exists");
|
||||||
|
let submitted = executor
|
||||||
|
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
|
||||||
|
.expect("the evaluation is submitted");
|
||||||
|
|
||||||
|
let mut messages = editor.dispatch(submitted);
|
||||||
|
editor.runtime.update();
|
||||||
|
let frame = editor.runtime.run().await;
|
||||||
|
messages.extend(editor.dispatch(Message::Wake));
|
||||||
|
|
||||||
|
(messages, frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn endless_layers_clip_to_the_shape_beneath_them() {
|
||||||
|
let size = UVec2::new(256, 256);
|
||||||
|
|
||||||
|
let frame_pixels = async |editor: &mut EditorTestUtils| {
|
||||||
|
let (_, frame) = evaluate_viewport(editor, size).await;
|
||||||
|
let frame = frame.expect("the viewport presents a frame");
|
||||||
|
gpu_executor().read_texture_pixels(&frame).expect("the frame reads back")
|
||||||
|
};
|
||||||
|
let pixel = |pixels: &[u8], x: u32, y: u32| {
|
||||||
|
let index = (y * size.x + x) as usize * 4;
|
||||||
|
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
|
||||||
|
};
|
||||||
|
|
||||||
|
for endless in [Endless::Color, Endless::Gradient, Endless::NoisePattern] {
|
||||||
|
// In the viewport's Vello render, the endless content covers the rectangle but leaves the canvas past it as the rectangle alone left it
|
||||||
|
let mut editor = document_with_a_rectangle(RenderMode::Normal).await;
|
||||||
|
let rectangle_alone = frame_pixels(&mut editor).await;
|
||||||
|
add_clipped_endless_layer(&mut editor, endless).await;
|
||||||
|
let clipped = frame_pixels(&mut editor).await;
|
||||||
|
|
||||||
|
assert_ne!(pixel(&clipped, 90, 90), pixel(&rectangle_alone, 90, 90), "{endless:?}: the content shows within the rectangle");
|
||||||
|
for (x, y) in [(20, 20), (200, 90), (90, 200), (230, 230)] {
|
||||||
|
assert_eq!(
|
||||||
|
pixel(&clipped, x, y),
|
||||||
|
pixel(&rectangle_alone, x, y),
|
||||||
|
"{endless:?}: the content is clipped away at ({x}, {y}), past the rectangle"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// In SVG Preview, the endless content is drawn only within the rectangle's mask
|
||||||
|
let mut editor = document_with_a_rectangle(RenderMode::SvgPreview).await;
|
||||||
|
add_clipped_endless_layer(&mut editor, endless).await;
|
||||||
|
let (messages, _) = evaluate_viewport(&mut editor, size).await;
|
||||||
|
let svg = messages
|
||||||
|
.into_iter()
|
||||||
|
.find_map(|message| match message {
|
||||||
|
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.expect("the viewport's artwork is sent as SVG");
|
||||||
|
|
||||||
|
let (unmasked, masked) = svg.split_once(r#"mask="url(#mask-"#).unwrap_or_else(|| panic!("{endless:?}: the content is masked: {svg}"));
|
||||||
|
let draws_endless_content = |markup: &str| ["<polyline", "<foreignObject"].iter().any(|tag| markup.contains(tag));
|
||||||
|
assert!(
|
||||||
|
!draws_endless_content(unmasked) && draws_endless_content(masked),
|
||||||
|
"{endless:?}: the content is drawn within the mask: {svg}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
|
||||||
|
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
|
||||||
|
for base in [Base::VectorLayer, Base::ImageLayer, Base::Group] {
|
||||||
|
let stack = clipped_stack(base, effect.clone()).await;
|
||||||
|
assert_clip(&format!("{base:?} with {effect_name}"), &Graphic::GraphicList(stack.clone()), blurred);
|
||||||
|
|
||||||
|
// Flattened into one list of vectors, the base clips its sibling by the same rule
|
||||||
|
if let Base::VectorLayer = base {
|
||||||
|
let flattened: List<Vector> = stack.into_flattened_list();
|
||||||
|
assert_clip(&format!("flattened vectors with {effect_name}"), &Graphic::VectorList(flattened), blurred);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
|||||||
use crate::node_graph_executor::InspectedContext;
|
use crate::node_graph_executor::InspectedContext;
|
||||||
use glam::{Affine2, DAffine2, Vec2};
|
use glam::{Affine2, DAffine2, Vec2};
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
|
use graphene_std::WarpStyle;
|
||||||
use graphene_std::animation::RealTimeMode;
|
use graphene_std::animation::RealTimeMode;
|
||||||
use graphene_std::blending::BlendMode;
|
use graphene_std::blending::BlendMode;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
@@ -34,9 +35,10 @@ use graphene_std::vector::style::{
|
|||||||
};
|
};
|
||||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||||
use graphene_std::{
|
use graphene_std::{
|
||||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
|
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource,
|
||||||
MaskMode,
|
GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||||
};
|
};
|
||||||
|
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||||
use kurbo::BezPath;
|
use kurbo::BezPath;
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
@@ -1271,16 +1273,23 @@ impl_table_item_layout_for_choice_enum!(
|
|||||||
BevelDirection,
|
BevelDirection,
|
||||||
BevelTechnique,
|
BevelTechnique,
|
||||||
BevelStyle,
|
BevelStyle,
|
||||||
|
RadialBlurMethod,
|
||||||
|
WarpStyle,
|
||||||
|
WaveType,
|
||||||
|
DisplaceMode,
|
||||||
|
BlendIfChannel,
|
||||||
EffectKind,
|
EffectKind,
|
||||||
Generator,
|
Generator,
|
||||||
GlowSource,
|
GlowSource,
|
||||||
MaskMode,
|
MaskMode,
|
||||||
|
MinimumMaximumMode,
|
||||||
GradientForm,
|
GradientForm,
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
GradientSpace,
|
GradientSpace,
|
||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
GradientInterpolation,
|
GradientInterpolation,
|
||||||
GlowTechnique,
|
GlowTechnique,
|
||||||
|
NoiseDistribution,
|
||||||
StrokeJoin,
|
StrokeJoin,
|
||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
@@ -1456,9 +1465,15 @@ macro_rules! known_item_types {
|
|||||||
EffectKind,
|
EffectKind,
|
||||||
GlowSource,
|
GlowSource,
|
||||||
MaskMode,
|
MaskMode,
|
||||||
|
MinimumMaximumMode,
|
||||||
BevelStyle,
|
BevelStyle,
|
||||||
BevelDirection,
|
BevelDirection,
|
||||||
BevelTechnique,
|
BevelTechnique,
|
||||||
|
RadialBlurMethod,
|
||||||
|
WarpStyle,
|
||||||
|
WaveType,
|
||||||
|
DisplaceMode,
|
||||||
|
BlendIfChannel,
|
||||||
DashPattern,
|
DashPattern,
|
||||||
BoxCorners,
|
BoxCorners,
|
||||||
TransferCurve,
|
TransferCurve,
|
||||||
@@ -1469,6 +1484,7 @@ macro_rules! known_item_types {
|
|||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
GradientInterpolation,
|
GradientInterpolation,
|
||||||
GlowTechnique,
|
GlowTechnique,
|
||||||
|
NoiseDistribution,
|
||||||
StrokeJoin,
|
StrokeJoin,
|
||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate,
|
|||||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
|
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
|
||||||
use crate::messages::portfolio::utility_types::PanelType;
|
use crate::messages::portfolio::utility_types::PanelType;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use glam::{DAffine2, IVec2, UVec2};
|
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
use graphene_std::Appearance;
|
use graphene_std::Appearance;
|
||||||
use graphene_std::list::Item;
|
use graphene_std::list::Item;
|
||||||
@@ -334,6 +334,7 @@ pub enum DocumentMessage {
|
|||||||
},
|
},
|
||||||
UpdateEffectsReach {
|
UpdateEffectsReach {
|
||||||
effects_reach: HashMap<NodeId, f64>,
|
effects_reach: HashMap<NodeId, f64>,
|
||||||
|
effects_frames: HashMap<NodeId, [DVec2; 2]>,
|
||||||
},
|
},
|
||||||
Undo,
|
Undo,
|
||||||
UngroupSelectedLayers,
|
UngroupSelectedLayers,
|
||||||
|
|||||||
@@ -304,8 +304,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
|||||||
let visibility_settings = self.overlays_visibility_settings;
|
let visibility_settings = self.overlays_visibility_settings;
|
||||||
|
|
||||||
// Send the overlays message to the overlays message handler
|
// Send the overlays message to the overlays message handler
|
||||||
self.overlays_message_handler
|
self.overlays_message_handler.process_message(
|
||||||
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
|
message,
|
||||||
|
responses,
|
||||||
|
OverlaysMessageContext {
|
||||||
|
visibility_settings,
|
||||||
|
viewport,
|
||||||
|
graph_open: self.graph_view_overlay_open,
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
DocumentMessage::Inspector(message) => {
|
DocumentMessage::Inspector(message) => {
|
||||||
let context = InspectorMessageContext {
|
let context = InspectorMessageContext {
|
||||||
@@ -1945,13 +1952,20 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
|||||||
.collect();
|
.collect();
|
||||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||||
}
|
}
|
||||||
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
DocumentMessage::UpdateEffectsReach { effects_reach, effects_frames } => {
|
||||||
|
let is_document_layer = |node_id: &NodeId| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]);
|
||||||
|
|
||||||
let layer_effects_reach = effects_reach
|
let layer_effects_reach = effects_reach
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
|
.filter(|(node_id, _)| is_document_layer(node_id))
|
||||||
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
||||||
.collect();
|
.collect();
|
||||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
let layer_effects_frames = effects_frames
|
||||||
|
.into_iter()
|
||||||
|
.filter(|(node_id, _)| is_document_layer(node_id))
|
||||||
|
.map(|(node_id, frames)| (LayerNodeIdentifier::new(node_id, &self.network_interface), frames))
|
||||||
|
.collect();
|
||||||
|
self.network_interface.update_effects_reach(layer_effects_reach, layer_effects_frames);
|
||||||
}
|
}
|
||||||
DocumentMessage::Undo => {
|
DocumentMessage::Undo => {
|
||||||
if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
|
if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
|
||||||
@@ -2680,7 +2694,6 @@ impl DocumentMessageHandler {
|
|||||||
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
|
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
|
||||||
for path in self.network_interface.paths_reaching(&reconciled.networks) {
|
for path in self.network_interface.paths_reaching(&reconciled.networks) {
|
||||||
self.network_interface.unload_import_export_ports(&path);
|
self.network_interface.unload_import_export_ports(&path);
|
||||||
self.network_interface.unload_all_nodes_bounding_box(&path);
|
|
||||||
self.network_interface.unload_outward_wires(&path);
|
self.network_interface.unload_outward_wires(&path);
|
||||||
}
|
}
|
||||||
self.network_interface.load_structure();
|
self.network_interface.load_structure();
|
||||||
@@ -4125,7 +4138,7 @@ impl DocumentMessageHandler {
|
|||||||
})
|
})
|
||||||
.unwrap_or((None, None, None));
|
.unwrap_or((None, None, None));
|
||||||
|
|
||||||
let blend_mode_menu_entries = BlendMode::list_svg_subset()
|
let blend_mode_menu_entries = BlendMode::list()
|
||||||
.iter()
|
.iter()
|
||||||
.map(|modes| {
|
.map(|modes| {
|
||||||
modes
|
modes
|
||||||
@@ -4142,7 +4155,7 @@ impl DocumentMessageHandler {
|
|||||||
|
|
||||||
let widgets = vec![
|
let widgets = vec![
|
||||||
DropdownInput::new(blend_mode_menu_entries)
|
DropdownInput::new(blend_mode_menu_entries)
|
||||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32))
|
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32))
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
.draw_icon(false)
|
.draw_icon(false)
|
||||||
.sizing(WidgetSizing::default().grow(false))
|
.sizing(WidgetSizing::default().grow(false))
|
||||||
|
|||||||
-3
@@ -807,9 +807,6 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
|||||||
// Set positions for all imported descendants in a single O(n) pass
|
// Set positions for all imported descendants in a single O(n) pass
|
||||||
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
|
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
|
||||||
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
|
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
|
||||||
|
|
||||||
// Invalidate caches once after all positions are set
|
|
||||||
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
|
|
||||||
}
|
}
|
||||||
usvg::Node::Path(path) => {
|
usvg::Node::Path(path) => {
|
||||||
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
|
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
mod clipping_tests;
|
||||||
|
#[cfg(test)]
|
||||||
pub(crate) mod document_diff;
|
pub(crate) mod document_diff;
|
||||||
mod document_history;
|
mod document_history;
|
||||||
mod document_message;
|
mod document_message;
|
||||||
|
|||||||
@@ -139,18 +139,6 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
|
|||||||
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
||||||
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||||
let custom = vec![
|
let custom = vec![
|
||||||
DocumentNodeDefinition {
|
|
||||||
identifier: "Custom Node",
|
|
||||||
version: 1,
|
|
||||||
category: "Routing",
|
|
||||||
icon: Some("NodeCustomNode"),
|
|
||||||
node_template: NodeTemplate {
|
|
||||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
|
|
||||||
inspector: None,
|
|
||||||
},
|
|
||||||
DocumentNodeDefinition {
|
DocumentNodeDefinition {
|
||||||
identifier: "Merge",
|
identifier: "Merge",
|
||||||
version: 1,
|
version: 1,
|
||||||
@@ -688,6 +676,7 @@ fn static_node_inspector() -> NodeInspector {
|
|||||||
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
|
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
|
||||||
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
|
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
|
||||||
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
|
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
|
||||||
|
map.insert("blend_if_inspector".to_string(), Box::new(node_inspector::blend_if_inspector));
|
||||||
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
|
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
|
||||||
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
|
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
|
||||||
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
|
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
|
||||||
@@ -701,6 +690,8 @@ fn static_node_inspector() -> NodeInspector {
|
|||||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||||
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
|
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
|
||||||
|
map.insert("sharpen_inspector".to_string(), Box::new(node_inspector::sharpen_inspector));
|
||||||
|
map.insert("displace_inspector".to_string(), Box::new(node_inspector::displace_inspector));
|
||||||
map
|
map
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -709,6 +700,15 @@ 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
|
// 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);
|
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector);
|
||||||
|
|
||||||
|
/// The metadata of the proto node's field at `index`, cloned so the lock is released before the row is built, which locks the node metadata again.
|
||||||
|
fn proto_node_field(node_id: NodeId, index: usize, context: &mut NodeInspectorContext) -> Option<registry::FieldMetadata> {
|
||||||
|
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().ok()?.get(proto_node_identifier)?.fields.get(index).cloned())
|
||||||
|
}
|
||||||
|
|
||||||
/// Defines the logic for inputs to display a custom Inspector widget.
|
/// Defines the logic for inputs to display a custom Inspector widget.
|
||||||
fn static_input_inspector() -> InputInspector {
|
fn static_input_inspector() -> InputInspector {
|
||||||
let mut map: InputInspector = HashMap::new();
|
let mut map: InputInspector = HashMap::new();
|
||||||
@@ -873,15 +873,10 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
map.insert(
|
map.insert(
|
||||||
// A range slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them
|
// A slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them
|
||||||
"wrapping_range_slider".to_string(),
|
"wrapping_slider".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
let field = proto_node_field(node_id, index, context);
|
||||||
let 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().ok()?.get(proto_node_identifier)?.fields.get(index).cloned());
|
|
||||||
|
|
||||||
let mut number_input = NumberInput::default().mode_increment();
|
let mut number_input = NumberInput::default().mode_increment();
|
||||||
let mut period = None;
|
let mut period = None;
|
||||||
@@ -902,10 +897,51 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
let row = match period {
|
let row = match period {
|
||||||
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
|
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
|
||||||
let default = node_inspector::definition_default_number(¶meter_widgets_info);
|
let default = node_inspector::definition_default_number(¶meter_widgets_info);
|
||||||
node_inspector::wrapping_range_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
|
node_inspector::wrapping_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
log::error!("A wrapping range slider needs finite soft bounds at both ends");
|
log::error!("A wrapping slider needs finite soft bounds at both ends");
|
||||||
|
node_inspector::number_widget(parameter_widgets_info, number_input)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(vec![LayoutGroup::row(row)])
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
map.insert(
|
||||||
|
// A slider across the soft bounds (or the hard ones where a soft one is absent), beside a number input that types past them up to the hard bounds
|
||||||
|
"slider".to_string(),
|
||||||
|
Box::new(|node_id, index, context| {
|
||||||
|
let field = proto_node_field(node_id, index, context);
|
||||||
|
|
||||||
|
let mut number_input = NumberInput::default().mode_increment();
|
||||||
|
let mut extent = None;
|
||||||
|
if let Some(field) = field {
|
||||||
|
if let Some(unit) = field.unit {
|
||||||
|
number_input = number_input.unit(unit);
|
||||||
|
}
|
||||||
|
if let Some(display_decimal_places) = field.number_display_decimal_places {
|
||||||
|
number_input = number_input.display_decimal_places(display_decimal_places);
|
||||||
|
}
|
||||||
|
if let Some(number_step) = field.number_step {
|
||||||
|
number_input = number_input.step(number_step);
|
||||||
|
}
|
||||||
|
if let Some(min) = field.number_hard_min {
|
||||||
|
number_input = number_input.min(min);
|
||||||
|
}
|
||||||
|
if let Some(max) = field.number_hard_max {
|
||||||
|
number_input = number_input.max(max);
|
||||||
|
}
|
||||||
|
extent = field.number_soft_min.or(field.number_hard_min).zip(field.number_soft_max.or(field.number_hard_max));
|
||||||
|
}
|
||||||
|
|
||||||
|
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||||
|
let row = match extent {
|
||||||
|
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
|
||||||
|
let default = node_inspector::definition_default_number(¶meter_widgets_info);
|
||||||
|
node_inspector::slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
log::error!("A slider needs finite bounds at both ends");
|
||||||
node_inspector::number_widget(parameter_widgets_info, number_input)
|
node_inspector::number_widget(parameter_widgets_info, number_input)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1070,7 +1106,7 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
"noise_inspector_fractal_weighted_strength".to_string(),
|
"noise_inspector_fractal_weighted_strength".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||||
let fractal_weighted_strength = node_inspector::range_slider_widget(
|
let fractal_weighted_strength = node_inspector::slider_widget(
|
||||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||||
NumberInput::default()
|
NumberInput::default()
|
||||||
.min(0.)
|
.min(0.)
|
||||||
|
|||||||
@@ -45,6 +45,11 @@ pub enum NodeGraphMessage {
|
|||||||
xy: Option<(i32, i32)>,
|
xy: Option<(i32, i32)>,
|
||||||
add_transaction: bool,
|
add_transaction: bool,
|
||||||
},
|
},
|
||||||
|
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
|
||||||
|
CreateEmptySubgraph {
|
||||||
|
node_id: Option<NodeId>,
|
||||||
|
xy: Option<(i32, i32)>,
|
||||||
|
},
|
||||||
CreateWire {
|
CreateWire {
|
||||||
output_connector: OutputConnector,
|
output_connector: OutputConnector,
|
||||||
input_connector: InputConnector,
|
input_connector: InputConnector,
|
||||||
@@ -202,8 +207,6 @@ pub enum NodeGraphMessage {
|
|||||||
SelectedNodesSet {
|
SelectedNodesSet {
|
||||||
nodes: Vec<NodeId>,
|
nodes: Vec<NodeId>,
|
||||||
},
|
},
|
||||||
SendClickTargets,
|
|
||||||
EndSendClickTargets,
|
|
||||||
UnloadWires,
|
UnloadWires,
|
||||||
SendWires,
|
SendWires,
|
||||||
UpdateVisibleNodes,
|
UpdateVisibleNodes,
|
||||||
@@ -383,6 +386,7 @@ impl NodeGraphMessage {
|
|||||||
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
||||||
Self::AddNodes { .. }
|
Self::AddNodes { .. }
|
||||||
| Self::CreateNodeFromContextMenu { .. }
|
| Self::CreateNodeFromContextMenu { .. }
|
||||||
|
| Self::CreateEmptySubgraph { .. }
|
||||||
| Self::CreateWire { .. }
|
| Self::CreateWire { .. }
|
||||||
| Self::CreateWires { .. }
|
| Self::CreateWires { .. }
|
||||||
| Self::ConnectUpstreamOutputToInput { .. }
|
| Self::ConnectUpstreamOutputToInput { .. }
|
||||||
@@ -442,8 +446,6 @@ impl NodeGraphMessage {
|
|||||||
| Self::SelectedNodesAdd { .. }
|
| Self::SelectedNodesAdd { .. }
|
||||||
| Self::SelectedNodesRemove { .. }
|
| Self::SelectedNodesRemove { .. }
|
||||||
| Self::SelectedNodesSet { .. }
|
| Self::SelectedNodesSet { .. }
|
||||||
| Self::SendClickTargets
|
|
||||||
| Self::EndSendClickTargets
|
|
||||||
| Self::UnloadWires
|
| Self::UnloadWires
|
||||||
| Self::SendWires
|
| Self::SendWires
|
||||||
| Self::UpdateVisibleNodes
|
| Self::UpdateVisibleNodes
|
||||||
|
|||||||
@@ -5,13 +5,14 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
|
|||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
|
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
|
||||||
|
TransactionStatus,
|
||||||
};
|
};
|
||||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
||||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||||
@@ -23,14 +24,12 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e
|
|||||||
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
||||||
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
||||||
use crate::messages::viewport::Position;
|
use crate::messages::viewport::Position;
|
||||||
use glam::{DAffine2, DVec2, IVec2};
|
use glam::{DVec2, IVec2};
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
|
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
|
||||||
use graphene_std::math::math_ext::QuadExt;
|
|
||||||
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
|
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
|
||||||
use graphene_std::*;
|
use graphene_std::*;
|
||||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||||
use renderer::Quad;
|
|
||||||
|
|
||||||
#[derive(Debug, ExtractField)]
|
#[derive(Debug, ExtractField)]
|
||||||
pub struct NodeGraphMessageContext<'a> {
|
pub struct NodeGraphMessageContext<'a> {
|
||||||
@@ -422,6 +421,23 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
});
|
});
|
||||||
responses.add(NodeGraphMessage::SendGraph);
|
responses.add(NodeGraphMessage::SendGraph);
|
||||||
}
|
}
|
||||||
|
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
|
||||||
|
let node_id = node_id.unwrap_or_else(NodeId::new);
|
||||||
|
let (x, y) = xy.unwrap_or_else(|| {
|
||||||
|
network_interface
|
||||||
|
.node_graph_ptz(breadcrumb_network_path)
|
||||||
|
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
|
||||||
|
});
|
||||||
|
|
||||||
|
responses.add(DocumentMessage::AddTransaction);
|
||||||
|
responses.add(NodeGraphMessage::InsertNode {
|
||||||
|
node_id,
|
||||||
|
node_template: Box::new(NodeTemplate::empty_subgraph()),
|
||||||
|
});
|
||||||
|
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
|
||||||
|
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||||
|
responses.add(NodeGraphMessage::SendGraph);
|
||||||
|
}
|
||||||
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
||||||
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
||||||
log::error!("Failed to find upstream node for downstream_input");
|
log::error!("Failed to find upstream node for downstream_input");
|
||||||
@@ -769,24 +785,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
|
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
|
||||||
let encapsulating_node_id = NodeId::new();
|
let encapsulating_node_id = NodeId::new();
|
||||||
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
|
let mut subgraph_template = NodeTemplate::empty_subgraph();
|
||||||
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
||||||
log::error!("Could not get center of selected_nodes");
|
log::error!("Could not get center of selected_nodes");
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
||||||
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||||
responses.add(DocumentMessage::AddTransaction);
|
responses.add(DocumentMessage::AddTransaction);
|
||||||
responses.add(NodeGraphMessage::InsertNode {
|
responses.add(NodeGraphMessage::InsertNode {
|
||||||
node_id: encapsulating_node_id,
|
node_id: encapsulating_node_id,
|
||||||
node_template: Box::new(default_node_template),
|
node_template: Box::new(subgraph_template),
|
||||||
});
|
|
||||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
|
||||||
node_id: encapsulating_node_id,
|
|
||||||
network_path: selection_network_path.to_vec(),
|
|
||||||
alias: "Untitled Node".to_string(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
||||||
@@ -2012,10 +2023,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
selected_nodes.set_selected_nodes(nodes);
|
selected_nodes.set_selected_nodes(nodes);
|
||||||
responses.add(EventMessage::SelectionChanged);
|
responses.add(EventMessage::SelectionChanged);
|
||||||
}
|
}
|
||||||
NodeGraphMessage::SendClickTargets => responses.add(FrontendMessage::UpdateClickTargets {
|
|
||||||
click_targets: Some(network_interface.collect_frontend_click_targets(breadcrumb_network_path)),
|
|
||||||
}),
|
|
||||||
NodeGraphMessage::EndSendClickTargets => responses.add(FrontendMessage::UpdateClickTargets { click_targets: None }),
|
|
||||||
NodeGraphMessage::UnloadWires => {
|
NodeGraphMessage::UnloadWires => {
|
||||||
self.frontend_wires.clear();
|
self.frontend_wires.clear();
|
||||||
responses.add(FrontendMessage::ClearAllNodeGraphWires);
|
responses.add(FrontendMessage::ClearAllNodeGraphWires);
|
||||||
@@ -2530,13 +2537,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
HashSet::new()
|
HashSet::new()
|
||||||
};
|
};
|
||||||
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
|
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
|
||||||
|
let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)];
|
||||||
for node_id in all_nodes {
|
for node_id in all_nodes {
|
||||||
let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else {
|
let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else {
|
||||||
log::error!("Could not get transient metadata for node {node_id}");
|
log::error!("Could not get the body of node {node_id}");
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let quad = Quad::from_box([box_selection_start, box_selection_end_graph]);
|
if body.overlaps(selection_min, selection_max) {
|
||||||
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
|
|
||||||
if alt {
|
if alt {
|
||||||
nodes.remove(&node_id);
|
nodes.remove(&node_id);
|
||||||
} else {
|
} else {
|
||||||
@@ -3198,11 +3205,6 @@ impl NodeGraphMessageHandler {
|
|||||||
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
|
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
|
||||||
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp);
|
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp);
|
||||||
|
|
||||||
// Only development builds draw the click targets, so users don't come across the overlay by accident
|
|
||||||
if cfg!(debug_assertions) {
|
|
||||||
common.extend(actions!(NodeGraphMessageDiscriminant; SendClickTargets, EndSendClickTargets));
|
|
||||||
}
|
|
||||||
|
|
||||||
if self.has_selection {
|
if self.has_selection {
|
||||||
common.extend(actions!(NodeGraphMessageDiscriminant;
|
common.extend(actions!(NodeGraphMessageDiscriminant;
|
||||||
Copy,
|
Copy,
|
||||||
@@ -3426,6 +3428,13 @@ impl NodeGraphMessageHandler {
|
|||||||
})
|
})
|
||||||
.disabled(read_only)
|
.disabled(read_only)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
|
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||||
|
TextButton::new("New Custom Node")
|
||||||
|
.tooltip_label("New Custom Node")
|
||||||
|
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
|
||||||
|
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
|
||||||
|
.disabled(read_only)
|
||||||
|
.widget_instance(),
|
||||||
//
|
//
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ use graph_craft::application_io::resource::{DataSource, Resource, ResourceId};
|
|||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||||
use graph_craft::{Type, concrete, item};
|
use graph_craft::{Type, concrete, item};
|
||||||
|
use graphene_std::WarpStyle;
|
||||||
use graphene_std::animation::RealTimeMode;
|
use graphene_std::animation::RealTimeMode;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::raster::{
|
use graphene_std::raster::{
|
||||||
@@ -40,7 +41,8 @@ use graphene_std::vector::style::{
|
|||||||
build_transform_with_y_preservation,
|
build_transform_with_y_preservation,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, Vector};
|
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||||
|
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||||
use graphene_std::{NodeParameter, ParameterRef};
|
use graphene_std::{NodeParameter, ParameterRef};
|
||||||
use math_parser::parser::{MessagePart, ParseError};
|
use math_parser::parser::{MessagePart, ParseError};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@@ -342,7 +344,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
match (number_input.min, number_input.max) {
|
match (number_input.min, number_input.max) {
|
||||||
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
|
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
|
||||||
let default = definition_default_number(&default_info);
|
let default = definition_default_number(&default_info);
|
||||||
range_slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
|
slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
|
||||||
}
|
}
|
||||||
_ => number_widget(default_info, number_input).into(),
|
_ => number_widget(default_info, number_input).into(),
|
||||||
}
|
}
|
||||||
@@ -393,7 +395,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
false => text_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::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &mut extra_widgets),
|
||||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
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)),
|
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||||
@@ -453,9 +455,16 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
|
||||||
|
Some(x) if id_is::<MinimumMaximumMode>(x) => enum_choice::<MinimumMaximumMode>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||||
|
Some(x) if id_is::<RadialBlurMethod>(x) => enum_choice::<RadialBlurMethod>().for_socket(default_info).inspector_row(),
|
||||||
|
Some(x) if id_is::<WarpStyle>(x) => enum_choice::<WarpStyle>().for_socket(default_info).inspector_row(),
|
||||||
|
Some(x) if id_is::<WaveType>(x) => enum_choice::<WaveType>().for_socket(default_info).inspector_row(),
|
||||||
|
Some(x) if id_is::<DisplaceMode>(x) => enum_choice::<DisplaceMode>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
||||||
|
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().for_socket(default_info).inspector_row(),
|
||||||
|
Some(x) if id_is::<BlendIfChannel>(x) => enum_choice::<BlendIfChannel>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||||
@@ -786,8 +795,10 @@ pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
|||||||
last.clone()
|
last.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
/// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size.
|
||||||
|
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||||
|
let size_unit = size_unit.unwrap_or("x");
|
||||||
|
|
||||||
let mut location_widgets = start_widgets(¶meter_widgets_info);
|
let mut location_widgets = start_widgets(¶meter_widgets_info);
|
||||||
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||||
@@ -854,7 +865,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
|||||||
scale_widgets.extend_from_slice(&[
|
scale_widgets.extend_from_slice(&[
|
||||||
NumberInput::new(Some(scale.x))
|
NumberInput::new(Some(scale.x))
|
||||||
.label("W")
|
.label("W")
|
||||||
.unit("x")
|
.unit(size_unit)
|
||||||
.on_update(update_value_at_index(
|
.on_update(update_value_at_index(
|
||||||
move |w: &NumberInput| {
|
move |w: &NumberInput| {
|
||||||
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix;
|
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix;
|
||||||
@@ -868,7 +879,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
|||||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||||
NumberInput::new(Some(scale.y))
|
NumberInput::new(Some(scale.y))
|
||||||
.label("H")
|
.label("H")
|
||||||
.unit("x")
|
.unit(size_unit)
|
||||||
.on_update(update_value_at_index(
|
.on_update(update_value_at_index(
|
||||||
move |h: &NumberInput| {
|
move |h: &NumberInput| {
|
||||||
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix;
|
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix;
|
||||||
@@ -1212,7 +1223,7 @@ pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_in
|
|||||||
|
|
||||||
let number_props = number_props.disabled(enabled == Some(false));
|
let number_props = number_props.disabled(enabled == Some(false));
|
||||||
let mut widgets = match slider {
|
let mut widgets = match slider {
|
||||||
Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider),
|
Some(slider) => slider_widget(parameter_widgets_info, number_props, slider),
|
||||||
None => number_widget(parameter_widgets_info, number_props),
|
None => number_widget(parameter_widgets_info, number_props),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1326,7 +1337,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
|||||||
return LayoutGroup::row(vec![]);
|
return LayoutGroup::row(vec![]);
|
||||||
};
|
};
|
||||||
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
|
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
|
||||||
let entries = BlendMode::list_svg_subset()
|
let entries = BlendMode::list()
|
||||||
.iter()
|
.iter()
|
||||||
.map(|category| {
|
.map(|category| {
|
||||||
category
|
category
|
||||||
@@ -1343,9 +1354,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
|||||||
|
|
||||||
widgets.extend_from_slice(&[
|
widgets.extend_from_slice(&[
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
DropdownInput::new(entries)
|
DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(),
|
||||||
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
|
|
||||||
.widget_instance(),
|
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
|
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
|
||||||
@@ -1906,6 +1915,8 @@ pub(crate) fn levels_inspector(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
enum MarkerScale {
|
enum MarkerScale {
|
||||||
/// A 0..100 percentage, placed linearly.
|
/// A 0..100 percentage, placed linearly.
|
||||||
Percent,
|
Percent,
|
||||||
|
/// A 0..100 percentage of a channel's 256 levels, placed linearly and shown to a tenth, which tells neighboring levels apart.
|
||||||
|
LevelPercent,
|
||||||
/// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center.
|
/// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center.
|
||||||
Gamma,
|
Gamma,
|
||||||
/// A hue of 0..360 degrees, placed linearly on a track that wraps around.
|
/// A hue of 0..360 degrees, placed linearly on a track that wraps around.
|
||||||
@@ -1915,7 +1926,7 @@ enum MarkerScale {
|
|||||||
impl MarkerScale {
|
impl MarkerScale {
|
||||||
fn position(self, value: f64) -> f64 {
|
fn position(self, value: f64) -> f64 {
|
||||||
match self {
|
match self {
|
||||||
Self::Percent => value / 100.,
|
Self::Percent | Self::LevelPercent => value / 100.,
|
||||||
Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(),
|
Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(),
|
||||||
Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(),
|
Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(),
|
||||||
Self::Degrees => {
|
Self::Degrees => {
|
||||||
@@ -1929,7 +1940,7 @@ impl MarkerScale {
|
|||||||
|
|
||||||
fn value(self, position: f64) -> f64 {
|
fn value(self, position: f64) -> f64 {
|
||||||
match self {
|
match self {
|
||||||
Self::Percent => (position * 100.).clamp(0., 100.),
|
Self::Percent | Self::LevelPercent => (position * 100.).clamp(0., 100.),
|
||||||
Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99),
|
Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99),
|
||||||
Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.),
|
Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.),
|
||||||
Self::Degrees => (position * 360.).clamp(0., 360.),
|
Self::Degrees => (position * 360.).clamp(0., 360.),
|
||||||
@@ -1939,6 +1950,7 @@ impl MarkerScale {
|
|||||||
fn number_input(self) -> NumberInput {
|
fn number_input(self) -> NumberInput {
|
||||||
match self {
|
match self {
|
||||||
Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0),
|
Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0),
|
||||||
|
Self::LevelPercent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(1),
|
||||||
Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2),
|
Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2),
|
||||||
Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0),
|
Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0),
|
||||||
}
|
}
|
||||||
@@ -1963,6 +1975,8 @@ struct SliderSectionParam {
|
|||||||
dash_to_next: bool,
|
dash_to_next: bool,
|
||||||
/// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move.
|
/// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move.
|
||||||
between_neighbors: bool,
|
between_neighbors: bool,
|
||||||
|
/// How the marker and the next parameter's marker may pass each other (see [`overlap_bounds`]).
|
||||||
|
overlap_next: MarkerOverlap,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SliderSectionParam {
|
impl SliderSectionParam {
|
||||||
@@ -1975,6 +1989,7 @@ impl SliderSectionParam {
|
|||||||
pair_with_next: false,
|
pair_with_next: false,
|
||||||
dash_to_next: false,
|
dash_to_next: false,
|
||||||
between_neighbors: false,
|
between_neighbors: false,
|
||||||
|
overlap_next: MarkerOverlap::Never,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1992,11 +2007,52 @@ impl SliderSectionParam {
|
|||||||
self.dash_to_next = true;
|
self.dash_to_next = true;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
||||||
|
self.overlap_next = overlap;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The span the marker at `index` may move within where markers may overlap their next (see [`MarkerOverlap`]).
|
||||||
|
fn overlap_bounds(positions: &[f64], overlaps_next: &[MarkerOverlap], index: usize) -> (f64, f64) {
|
||||||
|
let overlap = |i: Option<usize>| i.and_then(|i| overlaps_next.get(i)).copied().unwrap_or_default();
|
||||||
|
let position = |i: Option<usize>| i.and_then(|i| positions.get(i)).copied();
|
||||||
|
let (previous, before_previous, next, after_next) = (index.checked_sub(1), index.checked_sub(2), Some(index + 1), Some(index + 2));
|
||||||
|
let mut lower = 0_f64;
|
||||||
|
let mut upper = 1_f64;
|
||||||
|
|
||||||
|
// A neighbor bounds the marker unless they overlap
|
||||||
|
if overlap(previous) == MarkerOverlap::Never
|
||||||
|
&& let Some(previous) = position(previous)
|
||||||
|
{
|
||||||
|
lower = lower.max(previous);
|
||||||
|
}
|
||||||
|
if overlap(Some(index)) == MarkerOverlap::Never
|
||||||
|
&& let Some(next) = position(next)
|
||||||
|
{
|
||||||
|
upper = upper.min(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Past a neighbor overlapping only its next, the marker beyond bounds it too, unless either overlaps freely
|
||||||
|
let bounds_beyond = |near: MarkerOverlap, far: MarkerOverlap| (near == MarkerOverlap::NextOnly || far == MarkerOverlap::NextOnly) && near != MarkerOverlap::Freely && far != MarkerOverlap::Freely;
|
||||||
|
if bounds_beyond(overlap(previous), overlap(before_previous))
|
||||||
|
&& let Some(before_previous) = position(before_previous)
|
||||||
|
{
|
||||||
|
lower = lower.max(before_previous);
|
||||||
|
}
|
||||||
|
if bounds_beyond(overlap(Some(index)), overlap(next))
|
||||||
|
&& let Some(after_next) = position(after_next)
|
||||||
|
{
|
||||||
|
upper = upper.min(after_next);
|
||||||
|
}
|
||||||
|
|
||||||
|
(lower, upper)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row
|
/// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row
|
||||||
/// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display.
|
/// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display.
|
||||||
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do.
|
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do, except where they may overlap.
|
||||||
fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) {
|
fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) {
|
||||||
// Snapshot exposure and values before the mutable-borrow loop
|
// Snapshot exposure and values before the mutable-borrow loop
|
||||||
let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) {
|
let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) {
|
||||||
@@ -2024,6 +2080,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
let mut marker_scales = Vec::new();
|
let mut marker_scales = Vec::new();
|
||||||
let mut marker_positions = Vec::new();
|
let mut marker_positions = Vec::new();
|
||||||
let mut marker_between = Vec::new();
|
let mut marker_between = Vec::new();
|
||||||
|
let mut marker_overlaps = Vec::new();
|
||||||
let mut marker_colors_and_links = Vec::new();
|
let mut marker_colors_and_links = Vec::new();
|
||||||
for (i, param) in params.iter().enumerate() {
|
for (i, param) in params.iter().enumerate() {
|
||||||
let (exposed, value) = exposure_and_value[i];
|
let (exposed, value) = exposure_and_value[i];
|
||||||
@@ -2036,13 +2093,21 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
marker_default_positions.push(param.scale.position(param.default_value));
|
marker_default_positions.push(param.scale.position(param.default_value));
|
||||||
marker_scales.push(param.scale);
|
marker_scales.push(param.scale);
|
||||||
marker_between.push(param.between_neighbors);
|
marker_between.push(param.between_neighbors);
|
||||||
|
marker_overlaps.push(if next_has_marker { param.overlap_next } else { MarkerOverlap::Never });
|
||||||
marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker));
|
marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence.
|
// Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence.
|
||||||
// A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span.
|
// A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span.
|
||||||
let cyclic = params.iter().any(|param| param.scale.cyclic());
|
let cyclic = params.iter().any(|param| param.scale.cyclic());
|
||||||
if !cyclic {
|
let overlapping = marker_overlaps.iter().any(|&overlap| overlap != MarkerOverlap::Never);
|
||||||
|
if overlapping {
|
||||||
|
// Markers allowed to overlap are held only past those they can't pass, each bounded by markers earlier in the list
|
||||||
|
for i in 0..marker_positions.len() {
|
||||||
|
let (lower, _) = overlap_bounds(&marker_positions, &marker_overlaps, i);
|
||||||
|
marker_positions[i] = marker_positions[i].max(lower);
|
||||||
|
}
|
||||||
|
} else if !cyclic {
|
||||||
let mut floor = 0.;
|
let mut floor = 0.;
|
||||||
for (position, &between) in marker_positions.iter_mut().zip(&marker_between) {
|
for (position, &between) in marker_positions.iter_mut().zip(&marker_between) {
|
||||||
if between {
|
if between {
|
||||||
@@ -2063,8 +2128,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
let slider_markers: Vec<SliderMarker> = marker_positions
|
let slider_markers: Vec<SliderMarker> = marker_positions
|
||||||
.iter()
|
.iter()
|
||||||
.zip(&marker_colors_and_links)
|
.zip(&marker_colors_and_links)
|
||||||
.zip(&marker_between)
|
.zip(marker_between.iter().zip(&marker_overlaps))
|
||||||
.map(|((&position, &(handle_color, paired, dashed)), &between)| {
|
.map(|((&position, &(handle_color, paired, dashed)), (&between, &overlap))| {
|
||||||
let mut marker = SliderMarker::new(position, 0.5, handle_color);
|
let mut marker = SliderMarker::new(position, 0.5, handle_color);
|
||||||
if paired {
|
if paired {
|
||||||
marker = marker.pair_with_next();
|
marker = marker.pair_with_next();
|
||||||
@@ -2075,6 +2140,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
if between {
|
if between {
|
||||||
marker = marker.between_neighbors();
|
marker = marker.between_neighbors();
|
||||||
}
|
}
|
||||||
|
marker = marker.overlap_next(overlap);
|
||||||
marker
|
marker
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -2096,6 +2162,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
let marker_scales = marker_scales.clone();
|
let marker_scales = marker_scales.clone();
|
||||||
let marker_positions = marker_positions.clone();
|
let marker_positions = marker_positions.clone();
|
||||||
let marker_between = marker_between.clone();
|
let marker_between = marker_between.clone();
|
||||||
|
let marker_overlaps = marker_overlaps.clone();
|
||||||
move |update: &SliderInputUpdate| {
|
move |update: &SliderInputUpdate| {
|
||||||
let i = match update {
|
let i = match update {
|
||||||
SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize,
|
SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize,
|
||||||
@@ -2110,8 +2177,13 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
// The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the
|
// The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the
|
||||||
// nearest markers that bound it, which a marker placed between its neighbors never does
|
// nearest markers that bound it, which a marker placed between its neighbors never does
|
||||||
let bounding = |j: usize| between || !marker_between[j];
|
let bounding = |j: usize| between || !marker_between[j];
|
||||||
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
let (left, right) = if overlapping {
|
||||||
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
overlap_bounds(&marker_positions, &marker_overlaps, i)
|
||||||
|
} else {
|
||||||
|
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
||||||
|
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
||||||
|
(left, right)
|
||||||
|
};
|
||||||
|
|
||||||
let scale_position = match update {
|
let scale_position = match update {
|
||||||
SliderInputUpdate::MoveMarker { position, .. } if between => {
|
SliderInputUpdate::MoveMarker { position, .. } if between => {
|
||||||
@@ -2440,7 +2512,7 @@ fn slider_row(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A slider row running linearly across `slider`'s bounds.
|
/// A slider row running linearly across `slider`'s bounds.
|
||||||
pub(crate) fn range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
pub(crate) fn slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||||
slider_row(
|
slider_row(
|
||||||
parameter_widgets_info,
|
parameter_widgets_info,
|
||||||
number_props,
|
number_props,
|
||||||
@@ -2452,7 +2524,7 @@ pub(crate) fn range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo,
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them.
|
/// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them.
|
||||||
pub(crate) fn wrapping_range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
pub(crate) fn wrapping_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||||
slider_row(
|
slider_row(
|
||||||
parameter_widgets_info,
|
parameter_widgets_info,
|
||||||
number_props,
|
number_props,
|
||||||
@@ -2536,6 +2608,105 @@ pub(crate) fn threshold_inspector(node_id: NodeId, context: &mut NodeInspectorCo
|
|||||||
layout
|
layout
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn blend_if_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||||
|
use graphene_std::blending_nodes::blend_if::blend_if::*;
|
||||||
|
|
||||||
|
let channel = enum_choice::<BlendIfChannel>()
|
||||||
|
.for_socket(ParameterWidgetsInfo::new(node_id, ChannelInput, true, context))
|
||||||
|
.inspector_row();
|
||||||
|
|
||||||
|
let channel_value = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ChannelInput).cloned()) {
|
||||||
|
Some(TaggedValue::BlendIfChannel(channel)) => channel,
|
||||||
|
_ => BlendIfChannel::Gray,
|
||||||
|
};
|
||||||
|
let ([content, underlying], track_color): ([[ParameterRef; 4]; 2], Color) = match channel_value {
|
||||||
|
BlendIfChannel::Gray => (
|
||||||
|
[
|
||||||
|
[
|
||||||
|
ContentFalloffStartInput.into(),
|
||||||
|
ContentRangeStartInput.into(),
|
||||||
|
ContentRangeEndInput.into(),
|
||||||
|
ContentFalloffEndInput.into(),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
UnderlyingFalloffStartInput.into(),
|
||||||
|
UnderlyingRangeStartInput.into(),
|
||||||
|
UnderlyingRangeEndInput.into(),
|
||||||
|
UnderlyingFalloffEndInput.into(),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
Color::WHITE,
|
||||||
|
),
|
||||||
|
BlendIfChannel::Red => (
|
||||||
|
[
|
||||||
|
[
|
||||||
|
RedContentFalloffStartInput.into(),
|
||||||
|
RedContentRangeStartInput.into(),
|
||||||
|
RedContentRangeEndInput.into(),
|
||||||
|
RedContentFalloffEndInput.into(),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
RedUnderlyingFalloffStartInput.into(),
|
||||||
|
RedUnderlyingRangeStartInput.into(),
|
||||||
|
RedUnderlyingRangeEndInput.into(),
|
||||||
|
RedUnderlyingFalloffEndInput.into(),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
Color::RED,
|
||||||
|
),
|
||||||
|
BlendIfChannel::Green => (
|
||||||
|
[
|
||||||
|
[
|
||||||
|
GreenContentFalloffStartInput.into(),
|
||||||
|
GreenContentRangeStartInput.into(),
|
||||||
|
GreenContentRangeEndInput.into(),
|
||||||
|
GreenContentFalloffEndInput.into(),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
GreenUnderlyingFalloffStartInput.into(),
|
||||||
|
GreenUnderlyingRangeStartInput.into(),
|
||||||
|
GreenUnderlyingRangeEndInput.into(),
|
||||||
|
GreenUnderlyingFalloffEndInput.into(),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
Color::GREEN,
|
||||||
|
),
|
||||||
|
BlendIfChannel::Blue => (
|
||||||
|
[
|
||||||
|
[
|
||||||
|
BlueContentFalloffStartInput.into(),
|
||||||
|
BlueContentRangeStartInput.into(),
|
||||||
|
BlueContentRangeEndInput.into(),
|
||||||
|
BlueContentFalloffEndInput.into(),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
BlueUnderlyingFalloffStartInput.into(),
|
||||||
|
BlueUnderlyingRangeStartInput.into(),
|
||||||
|
BlueUnderlyingRangeEndInput.into(),
|
||||||
|
BlueUnderlyingFalloffEndInput.into(),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
Color::BLUE,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Each side's range runs along its channel's levels as a black split handle joined to a white one, with the fully shown range dashed between them
|
||||||
|
let track = Gradient::from(vec![Color::BLACK, track_color]);
|
||||||
|
let mut layout = vec![channel];
|
||||||
|
for [falloff_start, range_start, range_end, falloff_end] in [content, underlying] {
|
||||||
|
let params = [
|
||||||
|
SliderSectionParam::new(falloff_start, Color::BLACK, 0., MarkerScale::LevelPercent).pair_with_next(),
|
||||||
|
SliderSectionParam::new(range_start, Color::BLACK, 0., MarkerScale::LevelPercent)
|
||||||
|
.dash_to_next()
|
||||||
|
.overlap_next(MarkerOverlap::Freely),
|
||||||
|
SliderSectionParam::new(range_end, Color::WHITE, 100., MarkerScale::LevelPercent).pair_with_next(),
|
||||||
|
SliderSectionParam::new(falloff_end, Color::WHITE, 100., MarkerScale::LevelPercent),
|
||||||
|
];
|
||||||
|
build_shared_slider_section(node_id, context, &track, ¶ms, &mut layout);
|
||||||
|
}
|
||||||
|
layout
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||||
use graphene_std::raster::vibrance::*;
|
use graphene_std::raster::vibrance::*;
|
||||||
|
|
||||||
@@ -2545,8 +2716,8 @@ pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
|||||||
max: 100.,
|
max: 100.,
|
||||||
default: Some(0.),
|
default: Some(0.),
|
||||||
};
|
};
|
||||||
let vibrance = range_slider_widget(ParameterWidgetsInfo::new(node_id, VibranceInput, true, context), number_input.clone(), slider);
|
let vibrance = slider_widget(ParameterWidgetsInfo::new(node_id, VibranceInput, true, context), number_input.clone(), slider);
|
||||||
let saturation = range_slider_widget(ParameterWidgetsInfo::new(node_id, SaturationInput, true, context), number_input, slider);
|
let saturation = slider_widget(ParameterWidgetsInfo::new(node_id, SaturationInput, true, context), number_input, slider);
|
||||||
|
|
||||||
vec![LayoutGroup::row(vibrance), LayoutGroup::row(saturation)]
|
vec![LayoutGroup::row(vibrance), LayoutGroup::row(saturation)]
|
||||||
}
|
}
|
||||||
@@ -2906,7 +3077,7 @@ pub(crate) fn sample_polyline_inspector(node_id: NodeId, context: &mut NodeInspe
|
|||||||
pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||||
use graphene_std::raster::exposure::*;
|
use graphene_std::raster::exposure::*;
|
||||||
|
|
||||||
let exposure = range_slider_widget(
|
let exposure = slider_widget(
|
||||||
ParameterWidgetsInfo::new(node_id, ExposureInput, true, context),
|
ParameterWidgetsInfo::new(node_id, ExposureInput, true, context),
|
||||||
NumberInput::default().min(-20.).max(20.),
|
NumberInput::default().min(-20.).max(20.),
|
||||||
SliderRange {
|
SliderRange {
|
||||||
@@ -2915,7 +3086,7 @@ pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
|||||||
default: Some(0.),
|
default: Some(0.),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
let offset = range_slider_widget(
|
let offset = slider_widget(
|
||||||
ParameterWidgetsInfo::new(node_id, OffsetInput, true, context),
|
ParameterWidgetsInfo::new(node_id, OffsetInput, true, context),
|
||||||
NumberInput::default().min(-0.5).max(0.5),
|
NumberInput::default().min(-0.5).max(0.5),
|
||||||
SliderRange {
|
SliderRange {
|
||||||
@@ -3768,6 +3939,61 @@ pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
|||||||
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
|
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn sharpen_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||||
|
use graphene_std::blending_nodes::filters::sharpen::*;
|
||||||
|
|
||||||
|
// Edges Only compares against the four nearest neighbors in place of the blur, so it doesn't read the radius
|
||||||
|
let edges_only = get_document_node(node_id, context)
|
||||||
|
.ok()
|
||||||
|
.and_then(|document_node| document_node.input(EdgesOnlyInput).and_then(|input| input.as_value()))
|
||||||
|
.is_some_and(|tagged| matches!(tagged, TaggedValue::Bool(true)));
|
||||||
|
|
||||||
|
let number_input = NumberInput::default().mode_range().unit("%").min(0.).range_max(Some(500.));
|
||||||
|
let amount = number_widget(ParameterWidgetsInfo::new(node_id, AmountInput, true, context), number_input);
|
||||||
|
|
||||||
|
let number_input = NumberInput::default().mode_range().unit(" px").min(0.).range_max(Some(250.)).disabled(edges_only);
|
||||||
|
let radius = number_widget(ParameterWidgetsInfo::new(node_id, RadiusInput, true, context), number_input);
|
||||||
|
|
||||||
|
let number_input = NumberInput::default().mode_range().min(0.).range_max(Some(255.));
|
||||||
|
let threshold = number_widget(ParameterWidgetsInfo::new(node_id, ThresholdInput, true, context), number_input);
|
||||||
|
|
||||||
|
let edges_only = bool_widget(ParameterWidgetsInfo::new(node_id, EdgesOnlyInput, true, context), CheckboxInput::default());
|
||||||
|
|
||||||
|
vec![LayoutGroup::row(amount), LayoutGroup::row(radius), LayoutGroup::row(threshold), LayoutGroup::row(edges_only)]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn displace_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||||
|
use graphene_std::blending_nodes::distortions::displace::*;
|
||||||
|
|
||||||
|
// Each mode shows only the maps and distances it reads, and a wired mode shows both sets
|
||||||
|
let mode = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ModeInput)) {
|
||||||
|
Some(TaggedValue::DisplaceMode(mode)) => Some(*mode),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut layout = vec![enum_choice::<DisplaceMode>().for_socket(ParameterWidgetsInfo::new(node_id, ModeInput, true, context)).inspector_row()];
|
||||||
|
if !matches!(mode, Some(DisplaceMode::XAndY)) {
|
||||||
|
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, DisplacementInput, true, context), ColorInput::default()));
|
||||||
|
|
||||||
|
let number_input = NumberInput::default().mode_range().unit("°").range_min(Some(-180.)).range_max(Some(180.));
|
||||||
|
layout.push(LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, AngleInput, true, context), number_input)));
|
||||||
|
|
||||||
|
let number_input = NumberInput::default().unit(" px");
|
||||||
|
layout.push(LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), number_input)));
|
||||||
|
}
|
||||||
|
if !matches!(mode, Some(DisplaceMode::Angle)) {
|
||||||
|
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, XDisplacementInput, true, context), ColorInput::default()));
|
||||||
|
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, YDisplacementInput, true, context), ColorInput::default()));
|
||||||
|
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, false, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
let edge_mode = enum_choice::<GradientSpread>()
|
||||||
|
.for_socket(ParameterWidgetsInfo::new(node_id, EdgeModeInput, true, context))
|
||||||
|
.inspector_row();
|
||||||
|
layout.push(edge_mode);
|
||||||
|
layout
|
||||||
|
}
|
||||||
|
|
||||||
pub struct ParameterWidgetsInfo<'a> {
|
pub struct ParameterWidgetsInfo<'a> {
|
||||||
document_id: DocumentId,
|
document_id: DocumentId,
|
||||||
network_interface: &'a NodeNetworkInterface,
|
network_interface: &'a NodeNetworkInterface,
|
||||||
|
|||||||
@@ -212,23 +212,6 @@ pub struct NodeEvaluationError {
|
|||||||
pub message: String,
|
pub message: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
|
||||||
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
|
||||||
pub struct FrontendClickTargets {
|
|
||||||
#[serde(rename = "nodeClickTargets")]
|
|
||||||
pub node_click_targets: Vec<String>,
|
|
||||||
#[serde(rename = "layerClickTargets")]
|
|
||||||
pub layer_click_targets: Vec<String>,
|
|
||||||
#[serde(rename = "connectorClickTargets")]
|
|
||||||
pub connector_click_targets: Vec<String>,
|
|
||||||
#[serde(rename = "iconClickTargets")]
|
|
||||||
pub icon_click_targets: Vec<String>,
|
|
||||||
#[serde(rename = "allNodesBoundingBox")]
|
|
||||||
pub all_nodes_bounding_box: String,
|
|
||||||
#[serde(rename = "importExportNames")]
|
|
||||||
pub import_export_names: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum Direction {
|
pub enum Direction {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ use crate::messages::prelude::*;
|
|||||||
pub struct OverlaysMessageContext<'a> {
|
pub struct OverlaysMessageContext<'a> {
|
||||||
pub visibility_settings: OverlaysVisibilitySettings,
|
pub visibility_settings: OverlaysVisibilitySettings,
|
||||||
pub viewport: &'a ViewportMessageHandler,
|
pub viewport: &'a ViewportMessageHandler,
|
||||||
|
pub graph_open: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, ExtractField)]
|
#[derive(Debug, Clone, Default, ExtractField)]
|
||||||
@@ -25,7 +26,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
|||||||
|
|
||||||
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
|
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
|
||||||
|
|
||||||
if visibility_settings.all() {
|
if visibility_settings.all() && !context.graph_open {
|
||||||
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
|
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
|
||||||
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
|
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
|
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
|
||||||
|
|
||||||
use super::test_support::open_demo;
|
use super::test_support::open_demo;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector};
|
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
|
||||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||||
use glam::DVec2;
|
use glam::DVec2;
|
||||||
use graphene_std::uuid::NodeId;
|
use graphene_std::uuid::NodeId;
|
||||||
@@ -20,20 +20,32 @@ const DEMOS: [&str; 8] = [
|
|||||||
const REPETITIONS: u32 = 200;
|
const REPETITIONS: u32 = 200;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn wire_anchors_match_the_ports_of_every_demo_node() {
|
fn wire_anchors_lie_on_the_ports_of_every_demo_node() {
|
||||||
for demo in DEMOS {
|
for demo in DEMOS {
|
||||||
let document = open_demo(demo);
|
let document = open_demo(demo);
|
||||||
let interface = &document.network_interface;
|
let interface = &document.network_interface;
|
||||||
|
|
||||||
for node_id in interface.document_network().nodes.keys() {
|
for node_id in interface.document_network().nodes.keys() {
|
||||||
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
|
// A redirect dot's wires attach at its center, between the gutters they're grabbed from
|
||||||
|
let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body");
|
||||||
|
let is_redirect_dot = interface.is_redirect_dot(node_id, &[]);
|
||||||
|
let on_port = |wanted: Part, anchor: Option<DVec2>| {
|
||||||
|
let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target));
|
||||||
|
match (port, anchor) {
|
||||||
|
(Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2.,
|
||||||
|
(Some(port), Some(anchor)) => port.contains(anchor),
|
||||||
|
(None, None) => true,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
for index in 0..interface.number_of_inputs(node_id, &[]) {
|
for index in 0..interface.number_of_inputs(node_id, &[]) {
|
||||||
let input = InputConnector::node_at_index(*node_id, index);
|
let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]);
|
||||||
assert_eq!(interface.input_position(&input, &[]), ports.input_port_position(index), "{demo}: input {index} of node {node_id}");
|
assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}");
|
||||||
}
|
}
|
||||||
for index in 0..interface.number_of_outputs(node_id, &[]) {
|
for index in 0..interface.number_of_outputs(node_id, &[]) {
|
||||||
let output = OutputConnector::node(*node_id, index);
|
let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]);
|
||||||
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}");
|
assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,7 +72,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
|
|||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
for _ in 0..REPETITIONS {
|
for _ in 0..REPETITIONS {
|
||||||
for node_id in &node_ids {
|
for node_id in &node_ids {
|
||||||
std::hint::black_box(interface.node_click_targets(node_id, &[]));
|
std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let all_click_targets = start.elapsed() / REPETITIONS;
|
let all_click_targets = start.elapsed() / REPETITIONS;
|
||||||
|
|||||||
@@ -35,7 +35,6 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
|
|||||||
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
|
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||||
node.set_absolute_position(*position);
|
node.set_absolute_position(*position);
|
||||||
}
|
}
|
||||||
interface.invalidate_positions(network_path);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,14 +171,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
|
|||||||
interface.finish_drag(&[]);
|
interface.finish_drag(&[]);
|
||||||
|
|
||||||
let kept = interface.positions(node_ids.iter().copied(), &[]);
|
let kept = interface.positions(node_ids.iter().copied(), &[]);
|
||||||
let Some((_, indices, graph)) = interface.layout_graph(&[]) else {
|
let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
|
||||||
panic!("the root network is laid out")
|
panic!("the root network is laid out")
|
||||||
};
|
};
|
||||||
let fresh = graph_layout::Layout::new(&graph);
|
let fresh = graph_layout::Layout::new(&graph);
|
||||||
for (other, position) in kept {
|
for (other, position) in kept {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Some(position),
|
Some(position),
|
||||||
indices.get(&other).map(|index| fresh.node(*index).position),
|
laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
|
||||||
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
|
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,6 +53,8 @@ pub struct DocumentMetadata {
|
|||||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||||
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
|
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
|
||||||
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
|
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
|
||||||
|
/// The bounding box of the frames that each layer's effects paint anywhere in, in document pixels, for the layers with such effects.
|
||||||
|
pub layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>,
|
||||||
/// Transform from document space to viewport space.
|
/// Transform from document space to viewport space.
|
||||||
pub document_to_viewport: DAffine2,
|
pub document_to_viewport: DAffine2,
|
||||||
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
||||||
@@ -364,7 +366,7 @@ impl DocumentMetadata {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
|
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
|
||||||
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a
|
/// stroke geometry when the layer is a vector with a stroke style, the frames its effects paint anywhere in, and how far they paint past it. Only the first item of a
|
||||||
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
|
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||||
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||||
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
||||||
@@ -372,7 +374,8 @@ impl DocumentMetadata {
|
|||||||
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
||||||
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
|
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
|
||||||
});
|
});
|
||||||
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
let frames = self.layer_effects_frames.get(&layer).copied();
|
||||||
|
let [min, max] = [stroked, self.bounding_box_document(layer), frames].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||||
|
|
||||||
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
||||||
Some([min - reach, max + reach])
|
Some([min - reach, max + reach])
|
||||||
@@ -751,6 +754,25 @@ mod tests {
|
|||||||
assert_eq!((min.x, max.x), (0., 110.));
|
assert_eq!((min.x, max.x), (0., 110.));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bounds_with_effects_hold_the_frames_the_effects_paint_in() {
|
||||||
|
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||||
|
let mut square = BezPath::new();
|
||||||
|
square.move_to((-30., -30.));
|
||||||
|
square.line_to((30., -30.));
|
||||||
|
square.line_to((30., 30.));
|
||||||
|
square.line_to((-30., 30.));
|
||||||
|
square.close_path();
|
||||||
|
|
||||||
|
// A layer 30 across each way from its middle, with effects painting anywhere in a frame reaching 40 from it, and 2 past that
|
||||||
|
let mut metadata = DocumentMetadata::default();
|
||||||
|
metadata.click_targets.insert(layer, vec![Arc::new(ClickTarget::new_with_path(square, 0.))]);
|
||||||
|
metadata.layer_effects_frames.insert(layer, [DVec2::splat(-40.), DVec2::splat(40.)]);
|
||||||
|
metadata.layer_effects_reach.insert(layer, 2.);
|
||||||
|
|
||||||
|
assert_eq!(metadata.bounding_box_document_with_stroke_and_effects(layer), Some([DVec2::splat(-42.), DVec2::splat(42.)]));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
|
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
|
||||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ mod layout;
|
|||||||
mod layout_pass;
|
mod layout_pass;
|
||||||
mod memo_network;
|
mod memo_network;
|
||||||
mod mutations;
|
mod mutations;
|
||||||
|
mod node_parts;
|
||||||
mod queries;
|
mod queries;
|
||||||
mod reconcile;
|
mod reconcile;
|
||||||
mod resolved_types;
|
mod resolved_types;
|
||||||
@@ -36,6 +37,7 @@ mod view;
|
|||||||
|
|
||||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||||
pub use layout_pass::NetworkLayout;
|
pub use layout_pass::NetworkLayout;
|
||||||
|
pub use node_parts::{Part, PartTarget};
|
||||||
pub use reconcile::{ReconcileError, Reconciled};
|
pub use reconcile::{ReconcileError, Reconciled};
|
||||||
use store::Guarded;
|
use store::Guarded;
|
||||||
pub use store::NodeLocator;
|
pub use store::NodeLocator;
|
||||||
@@ -52,7 +54,7 @@ use crate::consts::{
|
|||||||
STACK_VERTICAL_GAP,
|
STACK_VERTICAL_GAP,
|
||||||
};
|
};
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type};
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type};
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
|
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
|
||||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ impl NodeNetworkInterface {
|
|||||||
EditorDelta::NodeMetadata { network, node_id, change } => {
|
EditorDelta::NodeMetadata { network, node_id, change } => {
|
||||||
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
|
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
|
||||||
match change {
|
match change {
|
||||||
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
|
NodeMetadataChange::NodeType(node_type) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()),
|
||||||
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
|
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
|
||||||
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
|
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
|
||||||
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
|
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
|
||||||
|
|||||||
@@ -88,34 +88,15 @@ impl NodeNetworkInterface {
|
|||||||
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
|
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
|
/// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed.
|
||||||
self.load_import_export_ports(network_path);
|
|
||||||
|
|
||||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
|
||||||
log::error!("Could not get nested network_metadata in import_export_ports");
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
|
|
||||||
log::error!("Could not load import export ports in import_export_ports");
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
Some(ports)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads the import/export ports through &self, loading them first if needed.
|
|
||||||
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
|
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
|
||||||
self.network_metadata(network_path)?
|
let generation = self.with_layout(network_path, NetworkLayout::generation)?;
|
||||||
.transient_metadata
|
let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
|
||||||
.import_export_ports
|
if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
|
||||||
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
|
cache.unload();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
|
cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports))
|
||||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
|
||||||
log::error!("Could not get nested network_metadata in load_import_export_ports");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
|
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
|
||||||
@@ -126,78 +107,13 @@ impl NodeNetworkInterface {
|
|||||||
transient.import_export_ports.unload();
|
transient.import_export_ports.unload();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
|
||||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
|
||||||
log::error!("Could not get nested network_metadata in all_nodes_bounding_box");
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
|
|
||||||
let bounding_box = network_metadata
|
|
||||||
.transient_metadata
|
|
||||||
.all_nodes_bounding_box
|
|
||||||
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
|
|
||||||
if bounding_box.is_none() {
|
|
||||||
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
|
|
||||||
}
|
|
||||||
bounding_box
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The combined bounds of every node in the network, in node graph space.
|
/// The combined bounds of every node in the network, in node graph space.
|
||||||
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||||
let network_metadata = self.network_metadata(network_path)?;
|
self.with_layout(network_path, NetworkLayout::bounds)
|
||||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
|
||||||
|
|
||||||
Some(
|
|
||||||
nodes
|
|
||||||
.iter()
|
|
||||||
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
|
|
||||||
.reduce(Quad::combine_bounds)
|
|
||||||
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
|
|
||||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
|
||||||
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
transient.all_nodes_bounding_box.unload();
|
|
||||||
transient.import_export_clearance.unload();
|
|
||||||
self.unload_import_export_ports(network_path);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
self.with_layout(network_path, NetworkLayout::clearance)
|
||||||
log::error!("Could not get nested network_metadata in import_export_clearance");
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
|
|
||||||
network_metadata
|
|
||||||
.transient_metadata
|
|
||||||
.import_export_clearance
|
|
||||||
.with_loaded_or(|| self.compute_import_export_clearance(network_path), |clearance| *clearance)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The horizontal extents of the nodes in the network, with the redirect dots measured by their centers apart from the rest.
|
|
||||||
fn compute_import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
|
||||||
let network_metadata = self.network_metadata(network_path)?;
|
|
||||||
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
|
||||||
|
|
||||||
let mut clearance = ImportExportClearance::default();
|
|
||||||
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
|
|
||||||
let Some([top_left, bottom_right]) = self.node_bounding_box(node_id, network_path) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
if self.is_redirect_dot(node_id, network_path) {
|
|
||||||
let center = (top_left.x + bottom_right.x) / 2.;
|
|
||||||
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
|
||||||
} else {
|
|
||||||
clearance.node_sides = widen(clearance.node_sides, top_left.x, bottom_right.x);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(clearance)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
|
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
|
||||||
@@ -364,6 +280,10 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
|
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
|
||||||
|
self.layer_width_and_name_width(node_id, network_path).map(|(layer_width, _)| layer_width)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn layer_width_and_name_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(u32, f64)> {
|
||||||
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
|
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
|
||||||
log::error!("Could not get nested node_metadata in layer_width");
|
log::error!("Could not get nested node_metadata in layer_width");
|
||||||
return None;
|
return None;
|
||||||
@@ -376,7 +296,7 @@ impl NodeNetworkInterface {
|
|||||||
node_metadata
|
node_metadata
|
||||||
.transient_metadata
|
.transient_metadata
|
||||||
.layer_width
|
.layer_width
|
||||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
|
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |widths| *widths)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unloads layer width if the node is a layer.
|
/// Unloads layer width if the node is a layer.
|
||||||
@@ -475,7 +395,7 @@ impl NodeNetworkInterface {
|
|||||||
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||||
let thick = vertical_end && vertical_start;
|
let thick = vertical_end && vertical_start;
|
||||||
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
||||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
||||||
|
|
||||||
let path_string = vector_wire.to_svg();
|
let path_string = vector_wire.to_svg();
|
||||||
let center_path_string = center_line.to_svg();
|
let center_path_string = center_line.to_svg();
|
||||||
@@ -523,7 +443,7 @@ impl NodeNetworkInterface {
|
|||||||
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||||
let thick = vertical_end && vertical_start;
|
let thick = vertical_end && vertical_start;
|
||||||
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
|
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
|
||||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, wire_style);
|
||||||
Some((vector_wire, center_line, thick))
|
Some((vector_wire, center_line, thick))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -549,17 +469,10 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The node's body, ports, and handles, built where it is drawn now.
|
/// The node's body, ports, and handles, built where it is drawn now.
|
||||||
pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
/// The box around the node's body where it sits in its grid cell, in node graph space.
|
||||||
self.compute_node_click_targets(node_id, network_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
|
|
||||||
self.compute_node_click_targets(node_id, network_path).as_ref().map(read)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||||
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
|
let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?;
|
||||||
.flatten()
|
Some([body.min, body.max])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
use super::template::NodeTemplateImplementation;
|
use super::template::{NodeTemplate, NodeTemplateImplementation};
|
||||||
use super::{InputConnector, OutputConnector, catalog};
|
use super::{InputConnector, OutputConnector, catalog};
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
||||||
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
||||||
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
|
|||||||
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await;
|
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
||||||
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
||||||
|
|
||||||
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
|
|||||||
let custom = NodeId::new();
|
let custom = NodeId::new();
|
||||||
let blend = NodeId::new();
|
let blend = NodeId::new();
|
||||||
let interface = &mut editor.active_document_mut().network_interface;
|
let interface = &mut editor.active_document_mut().network_interface;
|
||||||
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]);
|
interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
|
||||||
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
||||||
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
||||||
panic!("the Blend should name a table entry")
|
panic!("the Blend should name a table entry")
|
||||||
|
|||||||
+88
-7
@@ -2,7 +2,7 @@ use super::{
|
|||||||
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
|
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
|
||||||
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
|
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
|
||||||
};
|
};
|
||||||
use crate::consts::{GRID_SIZE, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
|
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
|
||||||
@@ -330,7 +330,6 @@ async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
|
|||||||
}
|
}
|
||||||
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
|
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
|
||||||
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
|
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
|
||||||
network_interface.invalidate_positions(&[]);
|
|
||||||
|
|
||||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
|
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
|
||||||
|
|
||||||
@@ -3119,7 +3118,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
|
|||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
|
|
||||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
let path = [subgraph];
|
let path = [subgraph];
|
||||||
editor.enter_editable_network(subgraph).await;
|
editor.enter_editable_network(subgraph).await;
|
||||||
|
|
||||||
@@ -3506,7 +3505,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
|
|||||||
|
|
||||||
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
||||||
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
||||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
editor.enter_editable_network(subgraph).await;
|
editor.enter_editable_network(subgraph).await;
|
||||||
editor.handle_message(NodeGraphMessage::AddImport).await;
|
editor.handle_message(NodeGraphMessage::AddImport).await;
|
||||||
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
||||||
@@ -4041,18 +4040,30 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_new_subgraph_is_its_own_definition() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
|
||||||
|
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
|
let network_interface = &editor.active_document().network_interface;
|
||||||
|
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
|
||||||
|
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
|
||||||
|
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn cannot_preview_node_without_outputs() {
|
async fn cannot_preview_node_without_outputs() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
|
|
||||||
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||||
|
|
||||||
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
|
assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
|
||||||
|
|
||||||
// Attempting to toggle preview on a node without outputs should not enable previewing
|
// Attempting to toggle preview on a node without outputs should not enable previewing
|
||||||
network_interface.toggle_preview(custom_node, &[]);
|
network_interface.toggle_preview(subgraph, &[]);
|
||||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4216,3 +4227,73 @@ async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
|
|||||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||||
assert_invariants(&editor, "after grouping a group");
|
assert_invariants(&editor, "after grouping a group");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn indent_below_parent(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> Option<i32> {
|
||||||
|
let interface = &editor.active_document().network_interface;
|
||||||
|
let parent = layer.parent(interface.document_metadata())?;
|
||||||
|
Some(interface.position(&parent.to_node(), &[])?.x - interface.position(&layer.to_node(), &[])?.x)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn reordering_the_layers_of_a_group_keeps_them_indented_below_it() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
||||||
|
for x in [0., 50., 100.] {
|
||||||
|
editor.draw_rect(x, 0., x + 40., 40.).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let artboard = LayerNodeIdentifier::ROOT_PARENT
|
||||||
|
.children(editor.active_document().metadata())
|
||||||
|
.next()
|
||||||
|
.expect("the artboard should be a layer");
|
||||||
|
let top_two = artboard.children(editor.active_document().metadata()).take(2).map(LayerNodeIdentifier::to_node).collect();
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: top_two }).await;
|
||||||
|
group_selected_layers(&mut editor).await;
|
||||||
|
|
||||||
|
let group = artboard
|
||||||
|
.children(editor.active_document().metadata())
|
||||||
|
.next()
|
||||||
|
.expect("the group should be the top layer of the artboard");
|
||||||
|
for insert_index in [0, 2] {
|
||||||
|
let moved = group.children(editor.active_document().metadata()).nth(1 - insert_index / 2).expect("the group should hold two layers");
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![moved.to_node()] }).await;
|
||||||
|
editor.handle_message(DocumentMessage::MoveSelectedLayersTo { parent: group, insert_index }).await;
|
||||||
|
|
||||||
|
for layer in group.children(editor.active_document().metadata()).chain([group]) {
|
||||||
|
assert_eq!(indent_below_parent(&editor, layer), Some(LAYER_INDENT_OFFSET), "moving a layer to index {insert_index} of the group");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn releasing_a_drag_of_a_layer_in_a_stack_leaves_every_layer_where_the_drag_drew_it() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
||||||
|
for x in [0., 50., 100., 150.] {
|
||||||
|
editor.draw_rect(x, 0., x + 40., 40.).await;
|
||||||
|
}
|
||||||
|
let artboard = LayerNodeIdentifier::ROOT_PARENT
|
||||||
|
.children(editor.active_document().metadata())
|
||||||
|
.next()
|
||||||
|
.expect("the artboard should be a layer");
|
||||||
|
let third = artboard.children(editor.active_document().metadata()).nth(2).expect("the artboard should hold four layers");
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third.to_node()] }).await;
|
||||||
|
|
||||||
|
let interface = &mut editor.active_document_mut().network_interface;
|
||||||
|
let layers: Vec<NodeId> = interface.document_network().nodes.keys().copied().filter(|node_id| interface.is_layer(node_id, &[])).collect();
|
||||||
|
for keep_upstream in [false, true] {
|
||||||
|
for offset in [IVec2::new(0, 3), IVec2::new(0, -2), IVec2::new(5, 0)] {
|
||||||
|
let before = interface.positions(layers.iter().copied(), &[]);
|
||||||
|
interface.drag_selected_nodes(offset, keep_upstream, &[]);
|
||||||
|
let dragging = interface.positions(layers.iter().copied(), &[]);
|
||||||
|
interface.finish_drag(&[]);
|
||||||
|
|
||||||
|
assert_ne!(dragging, before, "dragging by {offset} keeping upstream: {keep_upstream} should move the layers");
|
||||||
|
|
||||||
|
assert_eq!(interface.positions(layers.iter().copied(), &[]), dragging, "dragging by {offset} keeping upstream: {keep_upstream}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
@@ -62,11 +62,21 @@ pub enum NodeMetadataChange {
|
|||||||
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
|
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
|
||||||
/// merge independently, so a concurrent move and a concurrent layer toggle both survive.
|
/// merge independently, so a concurrent move and a concurrent layer toggle both survive.
|
||||||
NodeType(NodeTypePersistentMetadata),
|
NodeType(NodeTypePersistentMetadata),
|
||||||
|
/// Where a node that stays a layer or stays a node sits. Encodes to `ui::position` alone.
|
||||||
|
Position(NodeTypePersistentMetadata),
|
||||||
DisplayName(String),
|
DisplayName(String),
|
||||||
Locked(bool),
|
Locked(bool),
|
||||||
Pinned(bool),
|
Pinned(bool),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl NodeMetadataChange {
|
||||||
|
/// The change from `before` to `after`, writing whether the node is a layer only when that changes.
|
||||||
|
pub fn placement(before: &NodeTypePersistentMetadata, after: NodeTypePersistentMetadata) -> Self {
|
||||||
|
let is_layer = |node_type: &NodeTypePersistentMetadata| matches!(node_type, NodeTypePersistentMetadata::Layer(_));
|
||||||
|
if is_layer(before) == is_layer(&after) { Self::Position(after) } else { Self::NodeType(after) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// One field of a network's persistent metadata. The navigation transform and width are absent
|
/// One field of a network's persistent metadata. The navigation transform and width are absent
|
||||||
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
|
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
@@ -319,6 +329,10 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
|
|||||||
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
|
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
NodeMetadataChange::Position(node_type) => vec![node_attribute(
|
||||||
|
node_attr::ui::POSITION,
|
||||||
|
Some(serialize_attribute(node_attr::ui::POSITION, &position_from_runtime(node_type))?),
|
||||||
|
)],
|
||||||
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
|
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
|
||||||
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
|
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
|
||||||
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
|
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
|
||||||
|
|||||||
+28
-1
@@ -3,6 +3,7 @@ use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange
|
|||||||
use super::storage_metadata::StorageMetadataView;
|
use super::storage_metadata::StorageMetadataView;
|
||||||
use super::{InputConnector, NodeTemplate};
|
use super::{InputConnector, NodeTemplate};
|
||||||
use crate::test_utils::test_prelude::*;
|
use crate::test_utils::test_prelude::*;
|
||||||
|
use document_graph_storage::attr::node as node_attr;
|
||||||
use document_graph_storage::delta::compute_deltas;
|
use document_graph_storage::delta::compute_deltas;
|
||||||
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
|
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
@@ -184,7 +185,7 @@ async fn per_field_metadata_edits_match_the_diff() {
|
|||||||
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
|
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
|
||||||
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
|
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
|
||||||
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
|
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
|
||||||
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())),
|
metadata_change(node, NodeMetadataChange::Position(metadata.node_type_metadata.clone())),
|
||||||
EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
||||||
network: None,
|
network: None,
|
||||||
node_id: node,
|
node_id: node,
|
||||||
@@ -283,6 +284,32 @@ async fn unchanged_writes_emit_nothing() {
|
|||||||
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
|
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn moving_a_layer_writes_only_its_position() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.draw_rect(0., 0., 40., 40.).await;
|
||||||
|
let layer = LayerNodeIdentifier::ROOT_PARENT
|
||||||
|
.children(editor.active_document().metadata())
|
||||||
|
.next()
|
||||||
|
.expect("the rectangle should be a layer")
|
||||||
|
.to_node();
|
||||||
|
|
||||||
|
let working = convert(&editor);
|
||||||
|
editor.active_document_mut().network_interface.discard_deltas();
|
||||||
|
editor.active_document_mut().network_interface.shift_node(&layer, glam::IVec2::new(3, 5), &[]);
|
||||||
|
|
||||||
|
let emitted = committed_deltas(&mut editor);
|
||||||
|
let written: Vec<String> = construct(&editor, &emitted, &working)
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|op| match op {
|
||||||
|
RegistryDelta::ChangeNodeAttribute { delta, .. } => Some(delta.key),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert_eq!(written, [node_attr::ui::POSITION]);
|
||||||
|
}
|
||||||
|
|
||||||
/// Structural writes go through the store too, so inserting and deleting a node must be recorded
|
/// Structural writes go through the store too, so inserting and deleting a node must be recorded
|
||||||
/// without the caller saying anything about it.
|
/// without the caller saying anything about it.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
+3
-190
@@ -46,193 +46,6 @@ impl NodeNetworkInterface {
|
|||||||
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
|
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn compute_node_ports(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Ports> {
|
|
||||||
let Some(node_position) = self.position(node_id, network_path) else {
|
|
||||||
log::error!("Could not get node position in compute_node_ports for node {node_id}");
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
let document_node = self.document_node(node_id, network_path)?;
|
|
||||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
|
||||||
let mut ports = Ports::new();
|
|
||||||
|
|
||||||
if self.is_redirect_dot(node_id, network_path) {
|
|
||||||
ports.insert_dot_ports(node_top_left + DVec2::new(0., GRID_SIZE as f64));
|
|
||||||
} else if !self.is_layer(node_id, network_path) {
|
|
||||||
let mut input_row_count = 0;
|
|
||||||
for (input_index, input) in document_node.inputs.iter().enumerate() {
|
|
||||||
if input.is_exposed() {
|
|
||||||
ports.insert_node_input(input_index, input_row_count, node_top_left);
|
|
||||||
}
|
|
||||||
if input_index == 0 || input.is_exposed() {
|
|
||||||
input_row_count += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
|
|
||||||
for output_index in start_index..self.number_of_outputs(node_id, network_path) {
|
|
||||||
ports.insert_node_output(output_index, node_top_left);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ports.insert_layer_input(0, node_top_left);
|
|
||||||
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
|
|
||||||
ports.insert_layer_input(1, node_top_left);
|
|
||||||
}
|
|
||||||
ports.insert_layer_output(node_top_left);
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(ports)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
|
|
||||||
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
|
||||||
let Some(node_position) = self.position(node_id, network_path) else {
|
|
||||||
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
let node_metadata = self.node_metadata(node_id, network_path)?;
|
|
||||||
let port_click_targets = self.compute_node_ports(node_id, network_path)?;
|
|
||||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
|
||||||
|
|
||||||
// A redirect dot is centered on the grid point at the connector height of an ordinary node's first row.
|
|
||||||
// Its body also covers the gutters beside it holding its ports, so every press near it moves the dot unless it lands on an available port.
|
|
||||||
if self.is_redirect_dot(node_id, network_path) {
|
|
||||||
const DOT_HALF_WIDTH: f64 = 15.;
|
|
||||||
const DOT_HALF_HEIGHT: f64 = 8.;
|
|
||||||
|
|
||||||
let center = node_top_left + DVec2::new(0., GRID_SIZE as f64);
|
|
||||||
let path = rounded_rectangle_path(
|
|
||||||
center - DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
|
||||||
center + DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
|
||||||
[DOT_HALF_HEIGHT; 4],
|
|
||||||
);
|
|
||||||
|
|
||||||
return Some(DocumentNodeClickTargets {
|
|
||||||
node_click_target: ClickTarget::new_with_path(path, 0.),
|
|
||||||
port_click_targets,
|
|
||||||
node_type_metadata: NodeTypeClickTargets::Node,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
|
|
||||||
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
|
|
||||||
let width = 5 * GRID_SIZE;
|
|
||||||
// Offset down by half a grid so the click target sits below the top connector strip.
|
|
||||||
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
|
|
||||||
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
|
|
||||||
|
|
||||||
let radius = 3.;
|
|
||||||
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
|
|
||||||
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
|
||||||
|
|
||||||
DocumentNodeClickTargets {
|
|
||||||
node_click_target,
|
|
||||||
port_click_targets,
|
|
||||||
node_type_metadata: NodeTypeClickTargets::Node,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
|
|
||||||
log::error!("Could not get layer width in compute_node_click_targets");
|
|
||||||
0
|
|
||||||
});
|
|
||||||
let width = layer_width_cells * GRID_SIZE;
|
|
||||||
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
|
|
||||||
let locked = self.is_locked(node_id, network_path);
|
|
||||||
|
|
||||||
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
|
|
||||||
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
|
|
||||||
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
|
|
||||||
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
|
|
||||||
|
|
||||||
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
|
|
||||||
let path = rounded_rectangle_path(
|
|
||||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
|
|
||||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
|
|
||||||
[3.; 4],
|
|
||||||
);
|
|
||||||
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
|
|
||||||
|
|
||||||
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
|
|
||||||
let lock_click_target = if locked {
|
|
||||||
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
|
|
||||||
let path = rounded_rectangle_path(
|
|
||||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
|
|
||||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
|
|
||||||
[3.; 4],
|
|
||||||
);
|
|
||||||
Some(ClickTarget::new_with_path(path, 0.))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
|
|
||||||
const GRIP_WIDTH: f64 = 8.;
|
|
||||||
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
|
|
||||||
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
|
|
||||||
let path = rounded_rectangle_path(
|
|
||||||
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
|
|
||||||
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
|
|
||||||
[0.; 4],
|
|
||||||
);
|
|
||||||
let grip_click_target = ClickTarget::new_with_path(path, 0.);
|
|
||||||
|
|
||||||
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
|
|
||||||
// so the rest of the layer still drills into the subgraph on double-click
|
|
||||||
|
|
||||||
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
|
|
||||||
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
|
|
||||||
/// `.thumbnail` (70px) + its 1px side margins (= 72)
|
|
||||||
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
|
|
||||||
/// `.details` margin-left
|
|
||||||
const DETAILS_LEFT_MARGIN: f64 = 8.;
|
|
||||||
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
|
|
||||||
/// Distance from layer's right edge to visibility's left edge (= 12)
|
|
||||||
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
|
|
||||||
const FONT_SIZE: f64 = 14.;
|
|
||||||
|
|
||||||
let display_name = self.display_name(node_id, network_path);
|
|
||||||
let name_click_target = if display_name.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
|
|
||||||
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
|
|
||||||
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
|
|
||||||
let name_width = text_width(&display_name, FONT_SIZE);
|
|
||||||
let name_right = (name_left + name_width).min(name_right_max);
|
|
||||||
if name_right > name_left {
|
|
||||||
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
|
|
||||||
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
|
|
||||||
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
|
|
||||||
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
|
|
||||||
Some(ClickTarget::new_with_path(path, 0.))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// The layer click target spans the layer and its chain background
|
|
||||||
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
|
|
||||||
|
|
||||||
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
|
|
||||||
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
|
|
||||||
const CORNER_RADIUS: f64 = 10.;
|
|
||||||
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
|
|
||||||
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
|
||||||
|
|
||||||
DocumentNodeClickTargets {
|
|
||||||
node_click_target,
|
|
||||||
port_click_targets,
|
|
||||||
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
|
|
||||||
visibility_click_target,
|
|
||||||
lock_click_target,
|
|
||||||
grip_click_target,
|
|
||||||
name_click_target,
|
|
||||||
})),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
Some(document_node_click_targets)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
|
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
|
||||||
/// Laid out as the frontend draws them, just past the connector.
|
/// Laid out as the frontend draws them, just past the connector.
|
||||||
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
|
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
|
||||||
@@ -339,9 +152,9 @@ impl NodeNetworkInterface {
|
|||||||
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
|
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached
|
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons, and the width of its name. Cached
|
||||||
/// because measuring the name's text is slow.
|
/// because measuring the name's text is slow.
|
||||||
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
|
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
|
||||||
const GAP_WIDTH: f64 = 8.;
|
const GAP_WIDTH: f64 = 8.;
|
||||||
const FONT_SIZE: f64 = 14.;
|
const FONT_SIZE: f64 = 14.;
|
||||||
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
|
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
|
||||||
@@ -356,7 +169,7 @@ impl NodeNetworkInterface {
|
|||||||
let icon_overhang_width = GRID_SIZE as f64 / 2.;
|
let icon_overhang_width = GRID_SIZE as f64 / 2.;
|
||||||
|
|
||||||
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
|
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
|
||||||
((layer_width_pixels / 24.).ceil() as u32).max(8)
|
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
|
||||||
}
|
}
|
||||||
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
|
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
|
||||||
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
|
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
|
||||||
|
|||||||
+59
-116
@@ -24,81 +24,6 @@ impl NodeNetworkInterface {
|
|||||||
all_selected_nodes
|
all_selected_nodes
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn collect_frontend_click_targets(&self, network_path: &[NodeId]) -> FrontendClickTargets {
|
|
||||||
let mut all_node_click_targets = Vec::new();
|
|
||||||
let mut connector_click_targets = Vec::new();
|
|
||||||
let mut icon_click_targets = Vec::new();
|
|
||||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
|
||||||
log::error!("Could not get nested network_metadata in collect_frontend_click_targets");
|
|
||||||
return FrontendClickTargets::default();
|
|
||||||
};
|
|
||||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
|
||||||
self.with_import_export_ports(network_path, |import_export_click_targets| {
|
|
||||||
for port in import_export_click_targets.click_targets() {
|
|
||||||
if let ClickTargetType::Path(path) = port.target_type() {
|
|
||||||
connector_click_targets.push(path.to_svg());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
nodes.into_iter().for_each(|node_id| {
|
|
||||||
self.with_node_click_targets(&node_id, network_path, |node_click_targets| {
|
|
||||||
let mut node_path = String::new();
|
|
||||||
|
|
||||||
if let ClickTargetType::Path(path) = node_click_targets.node_click_target.target_type() {
|
|
||||||
node_path.push_str(path.to_svg().as_str())
|
|
||||||
}
|
|
||||||
all_node_click_targets.push((node_id, node_path));
|
|
||||||
for port in node_click_targets.port_click_targets.click_targets() {
|
|
||||||
if let ClickTargetType::Path(path) = port.target_type() {
|
|
||||||
connector_click_targets.push(path.to_svg());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
|
|
||||||
// Visibility button (eye icon)
|
|
||||||
if let ClickTargetType::Path(path) = layer_metadata.visibility_click_target.target_type() {
|
|
||||||
icon_click_targets.push(path.to_svg());
|
|
||||||
}
|
|
||||||
// Lock button (padlock icon), only when the layer is locked
|
|
||||||
if let Some(lock_click_target) = &layer_metadata.lock_click_target
|
|
||||||
&& let ClickTargetType::Path(path) = lock_click_target.target_type()
|
|
||||||
{
|
|
||||||
icon_click_targets.push(path.to_svg());
|
|
||||||
}
|
|
||||||
// Drag grip (dotted symbol)
|
|
||||||
if let ClickTargetType::Path(path) = layer_metadata.grip_click_target.target_type() {
|
|
||||||
icon_click_targets.push(path.to_svg());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
let mut layer_click_targets = Vec::new();
|
|
||||||
let mut node_click_targets = Vec::new();
|
|
||||||
all_node_click_targets.into_iter().for_each(|(node_id, path)| {
|
|
||||||
if self.is_layer(&node_id, network_path) {
|
|
||||||
layer_click_targets.push(path);
|
|
||||||
} else {
|
|
||||||
node_click_targets.push(path);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let bounds = self.all_nodes_bounding_box(network_path).unwrap_or([DVec2::ZERO, DVec2::ZERO]);
|
|
||||||
let all_nodes_bounding_box = rectangle_path(bounds[0], bounds[1]).to_svg();
|
|
||||||
|
|
||||||
let import_export_names = self
|
|
||||||
.import_export_name_bounds(network_path)
|
|
||||||
.into_iter()
|
|
||||||
.map(|(_, [name_min, name_max])| rectangle_path(name_min, name_max).to_svg())
|
|
||||||
.collect();
|
|
||||||
FrontendClickTargets {
|
|
||||||
node_click_targets,
|
|
||||||
layer_click_targets,
|
|
||||||
connector_click_targets,
|
|
||||||
icon_click_targets,
|
|
||||||
all_nodes_bounding_box,
|
|
||||||
import_export_names,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) {
|
pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) {
|
||||||
self.document_metadata.document_to_viewport = transform;
|
self.document_metadata.document_to_viewport = transform;
|
||||||
}
|
}
|
||||||
@@ -123,6 +48,24 @@ impl NodeNetworkInterface {
|
|||||||
Some(&mut navigation.node_graph_ptz)
|
Some(&mut navigation.node_graph_ptz)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The first of the node's parts, its body last, that `find` picks something from. Each part is given in node graph space where the node sits in its
|
||||||
|
/// grid cell, and an input by its index rather than the row a node draws it in.
|
||||||
|
pub(crate) fn find_node_part<R>(&self, node_id: &NodeId, network_path: &[NodeId], mut find: impl FnMut(Part, &PartTarget) -> Option<R>) -> Option<R> {
|
||||||
|
let rows_are_inputs = self.is_layer(node_id, network_path) || self.is_redirect_dot(node_id, network_path);
|
||||||
|
let inputs = &self.document_node(node_id, network_path)?.inputs;
|
||||||
|
|
||||||
|
self.with_layout(network_path, |layout| {
|
||||||
|
layout.find_part(node_id, |target| {
|
||||||
|
let part = match target.part {
|
||||||
|
Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? as u32),
|
||||||
|
part => part,
|
||||||
|
};
|
||||||
|
find(part, target)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.flatten()
|
||||||
|
}
|
||||||
|
|
||||||
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
|
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
|
||||||
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
|
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
|
||||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||||
@@ -133,16 +76,13 @@ impl NodeNetworkInterface {
|
|||||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||||
// Each node is pressed where it's drawn, even while gliding into its grid cell
|
// Each node is pressed where it's drawn, even while gliding into its grid cell
|
||||||
let glide_offsets = self.glide_offsets(network_path);
|
let glide_offsets = self.glide_offsets(network_path);
|
||||||
let clicked_nodes = self
|
let reaching = self.nodes_reaching(point, network_path);
|
||||||
.nodes_reaching(point, network_path)
|
let clicked_nodes = self.with_layout(network_path, |layout| {
|
||||||
.iter()
|
reaching
|
||||||
.filter(|node_id| {
|
.into_iter()
|
||||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
.filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id))))
|
||||||
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id))
|
.collect::<Vec<_>>()
|
||||||
}) == Some(true)
|
})?;
|
||||||
})
|
|
||||||
.cloned()
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
|
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
|
||||||
let drawing_layer = |node_id: &NodeId| {
|
let drawing_layer = |node_id: &NodeId| {
|
||||||
if self.is_redirect_dot(node_id, network_path) {
|
if self.is_redirect_dot(node_id, network_path) {
|
||||||
@@ -165,25 +105,18 @@ impl NodeNetworkInterface {
|
|||||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||||
let glide_offsets = self.glide_offsets(network_path);
|
let glide_offsets = self.glide_offsets(network_path);
|
||||||
|
|
||||||
self.nodes_reaching(point, network_path)
|
let wanted = match click_target_type {
|
||||||
.iter()
|
LayerClickTargetTypes::Visibility => Part::Visibility,
|
||||||
.filter_map(|node_id| {
|
LayerClickTargetTypes::Lock => Part::Lock,
|
||||||
let point = point - glide_offsets.node(node_id);
|
LayerClickTargetTypes::Grip => Part::Grip,
|
||||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
LayerClickTargetTypes::Name => Part::Name,
|
||||||
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata {
|
};
|
||||||
match click_target_type {
|
|
||||||
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
self.nodes_reaching(point, network_path).into_iter().find(|node_id| {
|
||||||
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
let point = point - glide_offsets.node(node_id);
|
||||||
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(()))
|
||||||
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
.is_some()
|
||||||
}
|
})
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.flatten()
|
|
||||||
})
|
|
||||||
.next()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
|
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
|
||||||
@@ -269,13 +202,11 @@ impl NodeNetworkInterface {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||||
.filter_map(|node_id| {
|
.filter_map(|node_id| {
|
||||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
let point = point - glide_offsets.node(node_id);
|
||||||
transient_node_metadata
|
self.find_node_part(node_id, network_path, |part, target| match part {
|
||||||
.port_click_targets
|
Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)),
|
||||||
.clicked_input_port_from_point(point - glide_offsets.node(node_id))
|
_ => None,
|
||||||
.map(|port| InputConnector::node_at_index(*node_id, port))
|
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
})
|
})
|
||||||
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
||||||
.or_else(|| {
|
.or_else(|| {
|
||||||
@@ -302,13 +233,11 @@ impl NodeNetworkInterface {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||||
.filter_map(|node_id| {
|
.filter_map(|node_id| {
|
||||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
let point = point - glide_offsets.node(node_id);
|
||||||
transient_node_metadata
|
self.find_node_part(node_id, network_path, |part, target| match part {
|
||||||
.port_click_targets
|
Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)),
|
||||||
.clicked_output_port_from_point(point - glide_offsets.node(node_id))
|
_ => None,
|
||||||
.map(|output_index| OutputConnector::node(*node_id, output_index))
|
|
||||||
})
|
})
|
||||||
.flatten()
|
|
||||||
})
|
})
|
||||||
.next()
|
.next()
|
||||||
.or_else(|| {
|
.or_else(|| {
|
||||||
@@ -426,3 +355,17 @@ impl NodeNetworkInterface {
|
|||||||
(layer_widths, chain_widths, has_left_input_wire)
|
(layer_widths, chain_widths, has_left_input_wire)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The input drawn in `row` of a node, where the primary input's row is drawn even while it has no port.
|
||||||
|
fn input_in_row(inputs: &[NodeInput], row: usize) -> Option<usize> {
|
||||||
|
let mut current_row = 0;
|
||||||
|
for (index, input) in inputs.iter().enumerate() {
|
||||||
|
if input.is_exposed() && current_row == row {
|
||||||
|
return Some(index);
|
||||||
|
}
|
||||||
|
if index == 0 || input.is_exposed() {
|
||||||
|
current_row += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
@@ -6,10 +6,6 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
impl NodeNetworkInterface {
|
impl NodeNetworkInterface {
|
||||||
pub(crate) fn invalidate_positions(&mut self, network_path: &[NodeId]) {
|
|
||||||
self.unload_all_nodes_bounding_box(network_path);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Unloads the network's import and export ports.
|
/// Unloads the network's import and export ports.
|
||||||
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
|
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
|
||||||
self.unload_import_export_ports(network_path);
|
self.unload_import_export_ports(network_path);
|
||||||
@@ -17,6 +13,5 @@ impl NodeNetworkInterface {
|
|||||||
|
|
||||||
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||||
self.try_unload_layer_width(node_id, network_path);
|
self.try_unload_layer_width(node_id, network_path);
|
||||||
self.unload_all_nodes_bounding_box(network_path);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -52,7 +52,6 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
self.invalidate_positions(network_path);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
|
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
|
||||||
@@ -145,7 +144,6 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
self.invalidate_positions(network_path);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the position of a layer to a stack position
|
/// Sets the position of a layer to a stack position
|
||||||
@@ -159,8 +157,6 @@ impl NodeNetworkInterface {
|
|||||||
} else if node.set_stack_position(y_offset) {
|
} else if node.set_stack_position(y_offset) {
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
}
|
}
|
||||||
|
|
||||||
self.invalidate_positions(network_path);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the position of a node to a stack position without changing its y offset
|
/// Sets the position of a node to a stack position without changing its y offset
|
||||||
@@ -371,7 +367,6 @@ impl NodeNetworkInterface {
|
|||||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
|
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
|
||||||
if node.shift_absolute_position(position - current_position) {
|
if node.shift_absolute_position(position - current_position) {
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
self.invalidate_positions(network_path);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+158
-36
@@ -1,7 +1,9 @@
|
|||||||
|
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
|
||||||
use super::*;
|
use super::*;
|
||||||
use glam::UVec2;
|
use glam::UVec2;
|
||||||
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
|
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
|
||||||
const REACH_MARGIN: f64 = 16.;
|
const REACH_MARGIN: f64 = 16.;
|
||||||
|
|
||||||
@@ -9,13 +11,53 @@ const REACH_MARGIN: f64 = 16.;
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct NetworkLayout {
|
pub struct NetworkLayout {
|
||||||
revision: u64,
|
revision: u64,
|
||||||
|
generation: u64,
|
||||||
node_ids: Vec<NodeId>,
|
node_ids: Vec<NodeId>,
|
||||||
indices: HashMap<NodeId, NodeIndex>,
|
indices: HashMap<NodeId, NodeIndex>,
|
||||||
graph: Graph,
|
graph: Graph,
|
||||||
|
shapes: Vec<NodeShape>,
|
||||||
layout: Layout,
|
layout: Layout,
|
||||||
|
bounds: [DVec2; 2],
|
||||||
|
clearance: ImportExportClearance,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Counts every layout made, so whatever is derived from one can tell when it was replaced, even without a new revision.
|
||||||
|
static LAYOUT_GENERATIONS: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
impl NetworkLayout {
|
impl NetworkLayout {
|
||||||
|
fn new(revision: u64, laid_out: LaidOutNodes, graph: Graph, layout: Layout) -> Self {
|
||||||
|
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
|
||||||
|
let mut network_layout = Self {
|
||||||
|
revision,
|
||||||
|
generation: LAYOUT_GENERATIONS.fetch_add(1, Ordering::Relaxed),
|
||||||
|
node_ids,
|
||||||
|
indices,
|
||||||
|
graph,
|
||||||
|
shapes,
|
||||||
|
layout,
|
||||||
|
bounds: [DVec2::ZERO; 2],
|
||||||
|
clearance: ImportExportClearance::default(),
|
||||||
|
};
|
||||||
|
network_layout.measure_bounds_and_clearance();
|
||||||
|
network_layout
|
||||||
|
}
|
||||||
|
|
||||||
|
fn into_parts(self) -> (LaidOutNodes, Graph, Layout) {
|
||||||
|
let Self {
|
||||||
|
node_ids,
|
||||||
|
indices,
|
||||||
|
shapes,
|
||||||
|
graph,
|
||||||
|
layout,
|
||||||
|
..
|
||||||
|
} = self;
|
||||||
|
(LaidOutNodes { node_ids, indices, shapes }, graph, layout)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generation(&self) -> u64 {
|
||||||
|
self.generation
|
||||||
|
}
|
||||||
|
|
||||||
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
|
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
|
||||||
Some(self.node(node_id)?.position)
|
Some(self.node(node_id)?.position)
|
||||||
}
|
}
|
||||||
@@ -53,6 +95,33 @@ impl NetworkLayout {
|
|||||||
self.node(layer).map_or(0, |node| node.chain_length)
|
self.node(layer).map_or(0, |node| node.chain_length)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network.
|
||||||
|
pub fn bounds(&self) -> [DVec2; 2] {
|
||||||
|
self.bounds
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the imports and exports keep their distance from horizontally.
|
||||||
|
pub(crate) fn clearance(&self) -> ImportExportClearance {
|
||||||
|
self.clearance
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node's body where it sits in its grid cell, in node graph space.
|
||||||
|
pub fn body(&self, node_id: &NodeId) -> Option<PartTarget> {
|
||||||
|
Some(self.placed(*self.indices.get(node_id)?).body())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first of the node's parts, its body last, that `find` picks something from.
|
||||||
|
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&PartTarget) -> Option<R>) -> Option<R> {
|
||||||
|
let placed = self.placed(*self.indices.get(node_id)?);
|
||||||
|
let mut found = None;
|
||||||
|
placed.parts(|target| {
|
||||||
|
if found.is_none() {
|
||||||
|
found = find(&target);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
/// Whether `point`, in node graph space, lies within the box around everything the node draws.
|
/// Whether `point`, in node graph space, lies within the box around everything the node draws.
|
||||||
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
|
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
|
||||||
let Some(index) = self.indices.get(node_id) else { return false };
|
let Some(index) = self.indices.get(node_id) else { return false };
|
||||||
@@ -62,6 +131,38 @@ impl NetworkLayout {
|
|||||||
point.cmpge(min).all() && point.cmplt(max).all()
|
point.cmpge(min).all() && point.cmplt(max).all()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn placed(&self, index: NodeIndex) -> PlacedNode<'_> {
|
||||||
|
let node_layout = self.layout.node(index);
|
||||||
|
PlacedNode {
|
||||||
|
node: &self.graph[index],
|
||||||
|
shape: &self.shapes[index.index()],
|
||||||
|
position: node_layout.position,
|
||||||
|
chain_length: node_layout.chain_length,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Measures the combined bounds of the node bodies, and the horizontal extents the imports and exports keep clear of, with redirect dots measured by their centers.
|
||||||
|
fn measure_bounds_and_clearance(&mut self) {
|
||||||
|
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
||||||
|
|
||||||
|
let mut bounds: Option<[DVec2; 2]> = None;
|
||||||
|
let mut clearance = ImportExportClearance::default();
|
||||||
|
for index in (0..self.graph.nodes.len()).map(|index| NodeIndex::from(index as u32)) {
|
||||||
|
let body = self.placed(index).body();
|
||||||
|
bounds = Some(bounds.map_or([body.min, body.max], |[min, max]| [min.min(body.min), max.max(body.max)]));
|
||||||
|
|
||||||
|
if self.graph[index].kind == NodeKind::Waypoint {
|
||||||
|
let center = (body.min.x + body.max.x) / 2.;
|
||||||
|
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
||||||
|
} else {
|
||||||
|
clearance.node_sides = widen(clearance.node_sides, body.min.x, body.max.x);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.bounds = bounds.unwrap_or_default();
|
||||||
|
self.clearance = clearance;
|
||||||
|
}
|
||||||
|
|
||||||
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
|
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
|
||||||
Some(self.layout.node(*self.indices.get(node_id)?))
|
Some(self.layout.node(*self.indices.get(node_id)?))
|
||||||
}
|
}
|
||||||
@@ -86,12 +187,14 @@ struct DragOrigin {
|
|||||||
keep_upstream: bool,
|
keep_upstream: bool,
|
||||||
node_ids: Vec<NodeId>,
|
node_ids: Vec<NodeId>,
|
||||||
indices: HashMap<NodeId, NodeIndex>,
|
indices: HashMap<NodeId, NodeIndex>,
|
||||||
|
shapes: Vec<NodeShape>,
|
||||||
start: Graph,
|
start: Graph,
|
||||||
drag: Drag,
|
drag: Drag,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DragOrigin {
|
impl DragOrigin {
|
||||||
fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
fn new(laid_out: LaidOutNodes, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
||||||
|
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
|
||||||
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
|
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
|
||||||
Self {
|
Self {
|
||||||
revision,
|
revision,
|
||||||
@@ -99,6 +202,7 @@ impl DragOrigin {
|
|||||||
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
|
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
|
||||||
node_ids,
|
node_ids,
|
||||||
indices,
|
indices,
|
||||||
|
shapes,
|
||||||
start,
|
start,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -154,7 +258,6 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
transient.layout.unload();
|
transient.layout.unload();
|
||||||
self.invalidate_positions(network_path);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
|
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
|
||||||
@@ -178,9 +281,14 @@ impl NodeNetworkInterface {
|
|||||||
.filter(|((before, after), _)| before.placement != after.placement)
|
.filter(|((before, after), _)| before.placement != after.placement)
|
||||||
.map(|((_, after), node_id)| (*node_id, after.placement))
|
.map(|((_, after), node_id)| (*node_id, after.placement))
|
||||||
.collect();
|
.collect();
|
||||||
(moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved)
|
let laid_out = LaidOutNodes {
|
||||||
|
node_ids: std::mem::take(&mut origin.node_ids),
|
||||||
|
indices: std::mem::take(&mut origin.indices),
|
||||||
|
shapes: std::mem::take(&mut origin.shapes),
|
||||||
|
};
|
||||||
|
(moved_placements, laid_out, moved)
|
||||||
});
|
});
|
||||||
let Some((moved_placements, node_ids, indices, graph)) = finished else { return };
|
let Some((moved_placements, laid_out, graph)) = finished else { return };
|
||||||
|
|
||||||
let mut stored_all = true;
|
let mut stored_all = true;
|
||||||
for (node_id, placement) in moved_placements {
|
for (node_id, placement) in moved_placements {
|
||||||
@@ -189,13 +297,7 @@ impl NodeNetworkInterface {
|
|||||||
|
|
||||||
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
|
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
|
||||||
let layout = Layout::new(&graph);
|
let layout = Layout::new(&graph);
|
||||||
network_metadata.transient_metadata.layout.store(NetworkLayout {
|
network_metadata.transient_metadata.layout.store(NetworkLayout::new(store::revision(), laid_out, graph, layout));
|
||||||
revision: store::revision(),
|
|
||||||
layout,
|
|
||||||
graph,
|
|
||||||
node_ids,
|
|
||||||
indices,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,16 +310,15 @@ impl NodeNetworkInterface {
|
|||||||
let transient = self.network_transient_mut(network_path)?;
|
let transient = self.network_transient_mut(network_path)?;
|
||||||
let drag = transient.drag.take()?;
|
let drag = transient.drag.take()?;
|
||||||
transient.layout.unload();
|
transient.layout.unload();
|
||||||
self.invalidate_positions(network_path);
|
|
||||||
Some(drag)
|
Some(drag)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
|
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
|
||||||
let mut origin = drag.origin.borrow_mut();
|
let mut origin = drag.origin.borrow_mut();
|
||||||
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
|
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
|
||||||
let (node_ids, indices, start) = self.layout_graph(network_path)?;
|
let (laid_out, start) = self.layout_graph(network_path)?;
|
||||||
let start_layout = Layout::new(&start);
|
let start_layout = Layout::new(&start);
|
||||||
*origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
*origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
||||||
}
|
}
|
||||||
origin.as_mut().map(read)
|
origin.as_mut().map(read)
|
||||||
}
|
}
|
||||||
@@ -227,8 +328,8 @@ impl NodeNetworkInterface {
|
|||||||
let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
|
let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
|
||||||
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
|
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
|
||||||
|
|
||||||
let NetworkLayout { node_ids, indices, graph, layout, .. } = cached;
|
let (laid_out, graph, layout) = cached.into_parts();
|
||||||
Some(DragOrigin::new(node_ids, indices, graph, layout, dragged, keep_upstream, revision))
|
Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
|
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
|
||||||
@@ -246,40 +347,38 @@ impl NodeNetworkInterface {
|
|||||||
};
|
};
|
||||||
if node.set_node_type(node_type) {
|
if node.set_node_type(node_type) {
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
self.invalidate_positions(network_path);
|
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
|
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
|
||||||
let (node_ids, indices, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
let (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
||||||
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
|
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
|
||||||
let (graph, mut layout) = origin.drag.moved(drag.offset);
|
let (graph, mut layout) = origin.drag.moved(drag.offset);
|
||||||
layout.snap_chains(&graph);
|
layout.snap_chains(&graph);
|
||||||
(origin.node_ids.clone(), origin.indices.clone(), graph, layout)
|
let laid_out = LaidOutNodes {
|
||||||
|
node_ids: origin.node_ids.clone(),
|
||||||
|
indices: origin.indices.clone(),
|
||||||
|
shapes: origin.shapes.clone(),
|
||||||
|
};
|
||||||
|
(laid_out, graph, layout)
|
||||||
})?,
|
})?,
|
||||||
None => {
|
None => {
|
||||||
let (node_ids, indices, graph) = self.layout_graph(network_path)?;
|
let (laid_out, graph) = self.layout_graph(network_path)?;
|
||||||
let layout = Layout::new(&graph);
|
let layout = Layout::new(&graph);
|
||||||
(node_ids, indices, graph, layout)
|
(laid_out, graph, layout)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Some(NetworkLayout {
|
Some(NetworkLayout::new(revision, laid_out, graph, layout))
|
||||||
revision,
|
|
||||||
layout,
|
|
||||||
graph,
|
|
||||||
node_ids,
|
|
||||||
indices,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, Graph)> {
|
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> {
|
||||||
let network = self.nested_network(network_path)?;
|
let network = self.nested_network(network_path)?;
|
||||||
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
|
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
|
||||||
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
|
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
|
||||||
|
|
||||||
let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?;
|
let (nodes, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?;
|
||||||
let wires = node_ids
|
let wires = node_ids
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -297,10 +396,10 @@ impl NodeNetworkInterface {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
Some((node_ids, indices, Graph { nodes, wires }))
|
Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires }))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> {
|
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> {
|
||||||
let metadata = self.node_metadata(node_id, network_path)?;
|
let metadata = self.node_metadata(node_id, network_path)?;
|
||||||
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
|
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
|
||||||
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
|
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
|
||||||
@@ -314,17 +413,40 @@ impl NodeNetworkInterface {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
|
let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
|
||||||
|
let (layer_width, name_width) = if is_layer {
|
||||||
|
self.layer_width_and_name_width(node_id, network_path).unwrap_or_default()
|
||||||
|
} else {
|
||||||
|
(0, 0.)
|
||||||
|
};
|
||||||
let (kind, size) = match (is_layer, is_redirect_dot) {
|
let (kind, size) = match (is_layer, is_redirect_dot) {
|
||||||
(true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)),
|
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)),
|
||||||
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
|
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
|
||||||
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
|
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
|
||||||
};
|
};
|
||||||
Some(Node {
|
|
||||||
|
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
|
||||||
|
let node = Node {
|
||||||
placement,
|
placement,
|
||||||
kind,
|
kind,
|
||||||
size: size.as_ivec2(),
|
size: size.as_ivec2(),
|
||||||
chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path),
|
chainable: !is_redirect_dot && !primary_output_hidden,
|
||||||
held: false,
|
held: false,
|
||||||
})
|
};
|
||||||
|
let shape = NodeShape {
|
||||||
|
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
|
||||||
|
outputs: self.number_of_outputs(node_id, network_path) as u32,
|
||||||
|
primary_input_hidden: self.document_node(node_id, network_path)?.inputs.first().is_some_and(|input| !input.is_exposed()),
|
||||||
|
primary_output_hidden,
|
||||||
|
name_width,
|
||||||
|
locked: self.is_locked(node_id, network_path),
|
||||||
|
};
|
||||||
|
Some((node, shape))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The nodes of a network in the order the layout indexes them, with what each draws beyond its size in the layout.
|
||||||
|
pub(crate) struct LaidOutNodes {
|
||||||
|
pub(crate) node_ids: Vec<NodeId>,
|
||||||
|
pub(crate) indices: HashMap<NodeId, NodeIndex>,
|
||||||
|
shapes: Vec<NodeShape>,
|
||||||
|
}
|
||||||
+6
-17
@@ -94,11 +94,9 @@ impl NodeNetworkInterface {
|
|||||||
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
|
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the outward wires and bounding box for all nodes in the encapsulating network
|
// Update the outward wires for all nodes in the encapsulating network
|
||||||
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
|
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
|
||||||
encapsulating_transient.outward_wires.unload();
|
encapsulating_transient.outward_wires.unload();
|
||||||
encapsulating_transient.all_nodes_bounding_box.unload();
|
|
||||||
encapsulating_transient.import_export_clearance.unload();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
|
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
|
||||||
@@ -141,7 +139,6 @@ impl NodeNetworkInterface {
|
|||||||
|
|
||||||
// Update the metadata for the encapsulating node
|
// Update the metadata for the encapsulating node
|
||||||
self.unload_outward_wires(encapsulating_network_path);
|
self.unload_outward_wires(encapsulating_network_path);
|
||||||
self.unload_all_nodes_bounding_box(encapsulating_network_path);
|
|
||||||
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
|
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
|
||||||
}
|
}
|
||||||
if affects_document_structure {
|
if affects_document_structure {
|
||||||
@@ -179,7 +176,6 @@ impl NodeNetworkInterface {
|
|||||||
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
|
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
|
||||||
// Update the metadata for the encapsulating node
|
// Update the metadata for the encapsulating node
|
||||||
self.unload_outward_wires(encapsulating_network_path);
|
self.unload_outward_wires(encapsulating_network_path);
|
||||||
self.unload_all_nodes_bounding_box(encapsulating_network_path);
|
|
||||||
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
|
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
|
||||||
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
|
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
|
||||||
}
|
}
|
||||||
@@ -572,8 +568,7 @@ impl NodeNetworkInterface {
|
|||||||
|
|
||||||
/// Lightweight version of `set_input` for bulk import operations.
|
/// Lightweight version of `set_input` for bulk import operations.
|
||||||
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
||||||
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
|
/// or per-node cache invalidation. Call `load_structure` once after all import wiring is complete.
|
||||||
/// `unload_all_nodes_bounding_box` once after all import wiring is complete.
|
|
||||||
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
|
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
|
||||||
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
|
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
|
||||||
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
|
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
|
||||||
@@ -673,8 +668,6 @@ impl NodeNetworkInterface {
|
|||||||
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
|
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
|
||||||
// Exposing or hiding a value input changes the node's port count
|
// Exposing or hiding a value input changes the node's port count
|
||||||
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
|
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
|
||||||
self.unload_all_nodes_bounding_box(network_path);
|
|
||||||
|
|
||||||
// A nested network draws its interior ports from the encapsulating node's inputs
|
// A nested network draws its interior ports from the encapsulating node's inputs
|
||||||
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
|
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
|
||||||
let nested_path = [network_path, &[*node_id]].concat();
|
let nested_path = [network_path, &[*node_id]].concat();
|
||||||
@@ -904,7 +897,6 @@ impl NodeNetworkInterface {
|
|||||||
|
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
}
|
}
|
||||||
self.unload_all_nodes_bounding_box(network_path);
|
|
||||||
self.unload_outward_wires(network_path);
|
self.unload_outward_wires(network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -927,7 +919,6 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
self.unload_all_nodes_bounding_box(network_path);
|
|
||||||
|
|
||||||
previous_entry
|
previous_entry
|
||||||
}
|
}
|
||||||
@@ -1092,7 +1083,6 @@ impl NodeNetworkInterface {
|
|||||||
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
|
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.unload_all_nodes_bounding_box(network_path);
|
|
||||||
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
|
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
|
||||||
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
|
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
|
||||||
return;
|
return;
|
||||||
@@ -1126,10 +1116,10 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let reconnected_offset = reconnect_to_input
|
let reconnected_offset = reconnect_to_input.as_ref().and_then(NodeInput::as_node).and_then(|reconnected| {
|
||||||
.as_ref()
|
let offset = self.relative_offset(node_id, network_path).or_else(|| self.relative_offset(&reconnected, network_path))?;
|
||||||
.and_then(NodeInput::as_node)
|
Some((reconnected, offset))
|
||||||
.and_then(|reconnected| Some((reconnected, self.relative_offset(&reconnected, network_path)?)));
|
});
|
||||||
|
|
||||||
let mut exports_fed_by_import = Vec::new();
|
let mut exports_fed_by_import = Vec::new();
|
||||||
|
|
||||||
@@ -1365,7 +1355,6 @@ impl NodeNetworkInterface {
|
|||||||
transient.layer_width.unload();
|
transient.layer_width.unload();
|
||||||
|
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
self.unload_all_nodes_bounding_box(network_path);
|
|
||||||
self.invalidate_import_export(network_path);
|
self.invalidate_import_export(network_path);
|
||||||
self.load_structure();
|
self.load_structure();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
//! The areas of a laid out node that react to the pointer, in node graph pixels. A hit test scans each node's reach, a box around
|
||||||
|
//! everything the node draws, and builds the exact parts of only the nodes it lands in.
|
||||||
|
|
||||||
|
use crate::consts::{GRID_SIZE, HALF_GRID_SIZE};
|
||||||
|
use glam::{DVec2, IVec2};
|
||||||
|
use graph_layout::{CHAIN_WIDTH, Node, NodeKind};
|
||||||
|
|
||||||
|
const GRID: f64 = GRID_SIZE as f64;
|
||||||
|
const HALF_GRID: f64 = HALF_GRID_SIZE as f64;
|
||||||
|
/// How far a port on a node's side reaches outward, away from the node, and inward over it.
|
||||||
|
const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
|
||||||
|
const SIDE_PORT_INWARD_REACH: f64 = 8.;
|
||||||
|
const SIDE_PORT_HALF_HEIGHT: f64 = 12.;
|
||||||
|
const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||||
|
/// A waypoint's body also covers the gutters beside it, so a press near it moves it unless it lands on a port.
|
||||||
|
const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
|
||||||
|
/// A waypoint's wires attach at its center but are grabbed from a round gutter on either side of it.
|
||||||
|
const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
|
||||||
|
const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
|
||||||
|
const GRIP_WIDTH: f64 = 8.;
|
||||||
|
const NAME_LEFT_OFFSET: f64 = HALF_GRID + 3. * GRID + 8.;
|
||||||
|
|
||||||
|
/// What a node draws beyond the size the layout gives it.
|
||||||
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
|
pub struct NodeShape {
|
||||||
|
/// How many inputs have a port, which doesn't count a hidden primary input.
|
||||||
|
pub inputs: u32,
|
||||||
|
pub outputs: u32,
|
||||||
|
/// Whether a node's primary input has no port, though its row is still drawn.
|
||||||
|
pub primary_input_hidden: bool,
|
||||||
|
pub primary_output_hidden: bool,
|
||||||
|
/// The width of a layer's name in pixels.
|
||||||
|
pub name_width: f64,
|
||||||
|
pub locked: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Part {
|
||||||
|
Body,
|
||||||
|
/// The input drawn in this grid row of a node, or a layer's stack input at 0 and side input at 1.
|
||||||
|
Input(u32),
|
||||||
|
Output(u32),
|
||||||
|
Visibility,
|
||||||
|
Lock,
|
||||||
|
Grip,
|
||||||
|
Name,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A rounded rectangle of a node that reacts to the pointer.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct PartTarget {
|
||||||
|
pub min: DVec2,
|
||||||
|
pub max: DVec2,
|
||||||
|
pub corner_radius: f64,
|
||||||
|
pub part: Part,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartTarget {
|
||||||
|
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
|
||||||
|
Self {
|
||||||
|
min: center - half_size,
|
||||||
|
max: center + half_size,
|
||||||
|
corner_radius,
|
||||||
|
part,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A port on the left side of a node, reaching further out than over the node.
|
||||||
|
fn input_port(center: DVec2, input: u32) -> Self {
|
||||||
|
Self {
|
||||||
|
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||||
|
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||||
|
corner_radius: 4.,
|
||||||
|
part: Part::Input(input),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A port on the right side of a node, reaching further out than over the node.
|
||||||
|
fn output_port(center: DVec2, output: u32) -> Self {
|
||||||
|
Self {
|
||||||
|
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||||
|
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||||
|
corner_radius: 4.,
|
||||||
|
part: Part::Output(output),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the rounded rectangle shares any area with the box from `min` to `max`.
|
||||||
|
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
|
||||||
|
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let radius = self.clamped_radius();
|
||||||
|
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
|
||||||
|
gap == DVec2::ZERO || gap.length_squared() < radius * radius
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `point` is inside the rounded rectangle.
|
||||||
|
pub fn contains(&self, point: DVec2) -> bool {
|
||||||
|
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let radius = self.clamped_radius();
|
||||||
|
let inner = point.clamp(self.min + radius, self.max - radius);
|
||||||
|
point.distance_squared(inner) <= radius * radius
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clamped_radius(&self) -> f64 {
|
||||||
|
self.corner_radius.min((self.max - self.min).min_element() / 2.)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A node as drawn at `position`, in grid cells, with the chain it is drawn beside if it is a layer.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct PlacedNode<'a> {
|
||||||
|
pub node: &'a Node,
|
||||||
|
pub shape: &'a NodeShape,
|
||||||
|
pub position: IVec2,
|
||||||
|
pub chain_length: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PlacedNode<'_> {
|
||||||
|
/// The body: a layer with its chain span, a node below its top connector strip, or the pill around a waypoint.
|
||||||
|
pub fn body(&self) -> PartTarget {
|
||||||
|
let top_left = self.top_left();
|
||||||
|
let size = self.node.size.as_dvec2() * GRID;
|
||||||
|
|
||||||
|
match self.node.kind {
|
||||||
|
NodeKind::Waypoint => PartTarget::around(top_left + DVec2::new(0., GRID), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
|
||||||
|
NodeKind::Layer => PartTarget {
|
||||||
|
min: top_left - DVec2::new(self.chain_width(), 0.),
|
||||||
|
max: top_left + size,
|
||||||
|
corner_radius: 10.,
|
||||||
|
part: Part::Body,
|
||||||
|
},
|
||||||
|
NodeKind::Node => {
|
||||||
|
let body_top_left = top_left + DVec2::new(0., HALF_GRID);
|
||||||
|
PartTarget {
|
||||||
|
min: body_top_left,
|
||||||
|
max: body_top_left + size - DVec2::new(0., GRID),
|
||||||
|
corner_radius: 3.,
|
||||||
|
part: Part::Body,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Calls `visit` with each part, the body last.
|
||||||
|
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
|
||||||
|
match self.node.kind {
|
||||||
|
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
|
||||||
|
NodeKind::Layer => self.layer_parts(&mut visit),
|
||||||
|
NodeKind::Node => self.node_ports(&mut visit),
|
||||||
|
}
|
||||||
|
visit(self.body());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||||
|
let center = self.top_left() + DVec2::new(0., GRID);
|
||||||
|
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
|
||||||
|
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
|
||||||
|
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||||
|
let top_left = self.top_left();
|
||||||
|
let width = self.node.size.x as f64 * GRID;
|
||||||
|
let row_center = |row: u32| GRID * (row as f64 + 1.);
|
||||||
|
|
||||||
|
let first_input_row = u32::from(self.shape.primary_input_hidden);
|
||||||
|
for row in first_input_row..first_input_row + self.shape.inputs {
|
||||||
|
visit(PartTarget::input_port(top_left + DVec2::new(0., row_center(row)), row));
|
||||||
|
}
|
||||||
|
for output in u32::from(self.shape.primary_output_hidden)..self.shape.outputs {
|
||||||
|
visit(PartTarget::output_port(top_left + DVec2::new(width, row_center(output)), output));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||||
|
let top_left = self.top_left();
|
||||||
|
let size = self.node.size.as_dvec2() * GRID;
|
||||||
|
|
||||||
|
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, size.y + 8.), STACK_PORT_HALF_SIZE, 4., Part::Input(0)));
|
||||||
|
if self.has_side_input() {
|
||||||
|
visit(PartTarget::input_port(top_left + DVec2::new(0., GRID), 1));
|
||||||
|
}
|
||||||
|
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, -8.), STACK_PORT_HALF_SIZE, 4., Part::Output(0)));
|
||||||
|
|
||||||
|
let icon_half_size = DVec2::splat(HALF_GRID);
|
||||||
|
visit(PartTarget::around(top_left + DVec2::new(size.x, GRID), icon_half_size, 3., Part::Visibility));
|
||||||
|
if self.shape.locked {
|
||||||
|
visit(PartTarget::around(top_left + DVec2::new(size.x - GRID, GRID), icon_half_size, 3., Part::Lock));
|
||||||
|
}
|
||||||
|
|
||||||
|
let icons_width = if self.shape.locked { GRID } else { 0. };
|
||||||
|
let grip_right = top_left.x + size.x - HALF_GRID - icons_width;
|
||||||
|
let handle_top = top_left.y + HALF_GRID;
|
||||||
|
let handle_bottom = top_left.y + GRID + HALF_GRID;
|
||||||
|
visit(PartTarget {
|
||||||
|
min: DVec2::new(grip_right - GRIP_WIDTH, handle_top),
|
||||||
|
max: DVec2::new(grip_right, handle_bottom),
|
||||||
|
corner_radius: 0.,
|
||||||
|
part: Part::Grip,
|
||||||
|
});
|
||||||
|
|
||||||
|
let name_left = top_left.x + NAME_LEFT_OFFSET;
|
||||||
|
let name_right = (name_left + self.shape.name_width).min(grip_right - GRIP_WIDTH);
|
||||||
|
if name_right > name_left {
|
||||||
|
visit(PartTarget {
|
||||||
|
min: DVec2::new(name_left, handle_top),
|
||||||
|
max: DVec2::new(name_right, handle_bottom),
|
||||||
|
corner_radius: 3.,
|
||||||
|
part: Part::Name,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn top_left(&self) -> DVec2 {
|
||||||
|
self.position.as_dvec2() * GRID
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_side_input(&self) -> bool {
|
||||||
|
self.shape.inputs > 1
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chain_width(&self) -> f64 {
|
||||||
|
if self.has_side_input() { (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID } else { 0. }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -802,7 +802,7 @@ impl NodeNetworkInterface {
|
|||||||
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
|
/// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
|
||||||
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
||||||
self.reference(node_id, network_path)
|
self.reference(node_id, network_path)
|
||||||
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
||||||
@@ -875,16 +875,16 @@ impl NodeNetworkInterface {
|
|||||||
node.set_widget_override(index, widget_override);
|
node.set_widget_override(index, widget_override);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
|
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||||
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||||
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
||||||
.unwrap_or_else(|| "Custom Node".to_string())
|
.unwrap_or_else(|| "Subgraph".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
||||||
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||||
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
||||||
.unwrap_or_else(|| "Custom Node".to_string())
|
.unwrap_or_else(|| "Subgraph".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||||
|
|||||||
@@ -328,7 +328,10 @@ fn field_deltas(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
||||||
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
|
deltas.push(metadata(NodeMetadataChange::placement(
|
||||||
|
¤t_metadata.node_type_metadata,
|
||||||
|
target_metadata.node_type_metadata.clone(),
|
||||||
|
)));
|
||||||
}
|
}
|
||||||
if current_metadata.display_name != target_metadata.display_name {
|
if current_metadata.display_name != target_metadata.display_name {
|
||||||
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
||||||
|
|||||||
+7
-6
@@ -229,13 +229,14 @@ impl NodeMut<'_> {
|
|||||||
|
|
||||||
/// Whether the node is displayed as a layer or a node, together with its position.
|
/// Whether the node is displayed as a layer or a node, together with its position.
|
||||||
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
|
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
|
||||||
let changed = self.metadata.node_type_metadata != node_type;
|
if self.metadata.node_type_metadata == node_type {
|
||||||
self.metadata.node_type_metadata = node_type;
|
return false;
|
||||||
if changed {
|
|
||||||
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
|
|
||||||
self.deltas.metadata(change);
|
|
||||||
}
|
}
|
||||||
changed
|
|
||||||
|
let change = NodeMetadataChange::placement(&self.metadata.node_type_metadata, node_type.clone());
|
||||||
|
self.metadata.node_type_metadata = node_type;
|
||||||
|
self.deltas.metadata(change);
|
||||||
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.
|
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.
|
||||||
|
|||||||
@@ -200,10 +200,11 @@ impl NodeNetworkInterface {
|
|||||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update how far each layer's effects paint past its content.
|
/// Update how far each layer's effects paint past its content, and the frames they paint anywhere in.
|
||||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
|
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>, new_layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>) {
|
||||||
self.document_metadata.mark_changed();
|
self.document_metadata.mark_changed();
|
||||||
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
||||||
|
self.document_metadata.layer_effects_frames = new_layer_effects_frames;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,14 @@ pub struct NodeTemplate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NodeTemplate {
|
impl NodeTemplate {
|
||||||
|
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
|
||||||
|
pub fn empty_subgraph() -> Self {
|
||||||
|
Self {
|
||||||
|
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
||||||
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
||||||
self.inputs.get(P::INDEX)
|
self.inputs.get(P::INDEX)
|
||||||
|
|||||||
@@ -3,12 +3,7 @@ use graphene_std::ParameterRef;
|
|||||||
use graphene_std::vector::misc::dvec2_to_point;
|
use graphene_std::vector::misc::dvec2_to_point;
|
||||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||||
|
|
||||||
/// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets.
|
/// An axis-aligned rectangle spanning the two opposite corners, with per-corner radii ordered top left, top right, bottom right, bottom left.
|
||||||
pub fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
|
||||||
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(DEFAULT_ACCURACY)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Same as [`rectangle_path`] but with per-corner radii ordered top left, top right, bottom right, bottom left.
|
|
||||||
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
|
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
|
||||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||||
if radii.iter().all(|radius| *radius == 0.) {
|
if radii.iter().all(|radius| *radius == 0.) {
|
||||||
@@ -19,16 +14,6 @@ pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -
|
|||||||
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
|
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ellipse inscribed in the box spanning the two opposite corners.
|
|
||||||
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
|
||||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
|
||||||
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
|
|
||||||
|
|
||||||
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
|
|
||||||
path.close_path();
|
|
||||||
path
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
|
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
|
||||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct ChainNodeCopy {
|
pub struct ChainNodeCopy {
|
||||||
@@ -292,13 +277,6 @@ pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
|
|||||||
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
|
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The corners of the click target for a layer's top output or bottom input, which reaches only 8 px toward the connector it faces in a stack.
|
|
||||||
fn stack_port_bounds(center: DVec2) -> [DVec2; 2] {
|
|
||||||
const HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
|
||||||
|
|
||||||
[center - HALF_SIZE, center + HALF_SIZE]
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
|
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
|
||||||
const CORNER_RADIUS: f64 = 4.;
|
const CORNER_RADIUS: f64 = 4.;
|
||||||
|
|
||||||
@@ -332,13 +310,6 @@ impl Ports {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn click_targets(&self) -> impl Iterator<Item = &ClickTarget> {
|
|
||||||
self.input_ports
|
|
||||||
.iter()
|
|
||||||
.map(|(_, click_target)| click_target)
|
|
||||||
.chain(self.output_ports.iter().map(|(_, click_target)| click_target))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
|
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
|
||||||
self.input_ports.iter()
|
self.input_ports.iter()
|
||||||
}
|
}
|
||||||
@@ -348,51 +319,15 @@ impl Ports {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
||||||
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true)));
|
self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true))));
|
||||||
self.input_anchors.push((input_index, center));
|
self.input_anchors.push((input_index, center));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
|
|
||||||
self.input_ports.push((input_index, click_target));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
|
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
|
||||||
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false)));
|
self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false))));
|
||||||
self.output_anchors.push((output_index, center));
|
self.output_anchors.push((output_index, center));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
|
|
||||||
self.output_ports.push((output_index, click_target));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn insert_node_input(&mut self, input_index: usize, row_index: usize, node_top_left: DVec2) {
|
|
||||||
// The center of the click target is always 24 px down from the top left corner of the node
|
|
||||||
let center = node_top_left + DVec2::new(0., 24. + 24. * row_index as f64);
|
|
||||||
self.insert_input_port_at_center(input_index, center);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn insert_node_output(&mut self, output_index: usize, node_top_left: DVec2) {
|
|
||||||
// The center of the click target is always 24 px down from the top left corner of the node
|
|
||||||
let center = node_top_left + DVec2::new(5. * 24., 24. + 24. * output_index as f64);
|
|
||||||
self.insert_output_port_at_center(output_index, center);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
|
|
||||||
// The primary input sits beneath the layer's thumbnail, and the secondary input on its left side
|
|
||||||
if input_index == 0 {
|
|
||||||
let center = node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.);
|
|
||||||
self.insert_custom_input_port(input_index, port_click_target(stack_port_bounds(center)));
|
|
||||||
} else {
|
|
||||||
self.insert_input_port_at_center(input_index, node_top_left + DVec2::new(0., 24. * 1.));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
|
|
||||||
// The center of the click target is 8 px above the layer, over its thumbnail
|
|
||||||
let center = node_top_left + DVec2::new(2. * 24., -8.);
|
|
||||||
self.insert_custom_output_port(0, port_click_target(stack_port_bounds(center)));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
|
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
|
||||||
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||||
}
|
}
|
||||||
@@ -401,37 +336,12 @@ impl Ports {
|
|||||||
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds the input and output of a redirect dot. Its wires both attach at its center, but they're grabbed from the gutters on either side of its body.
|
|
||||||
pub(crate) fn insert_dot_ports(&mut self, center: DVec2) {
|
|
||||||
const GUTTER_OFFSET: f64 = 10.;
|
|
||||||
const GUTTER_RADIUS: f64 = 5.;
|
|
||||||
|
|
||||||
let gutter = |x_offset: f64| {
|
|
||||||
let gutter_center = center + DVec2::new(x_offset, 0.);
|
|
||||||
ClickTarget::new_with_path(ellipse_path(gutter_center - DVec2::splat(GUTTER_RADIUS), gutter_center + DVec2::splat(GUTTER_RADIUS)), 0.)
|
|
||||||
};
|
|
||||||
self.insert_custom_input_port(0, gutter(-GUTTER_OFFSET));
|
|
||||||
self.insert_custom_output_port(0, gutter(GUTTER_OFFSET));
|
|
||||||
self.input_anchors.push((0, center));
|
|
||||||
self.output_anchors.push((0, center));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
|
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
|
||||||
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
||||||
return Some(*anchor);
|
|
||||||
}
|
|
||||||
self.input_ports
|
|
||||||
.iter()
|
|
||||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
|
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
|
||||||
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
||||||
return Some(*anchor);
|
|
||||||
}
|
|
||||||
self.output_ports
|
|
||||||
.iter()
|
|
||||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -747,16 +657,12 @@ impl<T> TransientCache<T> {
|
|||||||
#[derive(Debug, Default, Clone)]
|
#[derive(Debug, Default, Clone)]
|
||||||
pub struct NodeNetworkTransientMetadata {
|
pub struct NodeNetworkTransientMetadata {
|
||||||
pub selected_nodes: SelectedNodes,
|
pub selected_nodes: SelectedNodes,
|
||||||
/// Cache for the bounding box around all nodes in node graph space.
|
|
||||||
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
|
|
||||||
/// Cache for what the imports and exports keep their distance from, unloaded along with `all_nodes_bounding_box`.
|
|
||||||
pub(crate) import_export_clearance: TransientCache<ImportExportClearance>,
|
|
||||||
/// Cache for all outward wire connections
|
/// Cache for all outward wire connections
|
||||||
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
|
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
|
||||||
pub(crate) layout: TransientCache<NetworkLayout>,
|
pub(crate) layout: TransientCache<NetworkLayout>,
|
||||||
pub(crate) drag: Option<super::layout_pass::DragPreview>,
|
pub(crate) drag: Option<super::layout_pass::DragPreview>,
|
||||||
/// All export connector click targets
|
/// The import and export connector click targets, with the generation of the layout they were placed by.
|
||||||
pub(crate) import_export_ports: TransientCache<Ports>,
|
pub(crate) import_export_ports: TransientCache<(u64, Ports)>,
|
||||||
|
|
||||||
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
|
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
|
||||||
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
|
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
|
||||||
@@ -1173,40 +1079,8 @@ impl From<LegacyNodePosition> for NodePosition {
|
|||||||
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
|
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
|
||||||
#[derive(Debug, Default, Clone)]
|
#[derive(Debug, Default, Clone)]
|
||||||
pub struct DocumentNodeTransientMetadata {
|
pub struct DocumentNodeTransientMetadata {
|
||||||
/// Width in grid units from the left edge of the layer's thumbnail to its left end, cached since text measurement is slow. Only loaded for layers.
|
/// Width in grid units from the left edge of the layer's thumbnail to its left end, and the measured width of its name, cached since text measurement is slow. Only loaded for layers.
|
||||||
pub(crate) layer_width: TransientCache<u32>,
|
pub(crate) layer_width: TransientCache<(u32, f64)>,
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct DocumentNodeClickTargets {
|
|
||||||
/// In order to keep the displayed position of the node in sync with the click target, the displayed position of a node is derived from the top left of the click target
|
|
||||||
/// Ensure node_click_target is kept in sync when modifying a node property that changes its size. Currently this is alias, inputs, is_layer, and metadata
|
|
||||||
pub node_click_target: ClickTarget,
|
|
||||||
/// Stores all port click targets in node graph space.
|
|
||||||
pub port_click_targets: Ports,
|
|
||||||
// Click targets that are specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
|
|
||||||
pub node_type_metadata: NodeTypeClickTargets,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub enum NodeTypeClickTargets {
|
|
||||||
Layer(Box<LayerClickTargets>),
|
|
||||||
Node, // No transient click targets are stored exclusively for nodes
|
|
||||||
}
|
|
||||||
|
|
||||||
/// All fields in TransientLayerMetadata should automatically be updated by using the network interface API
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct LayerClickTargets {
|
|
||||||
/// Cache for all visibility buttons. Should be automatically updated when update_click_target is called
|
|
||||||
pub visibility_click_target: ClickTarget,
|
|
||||||
/// Cache for the lock icon button, only present when the layer is locked.
|
|
||||||
pub lock_click_target: Option<ClickTarget>,
|
|
||||||
/// Cache for the grip icon, which is next to the visibility button.
|
|
||||||
pub grip_click_target: ClickTarget,
|
|
||||||
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
|
|
||||||
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
|
|
||||||
/// `None` for layers whose display name is empty.
|
|
||||||
pub name_click_target: Option<ClickTarget>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
|||||||
@@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
|||||||
.ok()
|
.ok()
|
||||||
.flatten()
|
.flatten()
|
||||||
.map(|identifier| identifier.implementation_name_from_identifier())
|
.map(|identifier| identifier.implementation_name_from_identifier())
|
||||||
.unwrap_or("Custom Node".to_string())
|
.unwrap_or("Subgraph".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||||
use glam::{DVec2, IVec2};
|
use glam::{DVec2, IVec2};
|
||||||
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
|
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
|
||||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, Point, Shape};
|
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
|
||||||
|
|
||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||||
@@ -125,23 +125,27 @@ fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -
|
|||||||
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
|
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The center line that cleaves a thick layer-stack wire. Its ends reach past the wire (1.5px toward the output
|
/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the
|
||||||
/// connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
|
/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
|
||||||
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> BezPath {
|
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
|
||||||
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
|
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
|
||||||
return BezPath::new();
|
return BezPath::new();
|
||||||
}
|
}
|
||||||
|
|
||||||
// The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots
|
let wire = build_vector_wire(output_position, input_position, true, true, graph_wire_style);
|
||||||
let sign = (input_position.y - output_position.y).signum();
|
let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else {
|
||||||
let output_trim = 1.5;
|
return BezPath::new();
|
||||||
let input_trim = 1.;
|
};
|
||||||
let start = output_position + DVec2::new(0., output_trim * sign);
|
|
||||||
let end = input_position - DVec2::new(0., input_trim * sign);
|
|
||||||
|
|
||||||
|
// The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead
|
||||||
|
let sign = (input_position.y - output_position.y).signum();
|
||||||
let mut center_line = BezPath::new();
|
let mut center_line = BezPath::new();
|
||||||
center_line.move_to(dvec2_to_point(start));
|
center_line.move_to(start - Vec2::new(0., 1.5 * sign));
|
||||||
center_line.line_to(dvec2_to_point(end));
|
center_line.line_to(start);
|
||||||
|
for element in wire.elements().iter().skip(1) {
|
||||||
|
center_line.push(*element);
|
||||||
|
}
|
||||||
|
center_line.line_to(end + Vec2::new(0., 2. * sign));
|
||||||
center_line
|
center_line
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -580,7 +584,7 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use kurbo::{Affine, Vec2};
|
use kurbo::{Affine, ParamCurveNearest};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() {
|
fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() {
|
||||||
@@ -603,4 +607,30 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_center_line_of_a_stack_wire_runs_inside_it() {
|
||||||
|
let ends = [
|
||||||
|
(DVec2::new(48., 12.), DVec2::new(48., 84.)),
|
||||||
|
(DVec2::new(240., 12.), DVec2::new(48., 132.)),
|
||||||
|
(DVec2::new(48., 0.), DVec2::new(0., 27.)),
|
||||||
|
];
|
||||||
|
let half_wire_width = 4.;
|
||||||
|
|
||||||
|
for (output, input) in ends {
|
||||||
|
for style in [GraphWireStyle::Direct, GraphWireStyle::GridAligned] {
|
||||||
|
let wire = build_vector_wire(output, input, true, true, style);
|
||||||
|
let center_line = build_thick_wire_center_line(output, input, true, true, style);
|
||||||
|
|
||||||
|
let samples = center_line.segments().flat_map(|segment| (0..=10).map(move |step| segment.eval(f64::from(step) / 10.)));
|
||||||
|
for sample in samples {
|
||||||
|
let distance = wire
|
||||||
|
.segments()
|
||||||
|
.map(|segment| segment.nearest(sample, DEFAULT_ACCURACY).distance_sq.sqrt())
|
||||||
|
.fold(f64::INFINITY, f64::min);
|
||||||
|
assert!(distance <= half_wire_width, "the center line from {output} to {input} drawn {style:?} leaves its wire at {sample:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1295,7 +1295,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
|
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
|
||||||
// Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
// Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
||||||
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
|
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
|
||||||
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
|
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
|
||||||
.network_interface
|
.network_interface
|
||||||
@@ -1771,6 +1771,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
migrate_custom_node_subgraphs(document);
|
||||||
|
|
||||||
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
|
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
|
||||||
let nodes = document
|
let nodes = document
|
||||||
.network_interface
|
.network_interface
|
||||||
@@ -1899,8 +1901,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
|
// The primary input comes before the Clip toggle where there is one, and the noise settings follow it in the current inputs' order
|
||||||
if let Some(clip_index) = clip_index {
|
if let Some(clip_index) = clip_index {
|
||||||
|
if *clip_index == 1
|
||||||
|
&& let Some(primary) = old_inputs.first()
|
||||||
|
{
|
||||||
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), primary.clone(), network_path);
|
||||||
|
}
|
||||||
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
|
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
|
||||||
}
|
}
|
||||||
@@ -1912,6 +1919,11 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
|
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
|
||||||
move_mandelbrot_to_old_origin(document, node_id, network_path);
|
move_mandelbrot_to_old_origin(document, node_id, network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Only a Noise Pattern old enough to have the Clip toggle is surely from before it wrote gamma-encoded grays
|
||||||
|
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
|
||||||
|
read_noise_through_gamma_correction(document, node_id, network_path);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||||
@@ -1984,6 +1996,9 @@ fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_
|
|||||||
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
|
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
|
||||||
.cloned()
|
.cloned()
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
if downstream_consumers.is_empty() {
|
||||||
|
return Some(());
|
||||||
|
}
|
||||||
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
|
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
|
||||||
|
|
||||||
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
|
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
|
||||||
@@ -2085,6 +2100,48 @@ fn move_mandelbrot_to_old_origin(document: &mut DocumentMessageHandler, mandelbr
|
|||||||
Some(())
|
Some(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Keeps an old Noise Pattern's look now that it writes its value as the gray at that gamma-encoded level rather than as linear light,
|
||||||
|
/// with a Gamma Correction at its default gamma of 2.2 turning the new gray back into about the old one wherever the pattern was read.
|
||||||
|
fn read_noise_through_gamma_correction(document: &mut DocumentMessageHandler, noise_node_id: &NodeId, network_path: &[NodeId]) -> Option<()> {
|
||||||
|
let downstream_consumers: Vec<InputConnector> = document
|
||||||
|
.network_interface
|
||||||
|
.outward_wires(network_path)
|
||||||
|
.and_then(|wires| wires.get(&OutputConnector::node(*noise_node_id, 0)))
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default();
|
||||||
|
if downstream_consumers.is_empty() {
|
||||||
|
return Some(());
|
||||||
|
}
|
||||||
|
let was_in_chain = document.network_interface.is_chain(noise_node_id, network_path);
|
||||||
|
let position = document.network_interface.position(noise_node_id, network_path);
|
||||||
|
|
||||||
|
let gamma_correction_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER))?.default_node_template();
|
||||||
|
let gamma_correction_id = NodeId::new();
|
||||||
|
document.network_interface.insert_node(gamma_correction_id, gamma_correction_template, network_path);
|
||||||
|
|
||||||
|
document
|
||||||
|
.network_interface
|
||||||
|
.set_input(&InputConnector::node_at_index(gamma_correction_id, 0), NodeInput::node(*noise_node_id, 0), network_path);
|
||||||
|
for consumer in &downstream_consumers {
|
||||||
|
document.network_interface.set_input(consumer, NodeInput::node(gamma_correction_id, 0), network_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
|
||||||
|
if !document.network_interface.is_visible(noise_node_id, network_path) {
|
||||||
|
document.network_interface.set_visibility(&gamma_correction_id, network_path, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The Gamma Correction takes the pattern's place, and the pattern moves before it
|
||||||
|
if was_in_chain {
|
||||||
|
document.network_interface.force_set_upstream_to_chain(&gamma_correction_id, network_path);
|
||||||
|
} else if let Some(position) = position {
|
||||||
|
document.network_interface.set_absolute_position(&gamma_correction_id, position, network_path);
|
||||||
|
document.network_interface.set_absolute_position(noise_node_id, position + IVec2::new(-7, 0), network_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||||
@@ -2410,6 +2467,26 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
inputs_count += 1;
|
inputs_count += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 'Outer Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth
|
||||||
|
if reference == DefinitionIdentifier::ProtoNode(outer_glow::IDENTIFIER) && inputs_count == 8 {
|
||||||
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
|
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||||
|
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
|
||||||
|
for (index, input) in old_inputs.into_iter().take(8).enumerate() {
|
||||||
|
let index = if index == 7 { 10 } else { index };
|
||||||
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||||
|
}
|
||||||
|
let smooth = [TaggedValue::Number(0.), TaggedValue::Number(0.), TaggedValue::Integer(0)];
|
||||||
|
for (index, value) in (7..).zip(smooth) {
|
||||||
|
document
|
||||||
|
.network_interface
|
||||||
|
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(value, false), network_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
inputs_count = 11;
|
||||||
|
}
|
||||||
|
|
||||||
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
|
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
|
||||||
// 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_form, _has_transform, _transform).
|
// 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_form, _has_transform, _transform).
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
|
||||||
@@ -2988,6 +3065,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
inputs_count = 3;
|
inputs_count = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Make Opaque gained a Strength input, set to 100% to keep making the content fully opaque
|
||||||
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::make_opaque::IDENTIFIER) && inputs_count == 1 {
|
||||||
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
|
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||||
|
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||||
|
document
|
||||||
|
.network_interface
|
||||||
|
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(100.), false), network_path);
|
||||||
|
inputs_count = 2;
|
||||||
|
}
|
||||||
|
|
||||||
// The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on
|
// The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 {
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
@@ -4045,6 +4134,25 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
|||||||
Some(())
|
Some(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button.
|
||||||
|
/// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed.
|
||||||
|
fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) {
|
||||||
|
let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into()));
|
||||||
|
let subgraphs: Vec<(NodeId, Vec<NodeId>)> = document
|
||||||
|
.network_interface
|
||||||
|
.document_network()
|
||||||
|
.recursive_nodes()
|
||||||
|
.filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node)
|
||||||
|
.map(|(node_id, _, path)| (*node_id, path))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
for (node_id, network_path) in subgraphs {
|
||||||
|
reset_default_display_name(document, &node_id, &network_path, "Custom Node");
|
||||||
|
reset_default_display_name(document, &node_id, &network_path, "Untitled Node");
|
||||||
|
document.network_interface.set_reference(&node_id, &network_path, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
||||||
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
||||||
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||||
@@ -4597,6 +4705,45 @@ mod tests {
|
|||||||
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
|
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() {
|
||||||
|
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
|
||||||
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||||
|
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
let from_catalog = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
|
let document = editor.active_document_mut();
|
||||||
|
let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else {
|
||||||
|
panic!("the subgraph should name a definitions table entry")
|
||||||
|
};
|
||||||
|
|
||||||
|
// A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made
|
||||||
|
let from_merging = NodeId::new();
|
||||||
|
let instance = NodeTemplate {
|
||||||
|
implementation: NodeTemplateImplementation::Definition(shared),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
document.network_interface.insert_node(from_merging, instance, &[]);
|
||||||
|
document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into()));
|
||||||
|
document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]);
|
||||||
|
document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]);
|
||||||
|
let serialized = document.serialize_document();
|
||||||
|
|
||||||
|
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||||
|
let interface = &opened.network_interface;
|
||||||
|
for node_id in [from_catalog, from_merging] {
|
||||||
|
assert!(
|
||||||
|
matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))),
|
||||||
|
"the subgraph should still exist"
|
||||||
|
);
|
||||||
|
assert_eq!(interface.reference(&node_id, &[]), None);
|
||||||
|
assert_eq!(interface.display_name(&node_id, &[]), "Subgraph");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn a_rasterize_node_on_the_export_compiles() {
|
async fn a_rasterize_node_on_the_export_compiles() {
|
||||||
use crate::test_utils::test_prelude::*;
|
use crate::test_utils::test_prelude::*;
|
||||||
@@ -5769,6 +5916,10 @@ mod tests {
|
|||||||
let mut document = DocumentMessageHandler::default();
|
let mut document = DocumentMessageHandler::default();
|
||||||
for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
|
for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
|
||||||
let mut inputs = template(identifier).inputs;
|
let mut inputs = template(identifier).inputs;
|
||||||
|
// Outer Glow's grain inputs came later, ahead of its contour
|
||||||
|
if *identifier == outer_glow::IDENTIFIER {
|
||||||
|
inputs.drain(7..10);
|
||||||
|
}
|
||||||
inputs.remove(2);
|
inputs.remove(2);
|
||||||
inputs.truncate(*count);
|
inputs.truncate(*count);
|
||||||
for (input_index, input) in inputs.iter_mut().enumerate() {
|
for (input_index, input) in inputs.iter_mut().enumerate() {
|
||||||
@@ -5792,7 +5943,9 @@ mod tests {
|
|||||||
let name = identifier.as_str();
|
let name = identifier.as_str();
|
||||||
assert_eq!(node.inputs.len(), template(identifier).inputs.len(), "{name} should take the current shape");
|
assert_eq!(node.inputs.len(), template(identifier).inputs.len(), "{name} should take the current shape");
|
||||||
assert_eq!(node.inputs[2], NodeInput::value(TaggedValue::BlendMode(BlendMode::Normal), false), "{name} should blend normally");
|
assert_eq!(node.inputs[2], NodeInput::value(TaggedValue::BlendMode(BlendMode::Normal), false), "{name} should blend normally");
|
||||||
for (input_index, input) in node.inputs.iter().enumerate().take(count + 1).skip(3) {
|
// Outer Glow's contour, its last saved input, moves past its grain to the end
|
||||||
|
let shifted = if *identifier == outer_glow::IDENTIFIER { *count } else { count + 1 };
|
||||||
|
for (input_index, input) in node.inputs.iter().enumerate().take(shifted).skip(3) {
|
||||||
if let Some(TaggedValue::Number(number)) = input.as_value() {
|
if let Some(TaggedValue::Number(number)) = input.as_value() {
|
||||||
assert_eq!(*number, (input_index - 1) as f64, "{name} should move its input {} past the blend mode", input_index - 1);
|
assert_eq!(*number, (input_index - 1) as f64, "{name} should move its input {} past the blend mode", input_index - 1);
|
||||||
}
|
}
|
||||||
@@ -5800,6 +5953,69 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outer_glows_from_before_their_grain_open_smooth() {
|
||||||
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||||
|
use graphene_std::blending_nodes::effects::outer_glow;
|
||||||
|
|
||||||
|
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(outer_glow::IDENTIFIER)).expect("the Outer Glow definition should exist");
|
||||||
|
let template = definition.default_node_template();
|
||||||
|
|
||||||
|
// One saved before its blend mode and one saved after it, but before its grain
|
||||||
|
let mut document = DocumentMessageHandler::default();
|
||||||
|
for (index, before_blend_mode) in [true, false].into_iter().enumerate() {
|
||||||
|
let mut inputs = template.inputs.clone();
|
||||||
|
inputs.drain(7..10);
|
||||||
|
if before_blend_mode {
|
||||||
|
inputs.remove(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
let node_template = NodeTemplate {
|
||||||
|
implementation: NodeTemplateImplementation::ProtoNode(outer_glow::IDENTIFIER),
|
||||||
|
inputs,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
document.network_interface.insert_node(NodeId(index as u64 + 1), node_template, &[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||||
|
|
||||||
|
let smooth = [TaggedValue::Number(0.), TaggedValue::Number(0.), TaggedValue::Integer(0)].map(|value| NodeInput::value(value, false));
|
||||||
|
for index in 0..2 {
|
||||||
|
let node = opened.network_interface.document_node(&NodeId(index + 1), &[]).expect("the node should still exist");
|
||||||
|
assert_eq!(node.inputs.len(), 11);
|
||||||
|
assert_eq!(node.inputs[7..10], smooth, "the glow should open without grain");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||||
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||||
|
use graphene_std::raster_nodes::adjustments::make_opaque;
|
||||||
|
|
||||||
|
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(make_opaque::IDENTIFIER)).expect("the Make Opaque definition should exist");
|
||||||
|
let mut inputs = definition.default_node_template().inputs;
|
||||||
|
inputs.truncate(1);
|
||||||
|
let content = inputs.clone();
|
||||||
|
|
||||||
|
// Saved with its content alone, before its strength
|
||||||
|
let mut document = DocumentMessageHandler::default();
|
||||||
|
let node_template = NodeTemplate {
|
||||||
|
implementation: NodeTemplateImplementation::ProtoNode(make_opaque::IDENTIFIER),
|
||||||
|
inputs,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
document.network_interface.insert_node(NodeId(1), node_template, &[]);
|
||||||
|
|
||||||
|
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||||
|
|
||||||
|
let node = opened.network_interface.document_node(&NodeId(1), &[]).expect("the node should still exist");
|
||||||
|
assert_eq!(node.inputs[..1], content, "Make Opaque should keep its content");
|
||||||
|
assert_eq!(node.inputs[1..], [NodeInput::value(TaggedValue::Number(100.), false)], "Make Opaque should open at full strength");
|
||||||
|
}
|
||||||
|
|
||||||
// Serialize, Sample Image, and Empty Image nodes open as As String, Passthrough, and Image nodes, keeping their wires and Serialize's stored text
|
// Serialize, Sample Image, and Empty Image nodes open as As String, Passthrough, and Image nodes, keeping their wires and Serialize's stored text
|
||||||
#[test]
|
#[test]
|
||||||
fn removed_nodes_open_as_their_stand_ins() {
|
fn removed_nodes_open_as_their_stand_ins() {
|
||||||
@@ -6351,6 +6567,9 @@ mod tests {
|
|||||||
assert_eq!(value(read, 1), Some(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5))));
|
assert_eq!(value(read, 1), Some(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5))));
|
||||||
read = upstream(read, 0).expect("the origin transform should read the pattern");
|
read = upstream(read, 0).expect("the origin transform should read the pattern");
|
||||||
}
|
}
|
||||||
|
if pattern == noise {
|
||||||
|
read = upstream(read, 0).expect("the Gamma Correction should read the pattern");
|
||||||
|
}
|
||||||
assert_eq!(read, pattern);
|
assert_eq!(read, pattern);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6364,6 +6583,130 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Noise Pattern once wrote its value as linear light, so whatever read an old one reads it through a Gamma Correction giving back about the old gray
|
||||||
|
#[tokio::test]
|
||||||
|
async fn old_noise_patterns_are_read_through_a_gamma_correction() {
|
||||||
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||||
|
use graphene_std::raster_nodes::adjustments::gamma_correction;
|
||||||
|
use graphene_std::raster_nodes::std_nodes::noise_pattern;
|
||||||
|
use graphene_std::transform_nodes::transform;
|
||||||
|
|
||||||
|
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
|
||||||
|
// Old patterns read by two nodes and the export, in a layer's chain, disabled, and unread, plus a current one in the new look
|
||||||
|
let read_thrice = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 0).await;
|
||||||
|
let readers = [
|
||||||
|
editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 0).await,
|
||||||
|
editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 5).await,
|
||||||
|
];
|
||||||
|
let chained = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 15, 20).await;
|
||||||
|
let layer = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 20, 20).await;
|
||||||
|
let disabled = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 30).await;
|
||||||
|
let disabled_reader = editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 30).await;
|
||||||
|
let disabled_primary = editor.create_node_by_name_at(proto(transform::IDENTIFIER), -10, 30).await;
|
||||||
|
let unread = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 40).await;
|
||||||
|
let unread_clipped = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 45).await;
|
||||||
|
let current = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 50).await;
|
||||||
|
let current_reader = editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 50).await;
|
||||||
|
|
||||||
|
let interface = &mut editor.active_document_mut().network_interface;
|
||||||
|
for reader in readers {
|
||||||
|
interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(read_thrice, 0), &[]);
|
||||||
|
}
|
||||||
|
interface.create_wire(&OutputConnector::primary_output(read_thrice), &InputConnector::Export(0), &[]);
|
||||||
|
interface.set_to_node_or_layer(&layer, &[], true);
|
||||||
|
interface.create_wire(&OutputConnector::primary_output(chained), &InputConnector::layer_secondary_input(layer), &[]);
|
||||||
|
interface.set_input(&InputConnector::node_at_index(disabled_reader, 0), NodeInput::node(disabled, 0), &[]);
|
||||||
|
interface.set_input(&InputConnector::node_at_index(disabled, 0), NodeInput::node(disabled_primary, 0), &[]);
|
||||||
|
interface.set_visibility(&disabled, &[], false);
|
||||||
|
interface.set_input(&InputConnector::node_at_index(current_reader, 0), NodeInput::node(current, 0), &[]);
|
||||||
|
assert!(interface.is_chain(&chained, &[]), "the pattern should be in the layer's chain: fixture is wrong");
|
||||||
|
|
||||||
|
// A pattern exported from a subgraph
|
||||||
|
let subgraph = editor.create_empty_subgraph_at(0, 60).await;
|
||||||
|
editor.enter_editable_network(subgraph).await;
|
||||||
|
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
||||||
|
let nested = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 10, 0).await;
|
||||||
|
editor
|
||||||
|
.handle_message(NodeGraphMessage::CreateWire {
|
||||||
|
output_connector: OutputConnector::primary_output(nested),
|
||||||
|
input_connector: InputConnector::Export(0),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Save the old patterns as an older editor did, with their Clip toggle off except on one of the unread ones
|
||||||
|
let document = editor.active_document_mut();
|
||||||
|
let old_patterns = [
|
||||||
|
(read_thrice, vec![], false),
|
||||||
|
(chained, vec![], false),
|
||||||
|
(disabled, vec![], false),
|
||||||
|
(unread, vec![], false),
|
||||||
|
(unread_clipped, vec![], true),
|
||||||
|
(nested, vec![subgraph], false),
|
||||||
|
];
|
||||||
|
for (node_id, network_path, clip) in old_patterns {
|
||||||
|
let mut inputs = document.network_interface.document_node(&node_id, &network_path).unwrap().inputs.clone();
|
||||||
|
inputs.insert(1, NodeInput::value(TaggedValue::Bool(clip), false));
|
||||||
|
let mut legacy = NodeTemplate { inputs, ..Default::default() };
|
||||||
|
legacy.normalize_input_metadata();
|
||||||
|
document.network_interface.replace_inputs(&node_id, &network_path, &mut legacy);
|
||||||
|
}
|
||||||
|
let serialized = document.serialize_document();
|
||||||
|
|
||||||
|
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||||
|
let interface = &opened.network_interface;
|
||||||
|
let upstream = |connector: InputConnector, network_path: &[NodeId]| interface.upstream_output_connector(&connector, network_path).and_then(|output| output.node_id());
|
||||||
|
|
||||||
|
// The Gamma Correction a reader of `pattern` reads instead, at the default gamma and reading the pattern
|
||||||
|
let gamma_correction_between = |pattern: NodeId, reader: InputConnector, network_path: &[NodeId]| {
|
||||||
|
let inserted = upstream(reader, network_path).expect("the reader should read a node");
|
||||||
|
assert_eq!(interface.reference(&inserted, network_path), Some(proto(gamma_correction::IDENTIFIER)));
|
||||||
|
|
||||||
|
let node = interface.document_node(&inserted, network_path).unwrap();
|
||||||
|
assert_eq!(node.input_value(gamma_correction::GammaInput), Some(&TaggedValue::Number(2.2)));
|
||||||
|
assert_eq!(node.input_value(gamma_correction::InverseInput), Some(&TaggedValue::Bool(false)));
|
||||||
|
assert_eq!(upstream(InputConnector::node_at_index(inserted, 0), network_path), Some(pattern));
|
||||||
|
inserted
|
||||||
|
};
|
||||||
|
|
||||||
|
// Every reader of the pattern read three times shares one Gamma Correction, which takes the pattern's place with the pattern before it
|
||||||
|
let shared = gamma_correction_between(read_thrice, InputConnector::Export(0), &[]);
|
||||||
|
for reader in readers {
|
||||||
|
assert_eq!(upstream(InputConnector::node_at_index(reader, 0), &[]), Some(shared));
|
||||||
|
}
|
||||||
|
let position = |node_id: NodeId| interface.position(&node_id, &[]).expect("the node should have a position");
|
||||||
|
assert_eq!(position(read_thrice) + IVec2::new(7, 0), position(shared));
|
||||||
|
|
||||||
|
let in_chain = gamma_correction_between(chained, InputConnector::layer_secondary_input(layer), &[]);
|
||||||
|
assert!(interface.is_chain(&in_chain, &[]) && interface.is_chain(&chained, &[]), "the layer's chain should hold both");
|
||||||
|
|
||||||
|
// Only a disabled pattern's Gamma Correction is disabled too, and the pattern keeps the primary input it passes through
|
||||||
|
let behind_disabled = gamma_correction_between(disabled, InputConnector::node_at_index(disabled_reader, 0), &[]);
|
||||||
|
assert!(!interface.is_visible(&behind_disabled, &[]) && interface.is_visible(&shared, &[]));
|
||||||
|
assert_eq!(upstream(InputConnector::node_at_index(disabled, 0), &[]), Some(disabled_primary));
|
||||||
|
|
||||||
|
gamma_correction_between(nested, InputConnector::Export(0), &[subgraph]);
|
||||||
|
assert_eq!(upstream(InputConnector::node_at_index(current_reader, 0), &[]), Some(current));
|
||||||
|
|
||||||
|
// Unread patterns gain nothing reading them, clipped or not
|
||||||
|
let read = |pattern: NodeId| interface.document_network().nodes.values().any(|node| node.inputs.iter().any(|input| input.as_node() == Some(pattern)));
|
||||||
|
assert!(!read(unread) && !read(unread_clipped));
|
||||||
|
|
||||||
|
// Reopening the upgraded document, as restoring an autosave does, inserts no more
|
||||||
|
let gamma_corrections = |document: &DocumentMessageHandler| {
|
||||||
|
let implementation = DocumentNodeImplementation::ProtoNode(gamma_correction::IDENTIFIER);
|
||||||
|
let nodes = document.network_interface.document_network().recursive_nodes();
|
||||||
|
nodes.filter(|(_, node, _)| node.implementation == implementation).count()
|
||||||
|
};
|
||||||
|
assert_eq!(gamma_corrections(&opened), 4);
|
||||||
|
let reopened = load_legacy_document(opened.serialize_document(), &HashMapResourceStorage::new(), false).expect("the upgraded document should open");
|
||||||
|
assert_eq!(gamma_corrections(&reopened), 4);
|
||||||
|
}
|
||||||
|
|
||||||
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn marbled_mandelbrot_renders_after_migration() {
|
async fn marbled_mandelbrot_renders_after_migration() {
|
||||||
|
|||||||
@@ -175,6 +175,8 @@ pub struct SnapSession {
|
|||||||
gesture: Option<Gesture>,
|
gesture: Option<Gesture>,
|
||||||
/// The targets woken by resting the pointer on them, from the one woken longest ago to the latest.
|
/// The targets woken by resting the pointer on them, from the one woken longest ago to the latest.
|
||||||
awake: Vec<Awake>,
|
awake: Vec<Awake>,
|
||||||
|
/// Those of them woken during the gesture under way, which go back to sleep when it ends.
|
||||||
|
woken_in_gesture: Vec<Awake>,
|
||||||
/// The layers each woken point of its own was found on, by its ID, which it goes back to sleep with.
|
/// The layers each woken point of its own was found on, by its ID, which it goes back to sleep with.
|
||||||
position_sources: HashMap<u64, Vec<LayerId>>,
|
position_sources: HashMap<u64, Vec<LayerId>>,
|
||||||
rest: Option<Rest>,
|
rest: Option<Rest>,
|
||||||
@@ -495,13 +497,17 @@ impl SnapSession {
|
|||||||
landed
|
landed
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to.
|
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to. What the gesture woke goes back to sleep with it.
|
||||||
pub fn end_gesture(&mut self) {
|
pub fn end_gesture(&mut self) {
|
||||||
self.gesture = None;
|
self.gesture = None;
|
||||||
self.constructions = None;
|
self.constructions = None;
|
||||||
self.rest = None;
|
self.rest = None;
|
||||||
self.crossings.clear();
|
self.crossings.clear();
|
||||||
self.forget();
|
self.forget();
|
||||||
|
|
||||||
|
let woken_in_gesture = std::mem::take(&mut self.woken_in_gesture);
|
||||||
|
self.awake.retain(|target| !woken_in_gesture.contains(target));
|
||||||
|
self.forget_targets_gone_to_sleep();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Forgets what the pointer was last snapped to, as when the pointer is no longer placing anything.
|
/// Forgets what the pointer was last snapped to, as when the pointer is no longer placing anything.
|
||||||
@@ -545,11 +551,14 @@ impl SnapSession {
|
|||||||
if let Awake::Position { id, .. } = target {
|
if let Awake::Position { id, .. } = target {
|
||||||
self.position_sources.insert(id, sources.clone());
|
self.position_sources.insert(id, sources.clone());
|
||||||
}
|
}
|
||||||
|
if self.gesture.is_some() {
|
||||||
|
self.woken_in_gesture.push(target);
|
||||||
|
}
|
||||||
self.awake.push(target);
|
self.awake.push(target);
|
||||||
}
|
}
|
||||||
let over_the_limit = self.awake.len().saturating_sub(AWAKE_LIMIT);
|
let over_the_limit = self.awake.len().saturating_sub(AWAKE_LIMIT);
|
||||||
self.awake.drain(..over_the_limit);
|
self.awake.drain(..over_the_limit);
|
||||||
self.forget_sources_of_sleeping_positions();
|
self.forget_targets_gone_to_sleep();
|
||||||
self.constructions = None;
|
self.constructions = None;
|
||||||
|
|
||||||
true
|
true
|
||||||
@@ -563,6 +572,7 @@ impl SnapSession {
|
|||||||
/// Puts every woken target back to sleep, and keeps the pointer from waking them again until it moves.
|
/// Puts every woken target back to sleep, and keeps the pointer from waking them again until it moves.
|
||||||
pub fn sleep_all(&mut self) {
|
pub fn sleep_all(&mut self) {
|
||||||
self.awake.clear();
|
self.awake.clear();
|
||||||
|
self.woken_in_gesture.clear();
|
||||||
self.position_sources.clear();
|
self.position_sources.clear();
|
||||||
self.constructions = None;
|
self.constructions = None;
|
||||||
|
|
||||||
@@ -583,10 +593,12 @@ impl SnapSession {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn forget_sources_of_sleeping_positions(&mut self) {
|
/// Lets go of what is kept about woken targets that have since gone back to sleep.
|
||||||
|
fn forget_targets_gone_to_sleep(&mut self) {
|
||||||
let awake = &self.awake;
|
let awake = &self.awake;
|
||||||
self.position_sources
|
self.position_sources
|
||||||
.retain(|id, _| awake.iter().any(|target| matches!(target, Awake::Position { id: awake_id, .. } if awake_id == id)));
|
.retain(|id, _| awake.iter().any(|target| matches!(target, Awake::Position { id: awake_id, .. } if awake_id == id)));
|
||||||
|
self.woken_in_gesture.retain(|target| awake.contains(target));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The woken targets, oldest first.
|
/// The woken targets, oldest first.
|
||||||
@@ -721,7 +733,7 @@ impl SnapSession {
|
|||||||
Awake::Anchor { layer, .. } | Awake::Curve { layer, .. } | Awake::Box { layer } => !changed.contains(layer),
|
Awake::Anchor { layer, .. } | Awake::Curve { layer, .. } | Awake::Box { layer } => !changed.contains(layer),
|
||||||
Awake::Position { id, .. } => position_sources.get(id).is_none_or(|sources| !sources.iter().any(|layer| changed.contains(layer))),
|
Awake::Position { id, .. } => position_sources.get(id).is_none_or(|sources| !sources.iter().any(|layer| changed.contains(layer))),
|
||||||
});
|
});
|
||||||
self.forget_sources_of_sleeping_positions();
|
self.forget_targets_gone_to_sleep();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1100,6 +1112,45 @@ mod tests {
|
|||||||
assert!(session.tick(1000 + WAKE_DWELL_IN_GESTURE));
|
assert!(session.tick(1000 + WAKE_DWELL_IN_GESTURE));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_gesture_keeps_track_of_only_the_targets_it_woke_that_are_still_awake() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.draw_rect(100., 100., 300., 240.).await;
|
||||||
|
editor.draw_rect(500., 100., 700., 240.).await;
|
||||||
|
let mut session = SnapSession::default();
|
||||||
|
let input = InputPreprocessorMessageHandler::default();
|
||||||
|
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
|
||||||
|
|
||||||
|
// Once the limit has put the first edge back to sleep, resting on it again wakes it a second time
|
||||||
|
let along_edges = [(150., 100.), (300., 140.), (250., 240.), (100., 200.), (550., 100.), (700., 140.), (150., 100.)];
|
||||||
|
for (index, position) in along_edges.into_iter().enumerate() {
|
||||||
|
assert!(rest(&mut session, &editor, position.into(), index as u64 * 2000), "nothing woke at {position:?}");
|
||||||
|
}
|
||||||
|
assert_eq!(session.woken_in_gesture, session.awake);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn what_a_gesture_wakes_goes_back_to_sleep_when_it_ends_while_what_was_woken_before_it_stays_awake() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.draw_rect(100., 100., 300., 240.).await;
|
||||||
|
let mut session = SnapSession::default();
|
||||||
|
|
||||||
|
// The top edge is woken before the gesture, and the right edge during it
|
||||||
|
assert!(rest(&mut session, &editor, DVec2::new(150., 100.), 0));
|
||||||
|
let woken_before = session.awake.clone();
|
||||||
|
|
||||||
|
let input = InputPreprocessorMessageHandler::default();
|
||||||
|
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
|
||||||
|
snap_at_time(&mut session, &editor, DVec2::new(300., 140.), 2000);
|
||||||
|
assert!(session.tick(2000 + WAKE_DWELL_IN_GESTURE));
|
||||||
|
assert_eq!(session.awake.len(), 2);
|
||||||
|
|
||||||
|
session.end_gesture();
|
||||||
|
assert_eq!(session.awake, woken_before);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn only_the_latest_few_woken_targets_stay_awake() {
|
async fn only_the_latest_few_woken_targets_stay_awake() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ mod recompile_tests;
|
|||||||
mod runtime;
|
mod runtime;
|
||||||
pub use runtime::*;
|
pub use runtime::*;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
pub struct ExecutionRequest {
|
pub struct ExecutionRequest {
|
||||||
execution_id: u64,
|
execution_id: u64,
|
||||||
render_config: RenderConfig,
|
render_config: RenderConfig,
|
||||||
@@ -41,6 +41,15 @@ pub struct ExecutionResponse {
|
|||||||
dropped_thumbnails: Vec<NodeId>,
|
dropped_thumbnails: Vec<NodeId>,
|
||||||
/// The latest result of each observation.
|
/// The latest result of each observation.
|
||||||
observations: HashMap<ObservationKey, InspectResult>,
|
observations: HashMap<ObservationKey, InspectResult>,
|
||||||
|
/// The canvas the frame was presented to
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
viewport_canvas_info: Option<ViewportCanvasInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
struct ViewportCanvasInfo {
|
||||||
|
id: u64,
|
||||||
|
resolution: DVec2,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Names an observation so it can be changed or stopped without touching the others.
|
/// Names an observation so it can be changed or stopped without touching the others.
|
||||||
@@ -192,18 +201,6 @@ impl NodeGraphExecutor {
|
|||||||
self.canvas_images_sent.clear();
|
self.canvas_images_sent.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Allows the test runner to see if any more executions have been queued.
|
|
||||||
#[cfg(test)]
|
|
||||||
pub fn current_execution_id(&self) -> u64 {
|
|
||||||
self.current_execution_id
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Allows the test runner to access last executions evaluation errors.
|
|
||||||
#[cfg(test)]
|
|
||||||
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
|
|
||||||
self.evaluation_errors.take()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Execute the network by flattening it and creating a borrow stack.
|
/// Execute the network by flattening it and creating a borrow stack.
|
||||||
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
|
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
|
||||||
let execution_id = self.current_execution_id;
|
let execution_id = self.current_execution_id;
|
||||||
@@ -253,29 +250,6 @@ impl NodeGraphExecutor {
|
|||||||
.expect("Failed to send the thumbnails in view");
|
.expect("Failed to send the thumbnails in view");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
|
|
||||||
// We should always invalidate the cache.
|
|
||||||
self.node_graph_hash = crate::application::generate_uuid();
|
|
||||||
let mut network = document.network_interface.document_network().clone();
|
|
||||||
network.inline_definitions().map_err(|error| error.to_string())?;
|
|
||||||
let instrumented = Instrumented::new(&network);
|
|
||||||
|
|
||||||
let resources = document.resources.registry.clone();
|
|
||||||
|
|
||||||
self.sender
|
|
||||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
|
||||||
network,
|
|
||||||
resources,
|
|
||||||
previewed: Vec::new(),
|
|
||||||
layers: document.network_interface.layer_paths(),
|
|
||||||
observations: self.observations(&document.network_interface),
|
|
||||||
}))
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
Ok(instrumented)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update the cached network if necessary.
|
/// Update the cached network if necessary.
|
||||||
fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> {
|
fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> {
|
||||||
let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect;
|
let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect;
|
||||||
@@ -527,6 +501,8 @@ impl NodeGraphExecutor {
|
|||||||
responses: existing_responses,
|
responses: existing_responses,
|
||||||
dropped_thumbnails,
|
dropped_thumbnails,
|
||||||
mut observations,
|
mut observations,
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
viewport_canvas_info,
|
||||||
} = *execution_response;
|
} = *execution_response;
|
||||||
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
|
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
|
||||||
|
|
||||||
@@ -569,6 +545,29 @@ impl NodeGraphExecutor {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
let mut result = result;
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
if let Some(canvas) = viewport_canvas_info {
|
||||||
|
let placeholder = format!(
|
||||||
|
r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
|
||||||
|
canvas.resolution.x, canvas.resolution.y, canvas.id,
|
||||||
|
);
|
||||||
|
match result.render_output() {
|
||||||
|
Some(RenderOutput {
|
||||||
|
data: RenderOutputType::Svg { svg, .. },
|
||||||
|
..
|
||||||
|
}) => {
|
||||||
|
let end = svg.rfind("</svg>").unwrap_or(svg.len());
|
||||||
|
svg.insert_str(end, &placeholder);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let svg = format!("<svg>{placeholder}</svg>");
|
||||||
|
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
responses.add(OverlaysMessage::Draw);
|
responses.add(OverlaysMessage::Draw);
|
||||||
|
|
||||||
// A pending graph keeps the last frame, and the errors shown with it
|
// A pending graph keeps the last frame, and the errors shown with it
|
||||||
@@ -1036,11 +1035,6 @@ impl NodeGraphExecutor {
|
|||||||
responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use });
|
responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use });
|
||||||
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
||||||
}
|
}
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
RenderOutputType::CanvasFrame { canvas_id, resolution } => {
|
|
||||||
let svg = format!("<svg>{}</svg>", viewport_canvas_placeholder(canvas_id, resolution));
|
|
||||||
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
|
||||||
}
|
|
||||||
RenderOutputType::Texture { .. } => {}
|
RenderOutputType::Texture { .. } => {}
|
||||||
RenderOutputType::Buffer { width, height, .. } => {
|
RenderOutputType::Buffer { width, height, .. } => {
|
||||||
log::error!("Invalid node graph output type: a {width}×{height} pixel buffer");
|
log::error!("Invalid node graph output type: a {width}×{height} pixel buffer");
|
||||||
@@ -1061,6 +1055,7 @@ impl NodeGraphExecutor {
|
|||||||
vector_data,
|
vector_data,
|
||||||
appearance_attributes,
|
appearance_attributes,
|
||||||
effects_reach,
|
effects_reach,
|
||||||
|
effects_frames,
|
||||||
backgrounds: _,
|
backgrounds: _,
|
||||||
} = render_output.metadata;
|
} = render_output.metadata;
|
||||||
|
|
||||||
@@ -1077,7 +1072,7 @@ impl NodeGraphExecutor {
|
|||||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
|
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach, effects_frames });
|
||||||
responses.add(DocumentMessage::RenderScrollbars);
|
responses.add(DocumentMessage::RenderScrollbars);
|
||||||
responses.add(DocumentMessage::RenderRulers);
|
responses.add(DocumentMessage::RenderRulers);
|
||||||
responses.add(OverlaysMessage::Draw);
|
responses.add(OverlaysMessage::Draw);
|
||||||
@@ -1205,15 +1200,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The SVG element the frontend replaces with the viewport canvas, covering the viewport at its logical `resolution`.
|
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
fn viewport_canvas_placeholder(canvas_id: u64, resolution: DVec2) -> String {
|
|
||||||
format!(
|
|
||||||
r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
|
|
||||||
resolution.x, resolution.y, canvas_id,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
|
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
|
||||||
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
||||||
DialogMessage::DisplayDialogError {
|
DialogMessage::DisplayDialogError {
|
||||||
@@ -1268,6 +1254,40 @@ mod test {
|
|||||||
use graphene_std::list::Item;
|
use graphene_std::list::Item;
|
||||||
use test_prelude::LayerNodeIdentifier;
|
use test_prelude::LayerNodeIdentifier;
|
||||||
|
|
||||||
|
impl NodeGraphExecutor {
|
||||||
|
/// Allows the test runner to see if any more executions have been queued.
|
||||||
|
pub fn current_execution_id(&self) -> u64 {
|
||||||
|
self.current_execution_id
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Allows the test runner to access last executions evaluation errors.
|
||||||
|
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
|
||||||
|
self.evaluation_errors.take()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
|
||||||
|
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
|
||||||
|
// We should always invalidate the cache.
|
||||||
|
self.node_graph_hash = crate::application::generate_uuid();
|
||||||
|
let mut network = document.network_interface.document_network().clone();
|
||||||
|
network.inline_definitions().map_err(|error| error.to_string())?;
|
||||||
|
let instrumented = Instrumented::new(&network);
|
||||||
|
|
||||||
|
let resources = document.resources.registry.clone();
|
||||||
|
|
||||||
|
self.sender
|
||||||
|
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||||
|
network,
|
||||||
|
resources,
|
||||||
|
previewed: Vec::new(),
|
||||||
|
layers: document.network_interface.layer_paths(),
|
||||||
|
observations: self.observations(&document.network_interface),
|
||||||
|
}))
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(instrumented)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The path of each proto node in an evaluated graph, by which tests read the values its inputs received.
|
/// The path of each proto node in an evaluated graph, by which tests read the values its inputs received.
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct Instrumented {
|
pub struct Instrumented {
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ use graphene_std::vector::style::RenderMode;
|
|||||||
use graphene_std::{Context, NodeError, Poll};
|
use graphene_std::{Context, NodeError, Poll};
|
||||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
||||||
use interpreted_executor::layer_paths::write_layer_paths;
|
use interpreted_executor::layer_paths::write_layer_paths;
|
||||||
use interpreted_executor::util::wrap_network_in_scope;
|
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||||
use observer::Observer;
|
use observer::Observer;
|
||||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -94,7 +94,7 @@ enum ViewportArtwork {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Messages passed from the editor thread to the node runtime thread.
|
/// Messages passed from the editor thread to the node runtime thread.
|
||||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug)]
|
||||||
pub enum GraphRuntimeRequest {
|
pub enum GraphRuntimeRequest {
|
||||||
GraphUpdate(GraphUpdate),
|
GraphUpdate(GraphUpdate),
|
||||||
ExecutionRequest(ExecutionRequest),
|
ExecutionRequest(ExecutionRequest),
|
||||||
@@ -114,7 +114,7 @@ pub enum GraphRuntimeRequest {
|
|||||||
RenderOverlays(OverlayContext),
|
RenderOverlays(OverlayContext),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug)]
|
||||||
pub struct GraphUpdate {
|
pub struct GraphUpdate {
|
||||||
pub(super) network: NodeNetwork,
|
pub(super) network: NodeNetwork,
|
||||||
pub(super) resources: ResourceRegistry,
|
pub(super) resources: ResourceRegistry,
|
||||||
@@ -302,7 +302,7 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if let Some(viewport) = viewport {
|
if let Some(viewport) = viewport {
|
||||||
texture = self.run_viewport(viewport).await;
|
self.run_viewport(viewport).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Overlays that changed without new artwork are drawn over the artwork already shown
|
// Overlays that changed without new artwork are drawn over the artwork already shown
|
||||||
@@ -315,63 +315,27 @@ impl NodeRuntime {
|
|||||||
texture
|
texture
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> {
|
async fn run_viewport(&mut self, request: ExecutionRequest) {
|
||||||
self.thumbnails.set_scale(request.render_config.scale);
|
self.thumbnails.set_scale(request.render_config.scale);
|
||||||
|
|
||||||
let mut result = self.evaluate(request)?;
|
let Some(mut result) = self.evaluate(request) else { return };
|
||||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||||
|
|
||||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
if let Some(RenderOutput { data, metadata }) = result.render_output() {
|
||||||
let resolution = request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale;
|
let content = match data {
|
||||||
|
RenderOutputType::Texture(texture) => Some(ViewportArtwork::Texture(texture.clone())),
|
||||||
let texture = if let Some(RenderOutput { data, metadata }) = result.render_output()
|
RenderOutputType::Svg { .. } if request.render_config.export_format == ExportFormat::Raster => Some(ViewportArtwork::Svg),
|
||||||
&& let RenderOutputType::Texture(texture) = data
|
_ => None,
|
||||||
{
|
};
|
||||||
self.viewport_artwork = Some(ViewportArtwork::Texture(texture.clone()));
|
if content.is_some() {
|
||||||
let path_contents = path_contents(&observations);
|
self.viewport_artwork = content;
|
||||||
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
|
let path_contents = path_contents(&observations);
|
||||||
self.overlays_stale = true;
|
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
|
||||||
let frame = self.composite_viewport_frame();
|
self.overlays_stale = true;
|
||||||
|
|
||||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
|
||||||
{
|
|
||||||
*data = RenderOutputType::CanvasFrame {
|
|
||||||
canvas_id: self.wasm_canvas_cache.id(),
|
|
||||||
resolution,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
frame
|
self.respond(request, result, observations).await;
|
||||||
} else if request.render_config.export_format == ExportFormat::Raster
|
|
||||||
&& let Some(RenderOutput {
|
|
||||||
data: RenderOutputType::Svg { .. },
|
|
||||||
metadata,
|
|
||||||
}) = result.render_output()
|
|
||||||
{
|
|
||||||
// The viewport was rendered as SVG in place of the requested raster, so the frontend draws it beneath the overlays
|
|
||||||
self.viewport_artwork = Some(ViewportArtwork::Svg);
|
|
||||||
let path_contents = path_contents(&observations);
|
|
||||||
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
|
|
||||||
self.overlays_stale = true;
|
|
||||||
let frame = self.composite_viewport_frame();
|
|
||||||
|
|
||||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
|
||||||
if let Some(RenderOutput {
|
|
||||||
data: RenderOutputType::Svg { svg, .. },
|
|
||||||
..
|
|
||||||
}) = result.render_output()
|
|
||||||
{
|
|
||||||
let end = svg.rfind("</svg>").unwrap_or(svg.len());
|
|
||||||
svg.insert_str(end, &viewport_canvas_placeholder(self.wasm_canvas_cache.id(), resolution));
|
|
||||||
}
|
|
||||||
|
|
||||||
frame
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
self.respond(request.execution_id, result, observations).await;
|
|
||||||
texture
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Draws the latest overlays over the viewport's artwork, or alone above SVG artwork, presenting the frame on web.
|
/// Draws the latest overlays over the viewport's artwork, or alone above SVG artwork, presenting the frame on web.
|
||||||
@@ -431,7 +395,7 @@ impl NodeRuntime {
|
|||||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||||
}
|
}
|
||||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||||
self.respond(request.execution_id, result, observations).await;
|
self.respond(request, result, observations).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||||
@@ -465,7 +429,7 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.output.node(), &context))) {
|
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) {
|
||||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||||
@@ -475,7 +439,7 @@ impl NodeRuntime {
|
|||||||
ExecutionResult::Fallback(value, self.resolve_errors(&error))
|
ExecutionResult::Fallback(value, self.resolve_errors(&error))
|
||||||
}
|
}
|
||||||
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
|
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
|
||||||
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error).error()), NodeErrorTrace::default())]))),
|
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
|
||||||
Err(payload) => {
|
Err(payload) => {
|
||||||
let response = ExecutionResponse {
|
let response = ExecutionResponse {
|
||||||
execution_id,
|
execution_id,
|
||||||
@@ -483,6 +447,8 @@ impl NodeRuntime {
|
|||||||
responses: VecDeque::new(),
|
responses: VecDeque::new(),
|
||||||
dropped_thumbnails: Vec::new(),
|
dropped_thumbnails: Vec::new(),
|
||||||
observations: HashMap::new(),
|
observations: HashMap::new(),
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
viewport_canvas_info: None,
|
||||||
};
|
};
|
||||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||||
return None;
|
return None;
|
||||||
@@ -491,18 +457,37 @@ impl NodeRuntime {
|
|||||||
Some(result)
|
Some(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn respond(&mut self, execution_id: u64, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
||||||
let mut responses = VecDeque::new();
|
let mut responses = VecDeque::new();
|
||||||
|
|
||||||
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
|
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
|
||||||
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
|
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
|
||||||
|
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
let mut result = result;
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
let viewport_canvas_info = (!request.render_config.for_export
|
||||||
|
&& match result.render_output() {
|
||||||
|
Some(RenderOutput { data, .. }) => match data {
|
||||||
|
RenderOutputType::Texture(_) => true,
|
||||||
|
RenderOutputType::Svg { .. } => request.render_config.export_format == ExportFormat::Raster,
|
||||||
|
RenderOutputType::Buffer { .. } => false,
|
||||||
|
},
|
||||||
|
None => false,
|
||||||
|
})
|
||||||
|
.then(|| ViewportCanvasInfo {
|
||||||
|
id: self.wasm_canvas_cache.id(),
|
||||||
|
resolution: request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale,
|
||||||
|
});
|
||||||
|
|
||||||
let response = ExecutionResponse {
|
let response = ExecutionResponse {
|
||||||
execution_id,
|
execution_id: request.execution_id,
|
||||||
result,
|
result,
|
||||||
responses,
|
responses,
|
||||||
dropped_thumbnails,
|
dropped_thumbnails,
|
||||||
observations,
|
observations,
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
viewport_canvas_info,
|
||||||
};
|
};
|
||||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||||
}
|
}
|
||||||
@@ -522,7 +507,7 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||||
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||||
|
|
||||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||||
@@ -586,7 +571,7 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ExecutionResult {
|
impl ExecutionResult {
|
||||||
fn render_output(&mut self) -> Option<&mut RenderOutput> {
|
pub(super) fn render_output(&mut self) -> Option<&mut RenderOutput> {
|
||||||
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
|
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
|
||||||
return None;
|
return None;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -423,6 +423,17 @@ impl EditorTestUtils {
|
|||||||
self.create_node(node_type, Some((x, y))).await
|
self.create_node(node_type, Some((x, y))).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Adds an empty subgraph at the grid position, as the graph's New Custom Node button does.
|
||||||
|
pub async fn create_empty_subgraph_at(&mut self, x: i32, y: i32) -> NodeId {
|
||||||
|
let node_id = NodeId::new();
|
||||||
|
self.handle_message(NodeGraphMessage::CreateEmptySubgraph {
|
||||||
|
node_id: Some(node_id),
|
||||||
|
xy: Some((x, y)),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
node_id
|
||||||
|
}
|
||||||
|
|
||||||
async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
|
async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
|
||||||
let node_id = NodeId::new();
|
let node_id = NodeId::new();
|
||||||
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
|
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||||
@@ -509,14 +520,18 @@ fn init_test_logger() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates application IO with the GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
|
/// The GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
|
||||||
/// Panics if no adapter is found, since tests render on the GPU like the app does.
|
/// Panics if no adapter is found, since tests render on the GPU like the app does.
|
||||||
fn gpu_application_io() -> PlatformApplicationIo {
|
pub fn gpu_executor() -> <PlatformApplicationIo as ApplicationIo>::Executor {
|
||||||
static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned());
|
static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned());
|
||||||
let executor = GPU_EXECUTOR.clone().expect(
|
GPU_EXECUTOR.clone().expect(
|
||||||
"Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).",
|
"Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).",
|
||||||
);
|
)
|
||||||
PlatformApplicationIo::new_with_executor(executor)
|
}
|
||||||
|
|
||||||
|
/// Creates application IO with the GPU executor every test shares (see [`gpu_executor`]).
|
||||||
|
fn gpu_application_io() -> PlatformApplicationIo {
|
||||||
|
PlatformApplicationIo::new_with_executor(gpu_executor())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs `operation`, returning its result along with the errors it logged.
|
/// Runs `operation`, returning its result along with the errors it logged.
|
||||||
|
|||||||
@@ -538,30 +538,6 @@
|
|||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<!-- Click target debug visualizations -->
|
|
||||||
{#if $nodeGraph.clickTargets}
|
|
||||||
<div class="click-targets" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
|
|
||||||
<svg>
|
|
||||||
{#each $nodeGraph.clickTargets.nodeClickTargets as pathString}
|
|
||||||
<path class="node" d={pathString} />
|
|
||||||
{/each}
|
|
||||||
{#each $nodeGraph.clickTargets.layerClickTargets as pathString}
|
|
||||||
<path class="layer" d={pathString} />
|
|
||||||
{/each}
|
|
||||||
{#each $nodeGraph.clickTargets.connectorClickTargets as pathString}
|
|
||||||
<path class="connector" d={pathString} />
|
|
||||||
{/each}
|
|
||||||
{#each $nodeGraph.clickTargets.iconClickTargets as pathString}
|
|
||||||
<path class="visibility" d={pathString} />
|
|
||||||
{/each}
|
|
||||||
<path class="all-nodes-bounding-box" d={$nodeGraph.clickTargets.allNodesBoundingBox} />
|
|
||||||
{#each $nodeGraph.clickTargets.importExportNames as pathString}
|
|
||||||
<path class="import-export-name" d={pathString} />
|
|
||||||
{/each}
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
<!-- Thick vertical layer connection wires -->
|
<!-- Thick vertical layer connection wires -->
|
||||||
<div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
|
<div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
|
||||||
<svg>
|
<svg>
|
||||||
@@ -1311,46 +1287,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.click-targets {
|
|
||||||
position: absolute;
|
|
||||||
pointer-events: none;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
z-index: 10;
|
|
||||||
|
|
||||||
svg {
|
|
||||||
overflow: visible;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
stroke-width: 1;
|
|
||||||
fill: none;
|
|
||||||
|
|
||||||
.layer {
|
|
||||||
stroke: yellow;
|
|
||||||
}
|
|
||||||
|
|
||||||
.node {
|
|
||||||
stroke: blue;
|
|
||||||
}
|
|
||||||
|
|
||||||
.connector {
|
|
||||||
stroke: green;
|
|
||||||
}
|
|
||||||
|
|
||||||
.visibility {
|
|
||||||
stroke: red;
|
|
||||||
}
|
|
||||||
|
|
||||||
.all-nodes-bounding-box {
|
|
||||||
stroke: purple;
|
|
||||||
}
|
|
||||||
|
|
||||||
.import-export-name {
|
|
||||||
stroke: orange;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.wires {
|
.wires {
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
|
|||||||
@@ -140,7 +140,9 @@
|
|||||||
const reorder = allowReorder && allowSelect;
|
const reorder = allowReorder && allowSelect;
|
||||||
let held = position;
|
let held = position;
|
||||||
|
|
||||||
if (!reorder && !allowWrap) {
|
if (!reorder && !allowWrap && markers.some((marker) => marker.overlapNext !== "Never")) {
|
||||||
|
held = holdWithOverlaps(first, last, position);
|
||||||
|
} else if (!reorder && !allowWrap) {
|
||||||
const lower = neighborBound(first, -1) ?? 0;
|
const lower = neighborBound(first, -1) ?? 0;
|
||||||
const upper = (neighborBound(last, 1) ?? 1) - spacing;
|
const upper = (neighborBound(last, 1) ?? 1) - spacing;
|
||||||
held = Math.max(lower, Math.min(upper, position));
|
held = Math.max(lower, Math.min(upper, position));
|
||||||
@@ -156,6 +158,33 @@
|
|||||||
return wrap ? held - Math.floor(held) : Math.max(0, Math.min(1 - spacing, held));
|
return wrap ? held - Math.floor(held) : Math.max(0, Math.min(1 - spacing, held));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Holds markers `first..=last` moving to `position` within the track and each member's bounds from the markers outside the run, as the backend's `overlap_bounds` gives them
|
||||||
|
function holdWithOverlaps(first: number, last: number, position: number): number {
|
||||||
|
const outsideRun = (i: number) => i >= 0 && i < markers.length && (i < first || i > last);
|
||||||
|
const overlap = (i: number) => (i >= 0 && i < markers.length ? markers[i].overlapNext : "Never");
|
||||||
|
const boundsBeyond = (near: number, far: number) => (overlap(near) === "NextOnly" || overlap(far) === "NextOnly") && overlap(near) !== "Freely" && overlap(far) !== "Freely";
|
||||||
|
|
||||||
|
let lower = 0;
|
||||||
|
let upper = 1;
|
||||||
|
for (let k = first; k <= last; k += 1) {
|
||||||
|
const offset = markers[k].position - markers[first].position;
|
||||||
|
lower = Math.max(lower, -offset);
|
||||||
|
upper = Math.min(upper, 1 - offset);
|
||||||
|
|
||||||
|
// A neighbor bounds the marker unless they overlap, and past a neighbor overlapping only its next, so does the marker beyond it
|
||||||
|
const lowerBounds = [overlap(k - 1) === "Never" ? k - 1 : -1, boundsBeyond(k - 1, k - 2) ? k - 2 : -1];
|
||||||
|
const upperBounds = [overlap(k) === "Never" ? k + 1 : -1, boundsBeyond(k, k + 1) ? k + 2 : -1];
|
||||||
|
lowerBounds.filter(outsideRun).forEach((i) => {
|
||||||
|
lower = Math.max(lower, markers[i].position - offset);
|
||||||
|
});
|
||||||
|
upperBounds.filter(outsideRun).forEach((i) => {
|
||||||
|
upper = Math.min(upper, markers[i].position - offset);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.max(lower, Math.min(upper, position));
|
||||||
|
}
|
||||||
|
|
||||||
// The position of the nearest marker past `index` in the direction of `step` that bounds others, skipping any placed between its neighbors since those follow them instead
|
// The position of the nearest marker past `index` in the direction of `step` that bounds others, skipping any placed between its neighbors since those follow them instead
|
||||||
function neighborBound(index: number, step: -1 | 1): number | undefined {
|
function neighborBound(index: number, step: -1 | 1): number | undefined {
|
||||||
for (let i = index + step; i >= 0 && i < markers.length; i += step) {
|
for (let i = index + step; i >= 0 && i < markers.length; i += step) {
|
||||||
@@ -657,7 +686,10 @@
|
|||||||
}
|
}
|
||||||
$: midpointPositions = diamondPositions(markers, showMidpoints, trackCyclic, trackInterpolation);
|
$: midpointPositions = diamondPositions(markers, showMidpoints, trackCyclic, trackInterpolation);
|
||||||
$: strips = markerSpans(markers, allowWrap, (marker) => marker.pairedWithNext);
|
$: strips = markerSpans(markers, allowWrap, (marker) => marker.pairedWithNext);
|
||||||
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext);
|
// A dashed link vanishes while the markers it joins have overlapped past each other, leaving no span between them
|
||||||
|
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext).filter(
|
||||||
|
({ index }) => markers[index].overlapNext === "Never" || markers[index + 1].position >= markers[index].position,
|
||||||
|
);
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
document.addEventListener("keydown", deleteShortcut);
|
document.addEventListener("keydown", deleteShortcut);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import type { Writable } from "svelte/store";
|
|||||||
import type { IconName } from "/src/icons";
|
import type { IconName } from "/src/icons";
|
||||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||||
import type { MessageBody } from "/src/subscriptions-router";
|
import type { MessageBody } from "/src/subscriptions-router";
|
||||||
import type { NodeGraphErrorDiagnostic, BoxSelection, FrontendClickTargets, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
import type { NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||||
|
|
||||||
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
|
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
|
||||||
|
|
||||||
@@ -13,7 +13,6 @@ export type ThumbnailCanvases = { layersPanelCanvasId: number; nodeGraphCanvasId
|
|||||||
|
|
||||||
type NodeGraphStoreState = {
|
type NodeGraphStoreState = {
|
||||||
box: BoxSelection | undefined;
|
box: BoxSelection | undefined;
|
||||||
clickTargets: FrontendClickTargets | undefined;
|
|
||||||
contextMenuInformation: ContextMenuInformation | undefined;
|
contextMenuInformation: ContextMenuInformation | undefined;
|
||||||
errors: NodeGraphErrorDiagnostic[];
|
errors: NodeGraphErrorDiagnostic[];
|
||||||
layerWidths: Map<bigint, number>;
|
layerWidths: Map<bigint, number>;
|
||||||
@@ -36,7 +35,6 @@ type NodeGraphStoreState = {
|
|||||||
};
|
};
|
||||||
const initialState: NodeGraphStoreState = {
|
const initialState: NodeGraphStoreState = {
|
||||||
box: undefined,
|
box: undefined,
|
||||||
clickTargets: undefined,
|
|
||||||
contextMenuInformation: undefined,
|
contextMenuInformation: undefined,
|
||||||
errors: [],
|
errors: [],
|
||||||
layerWidths: new Map(),
|
layerWidths: new Map(),
|
||||||
@@ -136,13 +134,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
subscriptions.subscribeFrontendMessage("UpdateClickTargets", (data) => {
|
|
||||||
update((state) => {
|
|
||||||
state.clickTargets = data.clickTargets;
|
|
||||||
return state;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => {
|
subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => {
|
||||||
update((state) => {
|
update((state) => {
|
||||||
state.contextMenuInformation = data.contextMenuInformation;
|
state.contextMenuInformation = data.contextMenuInformation;
|
||||||
@@ -330,7 +321,6 @@ export function destroyNodeGraphStore() {
|
|||||||
|
|
||||||
subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
|
subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
|
||||||
subscriptions.unsubscribeFrontendMessage("UpdateBox");
|
subscriptions.unsubscribeFrontendMessage("UpdateBox");
|
||||||
subscriptions.unsubscribeFrontendMessage("UpdateClickTargets");
|
|
||||||
subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation");
|
subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation");
|
||||||
subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex");
|
subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex");
|
||||||
subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex");
|
subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex");
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use super::mover::Mover;
|
use super::mover::Mover;
|
||||||
|
use crate::graph::LAYER_BOTTOM_GAP;
|
||||||
use crate::per_node::PerNode;
|
use crate::per_node::PerNode;
|
||||||
use crate::{NodeIndex, Placement};
|
use crate::{NodeIndex, Placement};
|
||||||
use glam::IVec2;
|
use glam::IVec2;
|
||||||
use std::mem;
|
|
||||||
|
|
||||||
pub(super) struct Snapshot {
|
pub(super) struct Snapshot {
|
||||||
placements: PerNode<Placement>,
|
placements: PerNode<Placement>,
|
||||||
@@ -16,38 +16,85 @@ impl Mover {
|
|||||||
Snapshot { placements, positions }
|
Snapshot { placements, positions }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn restore_followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) {
|
pub(super) fn restore_followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) {
|
||||||
let followers = self.followers(before, moved);
|
let followers = self.followers(before, kept);
|
||||||
let mut restored = PerNode::filled(&self.graph, false);
|
let mut pushed = PerNode::filled(&self.graph, None);
|
||||||
followers
|
for node in followers.indices().filter(|node| followers[*node]) {
|
||||||
.indices()
|
self.restore_follower(node, &followers, &before.positions, &mut pushed);
|
||||||
.filter(|node| followers[*node])
|
}
|
||||||
.for_each(|node| self.restore_follower(node, &followers, &before.positions, &mut restored));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) -> PerNode<bool> {
|
fn followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) -> PerNode<bool> {
|
||||||
let (graph, layout) = self.graph_and_layout();
|
let (graph, layout) = self.graph_and_layout();
|
||||||
PerNode::from_fn(graph, |node| {
|
PerNode::from_fn(graph, |node| {
|
||||||
let placement = graph[node].placement;
|
let placement = graph[node].placement;
|
||||||
let unchanged = placement == before.placements[node];
|
let unchanged = placement == before.placements[node];
|
||||||
let was_relative = matches!(before.placements[node], Placement::Relative(_));
|
let was_relative = matches!(before.placements[node], Placement::Relative(_));
|
||||||
let is_relative = matches!(placement, Placement::Relative(_));
|
let is_relative = matches!(placement, Placement::Relative(_));
|
||||||
!moved.contains(&node) && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node]
|
kept[node] && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node]
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, restored: &mut PerNode<bool>) {
|
fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, pushed: &mut PerNode<Option<IVec2>>) -> IVec2 {
|
||||||
if mem::replace(&mut restored[node], true) {
|
if let Some(push) = pushed[node] {
|
||||||
return;
|
return push;
|
||||||
}
|
}
|
||||||
|
pushed[node] = Some(IVec2::ZERO);
|
||||||
|
|
||||||
let following_readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).filter(|reader| followers[*reader]).collect();
|
let following_readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).filter(|reader| followers[*reader]).collect();
|
||||||
for reader in following_readers {
|
let pushed_by_readers = following_readers
|
||||||
self.restore_follower(reader, followers, positions_before, restored);
|
.into_iter()
|
||||||
|
.map(|reader| self.restore_follower(reader, followers, positions_before, pushed))
|
||||||
|
.fold(IVec2::ZERO, IVec2::max);
|
||||||
|
|
||||||
|
let shift = positions_before[node] + pushed_by_readers - self.position(node);
|
||||||
|
let shifted = self.graph[node].placement.shifted(shift);
|
||||||
|
let clear = self.clear_of_the_layer_above(node, shifted);
|
||||||
|
self.set_placement(node, clear);
|
||||||
|
|
||||||
|
let push = pushed_by_readers + clear.stored_offset() - shifted.stored_offset();
|
||||||
|
pushed[node] = Some(push);
|
||||||
|
push
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn carry_along(&mut self, before: &Snapshot, carried: &PerNode<bool>) {
|
||||||
|
let mut shifts = PerNode::filled(&self.graph, None);
|
||||||
|
for node in carried.indices().filter(|node| carried[*node]) {
|
||||||
|
self.carry(node, carried, &before.positions, &mut shifts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn carry(&mut self, node: NodeIndex, carried: &PerNode<bool>, positions_before: &PerNode<IVec2>, shifts: &mut PerNode<Option<IVec2>>) -> IVec2 {
|
||||||
|
if let Some(shift) = shifts[node] {
|
||||||
|
return shift;
|
||||||
|
}
|
||||||
|
shifts[node] = Some(IVec2::ZERO);
|
||||||
|
|
||||||
|
let readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).collect();
|
||||||
|
let mut shift = IVec2::ZERO;
|
||||||
|
for reader in readers {
|
||||||
|
shift = if carried[reader] {
|
||||||
|
self.carry(reader, carried, positions_before, shifts)
|
||||||
|
} else {
|
||||||
|
self.position(reader) - positions_before[reader]
|
||||||
|
};
|
||||||
|
if shift != IVec2::ZERO {
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let shift = positions_before[node] - self.position(node);
|
|
||||||
let shifted = self.graph[node].placement.shifted(shift);
|
let shifted = self.graph[node].placement.shifted(shift);
|
||||||
self.set_placement(node, shifted);
|
self.set_placement(node, shifted);
|
||||||
|
shifts[node] = Some(shift);
|
||||||
|
shift
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear_of_the_layer_above(&self, node: NodeIndex, placement: Placement) -> Placement {
|
||||||
|
let Placement::Relative(offset) = placement else { return placement };
|
||||||
|
let layer_above = self.readers.of(&self.graph, node).find(|wire| self.graph.feeds_stack(wire)).map(|wire| wire.target);
|
||||||
|
let Some(layer_above) = layer_above.filter(|_| offset.x == 0) else { return placement };
|
||||||
|
|
||||||
|
let lowest_free_row = self.graph[layer_above].size.y + LAYER_BOTTOM_GAP;
|
||||||
|
Placement::Relative(IVec2::new(0, offset.y.max(lowest_free_row)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
use crate::connections::WiresByNode;
|
||||||
|
use crate::per_node::PerNode;
|
||||||
|
use crate::{Graph, NodeIndex, Placement, Wire};
|
||||||
|
use glam::IVec2;
|
||||||
|
use std::mem;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub(super) struct UpstreamOfDragged {
|
||||||
|
moving_up_or_down: Upstream,
|
||||||
|
moving_sideways: Upstream,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub(super) struct Upstream {
|
||||||
|
pub(super) kept: PerNode<bool>,
|
||||||
|
pub(super) carried: PerNode<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UpstreamOfDragged {
|
||||||
|
pub(super) fn new(graph: &Graph, dragged: &[NodeIndex]) -> Self {
|
||||||
|
let inputs = WiresByNode::inputs(graph);
|
||||||
|
let everything = upstream_through(graph, &inputs, dragged, |_| true);
|
||||||
|
let into_a_node = |wire: &Wire| !graph[wire.target].is_layer();
|
||||||
|
let split = |kept: PerNode<bool>| {
|
||||||
|
let carried = PerNode::from_fn(graph, |node| everything[node] && !kept[node] && matches!(graph[node].placement, Placement::Absolute(_)));
|
||||||
|
Upstream { kept, carried }
|
||||||
|
};
|
||||||
|
Self {
|
||||||
|
moving_up_or_down: split(upstream_through(graph, &inputs, dragged, |wire| into_a_node(wire) || graph.feeds_stack(wire))),
|
||||||
|
moving_sideways: split(upstream_through(graph, &inputs, dragged, into_a_node)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn moving_by(&self, shift: IVec2) -> &Upstream {
|
||||||
|
if shift.x == 0 { &self.moving_up_or_down } else { &self.moving_sideways }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn upstream_through(graph: &Graph, inputs: &WiresByNode, dragged: &[NodeIndex], followed: impl Fn(&Wire) -> bool) -> PerNode<bool> {
|
||||||
|
let mut upstream = PerNode::filled(graph, false);
|
||||||
|
for node in dragged {
|
||||||
|
upstream[*node] = true;
|
||||||
|
}
|
||||||
|
dragged
|
||||||
|
.iter()
|
||||||
|
.flat_map(|node| inputs.of(graph, *node))
|
||||||
|
.filter(|wire| followed(wire))
|
||||||
|
.for_each(|wire| mark_upstream(graph, inputs, wire.source, &mut upstream));
|
||||||
|
for node in dragged {
|
||||||
|
upstream[*node] = false;
|
||||||
|
}
|
||||||
|
upstream
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mark_upstream(graph: &Graph, inputs: &WiresByNode, node: NodeIndex, upstream: &mut PerNode<bool>) {
|
||||||
|
if mem::replace(&mut upstream[node], true) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
inputs.of(graph, node).for_each(|wire| mark_upstream(graph, inputs, wire.source, upstream));
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
mod followers;
|
mod followers;
|
||||||
|
mod kept;
|
||||||
mod mover;
|
mod mover;
|
||||||
mod shift;
|
mod shift;
|
||||||
mod stack;
|
mod stack;
|
||||||
|
|
||||||
use crate::{Graph, Layout, NodeIndex, Placement};
|
use crate::{Graph, Layout, NodeIndex, Placement};
|
||||||
use glam::IVec2;
|
use glam::IVec2;
|
||||||
|
use kept::UpstreamOfDragged;
|
||||||
use mover::Mover;
|
use mover::Mover;
|
||||||
|
|
||||||
/// Nodes dragged from where they are drawn, computing the graph for any offset from the start alone.
|
/// Nodes dragged from where they are drawn, computing the graph for any offset from the start alone.
|
||||||
@@ -12,7 +14,7 @@ use mover::Mover;
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Drag {
|
pub struct Drag {
|
||||||
dragged: Vec<NodeIndex>,
|
dragged: Vec<NodeIndex>,
|
||||||
keep_upstream: bool,
|
upstream: Option<UpstreamOfDragged>,
|
||||||
rows_up: Vec<Graph>,
|
rows_up: Vec<Graph>,
|
||||||
held_in_place: Vec<HeldInPlace>,
|
held_in_place: Vec<HeldInPlace>,
|
||||||
}
|
}
|
||||||
@@ -26,8 +28,11 @@ struct HeldInPlace {
|
|||||||
|
|
||||||
impl Drag {
|
impl Drag {
|
||||||
/// Holds the `dragged` nodes of `start`. With `keep_upstream`, nodes only carried along by them stay where they are drawn.
|
/// Holds the `dragged` nodes of `start`. With `keep_upstream`, nodes only carried along by them stay where they are drawn.
|
||||||
|
/// Dragged layers still carry their content and chain, and carry the stacks below them when moved sideways.
|
||||||
|
/// Nodes starting a tree of their own upstream of what moves follow the nodes reading them.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(start: Graph, start_layout: Layout, dragged: Vec<NodeIndex>, keep_upstream: bool) -> Self {
|
pub fn new(start: Graph, start_layout: Layout, dragged: Vec<NodeIndex>, keep_upstream: bool) -> Self {
|
||||||
|
let upstream = keep_upstream.then(|| UpstreamOfDragged::new(&start, &dragged));
|
||||||
let stored: Vec<Placement> = start.nodes.iter().map(|node| node.placement).collect();
|
let stored: Vec<Placement> = start.nodes.iter().map(|node| node.placement).collect();
|
||||||
let mut mover = Mover::new(start, Some(start_layout));
|
let mut mover = Mover::new(start, Some(start_layout));
|
||||||
mover.hold(&dragged);
|
mover.hold(&dragged);
|
||||||
@@ -45,7 +50,7 @@ impl Drag {
|
|||||||
.collect();
|
.collect();
|
||||||
Self {
|
Self {
|
||||||
dragged,
|
dragged,
|
||||||
keep_upstream,
|
upstream,
|
||||||
rows_up: vec![held],
|
rows_up: vec![held],
|
||||||
held_in_place,
|
held_in_place,
|
||||||
}
|
}
|
||||||
@@ -74,7 +79,7 @@ impl Drag {
|
|||||||
[IVec2::new(0, offset.y.max(0)), IVec2::new(offset.x, 0)]
|
[IVec2::new(0, offset.y.max(0)), IVec2::new(offset.x, 0)]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|shift| *shift != IVec2::ZERO)
|
.filter(|shift| *shift != IVec2::ZERO)
|
||||||
.for_each(|shift| mover.shift_step(&self.dragged, shift, self.keep_upstream));
|
.for_each(|shift| mover.shift_step(&self.dragged, shift, self.upstream.as_ref().map(|upstream| upstream.moving_by(shift))));
|
||||||
mover.into_graph_and_layout()
|
mover.into_graph_and_layout()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +94,7 @@ impl Drag {
|
|||||||
fn one_row_further_up(&self) -> Graph {
|
fn one_row_further_up(&self) -> Graph {
|
||||||
let highest_so_far = self.rows_up.last().cloned().unwrap_or_default();
|
let highest_so_far = self.rows_up.last().cloned().unwrap_or_default();
|
||||||
let mut mover = Mover::new(highest_so_far, None);
|
let mut mover = Mover::new(highest_so_far, None);
|
||||||
mover.shift_step(&self.dragged, IVec2::NEG_Y, self.keep_upstream);
|
mover.shift_step(&self.dragged, IVec2::NEG_Y, self.upstream.as_ref().map(|upstream| upstream.moving_by(IVec2::NEG_Y)));
|
||||||
mover.into_graph()
|
mover.into_graph()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,27 +1,27 @@
|
|||||||
|
use super::kept::Upstream;
|
||||||
use super::mover::Mover;
|
use super::mover::Mover;
|
||||||
use crate::NodeIndex;
|
use crate::NodeIndex;
|
||||||
use glam::IVec2;
|
use glam::IVec2;
|
||||||
|
|
||||||
impl Mover {
|
impl Mover {
|
||||||
pub(super) fn shift_step(&mut self, dragged: &[NodeIndex], shift: IVec2, keep_upstream: bool) {
|
pub(super) fn shift_step(&mut self, dragged: &[NodeIndex], shift: IVec2, upstream: Option<&Upstream>) {
|
||||||
let before = keep_upstream.then(|| self.snapshot());
|
let before = upstream.map(|upstream| (self.snapshot(), upstream));
|
||||||
let shifted = self.shift_nodes(dragged, shift);
|
self.shift_nodes(dragged, shift);
|
||||||
if let Some(before) = before {
|
if let Some((before, upstream)) = before {
|
||||||
let moved: Vec<NodeIndex> = dragged.iter().chain(&shifted).copied().collect();
|
self.restore_followers(&before, &upstream.kept);
|
||||||
self.restore_followers(&before, &moved);
|
self.carry_along(&before, &upstream.carried);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn shift_nodes(&mut self, nodes: &[NodeIndex], shift: IVec2) -> Vec<NodeIndex> {
|
fn shift_nodes(&mut self, nodes: &[NodeIndex], shift: IVec2) {
|
||||||
let mut shifted = Vec::new();
|
let mut shifted = Vec::new();
|
||||||
for node in self.moving_on_their_own(nodes) {
|
for node in self.moving_on_their_own(nodes) {
|
||||||
self.shift_node(node, shift, &mut shifted);
|
self.shift_node(node, shift, &mut shifted);
|
||||||
}
|
}
|
||||||
shifted
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn shift_node(&mut self, node: NodeIndex, shift: IVec2, shifted: &mut Vec<NodeIndex>) {
|
fn shift_node(&mut self, node: NodeIndex, shift: IVec2, shifted: &mut Vec<NodeIndex>) {
|
||||||
let moving = self.node_moving_for(node, shift);
|
let Some(moving) = self.node_moving_for(node, shift) else { return };
|
||||||
if shifted.contains(&moving) {
|
if shifted.contains(&moving) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -34,12 +34,12 @@ impl Mover {
|
|||||||
self.place_at(moving, position + shift);
|
self.place_at(moving, position + shift);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn node_moving_for(&mut self, node: NodeIndex, shift: IVec2) -> NodeIndex {
|
fn node_moving_for(&mut self, node: NodeIndex, shift: IVec2) -> Option<NodeIndex> {
|
||||||
let (stack, layout) = self.stack_and_layout();
|
let (stack, layout) = self.stack_and_layout();
|
||||||
match shift {
|
match shift {
|
||||||
IVec2 { x: 0, y: -1 } => stack.lowest_layer_with_room_above(layout, node),
|
IVec2 { x: 0, y: -1 } => stack.lowest_layer_with_room_above(layout, node),
|
||||||
IVec2 { x: 0, .. } => node,
|
IVec2 { x: 0, .. } => Some(node),
|
||||||
_ => stack.top(node),
|
_ => Some(stack.top(node)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,8 +14,18 @@ impl Stack<'_> {
|
|||||||
self.climb(node, |layer| self.layer_above(layer))
|
self.climb(node, |layer| self.layer_above(layer))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn lowest_layer_with_room_above(&self, layout: &Layout, node: NodeIndex) -> NodeIndex {
|
pub(super) fn lowest_layer_with_room_above(&self, layout: &Layout, node: NodeIndex) -> Option<NodeIndex> {
|
||||||
self.climb(node, |layer| self.layer_above(layer).filter(|above| self.closed_up(layout, layer, *above)))
|
let top_of_closed_up_run = self.climb(node, |layer| self.layer_above(layer).filter(|above| self.closed_up(layout, layer, *above)));
|
||||||
|
(!self.closed_up_under_its_parent(layout, top_of_closed_up_run)).then_some(top_of_closed_up_run)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn closed_up_under_its_parent(&self, layout: &Layout, layer: NodeIndex) -> bool {
|
||||||
|
let parent = self
|
||||||
|
.readers
|
||||||
|
.of(self.graph, layer)
|
||||||
|
.find(|wire| wire.is_primary() && self.graph[wire.target].is_layer() && !self.graph.feeds_stack(wire))
|
||||||
|
.map(|wire| wire.target);
|
||||||
|
self.graph[layer].is_layer() && parent.is_some_and(|parent| self.closed_up(layout, layer, parent))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn closed_up(&self, layout: &Layout, layer: NodeIndex, above: NodeIndex) -> bool {
|
fn closed_up(&self, layout: &Layout, layer: NodeIndex, above: NodeIndex) -> bool {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
mod common;
|
mod common;
|
||||||
|
|
||||||
use common::{at, layer, stacked, wire};
|
use common::{CHAINED, at, layer, node, stacked, wire};
|
||||||
use glam::IVec2;
|
use glam::IVec2;
|
||||||
use graph_layout::{Drag, Graph, Layout, Placement};
|
use graph_layout::{Drag, Graph, Layout, Placement};
|
||||||
|
|
||||||
@@ -73,3 +73,148 @@ fn a_layer_pushed_up_with_its_upstream_kept_carries_the_layer_above_from_the_fir
|
|||||||
assert_eq!(layout.node(at(2)).position, before.node(at(2)).position + IVec2::new(0, -2));
|
assert_eq!(layout.node(at(2)).position, before.node(at(2)).position + IVec2::new(0, -2));
|
||||||
assert_eq!(layout.node(at(1)).position, before.node(at(1)).position + IVec2::new(0, -2));
|
assert_eq!(layout.node(at(1)).position, before.node(at(1)).position + IVec2::new(0, -2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_layer_dragged_up_with_its_upstream_kept_carries_its_chain_and_leaves_its_stack() {
|
||||||
|
let start = Graph {
|
||||||
|
nodes: vec![
|
||||||
|
layer(Placement::Absolute(IVec2::new(30, 10))),
|
||||||
|
node(CHAINED),
|
||||||
|
node(Placement::Relative(IVec2::new(-8, 0))),
|
||||||
|
layer(stacked(0)),
|
||||||
|
],
|
||||||
|
wires: vec![wire(1, 0, 1), wire(2, 1, 0), wire(3, 0, 0)],
|
||||||
|
};
|
||||||
|
let before = Layout::new(&start);
|
||||||
|
let offset = IVec2::new(0, -4);
|
||||||
|
|
||||||
|
let (_, layout) = Drag::new(start.clone(), Layout::new(&start), vec![at(0)], true).moved(offset);
|
||||||
|
|
||||||
|
for carried in [0, 1, 2] {
|
||||||
|
assert_eq!(layout.node(at(carried)).position, before.node(at(carried)).position + offset);
|
||||||
|
}
|
||||||
|
assert_eq!(layout.node(at(3)).position, before.node(at(3)).position);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stack_of_layers_with_chains() -> Graph {
|
||||||
|
let layers = [layer(Placement::Absolute(IVec2::new(30, 10))), layer(stacked(0)), layer(stacked(0))];
|
||||||
|
let chains = [node(CHAINED), node(CHAINED), node(CHAINED)];
|
||||||
|
let stack_wires = [wire(1, 0, 0), wire(2, 1, 0)];
|
||||||
|
let chain_wires = [wire(3, 0, 1), wire(4, 1, 1), wire(5, 2, 1)];
|
||||||
|
Graph {
|
||||||
|
nodes: layers.into_iter().chain(chains).collect(),
|
||||||
|
wires: stack_wires.into_iter().chain(chain_wires).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn moved_by_dragging(graph: &Graph, dragged: &[u32], offset: IVec2) -> Vec<u32> {
|
||||||
|
let before = Layout::new(graph);
|
||||||
|
let (_, layout) = Drag::new(graph.clone(), Layout::new(graph), dragged.iter().copied().map(at).collect(), true).moved(offset);
|
||||||
|
let node_count = u32::try_from(graph.nodes.len()).unwrap();
|
||||||
|
(0..node_count).filter(|index| layout.node(at(*index)).position != before.node(at(*index)).position).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_layer_in_the_middle_of_a_stack_dragged_sideways_with_its_upstream_kept_moves_its_whole_stack() {
|
||||||
|
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[1], IVec2::new(10, 0)), vec![0, 1, 2, 3, 4, 5]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_chain_node_dragged_with_its_upstream_kept_moves_alone() {
|
||||||
|
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[4], IVec2::new(0, 10)), vec![4]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_layer_pushed_up_with_its_upstream_kept_carries_the_closed_up_layers_above_with_their_chains() {
|
||||||
|
let graph = stack_of_layers_with_chains();
|
||||||
|
let mut stack_with_one_more_below = graph.clone();
|
||||||
|
stack_with_one_more_below.nodes.push(layer(stacked(0)));
|
||||||
|
stack_with_one_more_below.wires.push(wire(6, 2, 0));
|
||||||
|
|
||||||
|
assert_eq!(moved_by_dragging(&stack_with_one_more_below, &[2], IVec2::new(0, -1)), vec![0, 1, 2, 3, 4, 5]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn layers_of_one_stack_dragged_down_together_with_their_upstream_kept_carry_their_chains() {
|
||||||
|
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[1, 2], IVec2::new(0, 4)), vec![1, 2, 4, 5]);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn artboard_holding_a_stack_of_layers_with_chains() -> Graph {
|
||||||
|
let artboard = layer(Placement::Absolute(IVec2::new(30, 10)));
|
||||||
|
let layers = [layer(Placement::Relative(IVec2::new(-8, 3))), layer(stacked(0)), layer(stacked(0)), layer(stacked(0))];
|
||||||
|
let chains = (0..4).flat_map(|_| [node(CHAINED), node(CHAINED), node(CHAINED)]);
|
||||||
|
let stack_wires = [wire(1, 0, 1), wire(2, 1, 0), wire(3, 2, 0), wire(4, 3, 0)];
|
||||||
|
let chain_wires = (0..4).flat_map(|layer| {
|
||||||
|
let first = 5 + layer * 3;
|
||||||
|
[wire(first, layer + 1, 1), wire(first + 1, first, 0), wire(first + 2, first + 1, 0)]
|
||||||
|
});
|
||||||
|
Graph {
|
||||||
|
nodes: [artboard].into_iter().chain(layers).chain(chains).collect(),
|
||||||
|
wires: stack_wires.into_iter().chain(chain_wires).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn releasing_a_drag_draws_every_node_where_the_drag_drew_it() {
|
||||||
|
let stack = artboard_holding_a_stack_of_layers_with_chains();
|
||||||
|
let reading_a_tree = artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own();
|
||||||
|
let drags = [
|
||||||
|
(&stack, vec![1, 2], IVec2::new(5, 0), true),
|
||||||
|
(&stack, vec![1, 2], IVec2::new(5, 0), false),
|
||||||
|
(&stack, vec![2], IVec2::new(5, 0), false),
|
||||||
|
(&stack, vec![3], IVec2::new(0, -2), true),
|
||||||
|
(&stack, vec![3], IVec2::new(0, 3), true),
|
||||||
|
(&stack, vec![3], IVec2::new(0, -2), false),
|
||||||
|
(&stack, vec![3], IVec2::new(0, 3), false),
|
||||||
|
(&reading_a_tree, vec![2], IVec2::new(0, 3), true),
|
||||||
|
(&reading_a_tree, vec![2], IVec2::new(5, 0), true),
|
||||||
|
];
|
||||||
|
for (start, dragged, offset, keep_upstream) in drags {
|
||||||
|
let mut drag = Drag::new(start.clone(), Layout::new(start), dragged.iter().copied().map(at).collect(), keep_upstream);
|
||||||
|
let (_, dragging) = drag.moved(offset);
|
||||||
|
let released = Layout::new(&drag.released(offset));
|
||||||
|
|
||||||
|
let node_count = u32::try_from(start.nodes.len()).unwrap();
|
||||||
|
let drawn = |layout: &Layout| (0..node_count).map(|index| layout.node(at(index)).position).collect::<Vec<_>>();
|
||||||
|
assert_eq!(drawn(&released), drawn(&dragging), "dragging {dragged:?} by {offset} keeping upstream: {keep_upstream}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn layers_closed_up_under_the_layer_holding_them_cannot_be_pushed_up_into_it() {
|
||||||
|
let start = artboard_holding_a_stack_of_layers_with_chains();
|
||||||
|
for keep_upstream in [false, true] {
|
||||||
|
let (_, layout) = Drag::new(start.clone(), Layout::new(&start), vec![at(3)], keep_upstream).moved(IVec2::new(0, -2));
|
||||||
|
assert_eq!(layout.node(at(1)).position, Layout::new(&start).node(at(1)).position, "keeping upstream: {keep_upstream}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own() -> Graph {
|
||||||
|
Graph {
|
||||||
|
nodes: vec![
|
||||||
|
layer(Placement::Absolute(IVec2::new(30, 10))),
|
||||||
|
layer(Placement::Relative(IVec2::new(-8, 3))),
|
||||||
|
layer(stacked(0)),
|
||||||
|
node(CHAINED),
|
||||||
|
node(Placement::Absolute(IVec2::new(0, 30))),
|
||||||
|
node(CHAINED),
|
||||||
|
],
|
||||||
|
wires: vec![wire(1, 0, 1), wire(2, 1, 0), wire(3, 2, 1), wire(4, 3, 0), wire(5, 4, 0)],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_layer_dragged_with_its_upstream_kept_carries_the_trees_its_chain_reads() {
|
||||||
|
let graph = artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own();
|
||||||
|
|
||||||
|
assert_eq!(moved_by_dragging(&graph, &[2], IVec2::new(0, 3)), vec![2, 3, 4, 5]);
|
||||||
|
assert_eq!(moved_by_dragging(&graph, &[2], IVec2::new(5, 0)), vec![1, 2, 3, 4, 5]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_trees_a_blocked_layer_reads_stay_with_it() {
|
||||||
|
assert_eq!(
|
||||||
|
moved_by_dragging(&artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own(), &[2], IVec2::new(0, -2)),
|
||||||
|
Vec::<u32>::new()
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Only the definitions of nodes built from a nested network, such as the empty "Custom Node", are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
|
Only the definitions of built-in nodes made from a nested network are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
|
||||||
|
|
||||||
## Inspector
|
## Inspector
|
||||||
|
|
||||||
|
|||||||
@@ -542,9 +542,16 @@ tagged_value! {
|
|||||||
GlowTechnique(graphic_types::GlowTechnique),
|
GlowTechnique(graphic_types::GlowTechnique),
|
||||||
GlowSource(graphic_types::GlowSource),
|
GlowSource(graphic_types::GlowSource),
|
||||||
MaskMode(graphic_types::MaskMode),
|
MaskMode(graphic_types::MaskMode),
|
||||||
|
MinimumMaximumMode(graphic_types::MinimumMaximumMode),
|
||||||
BevelStyle(graphic_types::BevelStyle),
|
BevelStyle(graphic_types::BevelStyle),
|
||||||
BevelDirection(graphic_types::BevelDirection),
|
BevelDirection(graphic_types::BevelDirection),
|
||||||
BevelTechnique(graphic_types::BevelTechnique),
|
BevelTechnique(graphic_types::BevelTechnique),
|
||||||
|
NoiseDistribution(graphic_types::NoiseDistribution),
|
||||||
|
RadialBlurMethod(graphic_types::RadialBlurMethod),
|
||||||
|
WarpStyle(graphic_types::WarpStyle),
|
||||||
|
WaveType(graphic_types::WaveType),
|
||||||
|
DisplaceMode(graphic_types::DisplaceMode),
|
||||||
|
BlendIfChannel(graphic_types::BlendIfChannel),
|
||||||
GridType(vector::misc::GridType),
|
GridType(vector::misc::GridType),
|
||||||
GridTopology(vector::misc::GridTopology),
|
GridTopology(vector::misc::GridTopology),
|
||||||
ArcType(vector::misc::ArcType),
|
ArcType(vector::misc::ArcType),
|
||||||
@@ -679,18 +686,24 @@ impl TaggedValue {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Inspector's X, Y, W, H (e.g. "0., 0., 1000., 1000."), rendered at 100% resolution
|
// The Inspector's X, Y, W, H (e.g. "0., 0., 1000., 1000."), as a transform's translation and scale
|
||||||
fn to_footprint(input: &str) -> Option<Footprint> {
|
fn to_daffine2(input: &str) -> Option<DAffine2> {
|
||||||
let values: Option<Vec<f64>> = input.split(',').map(to_number).collect();
|
let values: Option<Vec<f64>> = input.split(',').map(to_number).collect();
|
||||||
let Some(&[x, y, width, height]) = values.as_deref() else {
|
let Some(&[x, y, width, height]) = values.as_deref() else {
|
||||||
log::error!("Invalid Footprint default, which needs X, Y, W, H: {input}");
|
log::error!("Invalid default, which needs X, Y, W, H: {input}");
|
||||||
return None;
|
return None;
|
||||||
};
|
};
|
||||||
let size = DVec2::new(width, height);
|
|
||||||
|
Some(DAffine2::from_scale_angle_translation(DVec2::new(width, height), 0., DVec2::new(x, y)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// The Inspector's X, Y, W, H, rendered at 100% resolution
|
||||||
|
fn to_footprint(input: &str) -> Option<Footprint> {
|
||||||
|
let transform = to_daffine2(input)?;
|
||||||
|
|
||||||
Some(Footprint {
|
Some(Footprint {
|
||||||
transform: DAffine2::from_scale_angle_translation(size, 0., DVec2::new(x, y)),
|
transform,
|
||||||
resolution: size.as_uvec2(),
|
resolution: transform.matrix2.diagonal().as_uvec2(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -714,6 +727,22 @@ impl TaggedValue {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn to_gradient_spread(input: &str) -> Option<vector::style::GradientSpread> {
|
||||||
|
use vector::style::GradientSpread;
|
||||||
|
|
||||||
|
let Some(("GradientSpread", variant)) = input.split_once("::").map(|(first, second)| (first.trim(), second.trim())) else {
|
||||||
|
log::error!("Invalid GradientSpread default type: {input}");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let spread = [GradientSpread::Pad, GradientSpread::Reflect, GradientSpread::Repeat, GradientSpread::Clear]
|
||||||
|
.into_iter()
|
||||||
|
.find(|spread| format!("{spread:?}") == variant);
|
||||||
|
if spread.is_none() {
|
||||||
|
log::error!("Invalid GradientSpread default type variant: {input}");
|
||||||
|
}
|
||||||
|
spread
|
||||||
|
}
|
||||||
|
|
||||||
fn to_blend_mode(input: &str) -> Option<core_types::blending::BlendMode> {
|
fn to_blend_mode(input: &str) -> Option<core_types::blending::BlendMode> {
|
||||||
use core_types::blending::BlendMode;
|
use core_types::blending::BlendMode;
|
||||||
|
|
||||||
@@ -747,6 +776,7 @@ impl TaggedValue {
|
|||||||
() if ty == TypeId::of::<f64>() => to_number(string).map(TaggedValue::Number)?,
|
() if ty == TypeId::of::<f64>() => to_number(string).map(TaggedValue::Number)?,
|
||||||
() if ty == TypeId::of::<i64>() => to_number(string).map(TaggedValue::Integer)?,
|
() if ty == TypeId::of::<i64>() => to_number(string).map(TaggedValue::Integer)?,
|
||||||
() if ty == TypeId::of::<DVec2>() => to_dvec2(string).map(TaggedValue::DVec2)?,
|
() if ty == TypeId::of::<DVec2>() => to_dvec2(string).map(TaggedValue::DVec2)?,
|
||||||
|
() if ty == TypeId::of::<DAffine2>() => to_daffine2(string).map(TaggedValue::DAffine2)?,
|
||||||
() if ty == TypeId::of::<bool>() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?,
|
() if ty == TypeId::of::<bool>() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?,
|
||||||
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
|
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
|
||||||
// The Fill/Stroke paint wires carry `Graphic` or `Gradient` elements, so a paint default parses through the element recursion as a color or gradient literal
|
// The Fill/Stroke paint wires carry `Graphic` or `Gradient` elements, so a paint default parses through the element recursion as a color or gradient literal
|
||||||
@@ -756,6 +786,7 @@ impl TaggedValue {
|
|||||||
() if ty == TypeId::of::<Footprint>() => to_footprint(string).map(TaggedValue::Footprint)?,
|
() if ty == TypeId::of::<Footprint>() => to_footprint(string).map(TaggedValue::Footprint)?,
|
||||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||||
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
|
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
|
||||||
|
() if ty == TypeId::of::<vector::style::GradientSpread>() => to_gradient_spread(string).map(TaggedValue::GradientSpread)?,
|
||||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
||||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||||
_ => {
|
_ => {
|
||||||
@@ -974,8 +1005,6 @@ pub enum RenderOutputType {
|
|||||||
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
|
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
|
||||||
image_data: Vec<(u64, CanvasImage)>,
|
image_data: Vec<(u64, CanvasImage)>,
|
||||||
},
|
},
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
CanvasFrame { canvas_id: u64, resolution: DVec2 },
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CacheHash for RenderOutputType {
|
impl CacheHash for RenderOutputType {
|
||||||
@@ -992,11 +1021,6 @@ impl CacheHash for RenderOutputType {
|
|||||||
svg.cache_hash(state);
|
svg.cache_hash(state);
|
||||||
image_data.cache_hash(state);
|
image_data.cache_hash(state);
|
||||||
}
|
}
|
||||||
#[cfg(target_family = "wasm")]
|
|
||||||
Self::CanvasFrame { canvas_id, resolution } => {
|
|
||||||
canvas_id.cache_hash(state);
|
|
||||||
resolution.cache_hash(state);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1128,6 +1152,13 @@ mod number_default_parsing {
|
|||||||
);
|
);
|
||||||
assert_eq!(TaggedValue::from_primitive_string("1., 2., 3.", &item!(Footprint)), None);
|
assert_eq!(TaggedValue::from_primitive_string("1., 2., 3.", &item!(Footprint)), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn transform_defaults_parse_as_x_y_width_height() {
|
||||||
|
let expected = DAffine2::from_scale_angle_translation(DVec2::new(500., 400.), 0., DVec2::new(250., -20.));
|
||||||
|
assert_eq!(TaggedValue::from_primitive_string("250., - 20., 500., 400.", &item!(DAffine2)), Some(TaggedValue::DAffine2(expected)));
|
||||||
|
assert_eq!(TaggedValue::from_primitive_string("1., 2.", &item!(DAffine2)), None);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ use graphene_std::application_io::ApplicationIo;
|
|||||||
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
||||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||||
use interpreted_executor::layer_paths::write_layer_paths;
|
use interpreted_executor::layer_paths::write_layer_paths;
|
||||||
use interpreted_executor::util::wrap_network_in_scope;
|
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
@@ -95,7 +95,7 @@ pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc<PlatformApplicationIo>, Arc
|
|||||||
/// Compile `network`, writing the path of each of its `layers` onto what that layer renders.
|
/// Compile `network`, writing the path of each of its `layers` onto what that layer renders.
|
||||||
pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||||
write_layer_paths(&mut network, layers);
|
write_layer_paths(&mut network, layers);
|
||||||
let mut network = wrap_network_in_scope(network, editor_api, runtime);
|
let mut network = wrap_network_with_render_node_in_scope(network, editor_api, runtime);
|
||||||
|
|
||||||
let preprocessor = preprocessor::Preprocessor::new();
|
let preprocessor = preprocessor::Preprocessor::new();
|
||||||
let preprocessed = match gdd {
|
let preprocessed = match gdd {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use graph_craft::util::{DEMO_ART, compile};
|
|||||||
use graphene_std::application_io::EditorApi;
|
use graphene_std::application_io::EditorApi;
|
||||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||||
use interpreted_executor::util::wrap_network_in_scope;
|
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork) {
|
pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork) {
|
||||||
@@ -13,7 +13,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
.network;
|
.network;
|
||||||
let editor_api = std::sync::Arc::new(EditorApi::default());
|
let editor_api = std::sync::Arc::new(EditorApi::default());
|
||||||
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
let mut network = wrap_network_with_render_node_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
||||||
let preprocessor = preprocessor::Preprocessor::new();
|
let preprocessor = preprocessor::Preprocessor::new();
|
||||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||||
let proto_network = compile(network);
|
let proto_network = compile(network);
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ use graphene_std::{Color, Context};
|
|||||||
use gungraun::prelude::*;
|
use gungraun::prelude::*;
|
||||||
use gungraun::{Callgrind, EntryPoint};
|
use gungraun::{Callgrind, EntryPoint};
|
||||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||||
use interpreted_executor::util::wrap_network_in_scope;
|
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||||
use std::hint::black_box;
|
use std::hint::black_box;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use wgpu_executor::{WgpuContextBuilder, WgpuExecutor};
|
use wgpu_executor::{WgpuContextBuilder, WgpuExecutor};
|
||||||
@@ -70,7 +70,7 @@ impl Session {
|
|||||||
|
|
||||||
/// Recompiles the document graph into the executor and renders the viewport, as the runtime does after an edit.
|
/// Recompiles the document graph into the executor and renders the viewport, as the runtime does after an edit.
|
||||||
fn update(&mut self, document: NodeNetwork) {
|
fn update(&mut self, document: NodeNetwork) {
|
||||||
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||||
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
|
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
|
||||||
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
|
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
|
||||||
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
|
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
|||||||
use graph_craft::document::value::RenderOutput;
|
use graph_craft::document::value::RenderOutput;
|
||||||
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
|
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
|
||||||
use graphene_animation::AnimationCurve;
|
use graphene_animation::AnimationCurve;
|
||||||
|
use graphene_std::WarpStyle;
|
||||||
use graphene_std::animation::RealTimeMode;
|
use graphene_std::animation::RealTimeMode;
|
||||||
use graphene_std::any::DynAnyNode;
|
use graphene_std::any::DynAnyNode;
|
||||||
use graphene_std::brush::Stroke;
|
use graphene_std::brush::Stroke;
|
||||||
@@ -28,7 +29,8 @@ use graphene_std::vector::misc::{
|
|||||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode};
|
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||||
|
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||||
use node_registry_macros::async_node;
|
use node_registry_macros::async_node;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -153,14 +155,24 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
)
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
// Keeps an adapter row under the identifier the preprocessor names it by and repeats it under the adapter node's own identifier,
|
||||||
|
// which the new compiler selects by signature
|
||||||
|
macro_rules! also_under_own_identifier {
|
||||||
|
($module:ident, $row:expr) => {{
|
||||||
|
let row: (ProtoNodeIdentifier, NodeConstructor, NodeIOTypes) = $row;
|
||||||
|
let own = (graphene_core::ops::$module::IDENTIFIER, row.1, row.2.clone());
|
||||||
|
[row, own]
|
||||||
|
}};
|
||||||
|
}
|
||||||
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
|
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
|
||||||
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
|
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
|
||||||
macro_rules! input_adapter_row {
|
macro_rules! input_adapter_row {
|
||||||
(from_element: $from:ty, element: $element:ty) => {{
|
(from_element: $from:ty, element: $element:ty) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
also_under_own_identifier!(into_item, input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||||
input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element),
|
also_under_own_identifier!(into_list, input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
|
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
|
||||||
@@ -252,7 +264,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||||
$(
|
$(
|
||||||
entries.extend(input_adapter_node!(element: $element));
|
entries.extend(input_adapter_node!(element: $element));
|
||||||
entries.push(item_to_list_node!(element: $element));
|
entries.extend(also_under_own_identifier!(item_to_list, item_to_list_node!(element: $element)));
|
||||||
)*
|
)*
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
@@ -292,9 +304,16 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
GlowTechnique,
|
GlowTechnique,
|
||||||
GlowSource,
|
GlowSource,
|
||||||
MaskMode,
|
MaskMode,
|
||||||
|
MinimumMaximumMode,
|
||||||
BevelStyle,
|
BevelStyle,
|
||||||
BevelDirection,
|
BevelDirection,
|
||||||
BevelTechnique,
|
BevelTechnique,
|
||||||
|
NoiseDistribution,
|
||||||
|
RadialBlurMethod,
|
||||||
|
WarpStyle,
|
||||||
|
WaveType,
|
||||||
|
DisplaceMode,
|
||||||
|
BlendIfChannel,
|
||||||
Stroke,
|
Stroke,
|
||||||
ScaleType,
|
ScaleType,
|
||||||
ReferencePoint,
|
ReferencePoint,
|
||||||
@@ -350,9 +369,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
||||||
macro_rules! list_dyn_rows {
|
macro_rules! list_dyn_rows {
|
||||||
($($element:ty),* $(,)?) => {{
|
($($element:ty),* $(,)?) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
$(input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn),)*
|
$(also_under_own_identifier!(into, input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn)),)*
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -385,8 +405,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
($($element:ty),* $(,)?) => {{
|
($($element:ty),* $(,)?) => {{
|
||||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||||
$(
|
$(
|
||||||
entries.push(bundle_node!(element: $element));
|
entries.extend(also_under_own_identifier!(bundle, bundle_node!(element: $element)));
|
||||||
entries.push(unbundle_node!(element: $element));
|
entries.extend(also_under_own_identifier!(unbundle, unbundle_node!(element: $element)));
|
||||||
)*
|
)*
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
@@ -446,10 +466,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
|
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
|
||||||
macro_rules! embed_adapter_row {
|
macro_rules! embed_adapter_row {
|
||||||
(from_element: $from:ty, element: $element:ty) => {{
|
(from_element: $from:ty, element: $element:ty) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
also_under_own_identifier!(embed_item, input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||||
input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element),
|
also_under_own_identifier!(embed_list, input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -466,10 +487,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
|
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
|
||||||
macro_rules! convert_adapter_node {
|
macro_rules! convert_adapter_node {
|
||||||
(from_element: $from:ty, element: $element:ty) => {{
|
(from_element: $from:ty, element: $element:ty) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
also_under_own_identifier!(convert_item, input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||||
input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element),
|
also_under_own_identifier!(convert_list, input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -491,13 +513,19 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
||||||
macro_rules! attribute_value_node {
|
macro_rules! attribute_value_node {
|
||||||
(Item<$element:ty>) => {
|
(Item<$element:ty>) => {
|
||||||
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
also_under_own_identifier!(
|
||||||
|
item_to_attribute_value,
|
||||||
|
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||||
|
)
|
||||||
};
|
};
|
||||||
(List<$element:ty>) => {
|
(List<$element:ty>) => {
|
||||||
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
also_under_own_identifier!(
|
||||||
|
list_to_attribute_value,
|
||||||
|
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||||
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
attribute_value_node!(Item<f64>),
|
attribute_value_node!(Item<f64>),
|
||||||
attribute_value_node!(Item<i64>),
|
attribute_value_node!(Item<i64>),
|
||||||
attribute_value_node!(Item<bool>),
|
attribute_value_node!(Item<bool>),
|
||||||
@@ -522,7 +550,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
attribute_value_node!(List<Raster<GPU>>),
|
attribute_value_node!(List<Raster<GPU>>),
|
||||||
attribute_value_node!(List<Graphic>),
|
attribute_value_node!(List<Graphic>),
|
||||||
attribute_value_node!(List<Artboard>),
|
attribute_value_node!(List<Artboard>),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
node_types.extend(attribute_value_rows);
|
node_types.extend(attribute_value_rows);
|
||||||
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
|
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
|
||||||
macro_rules! transform_list_node {
|
macro_rules! transform_list_node {
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use graphene_std::RuntimeHandle;
|
|||||||
use graphene_std::uuid::NodeId;
|
use graphene_std::uuid::NodeId;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
pub fn wrap_network_with_render_node_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
||||||
let definitions = std::mem::take(&mut network.definitions);
|
let definitions = std::mem::take(&mut network.definitions);
|
||||||
|
|
||||||
let inner_network = DocumentNode {
|
let inner_network = DocumentNode {
|
||||||
@@ -114,10 +114,28 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let network = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||||
|
nodes: [(NodeId(0), inner_network), (NodeId(1), render_node)].into_iter().collect(),
|
||||||
|
definitions,
|
||||||
|
generated: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
wrap_network_in_scope(network, editor_api, runtime)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
||||||
|
let definitions = std::mem::take(&mut network.definitions);
|
||||||
|
|
||||||
|
let inner_network = DocumentNode {
|
||||||
|
implementation: DocumentNodeImplementation::Network(network),
|
||||||
|
inputs: vec![],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
// wrap the inner network in a scope
|
// wrap the inner network in a scope
|
||||||
let nodes = vec![
|
let nodes = vec![
|
||||||
inner_network,
|
inner_network,
|
||||||
render_node,
|
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
|
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
|
||||||
inputs: vec![NodeInput::value(TaggedValue::EditorApi(editor_api), false)],
|
inputs: vec![NodeInput::value(TaggedValue::EditorApi(editor_api), false)],
|
||||||
@@ -130,12 +148,12 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
let scope_injections = vec![
|
let scope_injections = vec![
|
||||||
("editor-api".to_string(), (NodeId(2), item!(Arc<PlatformEditorApi>))),
|
("editor-api".to_string(), (NodeId(1), item!(Arc<PlatformEditorApi>))),
|
||||||
("runtime".to_string(), (NodeId(3), item!(RuntimeHandle))),
|
("runtime".to_string(), (NodeId(2), item!(RuntimeHandle))),
|
||||||
];
|
];
|
||||||
|
|
||||||
NodeNetwork {
|
NodeNetwork {
|
||||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
exports: vec![NodeInput::node(NodeId(0), 0)],
|
||||||
nodes: nodes.into_iter().enumerate().map(|(id, node)| (NodeId(id as u64), node)).collect(),
|
nodes: nodes.into_iter().enumerate().map(|(id, node)| (NodeId(id as u64), node)).collect(),
|
||||||
scope_injections: scope_injections.into_iter().collect(),
|
scope_injections: scope_injections.into_iter().collect(),
|
||||||
definitions,
|
definitions,
|
||||||
|
|||||||
@@ -72,31 +72,32 @@ impl BlendMode {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The subset of [`BlendMode::list()`] that is supported by SVG.
|
|
||||||
pub fn list_svg_subset() -> [&'static [BlendMode]; 6] {
|
|
||||||
use BlendMode::*;
|
|
||||||
[
|
|
||||||
// Normal group
|
|
||||||
&[Normal],
|
|
||||||
// Darken group
|
|
||||||
&[Darken, Multiply, ColorBurn],
|
|
||||||
// Lighten group
|
|
||||||
&[Lighten, Screen, ColorDodge],
|
|
||||||
// Contrast group
|
|
||||||
&[Overlay, SoftLight, HardLight],
|
|
||||||
// Inversion group
|
|
||||||
&[Difference, Exclusion],
|
|
||||||
// Component group
|
|
||||||
&[Hue, Saturation, Color, Luminosity],
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn index_in_list(&self) -> Option<usize> {
|
pub fn index_in_list(&self) -> Option<usize> {
|
||||||
Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
|
Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn index_in_list_svg_subset(&self) -> Option<usize> {
|
/// Whether a layer in this mode reads what lies beneath it to blend, since neither SVG's `mix-blend-mode` nor Vello's layers have the mode.
|
||||||
Self::list_svg_subset().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
|
/// The alpha-only utility modes, hidden from the list, draw layers normally.
|
||||||
|
pub fn reads_backdrop(&self) -> bool {
|
||||||
|
self.to_svg_style_name().is_none() && !matches!(self, BlendMode::Erase | BlendMode::Restore | BlendMode::MultiplyAlpha)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a paint's strength (an effect's opacity, or a layer's fill) moves its color toward the mode's neutral color, which then blends at full strength, rather than fading the blend, for PSD interop.
|
||||||
|
pub fn strength_moves_toward_neutral(&self) -> bool {
|
||||||
|
use BlendMode::*;
|
||||||
|
matches!(self, ColorDodge | LinearDodge | ColorBurn | LinearBurn | VividLight | LinearLight | HardMix)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a layer's fill moves its content toward the mode's neutral color (see [`Self::strength_moves_toward_neutral`]) rather than fading it, for PSD interop.
|
||||||
|
/// The layer then reads what lies beneath it to blend (see [`Self::layer_reads_backdrop`]).
|
||||||
|
pub fn fill_moves_layer_toward_neutral(&self) -> bool {
|
||||||
|
self.strength_moves_toward_neutral()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a layer in this mode at this `fill` reads what lies beneath it to blend: in a mode neither SVG's `mix-blend-mode` nor Vello's layers have,
|
||||||
|
/// or below a full fill moving it toward the mode's neutral color, which Color Dodge and Color Burn layers otherwise blend natively without.
|
||||||
|
pub fn layer_reads_backdrop(&self, fill: f32) -> bool {
|
||||||
|
self.reads_backdrop() || (fill < 1. && self.fill_moves_layer_toward_neutral())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convert the enum to the CSS string for the blend mode.
|
/// Convert the enum to the CSS string for the blend mode.
|
||||||
@@ -130,11 +131,14 @@ impl BlendMode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Renders the blend mode CSS style declaration.
|
/// Renders the blend mode CSS style declaration.
|
||||||
|
/// A mode CSS lacks, which layers read what lies beneath to blend by, draws normally where nothing beneath can be read, as for content without bounds.
|
||||||
pub fn render(&self) -> String {
|
pub fn render(&self) -> String {
|
||||||
format!(
|
format!(
|
||||||
r#" mix-blend-mode: {};"#,
|
r#" mix-blend-mode: {};"#,
|
||||||
self.to_svg_style_name().unwrap_or_else(|| {
|
self.to_svg_style_name().unwrap_or_else(|| {
|
||||||
log::warn!("Unsupported blend mode {self:?}");
|
if !self.reads_backdrop() {
|
||||||
|
log::warn!("Unsupported blend mode {self:?}");
|
||||||
|
}
|
||||||
"normal"
|
"normal"
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
@@ -156,7 +160,7 @@ impl Display for BlendMode {
|
|||||||
BlendMode::Lighten => write!(f, "Lighten"),
|
BlendMode::Lighten => write!(f, "Lighten"),
|
||||||
BlendMode::Screen => write!(f, "Screen"),
|
BlendMode::Screen => write!(f, "Screen"),
|
||||||
BlendMode::ColorDodge => write!(f, "Color Dodge"),
|
BlendMode::ColorDodge => write!(f, "Color Dodge"),
|
||||||
BlendMode::LinearDodge => write!(f, "Linear Dodge"),
|
BlendMode::LinearDodge => write!(f, "Linear Dodge (Add)"),
|
||||||
BlendMode::LighterColor => write!(f, "Lighter Color"),
|
BlendMode::LighterColor => write!(f, "Lighter Color"),
|
||||||
// Contrast group
|
// Contrast group
|
||||||
BlendMode::Overlay => write!(f, "Overlay"),
|
BlendMode::Overlay => write!(f, "Overlay"),
|
||||||
@@ -247,6 +251,30 @@ pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendM
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How strongly a layer whose fill moves it toward neutral (see [`BlendMode::fill_moves_layer_toward_neutral`]) shows over a backdrop of `backdrop_alpha`: fully over an opaque one,
|
||||||
|
/// by its `fill` over nothing, and between, the harmonic mean of the two weighted by that alpha, which shows nothing at no fill.
|
||||||
|
pub fn layer_fill_shown(backdrop_alpha: f32, fill: f32) -> f32 {
|
||||||
|
let weighted = (1. - backdrop_alpha) + backdrop_alpha * fill;
|
||||||
|
if weighted <= 0. { 0. } else { (fill / weighted).min(1.) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`apply_blend_mode`], with the foreground at `strength` (from 0 to 1) moved toward the mode's neutral color where it does that (see [`BlendMode::strength_moves_toward_neutral`]),
|
||||||
|
/// for the caller to composite at full strength. Other modes take the foreground as it is, for the caller to fade the blend by the strength.
|
||||||
|
pub fn apply_blend_mode_at_strength(foreground: Color, background: Color, blend_mode: BlendMode, strength: f32) -> Color {
|
||||||
|
let toward = |neutral: f32| {
|
||||||
|
let moved = |channel: f32| neutral + strength * (channel - neutral);
|
||||||
|
Color::from_rgbaf32_unchecked(moved(foreground.r()), moved(foreground.g()), moved(foreground.b()), foreground.a())
|
||||||
|
};
|
||||||
|
|
||||||
|
match blend_mode {
|
||||||
|
BlendMode::ColorDodge | BlendMode::LinearDodge => apply_blend_mode(toward(0.), background, blend_mode),
|
||||||
|
BlendMode::ColorBurn | BlendMode::LinearBurn => apply_blend_mode(toward(1.), background, blend_mode),
|
||||||
|
BlendMode::VividLight | BlendMode::LinearLight => apply_blend_mode(toward(0.5), background, blend_mode),
|
||||||
|
BlendMode::HardMix => background.blend_rgb(foreground, |backdrop, source| Color::blend_hard_mix_at_strength(backdrop, source, strength)),
|
||||||
|
_ => apply_blend_mode(foreground, background, blend_mode),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -261,9 +289,13 @@ mod tests {
|
|||||||
assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}");
|
assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Color Dodge gives white for a white source, and Divide keeps a black backdrop black and turns any other white under a black source
|
// Color Dodge, like Divide, keeps a black backdrop black under any source, even white, and turns any other white under a white source.
|
||||||
|
// Divide also turns any other white under a black source.
|
||||||
|
for backdrop in [0., 1e-7, -1e-7] {
|
||||||
|
assert_eq!(Color::blend_color_dodge(backdrop, 1.), 0., "a backdrop of {backdrop}");
|
||||||
|
}
|
||||||
for source in [1., 1. - 1e-7, 1. + 2e-7] {
|
for source in [1., 1. - 1e-7, 1. + 2e-7] {
|
||||||
assert_eq!(Color::blend_color_dodge(0., source), 1., "a source of {source}");
|
assert_eq!(Color::blend_color_dodge(0.5, source), 1., "a source of {source}");
|
||||||
}
|
}
|
||||||
for backdrop in [0., 1e-7, -1e-7] {
|
for backdrop in [0., 1e-7, -1e-7] {
|
||||||
assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}");
|
assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}");
|
||||||
@@ -339,6 +371,65 @@ mod tests {
|
|||||||
assert!((blended.a() - 1.).abs() < 1e-5, "alpha was {}", blended.a());
|
assert!((blended.a() - 1.).abs() < 1e-5, "alpha was {}", blended.a());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn darker_and_lighter_color_pick_the_whole_color_by_luma() {
|
||||||
|
// Blue's luma (0.11) is below the gray's (0.3), though its mean channel (a third) is above it
|
||||||
|
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||||
|
let gray = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 1.);
|
||||||
|
|
||||||
|
assert_eq!(apply_blend_mode(gray, blue, BlendMode::DarkerColor), blue);
|
||||||
|
assert_eq!(apply_blend_mode(gray, blue, BlendMode::LighterColor), gray);
|
||||||
|
assert_eq!(apply_blend_mode(blue, gray, BlendMode::DarkerColor), blue);
|
||||||
|
|
||||||
|
// Where the lumas tie, the backdrop stays, with the paint's alpha
|
||||||
|
let tied = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 0.5);
|
||||||
|
assert_eq!(apply_blend_mode(tied, gray, BlendMode::DarkerColor), gray.with_alpha(0.5));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hard_mix_ramps_steeper_with_strength_to_a_256th_wide_where_the_channels_sum_to_one() {
|
||||||
|
let hard_mix = |backdrop: f32, source: f32, strength: f32| Color::blend_hard_mix_at_strength(backdrop, source, strength).clamp(0., 1.);
|
||||||
|
|
||||||
|
// At full strength, white past a sum of 1 and black short of it, even a level away
|
||||||
|
assert_eq!(hard_mix(0.6, 0.5, 1.), 1.);
|
||||||
|
assert_eq!(hard_mix(0.5, 0.49, 1.), 0.);
|
||||||
|
assert_eq!(hard_mix(0.5, 0.51, 1.), 1.);
|
||||||
|
|
||||||
|
// For PSD interop, half a fill gives clamp(2b - 1 + s), and no strength leaves the backdrop as it is
|
||||||
|
for (backdrop, source) in [(0.5, 0.3), (0.4, 0.4), (0.7, 0.1)] {
|
||||||
|
let half = hard_mix(backdrop, source, 128. / 255.);
|
||||||
|
assert!((half - (2. * backdrop - 1. + source).clamp(0., 1.)).abs() < 0.01, "{backdrop}, {source}: {half}");
|
||||||
|
assert_eq!(hard_mix(backdrop, source, 0.), backdrop);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn strength_moves_a_paint_toward_the_modes_neutral_color() {
|
||||||
|
let backdrop = Color::from_rgbaf32_unchecked(0.4, 0.4, 0.4, 1.);
|
||||||
|
let paint = Color::from_rgbaf32_unchecked(0.8, 0.8, 0.8, 1.);
|
||||||
|
let at_half = |blend_mode: BlendMode| apply_blend_mode_at_strength(paint, backdrop, blend_mode, 0.5).r();
|
||||||
|
|
||||||
|
// Half the paint added, the paint halfway to white burned in, and the paint halfway to middle gray lighting
|
||||||
|
assert!((at_half(BlendMode::LinearDodge) - 0.8).abs() < 1e-6, "{}", at_half(BlendMode::LinearDodge));
|
||||||
|
assert!((at_half(BlendMode::LinearBurn) - 0.3).abs() < 1e-6, "{}", at_half(BlendMode::LinearBurn));
|
||||||
|
assert!((at_half(BlendMode::LinearLight) - 0.7).abs() < 1e-6, "{}", at_half(BlendMode::LinearLight));
|
||||||
|
|
||||||
|
// The modes whose strength fades their blend take the paint as it is
|
||||||
|
assert_eq!(at_half(BlendMode::Subtract), apply_blend_mode(paint, backdrop, BlendMode::Subtract).r());
|
||||||
|
|
||||||
|
// Layers read what lies beneath for the ten modes CSS lacks, of which five move their content toward neutral by their fill
|
||||||
|
let reading: Vec<BlendMode> = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop).collect();
|
||||||
|
assert_eq!(reading.len(), 10);
|
||||||
|
assert_eq!(reading.iter().filter(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()).count(), 5);
|
||||||
|
assert!(!BlendMode::Erase.reads_backdrop());
|
||||||
|
|
||||||
|
// Color Dodge and Color Burn do too below a full fill, which they otherwise blend natively at
|
||||||
|
for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] {
|
||||||
|
assert!(!blend_mode.reads_backdrop() && !blend_mode.layer_reads_backdrop(1.) && blend_mode.layer_reads_backdrop(0.5) && blend_mode.layer_reads_backdrop(0.));
|
||||||
|
}
|
||||||
|
assert!(!BlendMode::Multiply.layer_reads_backdrop(0.5) && BlendMode::LinearBurn.layer_reads_backdrop(1.));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn source_over_weights_straight_colors_by_alpha() {
|
fn source_over_weights_straight_colors_by_alpha() {
|
||||||
let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5);
|
let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5);
|
||||||
|
|||||||
@@ -633,14 +633,20 @@ impl Color {
|
|||||||
c_b + c_s - 1.
|
c_b + c_s - 1.
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whole-color "Darker Color" blend: keeps whichever color has the lower mean RGB, with `other`'s alpha.
|
/// Whole-color "Darker Color" blend: keeps whichever color has the lower luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn blend_darker_color(&self, other: Color) -> Color {
|
pub fn blend_darker_color(&self, other: Color) -> Color {
|
||||||
let darker = if self.average_rgb_channels() <= other.average_rgb_channels() { *self } else { other };
|
let darker = if self.blend_luma() <= other.blend_luma() { *self } else { other };
|
||||||
|
|
||||||
darker.with_alpha(other.alpha)
|
darker.with_alpha(other.alpha)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The luma that Darker Color and Lighter Color compare, as the component blend modes measure it.
|
||||||
|
#[inline(always)]
|
||||||
|
fn blend_luma(&self) -> f32 {
|
||||||
|
luma_rec_601_rounded(self.red, self.green, self.blue)
|
||||||
|
}
|
||||||
|
|
||||||
/// Per-channel "Screen" blend.
|
/// Per-channel "Screen" blend.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn blend_screen(c_b: f32, c_s: f32) -> f32 {
|
pub fn blend_screen(c_b: f32, c_s: f32) -> f32 {
|
||||||
@@ -653,10 +659,16 @@ impl Color {
|
|||||||
c_s.max(c_b)
|
c_s.max(c_b)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Per-channel "Color Dodge" blend.
|
/// Per-channel "Color Dodge" blend, where a black backdrop stays black and any other turns white under a white source, as the W3C formula orders them.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
|
pub fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
|
||||||
if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE { 1. } else { (c_b / (1. - c_s)).min(1.) }
|
if c_b.abs() <= BLEND_EDGE_TOLERANCE {
|
||||||
|
0.
|
||||||
|
} else if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE {
|
||||||
|
1.
|
||||||
|
} else {
|
||||||
|
(c_b / (1. - c_s)).min(1.)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Per-channel "Linear Dodge" (Add) blend.
|
/// Per-channel "Linear Dodge" (Add) blend.
|
||||||
@@ -665,10 +677,10 @@ impl Color {
|
|||||||
c_b + c_s
|
c_b + c_s
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher mean RGB, with `other`'s alpha.
|
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn blend_lighter_color(&self, other: Color) -> Color {
|
pub fn blend_lighter_color(&self, other: Color) -> Color {
|
||||||
let lighter = if self.average_rgb_channels() >= other.average_rgb_channels() { *self } else { other };
|
let lighter = if self.blend_luma() >= other.blend_luma() { *self } else { other };
|
||||||
|
|
||||||
lighter.with_alpha(other.alpha)
|
lighter.with_alpha(other.alpha)
|
||||||
}
|
}
|
||||||
@@ -724,9 +736,15 @@ impl Color {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Per-channel "Hard Mix" blend: thresholds Linear Light at 0.5.
|
/// Per-channel "Hard Mix" blend: white where the channels sum to at least 1 and black below, along a ramp a 256th wide at full strength, for PSD interop.
|
||||||
pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 {
|
pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 {
|
||||||
if Color::blend_linear_light(c_b, c_s) < 0.5 { 0. } else { 1. }
|
Color::blend_hard_mix_at_strength(c_b, c_s, 1.)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Per-channel "Hard Mix" blend of a paint at `strength` (from 0 to 1), unclamped, whose ramp steepens from none (the backdrop as it is) to a 256th wide at full strength, for PSD interop.
|
||||||
|
pub fn blend_hard_mix_at_strength(c_b: f32, c_s: f32, strength: f32) -> f32 {
|
||||||
|
let steepness = 255. * strength / 256.;
|
||||||
|
(c_b - steepness * (1. - c_s)) / (1. - steepness)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Per-channel "Difference" blend.
|
/// Per-channel "Difference" blend.
|
||||||
|
|||||||
@@ -805,6 +805,11 @@ impl OwnedContextImpl {
|
|||||||
self.varargs = Some(Arc::new([value]));
|
self.varargs = Some(Arc::new([value]));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
pub fn with_varargs<const N: usize>(mut self, values: [Box<dyn AnyHash + Send + Sync>; N]) -> Self {
|
||||||
|
assert!(self.varargs.is_none_or(|value| value.is_empty()));
|
||||||
|
self.varargs = Some(Arc::new(values));
|
||||||
|
self
|
||||||
|
}
|
||||||
pub fn with_generations(mut self, generations: Generations) -> Self {
|
pub fn with_generations(mut self, generations: Generations) -> Self {
|
||||||
self.generations = (!generations.is_empty()).then_some(generations);
|
self.generations = (!generations.is_empty()).then_some(generations);
|
||||||
self
|
self
|
||||||
|
|||||||
@@ -281,11 +281,11 @@ impl<'a, N> LazyInput<'a, N> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn eval<Input>(&self, input: Input) -> Result<N::Output, Interrupt>
|
pub fn eval<Input>(&self, input: &Input) -> Result<N::Output, Interrupt>
|
||||||
where
|
where
|
||||||
N: Node<Input>,
|
N: Node<Input>,
|
||||||
{
|
{
|
||||||
self.status.record(self.index, self.node.eval(&input))
|
self.status.record(self.index, self.node.eval(input))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,17 @@ pub struct NodeFlags {
|
|||||||
pub forwards_input: bool,
|
pub forwards_input: bool,
|
||||||
pub inject_scope: bool,
|
pub inject_scope: bool,
|
||||||
pub asynchronous: bool,
|
pub asynchronous: bool,
|
||||||
|
/// Whether type resolution may insert this node on an edge, from `#[node_macro::node(adapter(...))]`.
|
||||||
|
pub adapter: Option<AdapterKind>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How an adapter node changes the wire it is inserted on.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum AdapterKind {
|
||||||
|
/// Converts the wire's element into another element type.
|
||||||
|
Conversion,
|
||||||
|
/// Changes the wire's rank, like raising an `Item` onto a `List`.
|
||||||
|
Rank,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Translation struct between macro and definition
|
// Translation struct between macro and definition
|
||||||
|
|||||||
@@ -232,6 +232,17 @@ impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<K: CacheHash, V: CacheHash> CacheHash for std::collections::BTreeMap<K, V> {
|
||||||
|
#[inline]
|
||||||
|
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||||
|
core::hash::Hash::hash(&self.len(), state);
|
||||||
|
for (key, value) in self {
|
||||||
|
key.cache_hash(state);
|
||||||
|
value.cache_hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
|
impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||||
|
|||||||
@@ -23,7 +23,10 @@ pub enum Adjustment {
|
|||||||
gamma: f64,
|
gamma: f64,
|
||||||
inverse: bool,
|
inverse: bool,
|
||||||
},
|
},
|
||||||
MakeOpaque,
|
MakeOpaque {
|
||||||
|
/// Percent.
|
||||||
|
strength: f64,
|
||||||
|
},
|
||||||
BrightnessContrast {
|
BrightnessContrast {
|
||||||
/// Percent.
|
/// Percent.
|
||||||
brightness: f64,
|
brightness: f64,
|
||||||
@@ -82,6 +85,7 @@ pub enum Adjustment {
|
|||||||
/// Percent.
|
/// Percent.
|
||||||
opacity: f64,
|
opacity: f64,
|
||||||
},
|
},
|
||||||
|
Solarize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Adjustment {
|
impl Adjustment {
|
||||||
@@ -89,7 +93,7 @@ impl Adjustment {
|
|||||||
match self {
|
match self {
|
||||||
Self::Desaturate { .. } => EffectKind::Desaturate,
|
Self::Desaturate { .. } => EffectKind::Desaturate,
|
||||||
Self::GammaCorrection { .. } => EffectKind::GammaCorrection,
|
Self::GammaCorrection { .. } => EffectKind::GammaCorrection,
|
||||||
Self::MakeOpaque => EffectKind::MakeOpaque,
|
Self::MakeOpaque { .. } => EffectKind::MakeOpaque,
|
||||||
Self::BrightnessContrast { .. } => EffectKind::BrightnessContrast,
|
Self::BrightnessContrast { .. } => EffectKind::BrightnessContrast,
|
||||||
Self::Levels(_) => EffectKind::Levels,
|
Self::Levels(_) => EffectKind::Levels,
|
||||||
Self::Curves(_) => EffectKind::Curves,
|
Self::Curves(_) => EffectKind::Curves,
|
||||||
@@ -107,6 +111,7 @@ impl Adjustment {
|
|||||||
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
||||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||||
|
Self::Solarize => EffectKind::Solarize,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +120,7 @@ impl Adjustment {
|
|||||||
matches!(
|
matches!(
|
||||||
self,
|
self,
|
||||||
Self::GammaCorrection { .. }
|
Self::GammaCorrection { .. }
|
||||||
| Self::MakeOpaque
|
| Self::MakeOpaque { .. }
|
||||||
| Self::BrightnessContrast { .. }
|
| Self::BrightnessContrast { .. }
|
||||||
| Self::Levels(_)
|
| Self::Levels(_)
|
||||||
| Self::Curves(_)
|
| Self::Curves(_)
|
||||||
@@ -123,6 +128,7 @@ impl Adjustment {
|
|||||||
| Self::Posterize { .. }
|
| Self::Posterize { .. }
|
||||||
| Self::Exposure { .. }
|
| Self::Exposure { .. }
|
||||||
| Self::ColorBalance(_)
|
| Self::ColorBalance(_)
|
||||||
|
| Self::Solarize
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,7 +140,8 @@ impl Adjustment {
|
|||||||
visitor.parameter("gamma", gamma, 2.2);
|
visitor.parameter("gamma", gamma, 2.2);
|
||||||
visitor.parameter("inverse", inverse, false);
|
visitor.parameter("inverse", inverse, false);
|
||||||
}
|
}
|
||||||
Self::MakeOpaque | Self::Invert => {}
|
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
||||||
|
Self::Invert | Self::Solarize => {}
|
||||||
Self::BrightnessContrast {
|
Self::BrightnessContrast {
|
||||||
brightness,
|
brightness,
|
||||||
contrast,
|
contrast,
|
||||||
@@ -293,7 +300,7 @@ impl Adjustment {
|
|||||||
pub enum DesaturateMethod {
|
pub enum DesaturateMethod {
|
||||||
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
|
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
|
||||||
///
|
///
|
||||||
/// Accessibility contrast ratios and SVG luminance masks use this.
|
/// Accessibility contrast ratios use this.
|
||||||
#[default]
|
#[default]
|
||||||
#[label("Luminance (Rec. 709)")]
|
#[label("Luminance (Rec. 709)")]
|
||||||
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
|
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
|
||||||
|
|||||||
@@ -0,0 +1,361 @@
|
|||||||
|
//! Blend If, shaped for PSD interop as its blending ranges: the content shows only where its own colors, and the colors of what lies beneath it, fall within a range of each channel's levels.
|
||||||
|
//! The content's own range fades it like its fill does, leaving the shadows and glows cast from it as they are, and the range beneath fades everything the content draws like its opacity does.
|
||||||
|
|
||||||
|
use crate::effect_layers::is_pixel_filter;
|
||||||
|
use crate::effects::EffectOperation;
|
||||||
|
use crate::parameters::ParameterVisitor;
|
||||||
|
use core_types::graphene_hash::CacheHash;
|
||||||
|
use dyn_any::DynAny;
|
||||||
|
|
||||||
|
/// For PSD interop, the gray channel weighs the levels of the gamma-encoded red, green, and blue channels by these percentages.
|
||||||
|
pub const GRAY_PERCENTAGES: [usize; 3] = [30, 59, 11];
|
||||||
|
|
||||||
|
/// How many levels each renderer reads a channel at before weighing it, the 8 bits browsers filter with, so every renderer cuts off the same pixels.
|
||||||
|
pub const CHANNEL_LEVELS: usize = 256;
|
||||||
|
|
||||||
|
/// How near a cutoff a channel may lie, as a fraction of its full scale, and still count as reaching it: a quarter of a level, so a cutoff given in percent lands on the level it names.
|
||||||
|
const CUTOFF_TOLERANCE: f64 = 1. / 1024.;
|
||||||
|
|
||||||
|
/// Which channel of the colors a Blend If range reads.
|
||||||
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||||
|
#[widget(Dropdown)]
|
||||||
|
pub enum BlendIfChannel {
|
||||||
|
/// The lightness of the colors, weighing red, green, and blue by 30%, 59%, and 11%.
|
||||||
|
#[default]
|
||||||
|
Gray,
|
||||||
|
Red,
|
||||||
|
Green,
|
||||||
|
Blue,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A range of one channel's levels, in percent, which shows the content fully from its range start to its end and fades it out linearly to nothing at its falloff start and end.
|
||||||
|
/// A falloff that meets its end of the range is a sharp cutoff, which shows the content at the level it lies on.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||||
|
pub struct BlendRange {
|
||||||
|
pub falloff_start: f64,
|
||||||
|
pub range_start: f64,
|
||||||
|
pub range_end: f64,
|
||||||
|
pub falloff_end: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for BlendRange {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
falloff_start: 0.,
|
||||||
|
range_start: 0.,
|
||||||
|
range_end: 100.,
|
||||||
|
falloff_end: 100.,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BlendRange {
|
||||||
|
/// How strongly the content shows where the channel is `value`, from 0 to 1.
|
||||||
|
pub fn weight(&self, value: f64) -> f64 {
|
||||||
|
let value = value * 100.;
|
||||||
|
let tolerance = CUTOFF_TOLERANCE * 100.;
|
||||||
|
|
||||||
|
// Each side rises (or falls) across its falloff, with its ends taken in either order
|
||||||
|
let side = |falloff: f64, range: f64, rising: bool| {
|
||||||
|
let (low, high) = (falloff.min(range), falloff.max(range));
|
||||||
|
match (high - low > tolerance, rising) {
|
||||||
|
(true, true) => ((value - low) / (high - low)).clamp(0., 1.),
|
||||||
|
(true, false) => ((high - value) / (high - low)).clamp(0., 1.),
|
||||||
|
(false, true) => f64::from(value >= low - tolerance),
|
||||||
|
(false, false) => f64::from(value <= high + tolerance),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
side(self.falloff_start, self.range_start, true) * side(self.falloff_end, self.range_end, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the range shows every level fully, so it changes nothing.
|
||||||
|
pub fn shows_everything(&self) -> bool {
|
||||||
|
// Rising then falling, it's full everywhere once it's full at both ends
|
||||||
|
self.weight(0.) >= 1. && self.weight(1.) >= 1.
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The weight at each of the [`CHANNEL_LEVELS`] levels, from black to white.
|
||||||
|
pub fn level_weights(&self) -> Vec<f64> {
|
||||||
|
(0..CHANNEL_LEVELS).map(|level| self.weight(level as f64 / (CHANNEL_LEVELS - 1) as f64)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||||
|
let key = |parameter: &str| format!("{group}_{parameter}");
|
||||||
|
visitor.parameter(&key("falloff_start"), &mut self.falloff_start, 0.);
|
||||||
|
visitor.parameter(&key("range_start"), &mut self.range_start, 0.);
|
||||||
|
visitor.parameter(&key("range_end"), &mut self.range_end, 100.);
|
||||||
|
visitor.parameter(&key("falloff_end"), &mut self.falloff_end, 100.);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ranges each channel's levels must fall within for the content to show, which multiply.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||||
|
pub struct ChannelRanges {
|
||||||
|
pub gray: BlendRange,
|
||||||
|
pub red: BlendRange,
|
||||||
|
pub green: BlendRange,
|
||||||
|
pub blue: BlendRange,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ChannelRanges {
|
||||||
|
/// Each channel with its range, in the order the GPU takes them.
|
||||||
|
pub fn channels(&self) -> [(BlendIfChannel, &BlendRange); 4] {
|
||||||
|
[
|
||||||
|
(BlendIfChannel::Gray, &self.gray),
|
||||||
|
(BlendIfChannel::Red, &self.red),
|
||||||
|
(BlendIfChannel::Green, &self.green),
|
||||||
|
(BlendIfChannel::Blue, &self.blue),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The channels with ranges that hide some levels.
|
||||||
|
pub fn limiting(&self) -> impl Iterator<Item = (BlendIfChannel, &BlendRange)> {
|
||||||
|
self.channels().into_iter().filter(|(_, range)| !range.shows_everything())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether every channel's range shows every level fully, so they change nothing.
|
||||||
|
pub fn show_everything(&self) -> bool {
|
||||||
|
self.limiting().next().is_none()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How strongly the content shows for a straight gamma-encoded `color`, each channel (and the gray from them) read at its nearest level.
|
||||||
|
pub fn weight(&self, color: [f64; 3]) -> f64 {
|
||||||
|
self.channel_weights(color).into_iter().product()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The weight each channel's range gives a straight gamma-encoded `color`, in the order of [`Self::channels`], which multiply to its [`Self::weight`].
|
||||||
|
pub fn channel_weights(&self, color: [f64; 3]) -> [f64; 4] {
|
||||||
|
let levels = color.map(channel_level);
|
||||||
|
let value = |level: usize| level as f64 / (CHANNEL_LEVELS - 1) as f64;
|
||||||
|
let [red, green, blue] = levels.map(value);
|
||||||
|
|
||||||
|
[self.gray.weight(value(gray_level(levels))), self.red.weight(red), self.green.weight(green), self.blue.weight(blue)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, side: &str) {
|
||||||
|
self.gray.visit_parameters(visitor, side);
|
||||||
|
self.red.visit_parameters(visitor, &format!("red_{side}"));
|
||||||
|
self.green.visit_parameters(visitor, &format!("green_{side}"));
|
||||||
|
self.blue.visit_parameters(visitor, &format!("blue_{side}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The level from 0 to 255 nearest a channel's `value` from 0 to 1, with halves rounding up as the browsers' 8-bit filters round them.
|
||||||
|
pub fn channel_level(value: f64) -> usize {
|
||||||
|
((value.clamp(0., 1.) * (CHANNEL_LEVELS - 1) as f64 + 0.5).floor() as usize).min(CHANNEL_LEVELS - 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The gray level of red, green, and blue levels, worked out in whole numbers so a gray exactly between two levels rounds up in every renderer.
|
||||||
|
pub fn gray_level(levels: [usize; 3]) -> usize {
|
||||||
|
let weighed: usize = levels.iter().zip(GRAY_PERCENTAGES).map(|(level, percentage)| level * percentage).sum();
|
||||||
|
(weighed + 50) / 100
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ranges of Blend If's two sides: those of the content's own colors, which fade the content like its fill, and those of what lies beneath it, which fade all it draws like its opacity.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||||
|
pub struct BlendIfRanges {
|
||||||
|
pub content: ChannelRanges,
|
||||||
|
pub underlying: ChannelRanges,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BlendIfRanges {
|
||||||
|
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||||
|
self.content.visit_parameters(visitor, "content");
|
||||||
|
self.underlying.visit_parameters(visitor, "underlying");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How strongly all the content draws shows over a backdrop pixel with the straight gamma-encoded `color` and `alpha`, by the `underlying` ranges.
|
||||||
|
/// Where nothing lies beneath, nothing is hidden, so the weight eases to full as the backdrop turns transparent.
|
||||||
|
pub fn underlying_weight(underlying: &ChannelRanges, color: [f64; 3], alpha: f64) -> f64 {
|
||||||
|
1. - alpha.clamp(0., 1.) * (1. - underlying.weight(color))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Blend If rows that act just before the row at `index` among `rows`: once `index` is the first row (or follows a pixel filter, like a blur or adjustment), those from it up to the next pixel filter.
|
||||||
|
/// So each Blend If reads and fades the content as the pixel filters before it leave it, ahead of the shadows and glows around it, which are knocked out by the content as it then shows.
|
||||||
|
pub fn blend_ifs_acting_before(rows: &[EffectOperation], index: usize) -> Vec<&BlendIfRanges> {
|
||||||
|
let follows_pixel_filter = index.checked_sub(1).is_none_or(|previous| processes_pixels(&rows[previous]));
|
||||||
|
if !follows_pixel_filter {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
(rows[index..].iter())
|
||||||
|
.take_while(|operation| !processes_pixels(operation))
|
||||||
|
.filter_map(|operation| match operation {
|
||||||
|
EffectOperation::BlendIf(ranges) => Some(ranges.as_ref()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a solid paint overlay at `index` among `rows` may mix into the content's own colors ahead of the other effects.
|
||||||
|
/// Not where a Blend If reading those colors acts in the same stretch between pixel filters, since it reads them before the overlay paints.
|
||||||
|
pub fn paint_overlay_folds(rows: &[EffectOperation], index: usize) -> bool {
|
||||||
|
let start = rows[..index].iter().rposition(processes_pixels).map_or(0, |previous| previous + 1);
|
||||||
|
let end = rows[index..].iter().position(processes_pixels).map_or(rows.len(), |next| index + next);
|
||||||
|
!fades_content(&rows[start..end])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a Blend If among the `operations` fades the content by its own colors, as a fill varying across it does.
|
||||||
|
pub fn fades_content(operations: &[EffectOperation]) -> bool {
|
||||||
|
operations
|
||||||
|
.iter()
|
||||||
|
.any(|operation| matches!(operation, EffectOperation::BlendIf(ranges) if !ranges.content.show_everything()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a row processes the pixels of everything before it, as a pixel filter (like a blur or adjustment) that changes something does, which ends a stretch of rows that Blend Ifs act at the start of.
|
||||||
|
fn processes_pixels(operation: &EffectOperation) -> bool {
|
||||||
|
is_pixel_filter(operation) && !operation.changes_nothing()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ranges beneath of each Blend If row among the `operations` that hides anything by what lies beneath, which multiply.
|
||||||
|
pub fn underlying_ranges<'a>(operations: impl IntoIterator<Item = &'a EffectOperation>) -> Vec<ChannelRanges> {
|
||||||
|
(operations.into_iter())
|
||||||
|
.filter_map(|operation| match operation {
|
||||||
|
EffectOperation::BlendIf(ranges) if !ranges.underlying.show_everything() => Some(ranges.underlying),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn range(falloff_start: f64, range_start: f64, range_end: f64, falloff_end: f64) -> BlendRange {
|
||||||
|
BlendRange {
|
||||||
|
falloff_start,
|
||||||
|
range_start,
|
||||||
|
range_end,
|
||||||
|
falloff_end,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A level from 0 to 255 as a channel value.
|
||||||
|
fn level(level: f64) -> f64 {
|
||||||
|
level / 255.
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ranges_fade_linearly_across_their_falloffs() {
|
||||||
|
let percent = |level: f64| level / 255. * 100.;
|
||||||
|
let soft = range(percent(64.), percent(128.), percent(192.), percent(224.));
|
||||||
|
|
||||||
|
assert_eq!(soft.weight(level(32.)), 0.);
|
||||||
|
assert!((soft.weight(level(96.)) - 0.5).abs() < 1e-12);
|
||||||
|
assert_eq!(soft.weight(level(160.)), 1.);
|
||||||
|
assert!((soft.weight(level(208.)) - 0.5).abs() < 1e-12);
|
||||||
|
assert_eq!(soft.weight(level(240.)), 0.);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsplit_cutoffs_keep_the_level_they_lie_on() {
|
||||||
|
// For PSD interop, black at 64 keeps 64 and white at 192 keeps 192, given in percent as they'd be imported
|
||||||
|
let percent = |level: f64| level / 255. * 100.;
|
||||||
|
let hard = range(percent(64.), percent(64.), percent(192.), percent(192.));
|
||||||
|
|
||||||
|
assert_eq!(hard.weight(level(63.)), 0.);
|
||||||
|
assert_eq!(hard.weight(level(64.)), 1.);
|
||||||
|
assert_eq!(hard.weight(level(192.)), 1.);
|
||||||
|
assert_eq!(hard.weight(level(193.)), 0.);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_default_range_shows_everything() {
|
||||||
|
assert!(BlendRange::default().shows_everything());
|
||||||
|
assert!(ChannelRanges::default().show_everything());
|
||||||
|
assert!(!range(0., 10., 100., 100.).shows_everything());
|
||||||
|
assert!(!range(0., 0., 100., 99.).shows_everything());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn channels_multiply_with_gray_weighing_the_color() {
|
||||||
|
let ranges = ChannelRanges {
|
||||||
|
gray: range(0., 50., 100., 100.),
|
||||||
|
red: range(0., 0., 50., 100.),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
// The gray of a light pink shows fully, but its red at full strength fades it to nothing
|
||||||
|
assert_eq!(ranges.weight([1., 0.5, 0.5]), 0.);
|
||||||
|
// A dark red's gray, read at its own level, lies partway up its falloff, while its red lies within its range
|
||||||
|
let red = level(77.);
|
||||||
|
let gray = gray_level([77, 0, 0]) as f64 / 255.;
|
||||||
|
let expected = (gray * 100. / 50.) * ((100. - red * 100.) / 50.).min(1.);
|
||||||
|
assert!((ranges.weight([red, 0., 0.]) - expected).abs() < 1e-12);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nothing_beneath_hides_nothing() {
|
||||||
|
let underlying = ChannelRanges {
|
||||||
|
gray: range(50., 50., 100., 100.),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(underlying_weight(&underlying, [0.; 3], 0.), 1.);
|
||||||
|
assert_eq!(underlying_weight(&underlying, [0.; 3], 1.), 0.);
|
||||||
|
assert!((underlying_weight(&underlying, [0.; 3], 0.25) - 0.75).abs() < 1e-12);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn blend_ifs_act_after_the_blurs_and_adjustments_before_them() {
|
||||||
|
let blend_if = EffectOperation::BlendIf(Box::default());
|
||||||
|
let blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Default::default(),
|
||||||
|
radius: 2.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
let shadow = EffectOperation::default_for(crate::EffectKind::DropShadow);
|
||||||
|
let rows = [shadow.clone(), blend_if.clone(), blur, shadow, blend_if];
|
||||||
|
|
||||||
|
// The first acts ahead of the shadow before it, and the second just after the blur, ahead of the shadow between them
|
||||||
|
let acting: Vec<usize> = (0..rows.len()).map(|index| blend_ifs_acting_before(&rows, index).len()).collect();
|
||||||
|
assert_eq!(acting, [1, 0, 0, 1, 0]);
|
||||||
|
|
||||||
|
// A blur of no radius changes nothing, so it starts no stretch of its own
|
||||||
|
let no_blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Default::default(),
|
||||||
|
radius: 0.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
let rows = [EffectOperation::default_for(crate::EffectKind::DropShadow), no_blur, EffectOperation::BlendIf(Box::default())];
|
||||||
|
assert_eq!(blend_ifs_acting_before(&rows, 0).len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn grays_between_two_levels_round_up() {
|
||||||
|
// Blue at 250 weighs 27.5 levels of gray, and 249 weighs 27.39
|
||||||
|
assert_eq!(gray_level([0, 0, 250]), 28);
|
||||||
|
assert_eq!(gray_level([0, 0, 249]), 27);
|
||||||
|
assert_eq!(gray_level([5, 0, 0]), 2);
|
||||||
|
assert_eq!(gray_level([255, 255, 255]), 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paint_overlays_keep_their_strength_where_a_blend_if_reads_the_content_beside_them() {
|
||||||
|
let overlay = EffectOperation::Adjustment(crate::Adjustment::ColorOverlay {
|
||||||
|
color: core_types::Color::RED,
|
||||||
|
blend_mode: core_types::blending::BlendMode::Normal,
|
||||||
|
opacity: 100.,
|
||||||
|
});
|
||||||
|
let mut ranges = BlendIfRanges::default();
|
||||||
|
ranges.content.gray.range_start = 40.;
|
||||||
|
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||||
|
let blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Default::default(),
|
||||||
|
radius: 2.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(!paint_overlay_folds(&[overlay.clone(), blend_if.clone(), blur.clone()], 0));
|
||||||
|
assert!(paint_overlay_folds(&[overlay.clone(), blur.clone(), blend_if.clone()], 0));
|
||||||
|
assert!(paint_overlay_folds(&[blend_if, blur, overlay.clone()], 2));
|
||||||
|
assert!(paint_overlay_folds(&[overlay, EffectOperation::BlendIf(Box::default())], 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ use crate::adjustment::Adjustment;
|
|||||||
use crate::effects::{BevelStyle, EffectCapture, EffectOperation, Effects, GlowFill, OutlineFill, outline_extents};
|
use crate::effects::{BevelStyle, EffectCapture, EffectOperation, Effects, GlowFill, OutlineFill, outline_extents};
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use core_types::blending::BlendMode;
|
use core_types::blending::BlendMode;
|
||||||
|
use std::borrow::Cow;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
|
|
||||||
/// Which side of the content a piece of an effect draws on, and how.
|
/// Which side of the content a piece of an effect draws on, and how.
|
||||||
@@ -21,6 +22,8 @@ pub enum PiecePlace {
|
|||||||
IntoContent { over: bool },
|
IntoContent { over: bool },
|
||||||
/// The part of an interior piece blending with what shows through the content's fill, in a layer of its mode beneath the content's, or with `over`, over it.
|
/// The part of an interior piece blending with what shows through the content's fill, in a layer of its mode beneath the content's, or with `over`, over it.
|
||||||
Through { over: bool },
|
Through { over: bool },
|
||||||
|
/// What lies beneath the content, filtered and cut to its silhouette, at the bottom of the content's own layer.
|
||||||
|
Backdrop,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One coverage of an effect that draws as a piece of its own, named like the map of it.
|
/// One coverage of an effect that draws as a piece of its own, named like the map of it.
|
||||||
@@ -62,20 +65,28 @@ pub struct EffectLayers {
|
|||||||
/// How many of the effects, from the first, are carried out within the content's image.
|
/// How many of the effects, from the first, are carried out within the content's image.
|
||||||
pub flattened: usize,
|
pub flattened: usize,
|
||||||
pub layers: Vec<EffectLayer>,
|
pub layers: Vec<EffectLayer>,
|
||||||
/// The rows from the first mask after every other effect to the end, which fade each finished layer at each pixel like the item's opacity. Empty where those masks flatten what's before them instead.
|
/// The rows from the first mask after every other effect to the end: masks, and Blend Ifs reading only what lies beneath, which fade each finished layer at each pixel like the item's opacity.
|
||||||
|
/// Empty where those masks flatten what's before them instead.
|
||||||
pub trailing_masks: Range<usize>,
|
pub trailing_masks: Range<usize>,
|
||||||
|
/// Whether a Blend If fades every layer by the colors of what lies beneath.
|
||||||
|
pub fades_by_underlying: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EffectLayers {
|
impl EffectLayers {
|
||||||
/// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask.
|
/// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask.
|
||||||
/// Content in a mode CSS lacks is drawn normally, so it's planned that way.
|
/// Content in a mode CSS lacks reads what lies beneath to blend by it (see [`BlendMode::reads_backdrop`]), but the alpha-only utility modes are planned as normal.
|
||||||
pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self {
|
pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self {
|
||||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||||
let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal };
|
let blend_mode = if blend_mode.to_svg_style_name().is_some() || blend_mode.reads_backdrop() {
|
||||||
|
blend_mode
|
||||||
|
} else {
|
||||||
|
BlendMode::Normal
|
||||||
|
};
|
||||||
|
|
||||||
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer
|
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer.
|
||||||
|
// A Blend If fading the content by its colors acts as a fill below full wherever it hides any.
|
||||||
let shares_content = blend_mode == BlendMode::Normal;
|
let shares_content = blend_mode == BlendMode::Normal;
|
||||||
let blends_into_content = shares_content && fill >= 1.;
|
let blends_into_content = shares_content && fill >= 1. && !crate::blend_if::fades_content(&operations);
|
||||||
|
|
||||||
// The masks after every other effect fade the layers rather than the content's image, so they flatten nothing before them
|
// The masks after every other effect fade the layers rather than the content's image, so they flatten nothing before them
|
||||||
let no_rows = operations.len()..operations.len();
|
let no_rows = operations.len()..operations.len();
|
||||||
@@ -99,9 +110,7 @@ impl EffectLayers {
|
|||||||
let has_beneath = |pieces: &[(EffectPiece, BlendMode)]| pieces.iter().any(|(piece, _)| piece.place == PiecePlace::Beneath);
|
let has_beneath = |pieces: &[(EffectPiece, BlendMode)]| pieces.iter().any(|(piece, _)| piece.place == PiecePlace::Beneath);
|
||||||
|
|
||||||
// Flattened shadows and glows that no later pixel filter merges into the content would draw over the layered ones, so then everything is flattened
|
// Flattened shadows and glows that no later pixel filter merges into the content would draw over the layered ones, so then everything is flattened
|
||||||
let last_pixel_filter = (operations[..flattened].iter())
|
let last_pixel_filter = merged_into_content(&operations[..flattened]);
|
||||||
.rposition(|operation| !operation.changes_nothing() && is_pixel_filter(operation))
|
|
||||||
.map_or(0, |index| index + 1);
|
|
||||||
let unmerged = pieces_from(last_pixel_filter, flattened);
|
let unmerged = pieces_from(last_pixel_filter, flattened);
|
||||||
let mut pieces = pieces_from(flattened, operations.len());
|
let mut pieces = pieces_from(flattened, operations.len());
|
||||||
if has_beneath(&unmerged) && has_beneath(&pieces) {
|
if has_beneath(&unmerged) && has_beneath(&pieces) {
|
||||||
@@ -116,10 +125,16 @@ impl EffectLayers {
|
|||||||
.chain([(LayerPart::Content, blend_mode)])
|
.chain([(LayerPart::Content, blend_mode)])
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
// A shadow not knocked out in the content's layer, flattened or layered, would hide a part placed beneath that layer
|
// A blurred backdrop, or a shadow not knocked out (flattened or layered), in the content's layer would hide a part placed beneath that layer
|
||||||
|
let backdrop: Vec<LayerPart> = pieces_from(0, operations.len())
|
||||||
|
.into_iter()
|
||||||
|
.filter(|(piece, _)| piece.place == PiecePlace::Backdrop)
|
||||||
|
.map(|(piece, _)| LayerPart::Piece(piece))
|
||||||
|
.collect();
|
||||||
let shows_through = |piece: &EffectPiece| piece.place == PiecePlace::Beneath && !piece.knocks_out;
|
let shows_through = |piece: &EffectPiece| piece.place == PiecePlace::Beneath && !piece.knocks_out;
|
||||||
let mut content_run = parts.iter().rev().skip(1).take_while(|(_, mode)| *mode == BlendMode::Normal);
|
let mut content_run = parts.iter().rev().skip(1).take_while(|(_, mode)| *mode == BlendMode::Normal);
|
||||||
let covered_beneath = content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
|
let covered_beneath =
|
||||||
|
!backdrop.is_empty() || content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
|
||||||
|
|
||||||
// Interior pieces of normal content blend within its share, in its layer. Below a full fill, a blended one splits off its part through the fill into a layer beneath
|
// Interior pieces of normal content blend within its share, in its layer. Below a full fill, a blended one splits off its part through the fill into a layer beneath
|
||||||
// the content's, or over it when its mode isn't straight along what lies beneath or a shadow covers that, as every later piece then does to keep their order.
|
// the content's, or over it when its mode isn't straight along what lies beneath or a shadow covers that, as every later piece then does to keep their order.
|
||||||
@@ -167,8 +182,10 @@ impl EffectLayers {
|
|||||||
layers.splice(content_layer..content_layer, through);
|
layers.splice(content_layer..content_layer, through);
|
||||||
}
|
}
|
||||||
|
|
||||||
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes
|
let fades_by_underlying = !crate::blend_if::underlying_ranges(&operations).is_empty();
|
||||||
if blends_into_content && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
|
|
||||||
|
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes, unless it reads what lies beneath
|
||||||
|
if blends_into_content && backdrop.is_empty() && !fades_by_underlying && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
|
||||||
let content = EffectLayer {
|
let content = EffectLayer {
|
||||||
blend_mode: BlendMode::Normal,
|
blend_mode: BlendMode::Normal,
|
||||||
parts: vec![LayerPart::Content],
|
parts: vec![LayerPart::Content],
|
||||||
@@ -177,10 +194,21 @@ impl EffectLayers {
|
|||||||
flattened: operations.len(),
|
flattened: operations.len(),
|
||||||
layers: vec![content],
|
layers: vec![content],
|
||||||
trailing_masks: no_rows,
|
trailing_masks: no_rows,
|
||||||
|
fades_by_underlying,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
Self { flattened, layers, trailing_masks }
|
// What lies beneath, filtered, goes at the bottom of the content's own layer, which fades and blends it with the content, even from a row flattened into the content
|
||||||
|
if let Some(content_layer) = layers.iter_mut().find(|layer| layer.holds_content()) {
|
||||||
|
content_layer.parts.splice(0..0, backdrop);
|
||||||
|
}
|
||||||
|
|
||||||
|
Self {
|
||||||
|
flattened,
|
||||||
|
layers,
|
||||||
|
trailing_masks,
|
||||||
|
fades_by_underlying,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Like [`Self::plan`], for effects stamped in more than one space (see [`Effects::runs`]), as renderers draw them.
|
/// Like [`Self::plan`], for effects stamped in more than one space (see [`Effects::runs`]), as renderers draw them.
|
||||||
@@ -202,6 +230,27 @@ impl EffectLayers {
|
|||||||
planned
|
planned
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a layered piece, a Blend If fading the layers, or a layer's blend mode reads what lies beneath the content.
|
||||||
|
pub fn reads_backdrop(&self) -> bool {
|
||||||
|
self.fades_by_underlying || self.reads_around_backdrop() || self.layers.iter().any(|layer| layer.blend_mode.reads_backdrop())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the content's layer reads what lies beneath it to blend at the content's `fill` (see [`BlendMode::layer_reads_backdrop`]).
|
||||||
|
/// Color Dodge and Color Burn blend natively instead over a piece beneath the content it doesn't knock out, which what lies beneath the item leaves out.
|
||||||
|
pub fn content_reads_backdrop(&self, fill: f32) -> bool {
|
||||||
|
let Some(content_layer) = self.content_layer() else { return false };
|
||||||
|
let blend_mode = self.layers[content_layer].blend_mode;
|
||||||
|
|
||||||
|
let shown_beneath = |part: &LayerPart| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Beneath && !piece.knocks_out);
|
||||||
|
let pieces_show_beneath = self.layers[..content_layer].iter().flat_map(|layer| &layer.parts).any(shown_beneath);
|
||||||
|
blend_mode.reads_backdrop() || (blend_mode.layer_reads_backdrop(fill) && !pieces_show_beneath)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself.
|
||||||
|
pub fn reads_around_backdrop(&self) -> bool {
|
||||||
|
(self.layers.iter().flat_map(|layer| &layer.parts)).any(|part| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Backdrop))
|
||||||
|
}
|
||||||
|
|
||||||
/// The index of the layer holding the content.
|
/// The index of the layer holding the content.
|
||||||
pub fn content_layer(&self) -> Option<usize> {
|
pub fn content_layer(&self) -> Option<usize> {
|
||||||
self.layers.iter().position(EffectLayer::holds_content)
|
self.layers.iter().position(EffectLayer::holds_content)
|
||||||
@@ -264,11 +313,30 @@ impl EffectLayers {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether any of the effects reads what lies beneath the content, like a background blur, or may, like a shadow in a mode CSS lacks.
|
||||||
|
pub fn effects_read_backdrop(effects: &Effects) -> bool {
|
||||||
|
effects.operations().any(|operation| match &operation {
|
||||||
|
EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(),
|
||||||
|
EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(),
|
||||||
|
_ => {
|
||||||
|
!operation.changes_nothing()
|
||||||
|
&& pieces(0, &operation)
|
||||||
|
.iter()
|
||||||
|
.any(|(piece, blend_mode)| piece.place == PiecePlace::Beneath && blend_mode.reads_backdrop())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
|
/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
|
||||||
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer,
|
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them. A piece in a mode CSS lacks reads what lies beneath the item to blend, so only one beneath the content
|
||||||
/// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
|
/// can, though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
|
||||||
fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool {
|
fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool {
|
||||||
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| blend_mode.to_svg_style_name().is_some() || (blend_into_content && piece.place == PiecePlace::Within);
|
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| match piece.place {
|
||||||
|
_ if blend_mode.to_svg_style_name().is_some() => true,
|
||||||
|
PiecePlace::Beneath => blend_mode.reads_backdrop(),
|
||||||
|
PiecePlace::Within => blend_into_content,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
!is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in)
|
!is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,30 +345,73 @@ fn is_straight_along_backdrop(blend_mode: BlendMode) -> bool {
|
|||||||
matches!(blend_mode, BlendMode::Normal | BlendMode::Multiply | BlendMode::Screen | BlendMode::Exclusion | BlendMode::HardLight)
|
matches!(blend_mode, BlendMode::Normal | BlendMode::Multiply | BlendMode::Screen | BlendMode::Exclusion | BlendMode::HardLight)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether an effect row processes the pixels of the content and everything drawn with it so far, as a blur, an adjustment, a mask, or a feather does.
|
/// Whether an effect row processes the pixels of the content and everything drawn with it so far, as a blur, an adjustment, a mask, a feather, or another filter does.
|
||||||
/// A solid paint overlay decodes into the color overlay adjustment, but it paints within the content like any other paint overlay.
|
/// A solid paint overlay decodes into the color overlay adjustment, but it paints within the content like any other paint overlay.
|
||||||
pub fn is_pixel_filter(operation: &EffectOperation) -> bool {
|
pub fn is_pixel_filter(operation: &EffectOperation) -> bool {
|
||||||
match operation {
|
match operation {
|
||||||
// TODO: Make a mask between other effects fade each layer drawn before it too, as the trailing masks do, rather than flattening those layers.
|
// TODO: Make a mask between other effects fade each layer drawn before it too, as the trailing masks do, rather than flattening those layers.
|
||||||
// TODO: Likewise for a trailing feather, faded by the footprint of every layer drawn together (not the content's alone, which would erase shadows past it).
|
// TODO: Likewise for a trailing feather, faded by the footprint of every layer drawn together (not the content's alone, which would erase shadows past it).
|
||||||
EffectOperation::Blur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } => true,
|
EffectOperation::Blur { .. }
|
||||||
|
| EffectOperation::MotionBlur { .. }
|
||||||
|
| EffectOperation::RadialBlur { .. }
|
||||||
|
| EffectOperation::Twirl { .. }
|
||||||
|
| EffectOperation::Pinch { .. }
|
||||||
|
| EffectOperation::Spherize { .. }
|
||||||
|
| EffectOperation::PolarCoordinates { .. }
|
||||||
|
| EffectOperation::Warp { .. }
|
||||||
|
| EffectOperation::Ripple { .. }
|
||||||
|
| EffectOperation::Wave { .. }
|
||||||
|
| EffectOperation::Displace { .. }
|
||||||
|
| EffectOperation::Pixelate { .. }
|
||||||
|
| EffectOperation::ColorHalftone { .. }
|
||||||
|
| EffectOperation::Mask { .. }
|
||||||
|
| EffectOperation::Feather { .. } => true,
|
||||||
|
operation if crate::filters::is_filter(operation) => true,
|
||||||
EffectOperation::Adjustment(adjustment) => !matches!(adjustment, Adjustment::ColorOverlay { .. }),
|
EffectOperation::Adjustment(adjustment) => !matches!(adjustment, Adjustment::ColorOverlay { .. }),
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How many of the `operations`, from the first, run through the last pixel filter among them, which merges the pieces before it into the content's image.
|
||||||
|
fn merged_into_content(operations: &[EffectOperation]) -> usize {
|
||||||
|
(operations.iter())
|
||||||
|
.rposition(|operation| !operation.changes_nothing() && is_pixel_filter(operation))
|
||||||
|
.map_or(0, |index| index + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it, leaving out each Blend If that reads only what lies beneath.
|
||||||
|
/// The other pieces are cast from or laid over the content, so for PSD interop they don't shape a clip. Borrowed if nothing is left out.
|
||||||
|
pub fn content_image_effects(effects: &Effects) -> Cow<'_, Effects> {
|
||||||
|
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||||
|
let trailing_masks = trailing_masks(&operations);
|
||||||
|
let merged = merged_into_content(&operations[..trailing_masks.start]);
|
||||||
|
|
||||||
|
// A Blend If reading only what lies beneath fades the finished layers wherever it sits, so it shapes no clip (and it's the only kind the trailing masks can hold)
|
||||||
|
let kept: Vec<usize> = (0..merged).chain(trailing_masks).filter(|&index| !reads_only_beneath(&operations[index])).collect();
|
||||||
|
if kept.len() == operations.len() {
|
||||||
|
return Cow::Borrowed(effects);
|
||||||
|
}
|
||||||
|
|
||||||
|
Cow::Owned(Effects(kept.into_iter().filter_map(|index| effects.0.clone_item(index)).collect()))
|
||||||
|
}
|
||||||
|
|
||||||
/// The rows from the first mask after every other effect that changes something to the end, or none without such a mask or an effect before it.
|
/// The rows from the first mask after every other effect that changes something to the end, or none without such a mask or an effect before it.
|
||||||
|
/// A Blend If reading only what lies beneath is passed over, since it fades the finished layers as the masks do, but one reading the content's colors counts as another effect.
|
||||||
fn trailing_masks(operations: &[EffectOperation]) -> Range<usize> {
|
fn trailing_masks(operations: &[EffectOperation]) -> Range<usize> {
|
||||||
let no_rows = operations.len()..operations.len();
|
let no_rows = operations.len()..operations.len();
|
||||||
let is_mask = |operation: &EffectOperation| matches!(operation, EffectOperation::Mask { .. });
|
let is_mask = |operation: &EffectOperation| matches!(operation, EffectOperation::Mask { .. });
|
||||||
|
let is_other = |operation: &EffectOperation| !operation.changes_nothing() && !is_mask(operation) && !reads_only_beneath(operation);
|
||||||
|
|
||||||
let Some(last_other) = operations.iter().rposition(|operation| !operation.changes_nothing() && !is_mask(operation)) else {
|
let Some(last_other) = operations.iter().rposition(is_other) else { return no_rows };
|
||||||
return no_rows;
|
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing() && is_mask(operation));
|
||||||
};
|
|
||||||
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing());
|
|
||||||
first_mask.map_or(no_rows, |offset| last_other + 1 + offset..operations.len())
|
first_mask.map_or(no_rows, |offset| last_other + 1 + offset..operations.len())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether the effect is a Blend If without ranges of the content's own colors, so it reads only what lies beneath (or changes nothing).
|
||||||
|
fn reads_only_beneath(operation: &EffectOperation) -> bool {
|
||||||
|
matches!(operation, EffectOperation::BlendIf(ranges) if ranges.content.show_everything())
|
||||||
|
}
|
||||||
|
|
||||||
/// The pieces the effect at `index` draws, each with the mode it blends by, leaving out those painting no color.
|
/// The pieces the effect at `index` draws, each with the mode it blends by, leaving out those painting no color.
|
||||||
fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendMode)> {
|
fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendMode)> {
|
||||||
// Only a drop shadow can show through the content
|
// Only a drop shadow can show through the content
|
||||||
@@ -358,8 +469,33 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
|||||||
inside.into_iter().chain(outside).flatten().collect()
|
inside.into_iter().chain(outside).flatten().collect()
|
||||||
}
|
}
|
||||||
EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)],
|
EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)],
|
||||||
|
EffectOperation::BackgroundBlur { .. } => vec![piece(0, Backdrop, None, BlendMode::Normal)],
|
||||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)],
|
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)],
|
||||||
EffectOperation::Blur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } | EffectOperation::Adjustment(_) => Vec::new(),
|
EffectOperation::Blur { .. }
|
||||||
|
| EffectOperation::MotionBlur { .. }
|
||||||
|
| EffectOperation::RadialBlur { .. }
|
||||||
|
| EffectOperation::Twirl { .. }
|
||||||
|
| EffectOperation::Pinch { .. }
|
||||||
|
| EffectOperation::Spherize { .. }
|
||||||
|
| EffectOperation::PolarCoordinates { .. }
|
||||||
|
| EffectOperation::Warp { .. }
|
||||||
|
| EffectOperation::Ripple { .. }
|
||||||
|
| EffectOperation::Wave { .. }
|
||||||
|
| EffectOperation::Displace { .. }
|
||||||
|
| EffectOperation::Pixelate { .. }
|
||||||
|
| EffectOperation::ColorHalftone { .. }
|
||||||
|
| EffectOperation::Mask { .. }
|
||||||
|
| EffectOperation::Feather { .. }
|
||||||
|
| EffectOperation::ConvolutionKernel { .. }
|
||||||
|
| EffectOperation::Emboss { .. }
|
||||||
|
| EffectOperation::FindEdges
|
||||||
|
| EffectOperation::MinimumMaximum { .. }
|
||||||
|
| EffectOperation::Sharpen { .. }
|
||||||
|
| EffectOperation::HighPass { .. }
|
||||||
|
| EffectOperation::Speckle { .. }
|
||||||
|
| EffectOperation::Dissolve { .. }
|
||||||
|
| EffectOperation::BlendIf(_)
|
||||||
|
| EffectOperation::Adjustment(_) => Vec::new(),
|
||||||
};
|
};
|
||||||
pieces.into_iter().flatten().collect()
|
pieces.into_iter().flatten().collect()
|
||||||
}
|
}
|
||||||
@@ -451,9 +587,11 @@ mod tests {
|
|||||||
let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true);
|
let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true);
|
||||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]);
|
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]);
|
||||||
|
|
||||||
// A mode CSS lacks is drawn normally, so it's planned that way, and an interior piece blending within the content's layer may take one too
|
// Content in a mode CSS lacks reads what lies beneath to blend by it, and an interior piece blending within the content's layer may take one too
|
||||||
let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true);
|
let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true);
|
||||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::LinearBurn, BlendMode::Screen, BlendMode::Normal]);
|
||||||
|
assert!(layers.reads_backdrop() && !layers.reads_around_backdrop());
|
||||||
|
assert!(!EffectLayers::plan(&effects, BlendMode::Overlay, 1., true).reads_backdrop());
|
||||||
let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]);
|
let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]);
|
||||||
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0);
|
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0);
|
||||||
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2);
|
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2);
|
||||||
@@ -511,6 +649,11 @@ mod tests {
|
|||||||
fn interior_pieces_go_over_the_content_where_its_layer_covers_what_lies_beneath_it() {
|
fn interior_pieces_go_over_the_content_where_its_layer_covers_what_lies_beneath_it() {
|
||||||
let red = RED.with_alpha(0.75);
|
let red = RED.with_alpha(0.75);
|
||||||
let through_over = PiecePlace::Through { over: true };
|
let through_over = PiecePlace::Through { over: true };
|
||||||
|
let background_blur = EffectOperation::BackgroundBlur {
|
||||||
|
radius: 4.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
|
||||||
let with_knockout = |knocks_out: bool| {
|
let with_knockout = |knocks_out: bool| {
|
||||||
let mut shadow = drop_shadow(Color::BLACK.with_alpha(0.75), BlendMode::Multiply);
|
let mut shadow = drop_shadow(Color::BLACK.with_alpha(0.75), BlendMode::Multiply);
|
||||||
@@ -520,23 +663,22 @@ mod tests {
|
|||||||
shadow
|
shadow
|
||||||
};
|
};
|
||||||
|
|
||||||
// A shadow not knocked out beneath the content in its layer would hide even a straight piece's part beneath that layer
|
// A blurred backdrop, or a shadow not knocked out, beneath the content in its layer would hide even a straight piece's part beneath that layer
|
||||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(false), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
for beneath in [background_blur, with_knockout(false)] {
|
||||||
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen]);
|
let layers = EffectLayers::plan(&Effects::from_operations([beneath.clone(), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
|
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen], "{beneath:?}");
|
||||||
|
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))], "{beneath:?}");
|
||||||
|
}
|
||||||
|
|
||||||
// A knocked-out shadow doesn't cover it there
|
// A knocked-out shadow doesn't cover it there
|
||||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||||
assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]);
|
assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]);
|
||||||
|
|
||||||
// One flattened for a mode CSS lacks covers it too
|
// One flattened before an interior piece in a mode CSS lacks covers it too
|
||||||
let mut flattened_shadow = with_knockout(false);
|
let flattening = [with_knockout(false), inner_shadow(red, BlendMode::LinearBurn), inner_shadow(red, BlendMode::Screen)];
|
||||||
if let EffectOperation::DropShadow { blend_mode, .. } = &mut flattened_shadow {
|
let layers = EffectLayers::plan(&Effects::from_operations(flattening), BlendMode::Normal, 0.5, true);
|
||||||
*blend_mode = BlendMode::LinearBurn;
|
assert_eq!(layers.flattened, 2);
|
||||||
}
|
assert_eq!(parts(&layers)[1], [Some((2, 0, through_over))]);
|
||||||
let layers = EffectLayers::plan(&Effects::from_operations([flattened_shadow, inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
|
||||||
assert_eq!(layers.flattened, 1);
|
|
||||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -564,6 +706,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn rows_that_change_nothing_neither_flatten_nor_split_the_others() {
|
fn rows_that_change_nothing_neither_flatten_nor_split_the_others() {
|
||||||
let no_blur = EffectOperation::Blur {
|
let no_blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Graphic::default(),
|
||||||
radius: 0.,
|
radius: 0.,
|
||||||
box_blur: false,
|
box_blur: false,
|
||||||
gamma: false,
|
gamma: false,
|
||||||
@@ -582,6 +725,13 @@ mod tests {
|
|||||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||||
assert_eq!(layers.flattened, 0);
|
assert_eq!(layers.flattened, 0);
|
||||||
assert_eq!(parts(&layers), [[Some((0, 0, PiecePlace::Beneath)), None, Some((2, 0, PiecePlace::Within))]]);
|
assert_eq!(parts(&layers), [[Some((0, 0, PiecePlace::Beneath)), None, Some((2, 0, PiecePlace::Within))]]);
|
||||||
|
|
||||||
|
// Making the content opaque at no strength leaves the multiplying shadow before it blending with what lies beneath, which any strength flattens
|
||||||
|
let make_opaque = |strength| Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), EffectOperation::Adjustment(Adjustment::MakeOpaque { strength })]);
|
||||||
|
let layers = EffectLayers::plan(&make_opaque(0.), BlendMode::Normal, 1., true);
|
||||||
|
assert_eq!(layers.flattened, 0);
|
||||||
|
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||||
|
assert_eq!(EffectLayers::plan(&make_opaque(1.), BlendMode::Normal, 1., true).flattened, 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn mask() -> EffectOperation {
|
fn mask() -> EffectOperation {
|
||||||
@@ -605,6 +755,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn trailing_masks_fade_each_layer_in_its_own_blend_mode() {
|
fn trailing_masks_fade_each_layer_in_its_own_blend_mode() {
|
||||||
let no_blur = EffectOperation::Blur {
|
let no_blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Graphic::default(),
|
||||||
radius: 0.,
|
radius: 0.,
|
||||||
box_blur: false,
|
box_blur: false,
|
||||||
gamma: false,
|
gamma: false,
|
||||||
@@ -634,14 +785,20 @@ mod tests {
|
|||||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2));
|
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2));
|
||||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5));
|
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5));
|
||||||
let unmerged = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply), mask()]);
|
let unmerged = Effects::from_operations([
|
||||||
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 1., true);
|
drop_shadow(RED, BlendMode::Multiply),
|
||||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (3, 3..3));
|
inner_shadow(RED, BlendMode::LinearBurn),
|
||||||
|
drop_shadow(RED, BlendMode::Multiply),
|
||||||
|
mask(),
|
||||||
|
]);
|
||||||
|
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 0.5, true);
|
||||||
|
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (4, 4..4));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn effects_before_a_blur_or_a_mode_css_lacks_are_flattened() {
|
fn effects_before_a_blur_or_a_mode_css_lacks_are_flattened() {
|
||||||
let blur = EffectOperation::Blur {
|
let blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Graphic::default(),
|
||||||
radius: 2.,
|
radius: 2.,
|
||||||
box_blur: false,
|
box_blur: false,
|
||||||
gamma: false,
|
gamma: false,
|
||||||
@@ -652,22 +809,138 @@ mod tests {
|
|||||||
assert_eq!(layers.flattened, 2);
|
assert_eq!(layers.flattened, 2);
|
||||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||||
|
|
||||||
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), drop_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
|
// An interior piece in a mode CSS lacks, which would read the content beneath it, flattens what's before it, where one beneath the content takes a layer of its own
|
||||||
|
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), inner_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
|
||||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||||
assert_eq!(layers.flattened, 2);
|
assert_eq!(layers.flattened, 2);
|
||||||
|
let layers = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn)]), BlendMode::Normal, 0.5, true);
|
||||||
|
assert_eq!((layers.flattened, modes(&layers)), (0, vec![BlendMode::LinearBurn, BlendMode::Normal]));
|
||||||
|
assert!(layers.reads_backdrop());
|
||||||
|
|
||||||
// A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens
|
// A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens
|
||||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
|
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), inner_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
|
||||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||||
assert_eq!(layers.flattened, 2);
|
assert_eq!(layers.flattened, 3);
|
||||||
assert_eq!(modes(&layers), [BlendMode::Normal]);
|
assert_eq!(modes(&layers), [BlendMode::Normal]);
|
||||||
|
|
||||||
// Clipped content flattens everything
|
// Clipped content flattens everything
|
||||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, false);
|
||||||
assert_eq!(layers.flattened, 2);
|
assert_eq!(layers.flattened, 3);
|
||||||
assert_eq!(parts(&layers), [[None]]);
|
assert_eq!(parts(&layers), [[None]]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_images_keep_the_filters_and_what_they_merge_but_not_the_pieces_around_them() {
|
||||||
|
let blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Graphic::default(),
|
||||||
|
radius: 2.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
let shadow = || drop_shadow(RED, BlendMode::Multiply);
|
||||||
|
let kinds = |operations: Vec<EffectOperation>| -> Vec<EffectKind> { content_image_effects(&Effects::from_operations(operations)).operations().map(|operation| operation.kind()).collect() };
|
||||||
|
|
||||||
|
// A shadow is cast from the content, unless a later filter merges it into the content's image
|
||||||
|
assert!(kinds(vec![shadow()]).is_empty());
|
||||||
|
assert_eq!(kinds(vec![blur.clone(), shadow()]), [EffectKind::Blur]);
|
||||||
|
let merged = Effects::from_operations([shadow(), blur.clone()]);
|
||||||
|
assert!(matches!(content_image_effects(&merged), Cow::Borrowed(_)));
|
||||||
|
|
||||||
|
// Trailing masks fade the content's image as they fade each layer
|
||||||
|
assert_eq!(kinds(vec![shadow(), mask()]), [EffectKind::Mask]);
|
||||||
|
let filtered = vec![mask(), inner_shadow(RED, BlendMode::Screen), blur, shadow(), mask()];
|
||||||
|
assert_eq!(kinds(filtered), [EffectKind::Mask, EffectKind::InnerShadow, EffectKind::Blur, EffectKind::Mask]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_background_blur_lies_at_the_bottom_of_the_contents_layer() {
|
||||||
|
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||||
|
let background_blur = EffectOperation::BackgroundBlur {
|
||||||
|
radius: 4.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
let blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Default::default(),
|
||||||
|
radius: 2.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Even beside a blended shadow, and flattened by a later blur, it fades and blends with the content
|
||||||
|
let effects = Effects::from_operations([drop_shadow(blue, BlendMode::Multiply), background_blur, blur]);
|
||||||
|
let layers = EffectLayers::plan(&effects, BlendMode::Screen, 1., true);
|
||||||
|
assert!(layers.reads_backdrop());
|
||||||
|
let content_layer = layers.content_layer().unwrap();
|
||||||
|
assert_eq!(layers.layers[content_layer].blend_mode, BlendMode::Screen);
|
||||||
|
assert_eq!(parts(&layers)[content_layer], [Some((1, 0, PiecePlace::Backdrop)), None]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn blend_ifs_draw_no_pieces_and_read_the_backdrop_only_by_their_ranges_beneath() {
|
||||||
|
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||||
|
ranges.content.gray.range_start = 50.;
|
||||||
|
let content_only = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
|
||||||
|
let layers = EffectLayers::plan(&content_only, BlendMode::Normal, 1., true);
|
||||||
|
assert_eq!(layers.layers.len(), 1);
|
||||||
|
assert!(!layers.reads_backdrop() && !effects_read_backdrop(&content_only));
|
||||||
|
|
||||||
|
ranges.underlying.blue.falloff_end = 50.;
|
||||||
|
let beneath = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
|
||||||
|
let layers = EffectLayers::plan(&beneath, BlendMode::Normal, 1., true);
|
||||||
|
assert_eq!(layers.layers[0].parts, [LayerPart::Content]);
|
||||||
|
assert!(layers.reads_backdrop() && effects_read_backdrop(&beneath));
|
||||||
|
|
||||||
|
// Fading the content by its colors, it splits a blended interior piece as a partial fill does, even at a full fill
|
||||||
|
let screen = Effects::from_operations([inner_shadow(RED.with_alpha(0.75), BlendMode::Screen), EffectOperation::BlendIf(Box::new(ranges))]);
|
||||||
|
let layers = EffectLayers::plan(&screen, BlendMode::Normal, 1., true);
|
||||||
|
assert_eq!(modes(&layers), [BlendMode::Screen, BlendMode::Normal]);
|
||||||
|
assert!(layers.reads_through_share());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn blend_ifs_after_trailing_masks_leave_them_trailing() {
|
||||||
|
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||||
|
ranges.underlying.gray.range_start = 50.;
|
||||||
|
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||||
|
let kinds = |effects: &Effects| -> Vec<EffectKind> { content_image_effects(effects).operations().map(|operation| operation.kind()).collect() };
|
||||||
|
|
||||||
|
// After the mask as before it, the shadow keeps its layer and mode while the mask fades each layer, and a clipping base takes the mask alone
|
||||||
|
for operations in [
|
||||||
|
[drop_shadow(RED, BlendMode::Multiply), mask(), blend_if.clone()],
|
||||||
|
[drop_shadow(RED, BlendMode::Multiply), blend_if.clone(), mask()],
|
||||||
|
] {
|
||||||
|
let effects = Effects::from_operations(operations);
|
||||||
|
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||||
|
assert_eq!(layers.flattened, 0, "{:?}", effects.operations().map(|operation| operation.kind()).collect::<Vec<_>>());
|
||||||
|
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||||
|
assert!(layers.fades_layers());
|
||||||
|
assert_eq!(kinds(&effects), [EffectKind::Mask]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// With nothing else to trail, a clipping base still takes the mask alone in either order
|
||||||
|
assert_eq!(kinds(&Effects::from_operations([blend_if.clone(), mask()])), [EffectKind::Mask]);
|
||||||
|
assert_eq!(kinds(&Effects::from_operations([mask(), blend_if])), [EffectKind::Mask]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn blend_ifs_reading_the_content_after_masks_keep_them_from_trailing() {
|
||||||
|
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||||
|
ranges.content.gray.range_start = 50.;
|
||||||
|
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||||
|
let kinds = |operations: Vec<EffectOperation>| -> Vec<EffectKind> { content_image_effects(&Effects::from_operations(operations)).operations().map(|operation| operation.kind()).collect() };
|
||||||
|
|
||||||
|
// The mask merges the shadow flattened before it into the content's image, which the Blend If then reads
|
||||||
|
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), mask(), blend_if.clone()]);
|
||||||
|
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||||
|
assert_eq!(layers.flattened, 2);
|
||||||
|
assert!(!layers.fades_layers());
|
||||||
|
|
||||||
|
// A clipping base takes the mask alone, with the Blend If before it or after it
|
||||||
|
assert_eq!(kinds(vec![blend_if.clone(), mask()]), [EffectKind::Mask]);
|
||||||
|
assert_eq!(kinds(vec![mask(), blend_if]), [EffectKind::Mask]);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn knocked_out_pieces_hide_behind_however_the_content_covers_them() {
|
fn knocked_out_pieces_hide_behind_however_the_content_covers_them() {
|
||||||
let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
|
let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,498 @@
|
|||||||
|
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the CPU, GPU, and SVG each carry out.
|
||||||
|
|
||||||
|
use crate::effects::{EffectOperation, Effects};
|
||||||
|
use core_types::graphene_hash::CacheHash;
|
||||||
|
use dyn_any::DynAny;
|
||||||
|
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
||||||
|
|
||||||
|
/// The most rows or columns a kernel takes, beyond which those around its center are kept, so its 65,025 weights at most keep each render within reach.
|
||||||
|
pub const MAX_KERNEL_SIDE: usize = 255;
|
||||||
|
|
||||||
|
/// The largest magnitude a weight divided by its divisor takes, so a kernel's sums stay finite.
|
||||||
|
const MAX_WEIGHT: f64 = 1e6;
|
||||||
|
|
||||||
|
/// The least alpha at which a pixel's own color is read, below which (for its faint, poorly known color) it reads the color of the nearest pixel at least this covered.
|
||||||
|
/// This is halfway between the sixteenth and fifteenth of 255 levels, so it divides 8-bit renders the same way everywhere.
|
||||||
|
pub const VISIBLE_ALPHA: f32 = 15.5 / 255.;
|
||||||
|
|
||||||
|
/// What a filter reads beyond the content's visible colors, and how its result returns to the content's coverage.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub enum Surroundings {
|
||||||
|
/// For PSD interop, a pixel too faint to be visible reads the nearest visible pixel's color (by [`fill_shifts`]) so colors continue past the edges, or with none within reach its own.
|
||||||
|
/// The result keeps the content's coverage, unless the convolution weighs that too.
|
||||||
|
Continued,
|
||||||
|
/// The content is composited over an opaque gray of this level and filtered, then lifted back off the gray within its coverage, so its silhouette shows as an edge.
|
||||||
|
Matted(f64),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A weighted sum of copies of the content's straight colors, each shifted by a length in document pixels, divided by a divisor and raised by an offset, keeping the content's coverage unless it weighs that too.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Convolution {
|
||||||
|
/// Each copy's shift from the pixel it adds into toward the pixel it reads, in document pixels, with its weight.
|
||||||
|
pub taps: Vec<(DVec2, f64)>,
|
||||||
|
/// What the weighted sum is divided by, which isn't zero.
|
||||||
|
pub divisor: f64,
|
||||||
|
/// How much the result's colors are raised, as a fraction of full brightness.
|
||||||
|
pub offset: f64,
|
||||||
|
/// What the sum reads beyond the content's visible colors, and how the result returns to the content's coverage.
|
||||||
|
pub surroundings: Surroundings,
|
||||||
|
/// Whether the coverage is weighed by the same copies, with none beyond the content and without the offset, then clamped, rather than kept.
|
||||||
|
pub weighs_coverage: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Convolution {
|
||||||
|
/// For PSD interop, the custom filter's kernel, given its weights row by row across `columns`, and kept to the [`MAX_KERNEL_SIDE`] rows and columns around its center.
|
||||||
|
/// Each weight multiplies the pixel at its place in the kernel, whose center cell lies on the pixel being found: the middle row and column, or for an even count, the one after the middle.
|
||||||
|
/// Weights that aren't finite count as zero, and a `scale` below 1 counts as 1.
|
||||||
|
pub fn custom(weights: &[f64], columns: usize, scale: f64, offset: f64) -> Self {
|
||||||
|
let scale = if scale.is_finite() { scale.max(1.) } else { 1. };
|
||||||
|
|
||||||
|
let taps = kept_weights(weights, columns)
|
||||||
|
.filter_map(|(shift, weight)| {
|
||||||
|
let weight = if weight.is_finite() { (weight / scale).clamp(-MAX_WEIGHT, MAX_WEIGHT) } else { 0. };
|
||||||
|
(weight != 0.).then_some((shift, weight))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Self {
|
||||||
|
taps,
|
||||||
|
divisor: 1.,
|
||||||
|
offset: if offset.is_finite() { offset / 255. } else { 0. },
|
||||||
|
surroundings: Surroundings::Continued,
|
||||||
|
weighs_coverage: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, emboss's difference between two samples `height` pixels apart along the direction the light comes from at `angle` degrees, scaled by the `amount` percentage and lifted to middle gray.
|
||||||
|
/// Each sample spreads over the pixels less than a pixel from it, weighted by how far short of a pixel they lie.
|
||||||
|
pub fn emboss(angle: f64, height: f64, amount: f64) -> Self {
|
||||||
|
// The direction without the rounding left by sines and cosines of right angles, so samples on whole pixels land exactly on them
|
||||||
|
let angle = angle.to_radians();
|
||||||
|
let without_rounding = |value: f64| if value.abs() < 1e-12 { 0. } else { value };
|
||||||
|
let half = DVec2::new(without_rounding(angle.cos()), without_rounding(-angle.sin())) * height.max(0.) / 2.;
|
||||||
|
let spread = |shift: DVec2| (1. - shift.length()).max(0.);
|
||||||
|
|
||||||
|
// Only the four pixels around each sample are less than a pixel from it, whatever the height. O(1).
|
||||||
|
let mut shifts: Vec<DVec2> = [half, -half]
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|sample| [DVec2::ZERO, DVec2::X, DVec2::Y, DVec2::ONE].map(|corner| sample.floor() + corner))
|
||||||
|
.collect();
|
||||||
|
shifts.sort_by(|a, b| a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)));
|
||||||
|
shifts.dedup();
|
||||||
|
let taps = shifts
|
||||||
|
.into_iter()
|
||||||
|
.map(|shift| (shift, (spread(shift - half) - spread(shift + half)) * amount / 100.))
|
||||||
|
.filter(|(_, weight)| weight.abs() > 1e-12)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Self {
|
||||||
|
taps,
|
||||||
|
divisor: 1.,
|
||||||
|
offset: 0.5,
|
||||||
|
surroundings: Surroundings::Matted(0.5),
|
||||||
|
weighs_coverage: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How far from a pixel the farthest copy reads along either axis, in document pixels.
|
||||||
|
pub fn reach(&self) -> f64 {
|
||||||
|
self.taps.iter().map(|(shift, _)| shift.abs().max_element()).fold(0., f64::max)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How far from a pixel its result reads in any direction, which a rotation can turn along an axis, in document pixels.
|
||||||
|
/// That's the farthest copy, then for continued colors a faint pixel's nearest visible one within the square of [`Self::reach`], plus two pixels for rounding and copies between pixels.
|
||||||
|
pub fn read_reach(&self) -> f64 {
|
||||||
|
let farthest = self.taps.iter().map(|(shift, _)| shift.length()).fold(0., f64::max);
|
||||||
|
let faint = match self.surroundings {
|
||||||
|
Surroundings::Continued => std::f64::consts::SQRT_2 * self.reach().ceil(),
|
||||||
|
Surroundings::Matted(_) => 0.,
|
||||||
|
};
|
||||||
|
farthest + faint + 2.
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the result is the content as it is.
|
||||||
|
pub fn is_identity(&self) -> bool {
|
||||||
|
self.offset == 0. && matches!(self.taps.as_slice(), [(shift, weight)] if *shift == DVec2::ZERO && *weight == self.divisor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The weights of a kernel written as text, row by row with each row padded by zeros to the widest, and how many columns it has.
|
||||||
|
/// Each line is a row, with its numbers separated by spaces, commas, or both. Blank lines are skipped, and a number that can't be read counts as zero.
|
||||||
|
pub fn parse_kernel(text: &str) -> (Vec<f64>, usize) {
|
||||||
|
let rows: Vec<Vec<f64>> = text
|
||||||
|
.lines()
|
||||||
|
.map(|line| {
|
||||||
|
let tokens = line.split(|character: char| character.is_whitespace() || character == ',').filter(|token| !token.is_empty());
|
||||||
|
tokens.map(|token| token.parse().unwrap_or(0.)).collect::<Vec<f64>>()
|
||||||
|
})
|
||||||
|
.filter(|row| !row.is_empty())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||||
|
let weights = rows.into_iter().flat_map(|row| {
|
||||||
|
let padding = columns - row.len();
|
||||||
|
row.into_iter().chain(std::iter::repeat_n(0., padding))
|
||||||
|
});
|
||||||
|
(weights.collect(), columns)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The scale that keeps a kernel's brightness the same: the sum of the finite weights [`Convolution::custom`] keeps, but at least 1.
|
||||||
|
pub fn automatic_scale(weights: &[f64], columns: usize) -> f64 {
|
||||||
|
let sum: f64 = kept_weights(weights, columns).map(|(_, weight)| weight).filter(|weight| weight.is_finite()).sum();
|
||||||
|
sum.clamp(1., f64::MAX)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The weights given row by row across `columns`, kept to the [`MAX_KERNEL_SIDE`] rows and columns around the center, each with its shift from the center cell.
|
||||||
|
fn kept_weights(weights: &[f64], columns: usize) -> impl Iterator<Item = (DVec2, f64)> + '_ {
|
||||||
|
let full = [columns.max(1), weights.len().div_ceil(columns.max(1))];
|
||||||
|
let kept = full.map(|count| count.min(MAX_KERNEL_SIDE));
|
||||||
|
let start = [0, 1].map(|axis| full[axis] / 2 - kept[axis] / 2);
|
||||||
|
let center = kept.map(|count| (count / 2) as f64);
|
||||||
|
|
||||||
|
(0..kept[0] * kept[1]).filter_map(move |index| {
|
||||||
|
let (column, row) = (index % kept[0], index / kept[0]);
|
||||||
|
let weight = *weights.get((row + start[1]) * full[0] + column + start[0])?;
|
||||||
|
Some((DVec2::new(column as f64 - center[0], row as f64 - center[1]), weight))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the operation is a pixel filter, which processes the pixels of the content and everything drawn with it so far.
|
||||||
|
pub fn is_filter(operation: &EffectOperation) -> bool {
|
||||||
|
matches!(
|
||||||
|
operation,
|
||||||
|
EffectOperation::ConvolutionKernel { .. }
|
||||||
|
| EffectOperation::Emboss { .. }
|
||||||
|
| EffectOperation::FindEdges
|
||||||
|
| EffectOperation::MinimumMaximum { .. }
|
||||||
|
| EffectOperation::Sharpen { .. }
|
||||||
|
| EffectOperation::HighPass { .. }
|
||||||
|
| EffectOperation::Speckle { .. }
|
||||||
|
| EffectOperation::Dissolve { .. }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the operation is a pixel filter reading the pixels around each one, its details and edges, rather than only the pixel itself and a random field.
|
||||||
|
pub fn reads_neighbors(operation: &EffectOperation) -> bool {
|
||||||
|
is_filter(operation) && !is_random_field_filter(operation)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the operation is a pixel filter combining each pixel with a random field fixed to the content, which changes endless content as much as any other.
|
||||||
|
pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
|
||||||
|
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
|
||||||
|
/// The random field filters change endless content without its neighbors (see [`is_random_field_filter`]).
|
||||||
|
pub fn has_filters(effects: &Effects) -> bool {
|
||||||
|
effects.operations().any(|operation| reads_neighbors(&operation) && !operation.changes_nothing())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
|
||||||
|
pub const SOBEL_TAPS: [(DVec2, [f64; 2]); 8] = [
|
||||||
|
(DVec2::new(-1., -1.), [-1., -1.]),
|
||||||
|
(DVec2::new(0., -1.), [0., -2.]),
|
||||||
|
(DVec2::new(1., -1.), [1., -1.]),
|
||||||
|
(DVec2::new(-1., 0.), [-2., 0.]),
|
||||||
|
(DVec2::new(1., 0.), [2., 0.]),
|
||||||
|
(DVec2::new(-1., 1.), [-1., 1.]),
|
||||||
|
(DVec2::new(0., 1.), [0., 2.]),
|
||||||
|
(DVec2::new(1., 1.), [1., 1.]),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The blurred visibility around a pixel below which unsharp masking compares the pixel against its own color, and above which against the average of the visible colors, easing between the two.
|
||||||
|
/// Below it, too little of the blur lands on visible pixels for 8-bit renders to know their average.
|
||||||
|
pub const AVERAGE_VISIBILITY_RAMP: [f32; 2] = [8. / 255., 24. / 255.];
|
||||||
|
|
||||||
|
/// For PSD interop, the middle gray a high pass centers its differences on, as an 8-bit level.
|
||||||
|
pub const HIGH_PASS_GRAY: f32 = 128. / 255.;
|
||||||
|
|
||||||
|
/// How much of the visible colors' average a pixel is compared against, the rest being its own color, given how much of the blur around it lands on visible pixels.
|
||||||
|
pub fn average_weight(visibility: f32) -> f32 {
|
||||||
|
let [start, end] = AVERAGE_VISIBILITY_RAMP;
|
||||||
|
((visibility - start) / (end - start)).clamp(0., 1.)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the filter sharpens or otherwise weighs the content's coverage, so a fill must fade its result rather than its input.
|
||||||
|
pub fn sharpens_coverage(operation: &EffectOperation) -> bool {
|
||||||
|
matches!(operation, EffectOperation::Sharpen { .. } | EffectOperation::ConvolutionKernel { apply_to_alpha: true, .. })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, the shifts of the four nearest neighbors in document pixels, whose average Edges Only compares each pixel against.
|
||||||
|
pub const SHARPEN_NEIGHBORS: [DVec2; 4] = [DVec2::new(0., -1.), DVec2::new(-1., 0.), DVec2::new(1., 0.), DVec2::new(0., 1.)];
|
||||||
|
|
||||||
|
/// For PSD interop, the Sobel gradient lengths (as Find Edges measures them, on values from 0 to 1) between which Edges Only ramps from no change to the whole of it.
|
||||||
|
/// A step between flat areas has a quarter of that length at a sixteenth of full contrast, and its whole length at a quarter.
|
||||||
|
pub const EDGE_GAIN_RAMP: [f32; 2] = [0.25, 1.];
|
||||||
|
|
||||||
|
/// For PSD interop, the share of its change that Edges Only makes in a channel whose Sobel gradient has the length `gradient`.
|
||||||
|
pub fn edge_gain(gradient: f32) -> f32 {
|
||||||
|
let [start, end] = EDGE_GAIN_RAMP;
|
||||||
|
((gradient - start) / (end - start)).clamp(0., 1.)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What unsharp masking or a high pass compares each pixel against.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub enum UnsharpBlur {
|
||||||
|
/// A Gaussian blur with this standard deviation in document pixels.
|
||||||
|
Gaussian(f64),
|
||||||
|
/// For Edges Only, the average of the four nearest neighbors, [`SHARPEN_NEIGHBORS`], read between pixels where they don't land on one.
|
||||||
|
/// Each channel is moved only part of the way toward it, by its [`edge_gain`], so it changes only along edges.
|
||||||
|
EdgeNeighbors,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a Sharpen or High Pass compares each pixel against, with a Sharpen's amount and threshold as fractions, or `None` for any other operation.
|
||||||
|
pub fn unsharp(operation: &EffectOperation) -> Option<(UnsharpBlur, Option<[f64; 2]>)> {
|
||||||
|
match *operation {
|
||||||
|
EffectOperation::Sharpen {
|
||||||
|
amount,
|
||||||
|
radius,
|
||||||
|
threshold,
|
||||||
|
edges_only,
|
||||||
|
} => {
|
||||||
|
let blur = if edges_only { UnsharpBlur::EdgeNeighbors } else { UnsharpBlur::Gaussian(radius) };
|
||||||
|
Some((blur, Some([amount / 100., threshold.max(0.) / 255.])))
|
||||||
|
}
|
||||||
|
EffectOperation::HighPass { radius } => Some((UnsharpBlur::Gaussian(radius), None)),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, unsharp masking's change to a value lying `difference` above the blur around it: the difference scaled by `amount`, softened toward none by `threshold`, both fractions.
|
||||||
|
pub fn unsharp_change(difference: f32, amount: f32, threshold: f32) -> f32 {
|
||||||
|
difference.signum() * (amount * difference.abs() - threshold).max(0.)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole radii a neighborhood minimum or maximum of `radius` document pixels mixes between, measured in pixels by `pixels_per_length`, with how far it lies toward the larger.
|
||||||
|
pub fn neighborhood_radii(radius: f64, pixels_per_length: f64) -> ([u32; 2], f64) {
|
||||||
|
let radius = radius.max(0.);
|
||||||
|
let whole = |radius: f64| (radius * pixels_per_length).round() as u32;
|
||||||
|
([whole(radius.floor()), whole(radius.ceil())], radius.fract())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole-pixel shifts out to `reach` pixels along each axis, nearest first, which a faint pixel looks along for the visible pixel to read the color of.
|
||||||
|
/// For PSD interop, ties go below before right, then left, then above. O(reach² log reach).
|
||||||
|
pub fn fill_shifts(reach: i32) -> Vec<[i32; 2]> {
|
||||||
|
let mut shifts: Vec<[i32; 2]> = (-reach..=reach).flat_map(|y| (-reach..=reach).map(move |x| [x, y])).collect();
|
||||||
|
shifts.sort_by_key(|&[x, y]| (x * x + y * y, -y, -x));
|
||||||
|
shifts
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the random offsets Speckle gives the colors are spread.
|
||||||
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||||
|
#[widget(Radio)]
|
||||||
|
pub enum NoiseDistribution {
|
||||||
|
/// Every offset up to the amount is equally likely.
|
||||||
|
#[default]
|
||||||
|
Uniform,
|
||||||
|
/// Offsets cluster around none, with the amount as their standard deviation, so most are subtle and a few reach well past it.
|
||||||
|
Gaussian,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, how many standard deviations Gaussian noise reaches, where its tails are cut off.
|
||||||
|
pub const GAUSSIAN_NOISE_LIMIT: f32 = 3.5;
|
||||||
|
|
||||||
|
/// The random fields a seed gives, each hashed apart so the fields of one seed are unrelated.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum RandomField {
|
||||||
|
/// Speckle's offset for each color, or for Gaussian noise its first uniform value.
|
||||||
|
NoiseOffsets,
|
||||||
|
/// Gaussian noise's second uniform value for each color, its angle.
|
||||||
|
NoiseAngles,
|
||||||
|
/// Dissolve's two thresholds, for the opacity and for the coverage.
|
||||||
|
Dissolve,
|
||||||
|
/// The grain a glow's noise and jitter share.
|
||||||
|
GlowGrain,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RandomField {
|
||||||
|
/// The value hashed with each cell for this field of the `seed`.
|
||||||
|
pub fn seed(self, seed: i64) -> u32 {
|
||||||
|
// Each seed spreads across four fields, and all four are taken
|
||||||
|
let offset = match self {
|
||||||
|
Self::NoiseOffsets => 0,
|
||||||
|
Self::NoiseAngles => 1,
|
||||||
|
Self::Dissolve => 2,
|
||||||
|
Self::GlowGrain => 3,
|
||||||
|
};
|
||||||
|
(seed as u32).wrapping_mul(4).wrapping_add(offset)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The largest offset Speckle of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
|
||||||
|
pub fn noise_extent(amount: f64, distribution: NoiseDistribution) -> f64 {
|
||||||
|
let deviations = match distribution {
|
||||||
|
NoiseDistribution::Uniform => 1.,
|
||||||
|
NoiseDistribution::Gaussian => GAUSSIAN_NOISE_LIMIT as f64,
|
||||||
|
};
|
||||||
|
(amount.max(0.) * deviations).min(1.)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The most samples a pixel takes of a random field along each of its axes, which it takes when it spans that many cells or more.
|
||||||
|
pub const MAX_FIELD_SAMPLES_PER_AXIS: u32 = 4;
|
||||||
|
|
||||||
|
/// Where each pixel of a render reads a random field of one value per cell, the unit squares of the effect space, which fixes it to the content.
|
||||||
|
/// A pixel no larger than a cell reads the one under its center. A larger one averages samples spread across it, as a downsample of the field at full size would.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct FieldSampling {
|
||||||
|
/// The cell at the render's origin, kept apart from the rest of the way to it so 32-bit math on a GPU stays precise far from the effect space's origin.
|
||||||
|
pub origin_cell: IVec2,
|
||||||
|
/// The rest of the way from the origin's cell to the origin.
|
||||||
|
pub origin_fraction: DVec2,
|
||||||
|
/// A step of one pixel along each axis, in cells.
|
||||||
|
pub pixel_axes: DMat2,
|
||||||
|
/// How many samples are taken along each of a pixel's axes.
|
||||||
|
pub counts: UVec2,
|
||||||
|
/// How far apart the outermost samples are along each axis, in pixels, so each lands near the middle of a cell of its own.
|
||||||
|
pub spreads: DVec2,
|
||||||
|
/// For pixels spanning more cells than they sample, how much less an average of them all would deviate from the field's mean than the samples' average does.
|
||||||
|
pub deviation_scale: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FieldSampling {
|
||||||
|
/// The sampling of a render with its pixels placed in the effect space by `pixels_to_effect`.
|
||||||
|
pub fn new(pixels_to_effect: DAffine2) -> Self {
|
||||||
|
let origin = pixels_to_effect.translation;
|
||||||
|
let origin_cell = origin.floor();
|
||||||
|
let pixel_axes = pixels_to_effect.matrix2;
|
||||||
|
|
||||||
|
// A pixel spanning a cell give or take rounding takes one sample
|
||||||
|
let spans = DVec2::new(pixel_axes.x_axis.length(), pixel_axes.y_axis.length());
|
||||||
|
let counts = spans.map(|span| (span - 1e-3).ceil().clamp(1., MAX_FIELD_SAMPLES_PER_AXIS as f64));
|
||||||
|
let spread = |span: f64, count: f64| if count > 1. { (span - 1.) / span * count / (count - 1.) } else { 0. };
|
||||||
|
|
||||||
|
Self {
|
||||||
|
origin_cell: origin_cell.as_ivec2(),
|
||||||
|
origin_fraction: origin - origin_cell,
|
||||||
|
pixel_axes,
|
||||||
|
counts: counts.as_uvec2(),
|
||||||
|
spreads: DVec2::new(spread(spans.x, counts.x), spread(spans.y, counts.y)),
|
||||||
|
deviation_scale: (counts / spans).min(DVec2::ONE).element_product().sqrt(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cell under the point `offset` pixels from the middle of the pixel at `pixel` (its column and row).
|
||||||
|
fn cell_at(&self, pixel: [usize; 2], offset: DVec2) -> IVec2 {
|
||||||
|
let position = DVec2::new(pixel[0] as f64, pixel[1] as f64) + 0.5 + offset;
|
||||||
|
self.origin_cell.wrapping_add((self.origin_fraction + self.pixel_axes * position).floor().as_ivec2())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cell under the middle of the pixel at `pixel`.
|
||||||
|
pub fn center_cell(&self, pixel: [usize; 2]) -> IVec2 {
|
||||||
|
self.cell_at(pixel, DVec2::ZERO)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cells the pixel at `pixel` samples, row by row.
|
||||||
|
pub fn sample_cells(&self, pixel: [usize; 2]) -> impl Iterator<Item = IVec2> + '_ {
|
||||||
|
let place = |index: u32, count: u32, spread: f64| ((index as f64 + 0.5) / count as f64 - 0.5) * spread;
|
||||||
|
(0..self.counts.y)
|
||||||
|
.flat_map(move |row| (0..self.counts.x).map(move |column| self.cell_at(pixel, DVec2::new(place(column, self.counts.x, self.spreads.x), place(row, self.counts.y, self.spreads.y)))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn kernels_parse_a_row_from_each_line() {
|
||||||
|
// Spaces, commas, and tabs separate the numbers, blank lines are skipped, and a number that can't be read counts as zero
|
||||||
|
let (weights, columns) = parse_kernel("1, 2 ,3\r\n\n 4\t-5e-1 x \n\n 6,,7\n");
|
||||||
|
assert_eq!(columns, 3);
|
||||||
|
assert_eq!(weights, vec![1., 2., 3., 4., -0.5, 0., 6., 7., 0.]);
|
||||||
|
|
||||||
|
// Rows shorter than the widest end in zeros
|
||||||
|
assert_eq!(parse_kernel("1\n2 3 4"), (vec![1., 0., 0., 2., 3., 4.], 3));
|
||||||
|
assert_eq!(parse_kernel(" \n\t\n"), (Vec::new(), 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn weights_read_row_by_row_around_the_center() {
|
||||||
|
// The weight right of the center reads the pixel to the right, divided by the scale
|
||||||
|
let convolution = Convolution::custom(&[0., 0., 0., 0., 0., 2., 0., 0., 0.], 3, 4., 128.);
|
||||||
|
assert_eq!(convolution.taps, vec![(DVec2::new(1., 0.), 0.5)]);
|
||||||
|
assert!((convolution.offset - 128. / 255.).abs() < 1e-12);
|
||||||
|
assert_eq!(convolution.reach(), 1.);
|
||||||
|
|
||||||
|
assert!(Convolution::custom(&[3.], 1, 3., 0.).is_identity());
|
||||||
|
assert!(!Convolution::custom(&[3.], 1, 1., 0.).is_identity());
|
||||||
|
// A scale below 1 divides by 1, and a weight past the largest stays finite
|
||||||
|
assert_eq!(Convolution::custom(&[2.], 1, 0., 0.).taps, vec![(DVec2::ZERO, 2.)]);
|
||||||
|
assert_eq!(Convolution::custom(&[2.], 1, 0.5, 0.).taps, vec![(DVec2::ZERO, 2.)]);
|
||||||
|
assert_eq!(Convolution::custom(&[1e300], 1, 1., 0.).taps, vec![(DVec2::ZERO, MAX_WEIGHT)]);
|
||||||
|
// Weights that aren't finite count as zero
|
||||||
|
assert!(Convolution::custom(&[f64::INFINITY, f64::NAN, 0., 0., 1., 0.], 3, 1., 0.).is_identity());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn kernels_center_on_their_middle_row_and_column() {
|
||||||
|
let shift = |x: f64, y: f64| DVec2::new(x, y);
|
||||||
|
let shifts = |convolution: Convolution| convolution.taps.into_iter().map(|(shift, _)| shift).collect::<Vec<_>>();
|
||||||
|
|
||||||
|
// A row reads across and a column reads down, each around its middle
|
||||||
|
assert_eq!(shifts(Convolution::custom(&[1., 2., 3.], 3, 1., 0.)), vec![shift(-1., 0.), shift(0., 0.), shift(1., 0.)]);
|
||||||
|
assert_eq!(shifts(Convolution::custom(&[1., 2., 3.], 1, 1., 0.)), vec![shift(0., -1.), shift(0., 0.), shift(0., 1.)]);
|
||||||
|
|
||||||
|
// An even count centers on the cell after its middle, so a 2×2 kernel reaches only up and left
|
||||||
|
let square = Convolution::custom(&[1., 2., 3., 4.], 2, 1., 0.);
|
||||||
|
assert_eq!(square.taps, vec![(shift(-1., -1.), 1.), (shift(0., -1.), 2.), (shift(-1., 0.), 3.), (shift(0., 0.), 4.)]);
|
||||||
|
let wide = Convolution::custom(&[1.; 8], 4, 1., 0.);
|
||||||
|
assert_eq!((wide.taps[0].0, wide.taps[7].0), (shift(-2., -1.), shift(1., 0.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn kernels_past_the_largest_keep_the_rows_and_columns_around_their_center() {
|
||||||
|
// A kernel larger than one pass of the GPU's taps keeps every weight
|
||||||
|
assert_eq!(Convolution::custom(&[1.; 121], 11, 1., 0.).taps.len(), 121);
|
||||||
|
|
||||||
|
let side = MAX_KERNEL_SIDE + 2;
|
||||||
|
let center = side / 2 * side + side / 2;
|
||||||
|
let mut wide = vec![0.; side * side];
|
||||||
|
wide[center] = 3.;
|
||||||
|
wide[center + 1] = 2.;
|
||||||
|
wide[0] = 1.;
|
||||||
|
assert_eq!(Convolution::custom(&wide, side, 1., 0.).taps, vec![(DVec2::ZERO, 3.), (DVec2::X, 2.)]);
|
||||||
|
assert_eq!(Convolution::custom(&vec![1.; side * side], side, 1., 0.).reach(), (MAX_KERNEL_SIDE / 2) as f64);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_automatic_scale_is_the_sum_of_the_kept_weights_but_at_least_1() {
|
||||||
|
assert_eq!(automatic_scale(&[1.; 9], 3), 9.);
|
||||||
|
assert_eq!(automatic_scale(&[2., f64::NAN, 3., f64::INFINITY], 4), 5.);
|
||||||
|
// A sum past the largest finite number stays finite, rather than counting as 1
|
||||||
|
assert_eq!(automatic_scale(&[f64::MAX, f64::MAX], 2), f64::MAX);
|
||||||
|
|
||||||
|
// Kernels summing below 1, like those finding edges, divide by 1
|
||||||
|
assert_eq!(automatic_scale(&[0., -1., 0., -1., 5., -1., 0., -1., 0.], 3), 1.);
|
||||||
|
assert_eq!(automatic_scale(&[-1., 0., 1.], 3), 1.);
|
||||||
|
assert_eq!(automatic_scale(&[0.25, 0.25], 2), 1.);
|
||||||
|
assert_eq!(automatic_scale(&[], 0), 1.);
|
||||||
|
|
||||||
|
let side = MAX_KERNEL_SIDE + 2;
|
||||||
|
assert_eq!(automatic_scale(&vec![1.; side * side], side), (MAX_KERNEL_SIDE * MAX_KERNEL_SIDE) as f64);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn emboss_differences_samples_spread_around_the_light_direction() {
|
||||||
|
// Light from the right at a height of 2 samples a pixel to each side, each exactly on one pixel
|
||||||
|
let emboss = Convolution::emboss(0., 2., 100.);
|
||||||
|
assert_eq!(emboss.taps, vec![(DVec2::new(-1., 0.), -1.), (DVec2::new(1., 0.), 1.)]);
|
||||||
|
assert_eq!(emboss.offset, 0.5);
|
||||||
|
|
||||||
|
// Halfway between pixels, each sample spreads over the two beside it
|
||||||
|
let between = Convolution::emboss(90., 1., 200.);
|
||||||
|
let weight = |shift: DVec2| between.taps.iter().find(|(tap, _)| *tap == shift).map_or(0., |(_, weight)| *weight);
|
||||||
|
assert!((weight(DVec2::new(0., -1.)) - 1.).abs() < 1e-12);
|
||||||
|
assert!((weight(DVec2::ZERO)).abs() < 1e-12);
|
||||||
|
assert!((weight(DVec2::new(0., 1.)) + 1.).abs() < 1e-12);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn faint_pixels_look_nearest_first_and_below_before_right() {
|
||||||
|
let shifts = fill_shifts(1);
|
||||||
|
assert_eq!(shifts.len(), 9);
|
||||||
|
assert_eq!(&shifts[..5], &[[0, 0], [0, 1], [1, 0], [-1, 0], [0, -1]]);
|
||||||
|
assert_eq!(shifts[5], [1, 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -315,3 +315,21 @@ impl GeneratorPattern {
|
|||||||
Self::decode(*item.element(), &|key| item.attributes().get_any(key))
|
Self::decode(*item.element(), &|key| item.attributes().get_any(key))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result.
|
||||||
|
pub fn pcg3d(input: [u32; 3]) -> [u32; 3] {
|
||||||
|
let mix = |[x, y, z]: [u32; 3]| {
|
||||||
|
let x = x.wrapping_add(y.wrapping_mul(z));
|
||||||
|
let y = y.wrapping_add(z.wrapping_mul(x));
|
||||||
|
let z = z.wrapping_add(x.wrapping_mul(y));
|
||||||
|
[x, y, z]
|
||||||
|
};
|
||||||
|
|
||||||
|
let v = mix(input.map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223)));
|
||||||
|
mix(v.map(|value| value ^ (value >> 16)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A hash's top 24 bits as a fraction from 0 to 1, which an f32 holds exactly.
|
||||||
|
pub fn hash_fraction(hash: u32) -> f32 {
|
||||||
|
(hash >> 8) as f32 / (1_u32 << 24) as f32
|
||||||
|
}
|
||||||
@@ -14,7 +14,7 @@ use dyn_any::DynAny;
|
|||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use raster_types::{CPU, GPU, Raster};
|
use raster_types::{CPU, GPU, Raster};
|
||||||
pub use vector_types::Vector;
|
pub use vector_types::Vector;
|
||||||
use vector_types::vector::{Path, paths_from_item_attributes, paths_from_list_row_attributes};
|
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
|
||||||
use vector_types::{Gradient, GradientSpread};
|
use vector_types::{Gradient, GradientSpread};
|
||||||
|
|
||||||
/// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node.
|
/// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node.
|
||||||
@@ -630,10 +630,11 @@ impl Graphic {
|
|||||||
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
||||||
match self {
|
match self {
|
||||||
Graphic::Vector(item) => {
|
Graphic::Vector(item) => {
|
||||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none() && vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
|
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing)
|
||||||
|
&& vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
|
||||||
}
|
}
|
||||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none()
|
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing)
|
||||||
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
||||||
}),
|
}),
|
||||||
_ => false,
|
_ => false,
|
||||||
@@ -742,6 +743,22 @@ impl Graphic {
|
|||||||
Graphic::StrokeList(list) => list.is_empty(),
|
Graphic::StrokeList(list) => list.is_empty(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether this graphic draws nothing at all, such as an empty list or an image without pixels.
|
||||||
|
pub fn draws_nothing(&self) -> bool {
|
||||||
|
use raster_types::Storage;
|
||||||
|
|
||||||
|
let no_pixels = |raster: &Raster<CPU>| raster.width == 0 || raster.height == 0;
|
||||||
|
match self {
|
||||||
|
Graphic::Graphic(item) => item.element().draws_nothing(),
|
||||||
|
Graphic::GraphicList(list) => list.iter_element_values().all(Graphic::draws_nothing),
|
||||||
|
Graphic::RasterCPU(item) => no_pixels(item.element()),
|
||||||
|
Graphic::RasterCPUList(list) => list.iter_element_values().all(no_pixels),
|
||||||
|
Graphic::RasterGPU(item) => item.element().is_empty(),
|
||||||
|
Graphic::RasterGPUList(list) => list.iter_element_values().all(Raster::<GPU>::is_empty),
|
||||||
|
graphic => graphic.is_empty(),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a vector object's own opacity and paint let a clipper reduce to an SVG `<clipPath>` instead of a `<mask>`.
|
/// Whether a vector object's own opacity and paint let a clipper reduce to an SVG `<clipPath>` instead of a `<mask>`.
|
||||||
@@ -857,6 +874,20 @@ pub fn vector_item_bounding_box(item: &Item<Vector>, transform: DAffine2, includ
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The bounding box of a vector list's item in its own space, before its transform, with its stroke, which is the frame its effects relative to its extent take.
|
||||||
|
pub fn vector_list_item_local_bounds(list: &List<Vector>, index: usize) -> Option<[DVec2; 2]> {
|
||||||
|
let stroke = list.attribute::<Appearance>(ATTR_APPEARANCE, index).and_then(Appearance::first_stroke_params);
|
||||||
|
let paths = paths_from_list_row_attributes(list, index).unwrap_or_else(|| no_paths());
|
||||||
|
list.element(index)?.stroke_inclusive_bounding_box_with_transform(paths, DAffine2::IDENTITY, stroke.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bounding box of a vector item in its own space, before its transform, with its stroke, which is the frame its effects relative to its extent take.
|
||||||
|
pub fn vector_item_local_bounds(item: &Item<Vector>) -> Option<[DVec2; 2]> {
|
||||||
|
let stroke = item.attribute::<Appearance>(ATTR_APPEARANCE).and_then(Appearance::first_stroke_params);
|
||||||
|
let paths = paths_from_item_attributes(item).unwrap_or_else(|| no_paths());
|
||||||
|
item.element().stroke_inclusive_bounding_box_with_transform(paths, DAffine2::IDENTITY, stroke.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
/// Combined bounding box of a vector list's items, inflating each item by its appearance's stroke when `include_stroke`.
|
/// Combined bounding box of a vector list's items, inflating each item by its appearance's stroke when `include_stroke`.
|
||||||
pub fn vector_list_bounding_box(list: &List<Vector>, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
pub fn vector_list_bounding_box(list: &List<Vector>, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||||
let mut combined_bounds: Option<[DVec2; 2]> = None;
|
let mut combined_bounds: Option<[DVec2; 2]> = None;
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
pub mod adjustment;
|
pub mod adjustment;
|
||||||
pub mod appearance;
|
pub mod appearance;
|
||||||
pub mod artboard;
|
pub mod artboard;
|
||||||
|
pub mod blend_if;
|
||||||
pub mod effect_layers;
|
pub mod effect_layers;
|
||||||
pub mod effects;
|
pub mod effects;
|
||||||
|
pub mod filters;
|
||||||
pub mod generator;
|
pub mod generator;
|
||||||
pub mod graphic;
|
pub mod graphic;
|
||||||
pub mod masks;
|
pub mod masks;
|
||||||
pub(crate) mod parameters;
|
pub(crate) mod parameters;
|
||||||
|
pub mod resampling;
|
||||||
|
pub mod warp;
|
||||||
|
|
||||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||||
pub use core_types;
|
pub use core_types;
|
||||||
@@ -17,13 +21,17 @@ pub use vector_types;
|
|||||||
pub use adjustment::Adjustment;
|
pub use adjustment::Adjustment;
|
||||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||||
pub use artboard::Artboard;
|
pub use artboard::Artboard;
|
||||||
|
pub use blend_if::BlendIfChannel;
|
||||||
pub use effects::{
|
pub use effects::{
|
||||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, fitted_paint, linked_to_content, paint_with_envelope_effects, stamp_effect,
|
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||||
stamped_transform,
|
stamp_effect, stamped_transform,
|
||||||
};
|
};
|
||||||
|
pub use filters::NoiseDistribution;
|
||||||
pub use generator::Generator;
|
pub use generator::Generator;
|
||||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||||
pub use masks::MaskMode;
|
pub use masks::MaskMode;
|
||||||
|
pub use resampling::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||||
|
pub use warp::WarpStyle;
|
||||||
|
|
||||||
pub mod migrations {
|
pub mod migrations {
|
||||||
use crate::Vector;
|
use crate::Vector;
|
||||||
|
|||||||
@@ -7,26 +7,45 @@ use dyn_any::DynAny;
|
|||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||||
#[widget(Radio)]
|
#[widget(Dropdown)]
|
||||||
pub enum MaskMode {
|
pub enum MaskMode {
|
||||||
/// White shows the content and black hides it, with transparent areas also hiding it.
|
/// White shows the content and black hides it, with transparent areas also hiding it. Brightness is judged by weighting the gamma-encoded RGB channels by `0.3, 0.59, 0.11`.
|
||||||
|
///
|
||||||
|
/// This matches the Luminosity family of blend modes.
|
||||||
#[default]
|
#[default]
|
||||||
Luminance,
|
Luminance,
|
||||||
|
/// Like Luminance, but brightness is judged by weighting the gamma-encoded RGB channels by `0.2125, 0.7154, 0.0721`, so greens show more of the content, and reds and blues less.
|
||||||
|
///
|
||||||
|
/// SVG luminance masks use this, so masks brought in from SVG keep their look.
|
||||||
|
#[label("Luminance (SVG)")]
|
||||||
|
LuminanceSvg,
|
||||||
/// Opaque areas show the content and transparent areas hide it, whatever their colors.
|
/// Opaque areas show the content and transparent areas hide it, whatever their colors.
|
||||||
Alpha,
|
Alpha,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The weights of the red, green, and blue channels in a mask's luminance, those of SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
|
/// The weights of the red, green, and blue channels in the luminance of a mask in the `Luminance` mode, taken on gamma-encoded channels, those the Luminosity family of blend modes uses.
|
||||||
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
|
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.3, 0.59, 0.11];
|
||||||
|
|
||||||
|
/// The weights of the red, green, and blue channels in SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
|
||||||
|
/// They weigh the luminance of a mask in the `LuminanceSvg` mode and of the maps that vary other effects, which SVG reads by `luminanceToAlpha`.
|
||||||
|
pub const SVG_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
|
||||||
|
|
||||||
|
impl MaskMode {
|
||||||
|
/// The weights of a mask graphic's premultiplied gamma-encoded red, green, blue, and alpha channels that sum to how much it shows the content.
|
||||||
|
pub fn channel_weights(self) -> [f32; 4] {
|
||||||
|
let ([red, green, blue], alpha) = match self {
|
||||||
|
Self::Luminance => (MASK_LUMINANCE_WEIGHTS, 0.),
|
||||||
|
Self::LuminanceSvg => (SVG_LUMINANCE_WEIGHTS, 0.),
|
||||||
|
Self::Alpha => ([0.; 3], 1.),
|
||||||
|
};
|
||||||
|
[red, green, blue, alpha]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// How much a pixel of the mask graphic, given as premultiplied gamma-encoded channels, shows the content, from 0 to 1.
|
/// How much a pixel of the mask graphic, given as premultiplied gamma-encoded channels, shows the content, from 0 to 1.
|
||||||
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in either mode.
|
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in every mode.
|
||||||
pub fn mask_coverage([red, green, blue, alpha]: [f32; 4], mode: MaskMode) -> f32 {
|
pub fn mask_coverage(channels: [f32; 4], mode: MaskMode) -> f32 {
|
||||||
let [red_weight, green_weight, blue_weight] = MASK_LUMINANCE_WEIGHTS;
|
let coverage: f32 = channels.into_iter().zip(mode.channel_weights()).map(|(channel, weight)| channel * weight).sum();
|
||||||
let coverage = match mode {
|
|
||||||
MaskMode::Luminance => red * red_weight + green * green_weight + blue * blue_weight,
|
|
||||||
MaskMode::Alpha => alpha,
|
|
||||||
};
|
|
||||||
coverage.clamp(0., 1.)
|
coverage.clamp(0., 1.)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,3 +79,81 @@ pub fn feather_parts(distance: f64) -> (f64, f64) {
|
|||||||
let distance = distance.max(0.);
|
let distance = distance.max(0.);
|
||||||
(distance / 2., distance / 6.)
|
(distance / 2., distance / 6.)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The most levels a masked radius blur interpolates between down to a document pixel, enough to halve from a radius of 1000 document pixels to one.
|
||||||
|
pub const MASKED_RADIUS_BLUR_MAX_LEVELS: usize = 12;
|
||||||
|
|
||||||
|
/// The most levels finer than a document pixel that a masked radius blur adds when zoomed in, enough to reach an output pixel at a zoom of 25600%.
|
||||||
|
pub const MASKED_RADIUS_BLUR_MAX_FINER_LEVELS: usize = 8;
|
||||||
|
|
||||||
|
/// The standard deviations, in document pixels, of the Gaussians a masked radius blur of `radius` interpolates between: none, then the radius halved while it spans a document pixel, or an output pixel at more `pixels_per_length` than one.
|
||||||
|
/// Levels a factor of 2 apart interpolate into what reads as one blur, and under a pixel a blur hardly differs from none.
|
||||||
|
pub fn masked_radius_blur_levels(radius: f64, pixels_per_length: f64) -> Vec<f64> {
|
||||||
|
let finest = 1. / pixels_per_length.max(1.);
|
||||||
|
|
||||||
|
let (mut blurred, mut finer) = (vec![radius.max(0.)], 0);
|
||||||
|
loop {
|
||||||
|
let next = blurred[0] / 2.;
|
||||||
|
let coarse = next >= 1. && blurred.len() + 1 < MASKED_RADIUS_BLUR_MAX_LEVELS;
|
||||||
|
let fine = (finest..1.).contains(&next) && finer < MASKED_RADIUS_BLUR_MAX_FINER_LEVELS;
|
||||||
|
if !(coarse || fine) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
finer += fine as usize;
|
||||||
|
blurred.insert(0, next);
|
||||||
|
}
|
||||||
|
std::iter::once(0.).chain(blurred).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The 8-bit code of a masked radius blur map's luminance at a pixel, given as premultiplied gamma-encoded channels, which picks the pixel's interpolation between blurs.
|
||||||
|
pub fn masked_radius_blur_code(channels: [f32; 4]) -> u8 {
|
||||||
|
(mask_coverage(channels, MaskMode::LuminanceSvg) * 255.).round() as u8
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For a masked radius blur map's luminance as an 8-bit `code`, the level below it among the `levels` (from [`masked_radius_blur_levels`]) and how many of 255 parts of the interpolation the level above takes, the rest going to the level below.
|
||||||
|
///
|
||||||
|
/// Each pixel of a Gaussian masked radius blur is the sum of its levels (its content blurred by Gaussians of their radii) weighed by their parts, on premultiplied gamma-encoded channels.
|
||||||
|
/// The map value's fraction of the full radius falls between two levels. The parts are linear in the radius from no blur to the first level, and linear in its logarithm between blurred levels.
|
||||||
|
/// On opaque hard edges, between Gaussian levels a factor of 2 apart, that strays at most about 20 of 255 sRGB levels from a true Gaussian of the map value's radius, against about 32 for the sum in linear light.
|
||||||
|
/// Summing in gamma, even when the levels blur in linear light, is deliberate: a power space near 2.7 strays only about 12, but SVG would need a 256-entry table per level for it, where gamma costs nothing.
|
||||||
|
pub fn masked_radius_blur_interpolation(code: u8, levels: &[f64]) -> (usize, u32) {
|
||||||
|
let Some(&radius) = levels.last().filter(|_| levels.len() >= 2) else { return (0, 0) };
|
||||||
|
let length = code as f64 / 255. * radius;
|
||||||
|
let below = (0..levels.len() - 1).rev().find(|&level| length >= levels[level]).unwrap_or(0);
|
||||||
|
let (low, high) = (levels[below], levels[below + 1]);
|
||||||
|
|
||||||
|
let share = match low > 0. {
|
||||||
|
true => (length / low).log2() / (high / low).log2(),
|
||||||
|
false => length / high,
|
||||||
|
};
|
||||||
|
(below, (share * 255.).round().clamp(0., 255.) as u32)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many of 255 parts of a masked radius blur's interpolation the `level` takes for the map luminance `code`, as [`masked_radius_blur_interpolation`] gives them.
|
||||||
|
pub fn masked_radius_blur_weight(level: usize, code: u8, levels: &[f64]) -> u32 {
|
||||||
|
let (below, above_parts) = masked_radius_blur_interpolation(code, levels);
|
||||||
|
match level {
|
||||||
|
_ if level == below => 255 - above_parts,
|
||||||
|
_ if level == below + 1 => above_parts,
|
||||||
|
_ => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn luminance_modes_weigh_pure_red_green_and_blue_by_their_own_weights() {
|
||||||
|
let level = |channels: [f32; 4], mode| (mask_coverage(channels, mode) * 255.).round() as u8;
|
||||||
|
let primaries = [[1., 0., 0., 1.], [0., 1., 0., 1.], [0., 0., 1., 1.]];
|
||||||
|
|
||||||
|
assert_eq!(primaries.map(|primary| level(primary, MaskMode::Luminance)), [77, 150, 28]);
|
||||||
|
assert_eq!(primaries.map(|primary| level(primary, MaskMode::LuminanceSvg)), [54, 182, 18]);
|
||||||
|
assert_eq!(primaries.map(|primary| level(primary, MaskMode::Alpha)), [255; 3]);
|
||||||
|
|
||||||
|
// Premultiplied channels count the color by its alpha
|
||||||
|
assert_eq!(level([0., 0.5, 0., 0.5], MaskMode::Luminance), 75);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,583 @@
|
|||||||
|
//! A warp: a bicubic Bezier patch over a box, bent into one of the preset styles, which carries each point of the box's unit square to where it lands.
|
||||||
|
//! It's geometry alone, so warping the pixels of a graphic and warping vector geometry can share it.
|
||||||
|
|
||||||
|
use core_types::graphene_hash::CacheHash;
|
||||||
|
use dyn_any::DynAny;
|
||||||
|
use glam::{DAffine2, DVec2, Vec2Swizzles};
|
||||||
|
|
||||||
|
/// The preset shape a warp bends its box into.
|
||||||
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||||
|
#[widget(Dropdown)]
|
||||||
|
pub enum WarpStyle {
|
||||||
|
/// Bends the content into a band of concentric arcs, like a rainbow, its bottom edge spanning its width.
|
||||||
|
#[default]
|
||||||
|
Arc,
|
||||||
|
/// Bulges the bottom edge down into an arc, keeping the top edge straight.
|
||||||
|
ArcLower,
|
||||||
|
/// Bulges the top edge up into an arc, keeping the bottom edge straight.
|
||||||
|
ArcUpper,
|
||||||
|
#[menu_separator]
|
||||||
|
/// Bends the content up into an arch, its top and bottom edges following the same arc.
|
||||||
|
Arch,
|
||||||
|
/// Bulges the top edge up and the bottom edge down into arcs.
|
||||||
|
Bulge,
|
||||||
|
/// Bends the bottom edge down into an arc, fanning out from the straight top edge like a seashell.
|
||||||
|
ShellLower,
|
||||||
|
/// Bends the top edge up into an arc, fanning out from the straight bottom edge like a seashell.
|
||||||
|
ShellUpper,
|
||||||
|
#[menu_separator]
|
||||||
|
/// Waves the content like a flag, its top and bottom edges rising and falling together.
|
||||||
|
Flag,
|
||||||
|
/// Waves the content's middle up and down between its straight edges.
|
||||||
|
Wave,
|
||||||
|
/// Swells the content's left side and pinches its right, like a fish.
|
||||||
|
Fish,
|
||||||
|
/// Lowers the content's left side along a smooth curve, so it rises toward its right.
|
||||||
|
Rise,
|
||||||
|
#[menu_separator]
|
||||||
|
/// Magnifies the content's middle as if seen through a wide lens.
|
||||||
|
Fisheye,
|
||||||
|
/// Puffs the content's edges out, like a pillow.
|
||||||
|
Inflate,
|
||||||
|
/// Squeezes the content's sides in and stretches its top and bottom out.
|
||||||
|
Squeeze,
|
||||||
|
/// Twists the content's middle around, clockwise for a positive bend.
|
||||||
|
Twist,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, a style's bend and distortions: what bends the box, from which the [`WarpMesh`] follows.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct Warp {
|
||||||
|
pub style: WarpStyle,
|
||||||
|
/// How strongly the style bends the box, from -1 to 1, the other way when negative.
|
||||||
|
pub bend: f64,
|
||||||
|
/// How much taller the right side grows than the left (the left than the right when negative), as if turned away in perspective, from -1 to 1.
|
||||||
|
pub horizontal_distortion: f64,
|
||||||
|
/// How much wider the bottom grows than the top (the top than the bottom when negative), as if tipped away in perspective, from -1 to 1.
|
||||||
|
pub vertical_distortion: f64,
|
||||||
|
/// Whether the style is built mirrored across the diagonal, bending the left and right edges instead of the top and bottom.
|
||||||
|
pub vertical: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Warp {
|
||||||
|
/// For PSD interop, the control points that bend a box `size` across, as fractions of that size.
|
||||||
|
/// The arcs are true circles in the box's own units, so the mesh depends on its aspect ratio. A box without area is left as it is.
|
||||||
|
pub fn mesh(&self, size: DVec2) -> WarpMesh {
|
||||||
|
use WarpStyle::*;
|
||||||
|
if !(size.cmpgt(DVec2::ZERO).all() && size.is_finite()) {
|
||||||
|
return WarpMesh::identity();
|
||||||
|
}
|
||||||
|
|
||||||
|
let bend = self.bend.clamp(-1., 1.);
|
||||||
|
let (horizontal, vertical) = (self.horizontal_distortion.clamp(-1., 1.), self.vertical_distortion.clamp(-1., 1.));
|
||||||
|
|
||||||
|
// Some styles take their distortions in closed form
|
||||||
|
match self.style {
|
||||||
|
Inflate => return WarpMesh(centered_mesh(DVec2::splat(bend), horizontal, vertical)),
|
||||||
|
Squeeze if self.vertical => return WarpMesh(centered_mesh(DVec2::new(bend, -bend), horizontal, vertical)),
|
||||||
|
Squeeze => return WarpMesh(centered_mesh(DVec2::new(-bend, bend), horizontal, vertical)),
|
||||||
|
// Built vertically, a wave moves its columns' inner points across, each by its row's width
|
||||||
|
Wave if self.vertical => {
|
||||||
|
let mut mesh = centered_mesh(DVec2::ZERO, horizontal, vertical);
|
||||||
|
for (row, wave) in [(1, 1.), (2, -1.)] {
|
||||||
|
for column in [1, 2] {
|
||||||
|
mesh[row][column].x += 4. / 3. * bend * wave * (1. + vertical * lattice_position(row));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return WarpMesh(mesh);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A vertical warp is the style built on the box with its axes swapped, then swapped back, except that a twist keeps its turn
|
||||||
|
let preset = match self.vertical && self.style != Twist {
|
||||||
|
true => transposed(preset_mesh(self.style, bend, size.yx())),
|
||||||
|
false => preset_mesh(self.style, bend, size),
|
||||||
|
};
|
||||||
|
|
||||||
|
// The distortions taper the rows, then the columns, in the box's own axes
|
||||||
|
let ruled = matches!(self.style, Arc | ArcLower | ArcUpper | Arch | Bulge | Flag | Wave | Fish | Rise);
|
||||||
|
let rows_tapered = tapered_rows(preset, vertical, ruled && !self.vertical);
|
||||||
|
WarpMesh(transposed(tapered_rows(transposed(rows_tapered), horizontal, ruled && self.vertical)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A bicubic Bezier patch as its 4x4 control points, in rows down its v direction, each row across its u direction.
|
||||||
|
/// Past the unit square, the patch continues each side along its tangent there, so it covers the whole plane smoothly.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct WarpMesh(pub [[DVec2; 4]; 4]);
|
||||||
|
|
||||||
|
impl WarpMesh {
|
||||||
|
/// The evenly spaced mesh leaving every point of the unit square where it is.
|
||||||
|
pub fn identity() -> Self {
|
||||||
|
Self(std::array::from_fn(|row| std::array::from_fn(|column| DVec2::new(column as f64, row as f64) / 3.)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the patch carries the point `uv`.
|
||||||
|
pub fn point(&self, uv: DVec2) -> DVec2 {
|
||||||
|
self.point_and_tangents(uv)[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the patch carries the point `uv`, and how fast that moves along u and along v there. O(1).
|
||||||
|
pub fn point_and_tangents(&self, uv: DVec2) -> [DVec2; 3] {
|
||||||
|
let (across, across_slopes) = extended_bases(uv.x);
|
||||||
|
let (down, down_slopes) = extended_bases(uv.y);
|
||||||
|
|
||||||
|
let mut result = [DVec2::ZERO; 3];
|
||||||
|
for (row, points) in self.0.iter().enumerate() {
|
||||||
|
for (column, &point) in points.iter().enumerate() {
|
||||||
|
result[0] += point * (down[row] * across[column]);
|
||||||
|
result[1] += point * (down[row] * across_slopes[column]);
|
||||||
|
result[2] += point * (down_slopes[row] * across[column]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The control points of the patch over the rectangle from `start` to `end` in (u, v), which restricts the patch to it when inside the unit square.
|
||||||
|
/// The rectangle must lie within one of the nine regions the unit square's sides divide the plane into, past which the patch is a different polynomial.
|
||||||
|
pub fn over(&self, start: DVec2, end: DVec2) -> Self {
|
||||||
|
let (across, down) = (bezier_bases_over(start.x, end.x), bezier_bases_over(start.y, end.y));
|
||||||
|
Self(std::array::from_fn(|row| {
|
||||||
|
std::array::from_fn(|column| {
|
||||||
|
let mut point = DVec2::ZERO;
|
||||||
|
for (mesh_row, points) in self.0.iter().enumerate() {
|
||||||
|
for (mesh_column, &mesh_point) in points.iter().enumerate() {
|
||||||
|
point += mesh_point * (down[mesh_row][row] * across[mesh_column][column]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
point
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The mesh with each control point carried through `transform`, which carries the patch along since Bezier patches keep their shape under affine maps.
|
||||||
|
pub fn transformed(&self, transform: DAffine2) -> Self {
|
||||||
|
Self(self.0.map(|row| row.map(|point| transform.transform_point2(point))))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bounding box of the control points, which holds the whole patch over the unit square.
|
||||||
|
pub fn hull_bounds(&self) -> [DVec2; 2] {
|
||||||
|
let points = self.0.iter().flatten();
|
||||||
|
[
|
||||||
|
points.clone().fold(DVec2::INFINITY, |min, &point| min.min(point)),
|
||||||
|
points.fold(DVec2::NEG_INFINITY, |max, &point| max.max(point)),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The longest the patch's u and v tangents can be over the unit square, which bounds how far a step along each moves.
|
||||||
|
pub fn tangent_bounds(&self) -> DVec2 {
|
||||||
|
let mut longest = DVec2::ZERO;
|
||||||
|
for row in 0..4 {
|
||||||
|
for step in 0..3 {
|
||||||
|
longest.x = longest.x.max((self.0[row][step + 1] - self.0[row][step]).length());
|
||||||
|
longest.y = longest.y.max((self.0[step + 1][row] - self.0[step][row]).length());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
longest * 3.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The four cubic Bernstein polynomials at `t` and their slopes, continuing past 0 and 1 along their tangents there.
|
||||||
|
fn extended_bases(t: f64) -> ([f64; 4], [f64; 4]) {
|
||||||
|
if t < 0. {
|
||||||
|
return ([1. - 3. * t, 3. * t, 0., 0.], [-3., 3., 0., 0.]);
|
||||||
|
}
|
||||||
|
if t > 1. {
|
||||||
|
let past = t - 1.;
|
||||||
|
return ([0., 0., -3. * past, 1. + 3. * past], [0., 0., -3., 3.]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rest = 1. - t;
|
||||||
|
(
|
||||||
|
[rest * rest * rest, 3. * t * rest * rest, 3. * t * t * rest, t * t * t],
|
||||||
|
[-3. * rest * rest, 3. * rest * rest - 6. * t * rest, 6. * t * rest - 3. * t * t, 3. * t * t],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each of the four extended Bernstein polynomials (see [`extended_bases`]) over the interval from `start` to `end` as the coefficients of the Bernstein polynomials of that interval.
|
||||||
|
/// Within one of the intervals that 0 and 1 divide the line into, each is a cubic, which its values and slopes at the interval's ends determine.
|
||||||
|
fn bezier_bases_over(start: f64, end: f64) -> [[f64; 4]; 4] {
|
||||||
|
let ((start_values, start_slopes), (end_values, end_slopes)) = (extended_bases(start), extended_bases(end));
|
||||||
|
let third = (end - start) / 3.;
|
||||||
|
std::array::from_fn(|basis| {
|
||||||
|
[
|
||||||
|
start_values[basis],
|
||||||
|
start_values[basis] + third * start_slopes[basis],
|
||||||
|
end_values[basis] - third * end_slopes[basis],
|
||||||
|
end_values[basis],
|
||||||
|
]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The four control points, in the units of `width`, of a circular arc with its chord from (0, `y`) to (`width`, `y`), turning through `half_angle` (in radians) each side of its middle,
|
||||||
|
/// bulging up toward -y when `up`, and grown out from its center by `radius_offset`. Each end handle is 4/3 tan(half angle / 2) of the radius long, so the curve's middle lies on the circle.
|
||||||
|
fn arc_row(width: f64, y: f64, half_angle: f64, up: bool, radius_offset: f64) -> [DVec2; 4] {
|
||||||
|
// Measured from the chord's ends, without the radius itself, which grows without bound as the arc flattens
|
||||||
|
let away_from_center = if up { -1. } else { 1. };
|
||||||
|
let (sin, cos) = half_angle.sin_cos();
|
||||||
|
let handle = width / (3. * (half_angle / 2.).cos().powi(2)) + radius_offset * 4. / 3. * (half_angle / 2.).tan();
|
||||||
|
|
||||||
|
let start = DVec2::new(0., y) + DVec2::new(-sin, away_from_center * cos) * radius_offset;
|
||||||
|
let end = DVec2::new(width, y) + DVec2::new(sin, away_from_center * cos) * radius_offset;
|
||||||
|
[
|
||||||
|
start,
|
||||||
|
start + DVec2::new(cos, away_from_center * sin) * handle,
|
||||||
|
end - DVec2::new(cos, -away_from_center * sin) * handle,
|
||||||
|
end,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A row of control points in the units of a box `size` across, as fractions of that size.
|
||||||
|
fn normalized(row: [DVec2; 4], size: DVec2) -> [DVec2; 4] {
|
||||||
|
row.map(|point| point / size)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rows from `top` to `bottom`, each control point a straight line between them.
|
||||||
|
fn rows_between(top: [DVec2; 4], bottom: [DVec2; 4]) -> [[DVec2; 4]; 4] {
|
||||||
|
std::array::from_fn(|row| std::array::from_fn(|column| top[column].lerp(bottom[column], row as f64 / 3.)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The mesh mirrored top to bottom.
|
||||||
|
fn flipped_vertically(mesh: [[DVec2; 4]; 4]) -> [[DVec2; 4]; 4] {
|
||||||
|
std::array::from_fn(|row| mesh[3 - row].map(|point| DVec2::new(point.x, 1. - point.y)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, the concentric arcs of an Arc of `bend` on a box `size` across: about a center below for a positive bend, the bottom row's chord spanning the width and each row above a third of the height farther out.
|
||||||
|
fn arc_mesh(bend: f64, size: DVec2) -> [[DVec2; 4]; 4] {
|
||||||
|
if bend < 0. {
|
||||||
|
return flipped_vertically(arc_mesh(-bend, size));
|
||||||
|
}
|
||||||
|
let half_angle = bend * std::f64::consts::FRAC_PI_2;
|
||||||
|
std::array::from_fn(|row| normalized(arc_row(size.x, size.y, half_angle, true, size.y * (3 - row) as f64 / 3.), size))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, the top or bottom edge bent into an arc through its ends by `bend`, bulging out of the box for a positive bend.
|
||||||
|
fn edge_arc(bend: f64, size: DVec2, top: bool) -> [DVec2; 4] {
|
||||||
|
let half_angle = bend.abs() * std::f64::consts::FRAC_PI_2;
|
||||||
|
let up = if top { bend > 0. } else { bend < 0. };
|
||||||
|
normalized(arc_row(size.x, if top { 0. } else { size.y }, half_angle, up, 0.), size)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, the control points of a style's `bend` (from -1 to 1) on a box `size` across, as fractions of that size.
|
||||||
|
fn preset_mesh(style: WarpStyle, bend: f64, size: DVec2) -> [[DVec2; 4]; 4] {
|
||||||
|
let mut mesh = WarpMesh::identity().0;
|
||||||
|
let [identity_top, .., identity_bottom] = mesh;
|
||||||
|
|
||||||
|
// Moves a control point by a fraction of the box
|
||||||
|
let mut nudge = |row: usize, column: usize, by: DVec2| mesh[row][column] += by;
|
||||||
|
|
||||||
|
match style {
|
||||||
|
WarpStyle::Arc => arc_mesh(bend, size),
|
||||||
|
WarpStyle::ArcLower => rows_between(identity_top, edge_arc(bend, size, false)),
|
||||||
|
WarpStyle::ArcUpper => rows_between(edge_arc(bend, size, true), identity_bottom),
|
||||||
|
WarpStyle::Arch => {
|
||||||
|
let top = edge_arc(bend, size, true);
|
||||||
|
std::array::from_fn(|row| top.map(|point| point + DVec2::new(0., row as f64 / 3.)))
|
||||||
|
}
|
||||||
|
WarpStyle::Bulge => rows_between(edge_arc(bend, size, true), edge_arc(bend, size, false)),
|
||||||
|
// A shell takes the outer arc and its side points from the arc bent the other way, keeping the rest
|
||||||
|
WarpStyle::ShellLower => {
|
||||||
|
let arc = arc_mesh(-bend, size);
|
||||||
|
mesh[3] = arc[3];
|
||||||
|
mesh[2][0] = arc[2][0];
|
||||||
|
mesh[2][3] = arc[2][3];
|
||||||
|
mesh
|
||||||
|
}
|
||||||
|
WarpStyle::ShellUpper => {
|
||||||
|
let arc = arc_mesh(bend, size);
|
||||||
|
mesh[0] = arc[0];
|
||||||
|
mesh[1][0] = arc[1][0];
|
||||||
|
mesh[1][3] = arc[1][3];
|
||||||
|
mesh
|
||||||
|
}
|
||||||
|
WarpStyle::Flag => {
|
||||||
|
for row in 0..4 {
|
||||||
|
nudge(row, 1, DVec2::new(0., 2. * bend));
|
||||||
|
nudge(row, 2, DVec2::new(0., -2. * bend));
|
||||||
|
}
|
||||||
|
mesh
|
||||||
|
}
|
||||||
|
WarpStyle::Wave => {
|
||||||
|
for row in [1, 2] {
|
||||||
|
nudge(row, 1, DVec2::new(0., 4. / 3. * bend));
|
||||||
|
nudge(row, 2, DVec2::new(0., -4. / 3. * bend));
|
||||||
|
}
|
||||||
|
mesh
|
||||||
|
}
|
||||||
|
WarpStyle::Fish => {
|
||||||
|
for row in 0..4 {
|
||||||
|
let shift = 2. * bend * (2. * row as f64 / 3. - 1.);
|
||||||
|
nudge(row, 1, DVec2::new(0., shift));
|
||||||
|
nudge(row, 2, DVec2::new(0., -shift));
|
||||||
|
}
|
||||||
|
mesh
|
||||||
|
}
|
||||||
|
WarpStyle::Rise => {
|
||||||
|
for row in 0..4 {
|
||||||
|
nudge(row, 0, DVec2::new(0., 2. * bend));
|
||||||
|
nudge(row, 1, DVec2::new(0., 2. * bend));
|
||||||
|
}
|
||||||
|
mesh
|
||||||
|
}
|
||||||
|
// The inner points move out from the middle
|
||||||
|
WarpStyle::Fisheye => {
|
||||||
|
for (row, column) in [(1, 1), (1, 2), (2, 1), (2, 2)] {
|
||||||
|
let outward = DVec2::new(if column == 1 { -1. } else { 1. }, if row == 1 { -1. } else { 1. });
|
||||||
|
nudge(row, column, outward * 2. * bend / 3.);
|
||||||
|
}
|
||||||
|
mesh
|
||||||
|
}
|
||||||
|
// The sides' middle points move out by a third of the bend (in for a squeeze's left and right)
|
||||||
|
WarpStyle::Inflate => centered_mesh(DVec2::splat(bend), 0., 0.),
|
||||||
|
WarpStyle::Squeeze => centered_mesh(DVec2::new(-bend, bend), 0., 0.),
|
||||||
|
// Each inner point moves the bend's size of the box toward the next inner point around, clockwise for a positive bend
|
||||||
|
WarpStyle::Twist => {
|
||||||
|
let amount = bend.abs();
|
||||||
|
let moves = match bend >= 0. {
|
||||||
|
true => [(1, 1, DVec2::X), (1, 2, DVec2::Y), (2, 2, -DVec2::X), (2, 1, -DVec2::Y)],
|
||||||
|
false => [(1, 1, DVec2::Y), (2, 1, DVec2::X), (2, 2, -DVec2::Y), (1, 2, -DVec2::X)],
|
||||||
|
};
|
||||||
|
for (row, column, direction) in moves {
|
||||||
|
nudge(row, column, direction * amount);
|
||||||
|
}
|
||||||
|
mesh
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the control points of row or column `index` lie in the evenly spaced mesh, from -1 at the first to 1 at the last.
|
||||||
|
fn lattice_position(index: usize) -> f64 {
|
||||||
|
2. * index as f64 / 3. - 1.
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The mesh with its rows and columns swapped, and each point's coordinates too.
|
||||||
|
fn transposed(mesh: [[DVec2; 4]; 4]) -> [[DVec2; 4]; 4] {
|
||||||
|
std::array::from_fn(|row| std::array::from_fn(|column| mesh[column][row].yx()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, the mesh with each row scaled about the middle of its end points by `1 + distortion` times its [`lattice_position`], so the top shrinks and the bottom grows for a positive distortion.
|
||||||
|
/// A `ruled` style scales only its outer rows, each inner point moving as its column's end points do, in proportion to how near it lies to each.
|
||||||
|
fn tapered_rows(mesh: [[DVec2; 4]; 4], distortion: f64, ruled: bool) -> [[DVec2; 4]; 4] {
|
||||||
|
let scaled = |row: usize| {
|
||||||
|
let middle = (mesh[row][0] + mesh[row][3]) / 2.;
|
||||||
|
mesh[row].map(|point| middle + (point - middle) * (1. + distortion * lattice_position(row)))
|
||||||
|
};
|
||||||
|
if !ruled {
|
||||||
|
return std::array::from_fn(scaled);
|
||||||
|
}
|
||||||
|
|
||||||
|
let (top, bottom) = (scaled(0), scaled(3));
|
||||||
|
std::array::from_fn(|row| {
|
||||||
|
let toward_bottom = row as f64 / 3.;
|
||||||
|
std::array::from_fn(|column| mesh[row][column] + (top[column] - mesh[0][column]) * (1. - toward_bottom) + (bottom[column] - mesh[3][column]) * toward_bottom)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, the mesh of an inflate or squeeze with `bends` across and down, in closed form with its `horizontal` and `vertical` distortions (each from -1 to 1).
|
||||||
|
/// Each point lies out from the middle of the box by its column's share of its row's width and its row's share of its column's height, which the bends widen at the middle rows and columns.
|
||||||
|
fn centered_mesh(bends: DVec2, horizontal: f64, vertical: f64) -> [[DVec2; 4]; 4] {
|
||||||
|
let side = |index: usize| if index < 2 { -1. } else { 1. };
|
||||||
|
let middle = |index: usize| if index == 1 || index == 2 { 1. } else { 0. };
|
||||||
|
|
||||||
|
std::array::from_fn(|row| {
|
||||||
|
std::array::from_fn(|column| {
|
||||||
|
let width = 1. + (1. + horizontal * side(column)) * (vertical * lattice_position(row) + 2. * bends.x / 3. * middle(row));
|
||||||
|
let height = 1. + horizontal * lattice_position(column) + 2. * bends.y / 3. * middle(column) * (1. + vertical * side(row));
|
||||||
|
DVec2::splat(0.5) + DVec2::new(lattice_position(column) * width, lattice_position(row) * height) / 2.
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn every_style() -> impl Iterator<Item = WarpStyle> {
|
||||||
|
use WarpStyle::*;
|
||||||
|
[Arc, ArcLower, ArcUpper, Arch, Bulge, ShellLower, ShellUpper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist].into_iter()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn warp(style: WarpStyle, bend: f64) -> Warp {
|
||||||
|
Warp {
|
||||||
|
style,
|
||||||
|
bend,
|
||||||
|
horizontal_distortion: 0.,
|
||||||
|
vertical_distortion: 0.,
|
||||||
|
vertical: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn warps_without_bend_or_distortion_change_nothing() {
|
||||||
|
for style in every_style() {
|
||||||
|
for vertical in [false, true] {
|
||||||
|
let mesh = Warp { vertical, ..warp(style, 0.) }.mesh(DVec2::new(300., 120.));
|
||||||
|
for (row, points) in mesh.0.iter().enumerate() {
|
||||||
|
for (column, point) in points.iter().enumerate() {
|
||||||
|
let expected = DVec2::new(column as f64, row as f64) / 3.;
|
||||||
|
assert!((*point - expected).length() < 1e-12, "{style:?} moves control point ({column}, {row}) to {point}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nor does a box without area, however far bent
|
||||||
|
for size in [DVec2::new(0., 100.), DVec2::new(100., -5.), DVec2::new(f64::INFINITY, 100.)] {
|
||||||
|
assert_eq!(warp(WarpStyle::Arc, 0.5).mesh(size), WarpMesh::identity(), "{size}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arcs_bend_into_concentric_circles() {
|
||||||
|
// For PSD interop, an Arc of 50% on a box 200 by 100 turns its rows through 45 degrees each side about a center below, the bottom row spanning the width
|
||||||
|
let size = DVec2::new(200., 100.);
|
||||||
|
let mesh = warp(WarpStyle::Arc, 0.5).mesh(size);
|
||||||
|
let at = |u: f64, v: f64| mesh.point(DVec2::new(u, v)) * size;
|
||||||
|
|
||||||
|
assert!((at(0., 1.) - DVec2::new(0., 100.)).length() < 1e-9);
|
||||||
|
assert!((at(0., 0.) - DVec2::new(-100. * 0.5_f64.sqrt(), 100. - 100. * 0.5_f64.sqrt())).length() < 1e-9);
|
||||||
|
let center = DVec2::new(100., 200.);
|
||||||
|
let inner_radius = 100. * 2_f64.sqrt();
|
||||||
|
assert!((at(0.5, 1.) - DVec2::new(100., 200. - inner_radius)).length() < 1e-9, "{}", at(0.5, 1.));
|
||||||
|
assert!((at(0.5, 0.) - DVec2::new(100., 200. - inner_radius - 100.)).length() < 1e-9);
|
||||||
|
|
||||||
|
// Between the ends and the middle, the cubics stray from their circles by under a thousandth of the radius
|
||||||
|
for t in [0.1, 0.25, 0.4, 0.7] {
|
||||||
|
let distance = (at(t, 1.) - center).length();
|
||||||
|
assert!((distance - inner_radius).abs() < 1e-3 * inner_radius, "{t} lies {distance} from the center");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bent the other way, the arc mirrors top to bottom
|
||||||
|
let flipped = warp(WarpStyle::Arc, -0.5).mesh(size);
|
||||||
|
let mirrored = flipped.point(DVec2::new(0.3, 0.)) * size;
|
||||||
|
assert!((mirrored - DVec2::new(at(0.3, 1.).x, 100. - at(0.3, 1.).y)).length() < 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn meshes_carry_points_where_psd_interop_measures_them() {
|
||||||
|
use WarpStyle::*;
|
||||||
|
|
||||||
|
// For PSD interop, where these points (u, v) land from the box's corner, measured on boxes warped by each case's style, bend, distortions, and size
|
||||||
|
let points = [(0.125, 0.875), (0.5, 0.5), (0.875, 0.25)];
|
||||||
|
let built_across = [
|
||||||
|
(Arc, 46., -46., 63., (137., 291.), [(-18.2693, 273.7009), (68.5, 142.5221), (147.3426, 129.4578)]),
|
||||||
|
(ArcLower, -10., 40., -17., (137., 291.), [(21.154, 220.248), (68.5, 143.2627), (125.9035, 50.4845)]),
|
||||||
|
(ArcUpper, 72., 83., -82., (137., 291.), [(21.7839, 179.6745), (68.5, 105.941), (164.3882, -0.2931)]),
|
||||||
|
(Arch, 60., -12., 21., (137., 291.), [(4.7147, 246.6993), (68.5, 110.5975), (117.7196, 65.5829)]),
|
||||||
|
(Bulge, -5., 92., -7., (137., 291.), [(17.4618, 178.7312), (68.5, 145.6884), (123.2537, 23.3591)]),
|
||||||
|
(ShellLower, -11., -32., 81., (250., 250.), [(-47.7217, 235.6717), (124.4881, 122.5727), (193.4388, 77.0996)]),
|
||||||
|
(ShellUpper, 28., 22., 79., (250., 250.), [(-15.6586, 205.5381), (125.4301, 129.278), (198.9814, 66.0233)]),
|
||||||
|
(Flag, -34., 96., -71., (400., 120.), [(57.455, 58.6496), (200., 60.), (451.53, 38.6517)]),
|
||||||
|
(Wave, -68., 64., -81., (400., 120.), [(86.045, 77.1135), (200., 73.056), (447.47, 34.9449)]),
|
||||||
|
(Fish, -74., 37., 83., (300., 200.), [(-8.0592, 48.0784), (150., 100.), (199.4978, 54.1741)]),
|
||||||
|
(Rise, 21., -41., 3., (400., 120.), [(45.3181, 167.7718), (200., 85.2), (348.6213, 41.6151)]),
|
||||||
|
(Fisheye, -41., 9., 9., (400., 120.), [(49.4018, 99.2699), (198.155, 59.4465), (327.1722, 30.8844)]),
|
||||||
|
(Inflate, -44., -1., -25., (137., 291.), [(31.8545, 247.6754), (68.5753, 149.5012), (117.8414, 82.486)]),
|
||||||
|
(Squeeze, -100., -23., -76., (300., 200.), [(86.4829, 184.5195), (141.375, 119.), (327.0879, 79.9531)]),
|
||||||
|
(Twist, -50., 24., 26., (300., 200.), [(32.6476, 161.1075), (150.2812, 95.3125), (227.5034, 37.7156)]),
|
||||||
|
];
|
||||||
|
let built_vertically = [
|
||||||
|
(Arc, -62., 57., -4., (400., 120.), [(51.7769, 143.6624), (281.6909, 62.3381), (414.7634, -239.3584)]),
|
||||||
|
(ArcLower, -34., 27., 97., (250., 250.), [(-13.9043, 199.8505), (103.2855, 125.2042), (130.5268, 48.473)]),
|
||||||
|
(ArcUpper, 9., -83., -59., (200., 300.), [(88.0162, 332.7032), (90.2822, 149.9693), (170.7866, 121.653)]),
|
||||||
|
(Arch, -85., -53., 82., (137., 291.), [(33.3319, 318.7345), (183.2029, 145.5), (165.5277, 91.453)]),
|
||||||
|
(Bulge, 1., -29., 26., (200., 300.), [(4.1491, 286.9706), (99.6583, 150.), (169.4088, 91.3111)]),
|
||||||
|
(ShellLower, 59., 77., 23., (137., 291.), [(14.9208, 183.6004), (89.0674, 140.4151), (185.5401, -57.6605)]),
|
||||||
|
(ShellUpper, -48., -13., 69., (400., 120.), [(-40.7272, 140.8086), (200.408, 64.7486), (305.3843, 32.0372)]),
|
||||||
|
(Flag, 12., 57., -90., (200., 300.), [(30.3873, 214.4063), (100., 150.), (253.6712, 42.9375)]),
|
||||||
|
(Wave, 47., 80., 36., (200., 300.), [(9.8851, 195.), (91.54, 150.), (159.0405, 30.)]),
|
||||||
|
(Fish, -65., 80., 86., (137., 291.), [(22.3632, 189.15), (99.1332, 145.5), (41.0932, 29.1)]),
|
||||||
|
(Rise, 26., -84., 45., (400., 120.), [(-108.2769, 133.35), (304., 60.), (484.505, 48.9)]),
|
||||||
|
(Fisheye, -59., 85., 44., (300., 200.), [(36.7591, 121.2068), (131.1938, 93.51), (197.0264, 24.3454)]),
|
||||||
|
(Inflate, -25., -87., -38., (200., 300.), [(73.5647, 332.1892), (105.4375, 153.5625), (175.6768, 129.9873)]),
|
||||||
|
(Squeeze, 92., -36., 24., (200., 300.), [(-14.3164, 264.5742), (91.72, 141.72), (185.5469, 105.8156)]),
|
||||||
|
(Twist, -69., 35., 4., (300., 200.), [(50.1306, 154.89), (143.9841, 94.9544), (232.9504, 32.6515)]),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (vertical, cases) in [(false, built_across), (true, built_vertically)] {
|
||||||
|
for (style, bend, horizontal_distortion, vertical_distortion, (width, height), landings) in cases {
|
||||||
|
let warp = Warp {
|
||||||
|
style,
|
||||||
|
bend: bend / 100.,
|
||||||
|
horizontal_distortion: horizontal_distortion / 100.,
|
||||||
|
vertical_distortion: vertical_distortion / 100.,
|
||||||
|
vertical,
|
||||||
|
};
|
||||||
|
let size = DVec2::new(width, height);
|
||||||
|
let mesh = warp.mesh(size);
|
||||||
|
for ((u, v), (x, y)) in points.into_iter().zip(landings) {
|
||||||
|
let landed = mesh.point(DVec2::new(u, v)) * size;
|
||||||
|
assert!(landed.distance(DVec2::new(x, y)) < 1e-3, "{warp:?} carries ({u}, {v}) to {landed}, not ({x}, {y})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vertical_warps_bend_the_sides() {
|
||||||
|
// Built vertically, an Arch bends its columns across, leaving the top and bottom edges' heights alone at the corners
|
||||||
|
let mesh = Warp {
|
||||||
|
vertical: true,
|
||||||
|
..warp(WarpStyle::Arch, 0.4)
|
||||||
|
}
|
||||||
|
.mesh(DVec2::new(100., 300.));
|
||||||
|
assert!(mesh.point(DVec2::new(0., 0.5)).x < -0.05, "the left edge bulges left");
|
||||||
|
assert!((mesh.point(DVec2::new(0., 0.)) - DVec2::ZERO).length() < 1e-9);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn patches_continue_each_side_along_its_tangent() {
|
||||||
|
let mesh = warp(WarpStyle::Flag, 0.6).mesh(DVec2::new(200., 100.));
|
||||||
|
|
||||||
|
// Past the right side, each point moves on in a straight line, at the speed it moved there
|
||||||
|
let [edge, across, _] = mesh.point_and_tangents(DVec2::new(1., 0.3));
|
||||||
|
for past in [0.1, 0.5, 2.] {
|
||||||
|
let point = mesh.point(DVec2::new(1. + past, 0.3));
|
||||||
|
assert!((point - (edge + across * past)).length() < 1e-12);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The tangents agree at the side, from either way
|
||||||
|
let inside = mesh.point_and_tangents(DVec2::new(1. - 1e-9, 0.3));
|
||||||
|
let outside = mesh.point_and_tangents(DVec2::new(1. + 1e-9, 0.3));
|
||||||
|
for (inside, outside) in inside.iter().zip(outside) {
|
||||||
|
assert!((*inside - outside).length() < 1e-6);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn meshes_over_part_of_the_plane_trace_the_same_patch() {
|
||||||
|
let mesh = warp(WarpStyle::Twist, 0.7).mesh(DVec2::new(150., 100.));
|
||||||
|
|
||||||
|
// Within the unit square, past its side, and past its corner
|
||||||
|
for (start, end) in [
|
||||||
|
(DVec2::new(0.2, 0.1), DVec2::new(0.6, 0.9)),
|
||||||
|
(DVec2::new(1., 0.3), DVec2::new(1.8, 0.5)),
|
||||||
|
(DVec2::new(-0.7, -0.4), DVec2::new(0., -0.1)),
|
||||||
|
] {
|
||||||
|
let part = mesh.over(start, end);
|
||||||
|
for st in [DVec2::new(0.3, 0.7), DVec2::new(0., 1.), DVec2::new(0.9, 0.2)] {
|
||||||
|
let expected = mesh.point(start + (end - start) * st);
|
||||||
|
assert!((part.point(st) - expected).length() < 1e-12, "over {start} to {end} at {st}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A part reaching the unit square's side continues past it as the whole patch does
|
||||||
|
let part = mesh.over(DVec2::new(0.5, 0.), DVec2::new(1., 1.));
|
||||||
|
assert!((part.point(DVec2::new(1.4, 0.5)) - mesh.point(DVec2::new(1.2, 0.5))).length() < 1e-12);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_control_points_hold_the_patch() {
|
||||||
|
for style in every_style() {
|
||||||
|
let mesh = warp(style, -0.8).mesh(DVec2::new(240., 90.));
|
||||||
|
let [min, max] = mesh.hull_bounds();
|
||||||
|
for index in 0..=100 {
|
||||||
|
let point = mesh.point(DVec2::new((index % 11) as f64 / 10., (index / 11) as f64 / 9.).min(DVec2::ONE));
|
||||||
|
assert!(point.cmpge(min - 1e-12).all() && point.cmple(max + 1e-12).all(), "{style:?} reaches {point} past {min} to {max}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,5 +25,6 @@ vector-types = { workspace = true }
|
|||||||
# Workspace dependencies
|
# Workspace dependencies
|
||||||
fastnoise-lite = { workspace = true }
|
fastnoise-lite = { workspace = true }
|
||||||
glam = { workspace = true }
|
glam = { workspace = true }
|
||||||
|
half = { workspace = true }
|
||||||
log = { workspace = true }
|
log = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
@@ -29,11 +29,12 @@ pub enum StepKind {
|
|||||||
PhotoFilter,
|
PhotoFilter,
|
||||||
ColorLookup,
|
ColorLookup,
|
||||||
ColorOverlay,
|
ColorOverlay,
|
||||||
|
Solarize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StepKind {
|
impl StepKind {
|
||||||
/// Every kind, in the order of their codes.
|
/// Every kind, in the order of their codes.
|
||||||
pub const ALL: [StepKind; 20] = [
|
pub const ALL: [StepKind; 21] = [
|
||||||
StepKind::Desaturate,
|
StepKind::Desaturate,
|
||||||
StepKind::GammaCorrection,
|
StepKind::GammaCorrection,
|
||||||
StepKind::MakeOpaque,
|
StepKind::MakeOpaque,
|
||||||
@@ -54,6 +55,7 @@ impl StepKind {
|
|||||||
StepKind::PhotoFilter,
|
StepKind::PhotoFilter,
|
||||||
StepKind::ColorLookup,
|
StepKind::ColorLookup,
|
||||||
StepKind::ColorOverlay,
|
StepKind::ColorOverlay,
|
||||||
|
StepKind::Solarize,
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
||||||
@@ -219,7 +221,7 @@ mod tests {
|
|||||||
let run = [
|
let run = [
|
||||||
Adjustment::Desaturate { method: Default::default() },
|
Adjustment::Desaturate { method: Default::default() },
|
||||||
Adjustment::GammaCorrection { gamma: 2.2, inverse: false },
|
Adjustment::GammaCorrection { gamma: 2.2, inverse: false },
|
||||||
Adjustment::MakeOpaque,
|
Adjustment::MakeOpaque { strength: 100. },
|
||||||
Adjustment::BrightnessContrast {
|
Adjustment::BrightnessContrast {
|
||||||
brightness: 10.,
|
brightness: 10.,
|
||||||
contrast: 10.,
|
contrast: 10.,
|
||||||
@@ -266,6 +268,7 @@ mod tests {
|
|||||||
blend_mode: Default::default(),
|
blend_mode: Default::default(),
|
||||||
opacity: 50.,
|
opacity: 50.,
|
||||||
},
|
},
|
||||||
|
Adjustment::Solarize,
|
||||||
];
|
];
|
||||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||||
|
|
||||||
|
|||||||
@@ -131,7 +131,9 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
|||||||
let exponent = if *inverse { 1. / gamma } else { gamma };
|
let exponent = if *inverse { 1. / gamma } else { gamma };
|
||||||
visitor.visit(GammaCorrection { exponent: exponent as f32 })
|
visitor.visit(GammaCorrection { exponent: exponent as f32 })
|
||||||
}
|
}
|
||||||
Adjustment::MakeOpaque => visitor.visit(MakeOpaque),
|
Adjustment::MakeOpaque { strength } => visitor.visit(MakeOpaque {
|
||||||
|
strength: (strength / 100.).clamp(0., 1.) as f32,
|
||||||
|
}),
|
||||||
Adjustment::BrightnessContrast {
|
Adjustment::BrightnessContrast {
|
||||||
brightness,
|
brightness,
|
||||||
contrast,
|
contrast,
|
||||||
@@ -223,6 +225,7 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
Adjustment::Invert => visitor.visit(Invert),
|
Adjustment::Invert => visitor.visit(Invert),
|
||||||
|
Adjustment::Solarize => visitor.visit(Solarize),
|
||||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||||
min_luminance: (min_luminance / 100.) as f32,
|
min_luminance: (min_luminance / 100.) as f32,
|
||||||
max_luminance: (max_luminance / 100.) as f32,
|
max_luminance: (max_luminance / 100.) as f32,
|
||||||
@@ -437,15 +440,23 @@ impl MapColor for GammaCorrection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct MakeOpaque;
|
struct MakeOpaque {
|
||||||
|
strength: f32,
|
||||||
|
}
|
||||||
|
|
||||||
impl MapColor for MakeOpaque {
|
impl MapColor for MakeOpaque {
|
||||||
fn map_cpu(&self, color: Color) -> Color {
|
fn map_cpu(&self, color: Color) -> Color {
|
||||||
color.with_alpha(1.)
|
// At full strength, even an alpha that isn't finite becomes opaque
|
||||||
|
if self.strength >= 1. {
|
||||||
|
return color.with_alpha(1.);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alpha moves toward 1 by the strength, in a form exact at both ends, keeping the straight color
|
||||||
|
color.with_alpha(color.a() * (1. - self.strength) + self.strength)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
||||||
steps.push(StepKind::MakeOpaque, []);
|
steps.push(StepKind::MakeOpaque, [texel(&[self.strength])]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1097,6 +1108,19 @@ impl MapColor for Invert {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, inverts each channel past middle gray, folding it back down.
|
||||||
|
struct Solarize;
|
||||||
|
|
||||||
|
impl MapColor for Solarize {
|
||||||
|
fn map_cpu(&self, color: Color) -> Color {
|
||||||
|
color.map_gamma_rgb(|channel| channel.min(1. - channel))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
||||||
|
steps.push(StepKind::Solarize, []);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct Threshold {
|
struct Threshold {
|
||||||
min_luminance: f32,
|
min_luminance: f32,
|
||||||
max_luminance: f32,
|
max_luminance: f32,
|
||||||
@@ -1964,4 +1988,23 @@ mod tests {
|
|||||||
assert_eq!((mapped(&ramp, 0), mapped(&ramp, 255)), (0., 1.), "{spread:?}");
|
assert_eq!((mapped(&ramp, 0), mapped(&ramp, 255)), (0., 1.), "{spread:?}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn making_opaque_lifts_alpha_by_its_strength_keeping_the_straight_color() {
|
||||||
|
let make_opaque = |strength| Adjustment::MakeOpaque { strength };
|
||||||
|
|
||||||
|
// Even a fully transparent pixel's hidden color shows, as the strength lifts its alpha
|
||||||
|
for color in [COLORS[1], Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, 0.), Color::from_rgbaf32_unchecked(0.3, 0.6, 0.1, 0.1)] {
|
||||||
|
assert_eq!(adjust_color(&make_opaque(0.), color), color);
|
||||||
|
assert_eq!(adjust_color(&make_opaque(100.), color), color.with_alpha(1.));
|
||||||
|
|
||||||
|
let half = adjust_color(&make_opaque(50.), color);
|
||||||
|
assert_eq!(half.with_alpha(color.a()), color);
|
||||||
|
assert!((half.a() - (color.a() + 1.) / 2.).abs() < 1e-6, "{half:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
for alpha in [f32::NAN, f32::INFINITY] {
|
||||||
|
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user