mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 15:53:26 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c403654745 |
No files matched your search
@@ -7,8 +7,6 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- 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)
|
||||
concurrency:
|
||||
@@ -247,8 +245,7 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
# 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' }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
@@ -262,9 +259,7 @@ jobs:
|
||||
rustflags: ""
|
||||
|
||||
- name: 📥 Fetch the base commit
|
||||
run: |
|
||||
git fetch --depth=1 origin "$BASE_REF"
|
||||
echo "BASE_SHA=$(git rev-parse FETCH_HEAD)" >> "$GITHUB_ENV"
|
||||
run: git fetch --depth=1 origin "$BASE_SHA"
|
||||
|
||||
- name: 🔬 Check migrations against the base commit
|
||||
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
|
||||
|
||||
Generated
-2
@@ -590,7 +590,6 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -5746,7 +5745,6 @@ dependencies = [
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"raster-types",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod bevel_and_emboss_v1;
|
||||
mod bevel_and_emboss_v2;
|
||||
mod blur_v2;
|
||||
mod convolution_kernel_v1;
|
||||
mod drop_shadow_v1;
|
||||
mod inner_glow_v1;
|
||||
mod inner_shadow_v1;
|
||||
@@ -11,9 +8,6 @@ mod mask_by_any_graphic;
|
||||
mod outer_glow_v1;
|
||||
mod outline_v1;
|
||||
mod outline_v2;
|
||||
mod outline_v3;
|
||||
mod paint_overlay_from_color_overlay;
|
||||
mod paint_overlay_v2;
|
||||
mod radial_blur_v1;
|
||||
mod renames;
|
||||
mod satin_v1;
|
||||
@@ -1,53 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,5 @@ mod mandelbrot_v1;
|
||||
mod mandelbrot_v2;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod noise_pattern_v2;
|
||||
mod pattern_square;
|
||||
mod renames;
|
||||
@@ -1,185 +0,0 @@
|
||||
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::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
@@ -196,6 +196,10 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "contextMenuInformation")]
|
||||
context_menu_information: Option<ContextMenuInformation>,
|
||||
},
|
||||
UpdateClickTargets {
|
||||
#[serde(rename = "clickTargets")]
|
||||
click_targets: Option<FrontendClickTargets>,
|
||||
},
|
||||
UpdateGraphViewOverlay {
|
||||
open: bool,
|
||||
},
|
||||
|
||||
@@ -87,7 +87,9 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
|
||||
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
|
||||
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
|
||||
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!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
|
||||
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
|
||||
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
|
||||
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
//! 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::blending_nodes::effects::{blur, drop_shadow};
|
||||
use graphene_std::graphic::{IntoGraphicList, extend};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
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");
|
||||
}
|
||||
|
||||
#[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,7 +7,6 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use crate::node_graph_executor::InspectedContext;
|
||||
use glam::{Affine2, DAffine2, Vec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::EnvelopeStyle;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
@@ -36,9 +35,8 @@ use graphene_std::vector::style::{
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
|
||||
MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||
MaskMode,
|
||||
};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::ops::Range;
|
||||
@@ -1273,22 +1271,16 @@ impl_table_item_layout_for_choice_enum!(
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
BevelStyle,
|
||||
RadialBlurMethod,
|
||||
EnvelopeStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
GradientInterpolation,
|
||||
GlowTechnique,
|
||||
NoiseDistribution,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
@@ -1464,14 +1456,9 @@ macro_rules! known_item_types {
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
RadialBlurMethod,
|
||||
EnvelopeStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
@@ -1482,7 +1469,6 @@ macro_rules! known_item_types {
|
||||
GradientHueDirection,
|
||||
GradientInterpolation,
|
||||
GlowTechnique,
|
||||
NoiseDistribution,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
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::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use glam::{DAffine2, IVec2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::list::Item;
|
||||
@@ -334,7 +334,6 @@ pub enum DocumentMessage {
|
||||
},
|
||||
UpdateEffectsReach {
|
||||
effects_reach: HashMap<NodeId, f64>,
|
||||
effects_frames: HashMap<NodeId, [DVec2; 2]>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
|
||||
@@ -304,15 +304,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let visibility_settings = self.overlays_visibility_settings;
|
||||
|
||||
// Send the overlays message to the overlays message handler
|
||||
self.overlays_message_handler.process_message(
|
||||
message,
|
||||
responses,
|
||||
OverlaysMessageContext {
|
||||
visibility_settings,
|
||||
viewport,
|
||||
graph_open: self.graph_view_overlay_open,
|
||||
},
|
||||
);
|
||||
self.overlays_message_handler
|
||||
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
|
||||
}
|
||||
DocumentMessage::Inspector(message) => {
|
||||
let context = InspectorMessageContext {
|
||||
@@ -1952,20 +1945,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||
}
|
||||
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, &[]);
|
||||
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
||||
let layer_effects_reach = effects_reach
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| is_document_layer(node_id))
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
|
||||
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
||||
.collect();
|
||||
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);
|
||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
|
||||
@@ -2694,6 +2680,7 @@ impl DocumentMessageHandler {
|
||||
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) {
|
||||
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.load_structure();
|
||||
|
||||
+3
@@ -807,6 +807,9 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
||||
// 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);
|
||||
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) => {
|
||||
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#[cfg(test)]
|
||||
mod clipping_tests;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod document_diff;
|
||||
mod document_history;
|
||||
mod document_message;
|
||||
|
||||
@@ -5,19 +5,16 @@ use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
|
||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
|
||||
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
|
||||
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
@@ -40,6 +37,11 @@ impl NodeInspectorContext<'_> {
|
||||
let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
|
||||
let widget_override = input_inspector_row.widget_override.clone()?;
|
||||
|
||||
// Older documents store number and Vec2 widget settings this way, but they come from the definition's parameter
|
||||
if matches!(widget_override.as_str(), "number" | "vec2") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
|
||||
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||
return None;
|
||||
@@ -51,11 +53,11 @@ impl NodeInspectorContext<'_> {
|
||||
}
|
||||
|
||||
/// Input position of the location parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
/// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::DimensionsInput::INDEX;
|
||||
/// Input position of the control path parameter on the "Blend" network node template.
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = graphene_std::subgraphs::blend::PathInput::INDEX;
|
||||
|
||||
/// The key used to access definitions for a network node or proto node.
|
||||
/// For proto nodes, this is their [`ProtoNodeIdentifier`].
|
||||
@@ -107,8 +109,7 @@ pub struct DocumentNodeDefinition {
|
||||
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
|
||||
pub identifier: &'static str,
|
||||
|
||||
/// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly.
|
||||
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
|
||||
/// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
|
||||
pub version: u32,
|
||||
|
||||
/// The default [`NodeTemplate`] this definition instantiates.
|
||||
@@ -136,529 +137,9 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
|
||||
|
||||
/// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry).
|
||||
/// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built.
|
||||
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
||||
/// A proto node within a definition takes its input and output metadata from the node macro in NODE_METADATA, and its display name too unless the definition gives one.
|
||||
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let custom = vec![
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
nodes: [
|
||||
// Primary (bottom) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
// Secondary (left) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of layers below this one, which the content is placed above.").into(),
|
||||
("Content", "The artwork this layer adds to the stack as a single item.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Artboard",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
|
||||
NodeInput::import(item!(TaggedValue), 2),
|
||||
NodeInput::import(item!(TaggedValue), 3),
|
||||
NodeInput::import(item!(TaggedValue), 4),
|
||||
NodeInput::import(item!(TaggedValue), 5),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Artboard), true),
|
||||
NodeInput::type_default(list!(Graphic), true),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
|
||||
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of artboards below this one, which this artboard is placed above.").into(),
|
||||
("Content", "Graphics to include within the artboard.").into(),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Location",
|
||||
"Coordinate of the top-left corner of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "X".to_string(),
|
||||
y: "Y".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Dimensions",
|
||||
"Width and height of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "W".to_string(),
|
||||
y: "H".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())),
|
||||
("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Blend",
|
||||
version: 1,
|
||||
category: "Vector: Deform",
|
||||
icon: Some("NodeBlend"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(16), 0)],
|
||||
nodes: [
|
||||
// 0: Separate Paths (split the vector into its individual paths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::separate_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Count (number of subpaths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::count::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Max (clamp subpath count to at least 1 for empty path case)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Number (the integer count enters the network's decimal math)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(item!(i64), 1)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Multiply (total_instances = count × subpath_count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Subtract (count - 1, open subpath denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Read Index (current repetition index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Divide (index / count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
|
||||
..Default::default()
|
||||
},
|
||||
// 8: Floor (floor(index / count) = subpath index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(7), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 9: Modulo (index % count = local index within subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 10: Path Is Closed (check if current subpath is closed)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::switch::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
|
||||
..Default::default()
|
||||
},
|
||||
// 12: Divide (local_index / denominator = within-subpath fraction)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 14: Add (subpath_index + clamped fraction = progression)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::add::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 15: Morph (content, progression, reverse, distribution, path)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::morph::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::node(NodeId(14), 0),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
|
||||
NodeInput::import(item!(Vector), 4),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
|
||||
..Default::default()
|
||||
},
|
||||
// 16: Repeat
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 17: Max (clamp count to at least 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::Integer(10), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Content", "The vector objects to create intermediate shapes between.").into(),
|
||||
(
|
||||
"Count",
|
||||
"The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.",
|
||||
)
|
||||
.into(),
|
||||
("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(),
|
||||
("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(),
|
||||
(
|
||||
"Path",
|
||||
"An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.",
|
||||
)
|
||||
.into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Origins to Polyline",
|
||||
version: 1,
|
||||
category: "Vector: Path",
|
||||
icon: Some("NodeOriginsToPolyline"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(7), 0)],
|
||||
nodes: [
|
||||
// 0: Read Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Extract Transform
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::extract_transform::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Decompose Translation
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::decompose_translation::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Vector (auto-converts the decomposed translation into a single-anchor List<Vector>)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::as_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Flatten Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Map
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Combine Paths
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Points to Polyline
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::points_to_polyline::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::value(TaggedValue::Bool(false), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Vector), true)],
|
||||
input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()],
|
||||
output_names: vec!["Vector".to_string()],
|
||||
output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Load Image",
|
||||
version: 1,
|
||||
category: "Data: I/O",
|
||||
icon: Some("NodeLoadImage"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
|
||||
input_metadata: vec![
|
||||
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
|
||||
("URL", "The web address or local asset path of the image to load.").into(),
|
||||
],
|
||||
output_names: vec!["Image".to_string()],
|
||||
output_descriptions: vec!["The loaded image.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Loads an image from a given URL."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Regex Find",
|
||||
version: 1,
|
||||
category: "String: Regex",
|
||||
icon: Some("NodeRegexFind"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![
|
||||
// Primary output: the whole match (String)
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
// Secondary output: capture groups (List<String>), each item carries `start`/`end`/`name` attributes from `regex_find`
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
nodes: [
|
||||
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(item!(String), 0),
|
||||
NodeInput::import(item!(String), 1),
|
||||
NodeInput::import(item!(i64), 2),
|
||||
NodeInput::import(item!(bool), 3),
|
||||
NodeInput::import(item!(bool), 4),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::String(String::new()), true),
|
||||
NodeInput::value(TaggedValue::String(String::new()), false),
|
||||
NodeInput::value(TaggedValue::Integer(0), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("String", "The string to search within.").into(),
|
||||
("Pattern", "The regular expression pattern to search for.").into(),
|
||||
(
|
||||
"Match Index",
|
||||
"Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.",
|
||||
)
|
||||
.into(),
|
||||
("Case Insensitive", "Match letters regardless of case.").into(),
|
||||
("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(),
|
||||
],
|
||||
output_names: vec!["Match".to_string(), "Captures".to_string()],
|
||||
output_descriptions: vec![
|
||||
"The whole portion of the string matching the pattern, or empty if there is no match.".to_string(),
|
||||
"The text matched by each capture group in the pattern, in order.".to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed(
|
||||
r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#,
|
||||
),
|
||||
inspector: None,
|
||||
},
|
||||
];
|
||||
|
||||
document_node_derive::post_process_nodes(custom)
|
||||
document_node_derive::derive_definitions()
|
||||
}
|
||||
|
||||
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
|
||||
@@ -689,8 +170,6 @@ fn static_node_inspector() -> NodeInspector {
|
||||
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("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
|
||||
}
|
||||
|
||||
@@ -728,91 +207,10 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"number".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
if let Some(unit) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
{
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
if let Some(min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.min(min);
|
||||
}
|
||||
if let Some(max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.max(max);
|
||||
}
|
||||
if let Some(step) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "step", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.step(step);
|
||||
}
|
||||
if let Some(mode) = context.network_interface.input_data(&node_id, index, "mode", context.selection_network_path).map(|value| {
|
||||
let mode: NumberInputMode = serde_json::from_value(value.clone()).unwrap();
|
||||
mode
|
||||
}) {
|
||||
number_input = number_input.mode(mode);
|
||||
}
|
||||
if let Some(range_min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_min(Some(range_min));
|
||||
}
|
||||
if let Some(range_max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_max(Some(range_max));
|
||||
}
|
||||
if let Some(is_integer) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
{
|
||||
number_input = number_input.is_integer(is_integer);
|
||||
}
|
||||
let blank_assist = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "blank_assist", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get blank assist when displaying number input for node {node_id}, index {index}");
|
||||
true
|
||||
});
|
||||
|
||||
Ok(vec![LayoutGroup::row(node_inspector::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context),
|
||||
number_input,
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// The custom number input settings are only available on proto nodes
|
||||
"optional_f64".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
if let Some(field) = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
{
|
||||
if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) {
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
@@ -907,57 +305,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"type_choice".to_string(),
|
||||
Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
|
||||
);
|
||||
map.insert(
|
||||
"vec2".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let x = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "x", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get x for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let y = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "y", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get y for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let unit = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get unit for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let min = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64());
|
||||
let is_integer = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
&x,
|
||||
&y,
|
||||
&unit,
|
||||
min,
|
||||
is_integer,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_scale".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -1130,6 +477,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
||||
)])
|
||||
@@ -1146,6 +494,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
||||
)])
|
||||
@@ -1252,6 +601,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
" px",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -1267,6 +617,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"H",
|
||||
"x",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -1387,7 +738,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"vec2_uv".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false, false)])
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)])
|
||||
}),
|
||||
);
|
||||
map
|
||||
@@ -1635,6 +986,18 @@ mod test {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// A `#[graph]` node with an inner node that has no definition is left out of the catalog with only a logged error
|
||||
#[test]
|
||||
fn every_registered_graph_has_a_definition() {
|
||||
// Released before resolving, since building the catalog locks the registry too
|
||||
let identifiers: Vec<&str> = graphene_std::registry::GRAPH_METADATA.lock().unwrap().iter().map(|graph| graph.identifier).collect();
|
||||
assert!(!identifiers.is_empty(), "the `#[graph]` nodes in `graphene_std::subgraphs` should be registered");
|
||||
|
||||
for identifier in identifiers {
|
||||
assert!(resolve_network_node_type(identifier).is_some(), "the '{identifier}' graph should have a definition");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||
use glam::{DAffine2, UVec2};
|
||||
@@ -1775,21 +1138,36 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn every_definition_default_value_satisfies_its_constraint() {
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
let name = &definition.node_template.display_name;
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name);
|
||||
// Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too
|
||||
fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec<String>) {
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name);
|
||||
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() {
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() {
|
||||
if let Some(value) = input.as_value()
|
||||
&& !constraint.accepts_default_value(&value.ty())
|
||||
{
|
||||
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty()));
|
||||
}
|
||||
|
||||
let takes_nothing = matches!(constraint, InputTypeConstraint::Limited(types) if !types.is_empty() && types.iter().all(|ty| ty == "()"));
|
||||
if takes_nothing && matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }) {
|
||||
violations.push(format!("{name} input {index}: a wire feeds it, but it takes nothing"));
|
||||
}
|
||||
}
|
||||
|
||||
if let NodeTemplateImplementation::Network(network) = &node_template.implementation {
|
||||
for (node_id, inner) in &network.nodes {
|
||||
check(inner, &format!("{name}, node {node_id}"), violations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
check(&definition.node_template, &definition.node_template.display_name, &mut violations);
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1806,7 +1184,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(String)));
|
||||
@@ -1820,7 +1198,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode2() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
|
||||
@@ -1829,8 +1207,8 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn network() {
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let inner_network = NodeNetworkTemplate {
|
||||
|
||||
+421
-30
@@ -1,11 +1,17 @@
|
||||
use super::DocumentNodeDefinition;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride,
|
||||
};
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::registry::*;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
/// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs.
|
||||
pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let mut definitions_map = HashMap::new();
|
||||
|
||||
// Add the protonodes from the macro.
|
||||
@@ -75,16 +81,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
inputs,
|
||||
call_argument: input_type.clone(),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
||||
// TODO: Store information for input overrides in the node macro
|
||||
input_metadata: fields
|
||||
.iter()
|
||||
.map(|f| match f.widget_override {
|
||||
RegistryWidgetOverride::None => (f.name, f.description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
|
||||
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
|
||||
})
|
||||
.collect(),
|
||||
input_metadata: input_metadata(fields),
|
||||
output_names,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -96,25 +93,242 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
);
|
||||
}
|
||||
|
||||
// Add the hand-written network nodes to the map and add the metadata for their internal protonodes
|
||||
for mut network_node in custom {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
|
||||
}
|
||||
let graphs = GRAPH_METADATA.lock().unwrap().clone();
|
||||
add_graph_definitions(graphs, &mut definitions_map);
|
||||
|
||||
definitions_map
|
||||
}
|
||||
|
||||
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
|
||||
/// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports.
|
||||
/// The rest of a parameter's widget settings are read from its field when the Inspector draws it.
|
||||
fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let (name, description) = (field.name, field.description);
|
||||
match field.widget_override {
|
||||
RegistryWidgetOverride::None => (name, description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())),
|
||||
RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Why a `#[graph]` node has no definition yet, or can't have one.
|
||||
enum GraphDefinitionError {
|
||||
/// A node inside it has no definition, which may be another graph not yet added.
|
||||
MissingNode(String),
|
||||
/// The graph's wiring is invalid, so it's left out of the catalog.
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
/// Adds the nodes defined as subgraphs by `#[graph]`, each once the definitions of the nodes inside it exist.
|
||||
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
|
||||
let mut identifier_counts = HashMap::new();
|
||||
for graph in &graphs {
|
||||
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
|
||||
}
|
||||
let mut rejected = HashSet::new();
|
||||
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
|
||||
.into_iter()
|
||||
.filter(|graph| {
|
||||
let taken = identifier_counts[graph.identifier] > 1;
|
||||
if taken {
|
||||
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
}
|
||||
!taken
|
||||
})
|
||||
.map(|graph| (graph, String::new()))
|
||||
.collect();
|
||||
|
||||
loop {
|
||||
let pending_count = pending_graphs.len();
|
||||
|
||||
let mut ready = Vec::new();
|
||||
pending_graphs.retain_mut(|(graph, missing)| {
|
||||
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
|
||||
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
|
||||
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(inner_graph) = rejected_inner_graph {
|
||||
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
return false;
|
||||
}
|
||||
|
||||
match graph_definition(graph, definitions_map) {
|
||||
Ok(definition) => {
|
||||
ready.push(definition);
|
||||
false
|
||||
}
|
||||
Err(GraphDefinitionError::MissingNode(missing_node)) => {
|
||||
*missing = missing_node;
|
||||
true
|
||||
}
|
||||
Err(GraphDefinitionError::Invalid(reason)) => {
|
||||
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
for definition in ready {
|
||||
let definition = prepare_network_definition(definition, definitions_map);
|
||||
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
|
||||
}
|
||||
|
||||
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (graph, missing_node) in pending_graphs {
|
||||
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills a network definition's nested proto node metadata and points its network at the definition.
|
||||
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
network_node
|
||||
}
|
||||
|
||||
/// Builds the catalog definition of a node defined as a subgraph by `#[graph]`.
|
||||
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
|
||||
let mut nodes = HashMap::new();
|
||||
for (index, node) in graph.nodes.iter().enumerate() {
|
||||
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
|
||||
let (identifier, name) = match &node.implementation {
|
||||
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
|
||||
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
|
||||
};
|
||||
let Some(definition) = definitions_map.get(&identifier) else {
|
||||
return Err(GraphDefinitionError::MissingNode(name));
|
||||
};
|
||||
let mut template = definition.default_node_template();
|
||||
|
||||
if let Some(call_argument) = &node.call_argument {
|
||||
template.call_argument = call_argument.clone();
|
||||
}
|
||||
template.visible = !node.hidden;
|
||||
template.locked = node.locked;
|
||||
template.pinned = node.pinned;
|
||||
if let Some(display_name) = node.display_name {
|
||||
template.display_name = display_name.to_string();
|
||||
}
|
||||
|
||||
let position = node.position.map_or(IVec2::ZERO, |(x, y)| IVec2::new(x, y));
|
||||
template.node_type_metadata = if node.layer {
|
||||
NodeTypePersistentMetadata::layer(position)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(position)
|
||||
};
|
||||
|
||||
for (input_index, source) in &node.inputs {
|
||||
let Some(input) = template.inputs.get_mut(*input_index) else {
|
||||
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
|
||||
};
|
||||
|
||||
// An input the compiler fills in can't be set, which the macro already prevents for the graphs it builds
|
||||
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
|
||||
return Err(GraphDefinitionError::Invalid(format!(
|
||||
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
|
||||
)));
|
||||
}
|
||||
|
||||
*input = graph_input(source, input);
|
||||
}
|
||||
|
||||
nodes.insert(NodeId(index as u64), template);
|
||||
}
|
||||
|
||||
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
|
||||
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
|
||||
|
||||
let exports = graph.exports.iter().map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false))).collect();
|
||||
|
||||
Ok(DocumentNodeDefinition {
|
||||
identifier: graph.identifier,
|
||||
version: graph.version,
|
||||
category: graph.category,
|
||||
icon: graph.icon,
|
||||
description: Cow::Borrowed(graph.description),
|
||||
inspector: None,
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
|
||||
inputs,
|
||||
input_metadata: input_metadata(&graph.imports),
|
||||
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
|
||||
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
|
||||
node_type_metadata: if graph.layer {
|
||||
NodeTypePersistentMetadata::layer(IVec2::ZERO)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(IVec2::ZERO)
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
|
||||
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> NodeInput {
|
||||
match source {
|
||||
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
|
||||
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
|
||||
GraphInputSource::Value { value, exposed } => {
|
||||
let ty = match default {
|
||||
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
|
||||
NodeInput::Import { import_type, .. } => import_type.clone(),
|
||||
_ => generic!(T),
|
||||
};
|
||||
NodeInput::value(graph_value(value, &ty), exposed.unwrap_or(default.is_exposed()))
|
||||
}
|
||||
GraphInputSource::Scope(key) => NodeInput::scope(*key),
|
||||
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
|
||||
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
|
||||
fn element_type(ty: &Type) -> &Type {
|
||||
let mut element = ty;
|
||||
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
|
||||
element = inner;
|
||||
}
|
||||
element
|
||||
}
|
||||
|
||||
/// Converts a value written in a graph definition to the type of the input it feeds.
|
||||
fn graph_value(value: &GraphValue, ty: &Type) -> TaggedValue {
|
||||
// An integer literal feeds an integer input as an integer, and any other as a number
|
||||
let is_integer = *element_type(ty) == concrete!(i64);
|
||||
|
||||
match value {
|
||||
GraphValue::Integer(integer) if is_integer => TaggedValue::Integer(*integer),
|
||||
GraphValue::Integer(integer) => TaggedValue::Number(*integer as f64),
|
||||
GraphValue::Number(number) => TaggedValue::Number(*number),
|
||||
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
|
||||
GraphValue::String(string) => TaggedValue::String(string.clone()),
|
||||
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
|
||||
GraphValue::Color(color) => TaggedValue::Color(*color),
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
|
||||
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
match &mut node_template.implementation {
|
||||
NodeTemplateImplementation::Network(network_template) => {
|
||||
@@ -128,13 +342,190 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
|
||||
return;
|
||||
};
|
||||
|
||||
// A display name, lock, or pin the network's author gave the node is kept
|
||||
let definition_template = &definition.node_template;
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
if node_template.display_name.is_empty() {
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
}
|
||||
node_template.input_metadata = definition_template.input_metadata.clone();
|
||||
node_template.output_names = definition_template.output_names.clone();
|
||||
node_template.locked = definition_template.locked;
|
||||
node_template.pinned = definition_template.pinned;
|
||||
node_template.locked |= definition_template.locked;
|
||||
node_template.pinned |= definition_template.pinned;
|
||||
}
|
||||
NodeTemplateImplementation::Definition(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
|
||||
fn number_import() -> FieldMetadata {
|
||||
FieldMetadata {
|
||||
name: "Value",
|
||||
description: "",
|
||||
internal: false,
|
||||
exposed: true,
|
||||
widget_override: RegistryWidgetOverride::None,
|
||||
value_source: RegistryValueSource::None,
|
||||
default_colors: None,
|
||||
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
number_hard_max: None,
|
||||
number_mode_range: false,
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph exporting one node, which is fed by the given inputs.
|
||||
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
|
||||
GraphMetadata {
|
||||
identifier,
|
||||
category: "Test",
|
||||
icon: None,
|
||||
description: "",
|
||||
version: 1,
|
||||
layer: false,
|
||||
imports: vec![number_import()],
|
||||
exports: vec![GraphExportMetadata {
|
||||
name: "Out",
|
||||
description: "",
|
||||
source: GraphInputSource::Node { node: 0, output: 0 },
|
||||
}],
|
||||
nodes: vec![GraphNodeMetadata {
|
||||
implementation,
|
||||
inputs,
|
||||
position: None,
|
||||
layer: false,
|
||||
display_name: None,
|
||||
hidden: false,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
call_argument: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn from_import() -> Vec<(usize, GraphInputSource)> {
|
||||
let ty = Type::Item(Box::new(concrete!(f64)));
|
||||
vec![(0, GraphInputSource::Import { index: 0, ty })]
|
||||
}
|
||||
|
||||
/// The definitions a test graph builds on: only the As Number proto node.
|
||||
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
|
||||
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
|
||||
HashMap::from([(identifier, definition)])
|
||||
}
|
||||
|
||||
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
|
||||
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
|
||||
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
|
||||
let inner = one_node_graph("Test Inner", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![outer, inner], &mut definitions_map);
|
||||
|
||||
assert!(has_graph(&definitions_map, "Test Inner"));
|
||||
assert!(has_graph(&definitions_map, "Test Outer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
|
||||
let mut inputs = from_import();
|
||||
inputs.push((
|
||||
100,
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Number(1.),
|
||||
exposed: None,
|
||||
},
|
||||
));
|
||||
let graph = one_node_graph("Test Missing Input", math_nodes::as_number::IDENTIFIER.into(), inputs);
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Missing Input"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
|
||||
let first = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let second = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Twin"));
|
||||
assert!(!has_graph(&definitions_map, "Test Dependent"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_integer_value_takes_the_type_of_the_input_it_feeds() {
|
||||
let integer = Type::Item(Box::new(concrete!(i64)));
|
||||
let number = Type::Item(Box::new(concrete!(f64)));
|
||||
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &integer), TaggedValue::Integer(3)));
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &number), TaggedValue::Number(value) if value == 3.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_start_from_their_default_or_type() {
|
||||
let unit_primary = FieldMetadata {
|
||||
default_type: Some(concrete!(())),
|
||||
..number_import()
|
||||
};
|
||||
let with_default = FieldMetadata {
|
||||
value_source: RegistryValueSource::Default("2.5"),
|
||||
..number_import()
|
||||
};
|
||||
let graph = GraphMetadata {
|
||||
imports: vec![unit_primary, with_default],
|
||||
..one_node_graph("Test Defaults", math_nodes::as_number::IDENTIFIER.into(), from_import())
|
||||
};
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
|
||||
|
||||
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
|
||||
assert!(!inputs[0].is_exposed());
|
||||
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
|
||||
assert!(inputs[1].is_exposed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_nodes_widget_settings_come_from_its_import() {
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
|
||||
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
|
||||
|
||||
let location = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
let field = document
|
||||
.network_interface
|
||||
.field_metadata(&node_id, location, &[])
|
||||
.expect("the location input should have its import's settings");
|
||||
assert_eq!(field.labels, Some(("X", "Y")));
|
||||
assert!(field.integer);
|
||||
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
|
||||
}
|
||||
}
|
||||
@@ -207,6 +207,8 @@ pub enum NodeGraphMessage {
|
||||
SelectedNodesSet {
|
||||
nodes: Vec<NodeId>,
|
||||
},
|
||||
SendClickTargets,
|
||||
EndSendClickTargets,
|
||||
UnloadWires,
|
||||
SendWires,
|
||||
UpdateVisibleNodes,
|
||||
@@ -446,6 +448,8 @@ impl NodeGraphMessage {
|
||||
| Self::SelectedNodesAdd { .. }
|
||||
| Self::SelectedNodesRemove { .. }
|
||||
| Self::SelectedNodesSet { .. }
|
||||
| Self::SendClickTargets
|
||||
| Self::EndSendClickTargets
|
||||
| Self::UnloadWires
|
||||
| Self::SendWires
|
||||
| Self::UpdateVisibleNodes
|
||||
|
||||
@@ -24,12 +24,14 @@ 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::utility_types::{HintData, HintGroup, HintInfo};
|
||||
use crate::messages::viewport::Position;
|
||||
use glam::{DVec2, IVec2};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
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::*;
|
||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||
use renderer::Quad;
|
||||
|
||||
#[derive(Debug, ExtractField)]
|
||||
pub struct NodeGraphMessageContext<'a> {
|
||||
@@ -2023,6 +2025,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
selected_nodes.set_selected_nodes(nodes);
|
||||
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 => {
|
||||
self.frontend_wires.clear();
|
||||
responses.add(FrontendMessage::ClearAllNodeGraphWires);
|
||||
@@ -2537,13 +2543,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
HashSet::new()
|
||||
};
|
||||
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 {
|
||||
let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else {
|
||||
log::error!("Could not get the body of node {node_id}");
|
||||
let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else {
|
||||
log::error!("Could not get transient metadata for node {node_id}");
|
||||
continue;
|
||||
};
|
||||
if body.overlaps(selection_min, selection_max) {
|
||||
let quad = Quad::from_box([box_selection_start, box_selection_end_graph]);
|
||||
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
|
||||
if alt {
|
||||
nodes.remove(&node_id);
|
||||
} else {
|
||||
@@ -3205,6 +3211,11 @@ impl NodeGraphMessageHandler {
|
||||
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
|
||||
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 {
|
||||
common.extend(actions!(NodeGraphMessageDiscriminant;
|
||||
Copy,
|
||||
|
||||
@@ -20,7 +20,6 @@ use graph_craft::application_io::resource::{DataSource, Resource, ResourceId};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graph_craft::{Type, concrete, item};
|
||||
use graphene_std::EnvelopeStyle;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::{
|
||||
@@ -41,8 +40,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -240,7 +238,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
||||
}
|
||||
|
||||
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ParameterOptions {
|
||||
pub soft_min: Option<f64>,
|
||||
pub soft_max: Option<f64>,
|
||||
@@ -252,6 +250,50 @@ pub(crate) struct ParameterOptions {
|
||||
pub unit: Option<&'static str>,
|
||||
pub display_decimal_places: Option<u32>,
|
||||
pub step: Option<f64>,
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
pub integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for ParameterOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
soft_min: None,
|
||||
soft_max: None,
|
||||
hard_min: None,
|
||||
hard_max: None,
|
||||
slider: false,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
unit: None,
|
||||
display_decimal_places: None,
|
||||
step: None,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ParameterOptions {
|
||||
/// The options a proto node's field or a graph's import gives its widget.
|
||||
pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self {
|
||||
Self {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
labels: field.labels,
|
||||
integer: field.integer,
|
||||
blank_assist: field.blank_assist,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
||||
@@ -305,9 +347,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
unit,
|
||||
display_decimal_places,
|
||||
step,
|
||||
labels,
|
||||
integer,
|
||||
blank_assist,
|
||||
} = options;
|
||||
|
||||
let mut number_input = NumberInput::default();
|
||||
let mut number_input = NumberInput::default().is_integer(integer);
|
||||
if slider {
|
||||
number_input = number_input.mode_range();
|
||||
}
|
||||
@@ -350,7 +395,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
}
|
||||
};
|
||||
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
|
||||
|
||||
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
|
||||
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
|
||||
@@ -394,8 +439,11 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
true => text_area_widget(default_info).into(),
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &mut extra_widgets),
|
||||
Some(x) if id_is::<DVec2>(x) => {
|
||||
let (x_label, y_label) = labels.unwrap_or(("X", "Y"));
|
||||
vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false)
|
||||
}
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
@@ -455,15 +503,9 @@ 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::<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::<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::<RadialBlurMethod>(x) => enum_choice::<RadialBlurMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<EnvelopeStyle>(x) => enum_choice::<EnvelopeStyle>().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::<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::<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::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -794,10 +836,8 @@ pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
||||
last.clone()
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||
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);
|
||||
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
@@ -864,7 +904,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
||||
scale_widgets.extend_from_slice(&[
|
||||
NumberInput::new(Some(scale.x))
|
||||
.label("W")
|
||||
.unit(size_unit)
|
||||
.unit("x")
|
||||
.on_update(update_value_at_index(
|
||||
move |w: &NumberInput| {
|
||||
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix;
|
||||
@@ -878,7 +918,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(scale.y))
|
||||
.label("H")
|
||||
.unit(size_unit)
|
||||
.unit("x")
|
||||
.on_update(update_value_at_index(
|
||||
move |h: &NumberInput| {
|
||||
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix;
|
||||
@@ -904,7 +944,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
||||
}
|
||||
}
|
||||
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, max: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
@@ -919,7 +959,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
||||
@@ -930,7 +970,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
||||
@@ -945,7 +985,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
||||
@@ -956,7 +996,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
||||
@@ -2798,10 +2838,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
||||
NumberInput::default().label("H").min(0.).unit(" px"),
|
||||
));
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false);
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false);
|
||||
widgets.extend([spacing, angles]);
|
||||
} else {
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false);
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
|
||||
widgets.push(spacing);
|
||||
}
|
||||
}
|
||||
@@ -3264,40 +3304,20 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
}
|
||||
|
||||
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
|
||||
let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path);
|
||||
let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default();
|
||||
|
||||
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
|
||||
log::error!("Could not get implementation for node {node_id}");
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut options = ParameterOptions::default();
|
||||
let input_type = match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||
let proto_node_identifier = proto_node_identifier.clone();
|
||||
|
||||
let mut default_type = None;
|
||||
if let Some(field) = graphene_std::registry::NODE_METADATA
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
options = ParameterOptions {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
};
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
if let Some(default) = default_type {
|
||||
if let Some(default) = field.and_then(|field| field.default_type) {
|
||||
break 'early_return default;
|
||||
}
|
||||
|
||||
@@ -3313,12 +3333,21 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
let Some(input_type) = input_type else { return Vec::new() };
|
||||
input_type.clone()
|
||||
}
|
||||
_ => context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.unwrap_or(concrete!(())),
|
||||
_ => {
|
||||
// A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph
|
||||
let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
|
||||
Type::Item(element) => *element,
|
||||
declared_type => declared_type,
|
||||
});
|
||||
|
||||
context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.or(declared_type)
|
||||
.unwrap_or(concrete!(()))
|
||||
}
|
||||
};
|
||||
|
||||
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
|
||||
@@ -3778,61 +3807,6 @@ pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
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> {
|
||||
document_id: DocumentId,
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
|
||||
@@ -212,6 +212,23 @@ pub struct NodeEvaluationError {
|
||||
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))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Direction {
|
||||
|
||||
@@ -5,7 +5,6 @@ use crate::messages::prelude::*;
|
||||
pub struct OverlaysMessageContext<'a> {
|
||||
pub visibility_settings: OverlaysVisibilitySettings,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
pub graph_open: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
@@ -26,7 +25,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
|
||||
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
|
||||
|
||||
if visibility_settings.all() && !context.graph_open {
|
||||
if visibility_settings.all() {
|
||||
responses.add(DocumentMessage::GridOverlays { 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.
|
||||
|
||||
use super::test_support::open_demo;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use glam::DVec2;
|
||||
use graphene_std::uuid::NodeId;
|
||||
@@ -20,32 +20,20 @@ const DEMOS: [&str; 8] = [
|
||||
const REPETITIONS: u32 = 200;
|
||||
|
||||
#[test]
|
||||
fn wire_anchors_lie_on_the_ports_of_every_demo_node() {
|
||||
fn wire_anchors_match_the_ports_of_every_demo_node() {
|
||||
for demo in DEMOS {
|
||||
let document = open_demo(demo);
|
||||
let interface = &document.network_interface;
|
||||
|
||||
for node_id in interface.document_network().nodes.keys() {
|
||||
// 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,
|
||||
}
|
||||
};
|
||||
|
||||
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
|
||||
for index in 0..interface.number_of_inputs(node_id, &[]) {
|
||||
let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]);
|
||||
assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}");
|
||||
let input = 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}");
|
||||
}
|
||||
for index in 0..interface.number_of_outputs(node_id, &[]) {
|
||||
let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]);
|
||||
assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}");
|
||||
let output = OutputConnector::node(*node_id, index);
|
||||
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,7 +60,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
|
||||
let start = Instant::now();
|
||||
for _ in 0..REPETITIONS {
|
||||
for node_id in &node_ids {
|
||||
std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
|
||||
std::hint::black_box(interface.node_click_targets(node_id, &[]));
|
||||
}
|
||||
}
|
||||
let all_click_targets = start.elapsed() / REPETITIONS;
|
||||
|
||||
@@ -35,6 +35,7 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
|
||||
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.set_absolute_position(*position);
|
||||
}
|
||||
interface.invalidate_positions(network_path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,14 +172,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
|
||||
interface.finish_drag(&[]);
|
||||
|
||||
let kept = interface.positions(node_ids.iter().copied(), &[]);
|
||||
let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
|
||||
let Some((_, indices, graph)) = interface.layout_graph(&[]) else {
|
||||
panic!("the root network is laid out")
|
||||
};
|
||||
let fresh = graph_layout::Layout::new(&graph);
|
||||
for (other, position) in kept {
|
||||
assert_eq!(
|
||||
Some(position),
|
||||
laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
|
||||
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"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -53,8 +53,6 @@ pub struct DocumentMetadata {
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
@@ -366,7 +364,7 @@ impl DocumentMetadata {
|
||||
}
|
||||
|
||||
/// 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, the frames its effects paint anywhere in, and how far they paint past it. Only the first item of a
|
||||
/// 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
|
||||
/// 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]> {
|
||||
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
||||
@@ -374,8 +372,7 @@ impl DocumentMetadata {
|
||||
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())
|
||||
});
|
||||
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 [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||
|
||||
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
||||
Some([min - reach, max + reach])
|
||||
@@ -754,25 +751,6 @@ mod tests {
|
||||
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]
|
||||
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
|
||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||
|
||||
@@ -22,7 +22,6 @@ mod layout;
|
||||
mod layout_pass;
|
||||
mod memo_network;
|
||||
mod mutations;
|
||||
mod node_parts;
|
||||
mod queries;
|
||||
mod reconcile;
|
||||
mod resolved_types;
|
||||
@@ -37,7 +36,6 @@ mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use layout_pass::NetworkLayout;
|
||||
pub use node_parts::{Part, PartTarget};
|
||||
pub use reconcile::{ReconcileError, Reconciled};
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
@@ -54,12 +52,11 @@ use crate::consts::{
|
||||
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::utility_types::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
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::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
|
||||
use deserialization::deserialize_node_persistent_metadata;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::Type;
|
||||
@@ -74,7 +71,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
|
||||
use graphene_std::vector::{Vector, VectorModificationType};
|
||||
use kurbo::BezPath;
|
||||
use memo_network::MemoNetwork;
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::Hash;
|
||||
use std::ops::Deref;
|
||||
|
||||
@@ -93,7 +93,7 @@ impl NodeNetworkInterface {
|
||||
EditorDelta::NodeMetadata { network, node_id, change } => {
|
||||
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
|
||||
match change {
|
||||
NodeMetadataChange::NodeType(node_type) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()),
|
||||
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
|
||||
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
|
||||
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
|
||||
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
|
||||
|
||||
@@ -88,15 +88,34 @@ impl NodeNetworkInterface {
|
||||
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
|
||||
}
|
||||
|
||||
/// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed.
|
||||
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
|
||||
let generation = self.with_layout(network_path, NetworkLayout::generation)?;
|
||||
let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
|
||||
if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
|
||||
cache.unload();
|
||||
}
|
||||
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
|
||||
self.load_import_export_ports(network_path);
|
||||
|
||||
cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports))
|
||||
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> {
|
||||
self.network_metadata(network_path)?
|
||||
.transient_metadata
|
||||
.import_export_ports
|
||||
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
|
||||
}
|
||||
|
||||
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
|
||||
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]) {
|
||||
@@ -107,13 +126,78 @@ impl NodeNetworkInterface {
|
||||
transient.import_export_ports.unload();
|
||||
}
|
||||
|
||||
/// The combined bounds of every node in the network, in node graph space.
|
||||
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
self.with_layout(network_path, NetworkLayout::bounds)
|
||||
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.
|
||||
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let network_metadata = self.network_metadata(network_path)?;
|
||||
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> {
|
||||
self.with_layout(network_path, NetworkLayout::clearance)
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
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>>> {
|
||||
@@ -280,10 +364,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
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 {
|
||||
log::error!("Could not get nested node_metadata in layer_width");
|
||||
return None;
|
||||
@@ -296,7 +376,7 @@ impl NodeNetworkInterface {
|
||||
node_metadata
|
||||
.transient_metadata
|
||||
.layer_width
|
||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |widths| *widths)
|
||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
|
||||
}
|
||||
|
||||
/// Unloads layer width if the node is a layer.
|
||||
@@ -395,7 +475,7 @@ impl NodeNetworkInterface {
|
||||
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 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, graph_wire_style);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
||||
|
||||
let path_string = vector_wire.to_svg();
|
||||
let center_path_string = center_line.to_svg();
|
||||
@@ -443,7 +523,7 @@ impl NodeNetworkInterface {
|
||||
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 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, wire_style);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
||||
Some((vector_wire, center_line, thick))
|
||||
}
|
||||
|
||||
@@ -469,10 +549,17 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// The node's body, ports, and handles, built where it is drawn now.
|
||||
/// The box around the node's body where it sits in its grid cell, in node graph space.
|
||||
pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
||||
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]> {
|
||||
let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?;
|
||||
Some([body.min, body.max])
|
||||
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
|
||||
.flatten()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-72
@@ -2,7 +2,7 @@ use super::{
|
||||
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
|
||||
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
|
||||
};
|
||||
use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
use crate::consts::{GRID_SIZE, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
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::utility_types::{ContextMenuData, Direction};
|
||||
@@ -330,6 +330,7 @@ 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))));
|
||||
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)));
|
||||
|
||||
@@ -2613,7 +2614,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir
|
||||
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
|
||||
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
let shaken = editor
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0)
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0)
|
||||
.await;
|
||||
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
|
||||
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
|
||||
@@ -4227,73 +4228,3 @@ async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
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,21 +62,11 @@ pub enum NodeMetadataChange {
|
||||
/// 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.
|
||||
NodeType(NodeTypePersistentMetadata),
|
||||
/// Where a node that stays a layer or stays a node sits. Encodes to `ui::position` alone.
|
||||
Position(NodeTypePersistentMetadata),
|
||||
DisplayName(String),
|
||||
Locked(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
|
||||
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -329,10 +319,6 @@ 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(_)))),
|
||||
]
|
||||
}
|
||||
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::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
|
||||
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
|
||||
|
||||
+1
-28
@@ -3,7 +3,6 @@ use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange
|
||||
use super::storage_metadata::StorageMetadataView;
|
||||
use super::{InputConnector, NodeTemplate};
|
||||
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::{PeerId, Registry, RegistryDelta, Session};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -185,7 +184,7 @@ async fn per_field_metadata_edits_match_the_diff() {
|
||||
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
|
||||
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
|
||||
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
|
||||
metadata_change(node, NodeMetadataChange::Position(metadata.node_type_metadata.clone())),
|
||||
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())),
|
||||
EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
||||
network: None,
|
||||
node_id: node,
|
||||
@@ -284,32 +283,6 @@ async fn unchanged_writes_emit_nothing() {
|
||||
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
|
||||
/// without the caller saying anything about it.
|
||||
#[tokio::test]
|
||||
|
||||
+190
-3
@@ -46,6 +46,193 @@ 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.)))
|
||||
}
|
||||
|
||||
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.
|
||||
/// 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])> {
|
||||
@@ -152,9 +339,9 @@ impl NodeNetworkInterface {
|
||||
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, and the width of its name. Cached
|
||||
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached
|
||||
/// because measuring the name's text is slow.
|
||||
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
|
||||
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
|
||||
const GAP_WIDTH: f64 = 8.;
|
||||
const FONT_SIZE: f64 = 14.;
|
||||
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
|
||||
@@ -169,7 +356,7 @@ impl NodeNetworkInterface {
|
||||
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;
|
||||
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
|
||||
((layer_width_pixels / 24.).ceil() as u32).max(8)
|
||||
}
|
||||
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 {
|
||||
|
||||
+116
-59
@@ -24,6 +24,81 @@ impl NodeNetworkInterface {
|
||||
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) {
|
||||
self.document_metadata.document_to_viewport = transform;
|
||||
}
|
||||
@@ -48,24 +123,6 @@ impl NodeNetworkInterface {
|
||||
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.
|
||||
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
@@ -76,13 +133,16 @@ impl NodeNetworkInterface {
|
||||
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
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
let reaching = self.nodes_reaching(point, network_path);
|
||||
let clicked_nodes = self.with_layout(network_path, |layout| {
|
||||
reaching
|
||||
.into_iter()
|
||||
.filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id))))
|
||||
.collect::<Vec<_>>()
|
||||
})?;
|
||||
let clicked_nodes = self
|
||||
.nodes_reaching(point, network_path)
|
||||
.iter()
|
||||
.filter(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id))
|
||||
}) == 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
|
||||
let drawing_layer = |node_id: &NodeId| {
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
@@ -105,18 +165,25 @@ impl NodeNetworkInterface {
|
||||
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 wanted = match click_target_type {
|
||||
LayerClickTargetTypes::Visibility => Part::Visibility,
|
||||
LayerClickTargetTypes::Lock => Part::Lock,
|
||||
LayerClickTargetTypes::Grip => Part::Grip,
|
||||
LayerClickTargetTypes::Name => Part::Name,
|
||||
};
|
||||
|
||||
self.nodes_reaching(point, network_path).into_iter().find(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(()))
|
||||
.is_some()
|
||||
})
|
||||
self.nodes_reaching(point, network_path)
|
||||
.iter()
|
||||
.filter_map(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
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),
|
||||
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||
}
|
||||
} 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.
|
||||
@@ -202,11 +269,13 @@ impl NodeNetworkInterface {
|
||||
.iter()
|
||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||
.filter_map(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.find_node_part(node_id, network_path, |part, target| match part {
|
||||
Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)),
|
||||
_ => None,
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata
|
||||
.port_click_targets
|
||||
.clicked_input_port_from_point(point - glide_offsets.node(node_id))
|
||||
.map(|port| InputConnector::node_at_index(*node_id, port))
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
||||
.or_else(|| {
|
||||
@@ -233,11 +302,13 @@ impl NodeNetworkInterface {
|
||||
.iter()
|
||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||
.filter_map(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.find_node_part(node_id, network_path, |part, target| match part {
|
||||
Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)),
|
||||
_ => None,
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata
|
||||
.port_click_targets
|
||||
.clicked_output_port_from_point(point - glide_offsets.node(node_id))
|
||||
.map(|output_index| OutputConnector::node(*node_id, output_index))
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.next()
|
||||
.or_else(|| {
|
||||
@@ -355,17 +426,3 @@ impl NodeNetworkInterface {
|
||||
(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,6 +6,10 @@
|
||||
use super::*;
|
||||
|
||||
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.
|
||||
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
|
||||
self.unload_import_export_ports(network_path);
|
||||
@@ -13,5 +17,6 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
self.try_unload_layer_width(node_id, network_path);
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -144,6 +145,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Sets the position of a layer to a stack position
|
||||
@@ -157,6 +159,8 @@ impl NodeNetworkInterface {
|
||||
} else if node.set_stack_position(y_offset) {
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Sets the position of a node to a stack position without changing its y offset
|
||||
@@ -367,6 +371,7 @@ impl NodeNetworkInterface {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
|
||||
if node.shift_absolute_position(position - current_position) {
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+36
-158
@@ -1,9 +1,7 @@
|
||||
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
|
||||
use super::*;
|
||||
use glam::UVec2;
|
||||
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
|
||||
use std::cell::RefCell;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
const REACH_MARGIN: f64 = 16.;
|
||||
|
||||
@@ -11,53 +9,13 @@ const REACH_MARGIN: f64 = 16.;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NetworkLayout {
|
||||
revision: u64,
|
||||
generation: u64,
|
||||
node_ids: Vec<NodeId>,
|
||||
indices: HashMap<NodeId, NodeIndex>,
|
||||
graph: Graph,
|
||||
shapes: Vec<NodeShape>,
|
||||
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 {
|
||||
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> {
|
||||
Some(self.node(node_id)?.position)
|
||||
}
|
||||
@@ -95,33 +53,6 @@ impl NetworkLayout {
|
||||
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.
|
||||
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
|
||||
let Some(index) = self.indices.get(node_id) else { return false };
|
||||
@@ -131,38 +62,6 @@ impl NetworkLayout {
|
||||
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> {
|
||||
Some(self.layout.node(*self.indices.get(node_id)?))
|
||||
}
|
||||
@@ -187,14 +86,12 @@ struct DragOrigin {
|
||||
keep_upstream: bool,
|
||||
node_ids: Vec<NodeId>,
|
||||
indices: HashMap<NodeId, NodeIndex>,
|
||||
shapes: Vec<NodeShape>,
|
||||
start: Graph,
|
||||
drag: Drag,
|
||||
}
|
||||
|
||||
impl DragOrigin {
|
||||
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;
|
||||
fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
||||
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
|
||||
Self {
|
||||
revision,
|
||||
@@ -202,7 +99,6 @@ impl DragOrigin {
|
||||
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
|
||||
node_ids,
|
||||
indices,
|
||||
shapes,
|
||||
start,
|
||||
}
|
||||
}
|
||||
@@ -258,6 +154,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
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.
|
||||
@@ -281,14 +178,9 @@ impl NodeNetworkInterface {
|
||||
.filter(|((before, after), _)| before.placement != after.placement)
|
||||
.map(|((_, after), node_id)| (*node_id, after.placement))
|
||||
.collect();
|
||||
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)
|
||||
(moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved)
|
||||
});
|
||||
let Some((moved_placements, laid_out, graph)) = finished else { return };
|
||||
let Some((moved_placements, node_ids, indices, graph)) = finished else { return };
|
||||
|
||||
let mut stored_all = true;
|
||||
for (node_id, placement) in moved_placements {
|
||||
@@ -297,7 +189,13 @@ impl NodeNetworkInterface {
|
||||
|
||||
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
|
||||
let layout = Layout::new(&graph);
|
||||
network_metadata.transient_metadata.layout.store(NetworkLayout::new(store::revision(), laid_out, graph, layout));
|
||||
network_metadata.transient_metadata.layout.store(NetworkLayout {
|
||||
revision: store::revision(),
|
||||
layout,
|
||||
graph,
|
||||
node_ids,
|
||||
indices,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,15 +208,16 @@ impl NodeNetworkInterface {
|
||||
let transient = self.network_transient_mut(network_path)?;
|
||||
let drag = transient.drag.take()?;
|
||||
transient.layout.unload();
|
||||
self.invalidate_positions(network_path);
|
||||
Some(drag)
|
||||
}
|
||||
|
||||
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();
|
||||
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
|
||||
let (laid_out, start) = self.layout_graph(network_path)?;
|
||||
let (node_ids, indices, start) = self.layout_graph(network_path)?;
|
||||
let start_layout = Layout::new(&start);
|
||||
*origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
||||
*origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
||||
}
|
||||
origin.as_mut().map(read)
|
||||
}
|
||||
@@ -328,8 +227,8 @@ impl NodeNetworkInterface {
|
||||
let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
|
||||
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
|
||||
|
||||
let (laid_out, graph, layout) = cached.into_parts();
|
||||
Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision))
|
||||
let NetworkLayout { node_ids, indices, graph, layout, .. } = cached;
|
||||
Some(DragOrigin::new(node_ids, indices, graph, layout, dragged, keep_upstream, revision))
|
||||
}
|
||||
|
||||
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
|
||||
@@ -347,38 +246,40 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
if node.set_node_type(node_type) {
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
|
||||
let (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
||||
let (node_ids, indices, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
||||
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
|
||||
let (graph, mut layout) = origin.drag.moved(drag.offset);
|
||||
layout.snap_chains(&graph);
|
||||
let laid_out = LaidOutNodes {
|
||||
node_ids: origin.node_ids.clone(),
|
||||
indices: origin.indices.clone(),
|
||||
shapes: origin.shapes.clone(),
|
||||
};
|
||||
(laid_out, graph, layout)
|
||||
(origin.node_ids.clone(), origin.indices.clone(), graph, layout)
|
||||
})?,
|
||||
None => {
|
||||
let (laid_out, graph) = self.layout_graph(network_path)?;
|
||||
let (node_ids, indices, graph) = self.layout_graph(network_path)?;
|
||||
let layout = Layout::new(&graph);
|
||||
(laid_out, graph, layout)
|
||||
(node_ids, indices, graph, layout)
|
||||
}
|
||||
};
|
||||
|
||||
Some(NetworkLayout::new(revision, laid_out, graph, layout))
|
||||
Some(NetworkLayout {
|
||||
revision,
|
||||
layout,
|
||||
graph,
|
||||
node_ids,
|
||||
indices,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> {
|
||||
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, Graph)> {
|
||||
let network = self.nested_network(network_path)?;
|
||||
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 (nodes, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?;
|
||||
let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?;
|
||||
let wires = node_ids
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -396,10 +297,10 @@ impl NodeNetworkInterface {
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires }))
|
||||
Some((node_ids, indices, Graph { nodes, wires }))
|
||||
}
|
||||
|
||||
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> {
|
||||
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> {
|
||||
let metadata = self.node_metadata(node_id, network_path)?;
|
||||
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
|
||||
@@ -413,40 +314,17 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
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) {
|
||||
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)),
|
||||
(true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)),
|
||||
(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))),
|
||||
};
|
||||
|
||||
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
|
||||
let node = Node {
|
||||
Some(Node {
|
||||
placement,
|
||||
kind,
|
||||
size: size.as_ivec2(),
|
||||
chainable: !is_redirect_dot && !primary_output_hidden,
|
||||
chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path),
|
||||
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>,
|
||||
}
|
||||
+17
-6
@@ -94,9 +94,11 @@ impl NodeNetworkInterface {
|
||||
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
|
||||
}
|
||||
|
||||
// Update the outward wires for all nodes in the encapsulating network
|
||||
// Update the outward wires and bounding box for all nodes in the encapsulating network
|
||||
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
|
||||
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
|
||||
@@ -139,6 +141,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
// Update the metadata for the encapsulating node
|
||||
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;
|
||||
}
|
||||
if affects_document_structure {
|
||||
@@ -176,6 +179,7 @@ impl NodeNetworkInterface {
|
||||
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
|
||||
// Update the metadata for the encapsulating node
|
||||
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) {
|
||||
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
|
||||
}
|
||||
@@ -568,7 +572,8 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Lightweight version of `set_input` for bulk import operations.
|
||||
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
||||
/// or per-node cache invalidation. Call `load_structure` once after all import wiring is complete.
|
||||
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
|
||||
/// `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]) {
|
||||
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");
|
||||
@@ -668,6 +673,8 @@ impl NodeNetworkInterface {
|
||||
(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
|
||||
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
|
||||
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
|
||||
let nested_path = [network_path, &[*node_id]].concat();
|
||||
@@ -897,6 +904,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
self.transaction_modified();
|
||||
}
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
self.unload_outward_wires(network_path);
|
||||
}
|
||||
|
||||
@@ -919,6 +927,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
|
||||
previous_entry
|
||||
}
|
||||
@@ -1083,6 +1092,7 @@ impl NodeNetworkInterface {
|
||||
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 {
|
||||
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
|
||||
return;
|
||||
@@ -1116,10 +1126,10 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
let reconnected_offset = reconnect_to_input.as_ref().and_then(NodeInput::as_node).and_then(|reconnected| {
|
||||
let offset = self.relative_offset(node_id, network_path).or_else(|| self.relative_offset(&reconnected, network_path))?;
|
||||
Some((reconnected, offset))
|
||||
});
|
||||
let reconnected_offset = reconnect_to_input
|
||||
.as_ref()
|
||||
.and_then(NodeInput::as_node)
|
||||
.and_then(|reconnected| Some((reconnected, self.relative_offset(&reconnected, network_path)?)));
|
||||
|
||||
let mut exports_fed_by_import = Vec::new();
|
||||
|
||||
@@ -1355,6 +1365,7 @@ impl NodeNetworkInterface {
|
||||
transient.layer_width.unload();
|
||||
|
||||
self.transaction_modified();
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
self.invalidate_import_export(network_path);
|
||||
self.load_structure();
|
||||
}
|
||||
|
||||
@@ -1,231 +0,0 @@
|
||||
//! 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. }
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
use super::*;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
|
||||
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
|
||||
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
|
||||
@@ -829,17 +826,27 @@ impl NodeNetworkInterface {
|
||||
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
|
||||
}
|
||||
|
||||
/// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph.
|
||||
/// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
||||
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
|
||||
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
|
||||
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
|
||||
}
|
||||
|
||||
node_metadata
|
||||
.get(proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(index))
|
||||
.is_some_and(|field| field.internal)
|
||||
/// The metadata the node macro records for a proto node's parameter, or the `#[graph]` macro for a graph node's import.
|
||||
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
|
||||
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
|
||||
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
|
||||
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
|
||||
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
|
||||
}
|
||||
|
||||
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
|
||||
return None;
|
||||
};
|
||||
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
|
||||
|
||||
let graphs = graphene_std::registry::GRAPH_METADATA.lock().ok()?;
|
||||
let field = graphs.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
|
||||
(field.name == input_name).then(|| field.clone())
|
||||
}
|
||||
|
||||
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
|
||||
@@ -1079,7 +1086,7 @@ impl NodeNetworkInterface {
|
||||
/// Whether the artboard layer clips the content inside it to its bounds.
|
||||
fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool {
|
||||
self.document_node(&artboard.to_node(), &[])
|
||||
.and_then(|artboard| artboard.inputs.get(ARTBOARD_CLIP_INPUT_INDEX))
|
||||
.and_then(|artboard| artboard.inputs.get(graphene_std::subgraphs::artboard::ClipInput::INDEX))
|
||||
.is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true)))
|
||||
}
|
||||
|
||||
|
||||
@@ -328,10 +328,7 @@ fn field_deltas(
|
||||
}
|
||||
|
||||
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
||||
deltas.push(metadata(NodeMetadataChange::placement(
|
||||
¤t_metadata.node_type_metadata,
|
||||
target_metadata.node_type_metadata.clone(),
|
||||
)));
|
||||
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
|
||||
}
|
||||
if current_metadata.display_name != target_metadata.display_name {
|
||||
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
||||
|
||||
+6
-7
@@ -229,14 +229,13 @@ impl NodeMut<'_> {
|
||||
|
||||
/// 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 {
|
||||
if self.metadata.node_type_metadata == node_type {
|
||||
return false;
|
||||
}
|
||||
|
||||
let change = NodeMetadataChange::placement(&self.metadata.node_type_metadata, node_type.clone());
|
||||
let changed = self.metadata.node_type_metadata != node_type;
|
||||
self.metadata.node_type_metadata = node_type;
|
||||
self.deltas.metadata(change);
|
||||
true
|
||||
if changed {
|
||||
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.
|
||||
|
||||
@@ -200,11 +200,10 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||
}
|
||||
|
||||
/// 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>, new_layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>) {
|
||||
/// Update how far each layer's effects paint past its content.
|
||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
|
||||
self.document_metadata.mark_changed();
|
||||
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
||||
self.document_metadata.layer_effects_frames = new_layer_effects_frames;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,12 @@ use graphene_std::ParameterRef;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||
|
||||
/// An axis-aligned rectangle spanning the two opposite corners, with per-corner radii ordered top left, top right, bottom right, bottom left.
|
||||
/// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets.
|
||||
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 {
|
||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||
if radii.iter().all(|radius| *radius == 0.) {
|
||||
@@ -14,6 +19,16 @@ 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)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ChainNodeCopy {
|
||||
@@ -277,6 +292,13 @@ 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)]
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
const CORNER_RADIUS: f64 = 4.;
|
||||
|
||||
@@ -310,6 +332,13 @@ 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)> {
|
||||
self.input_ports.iter()
|
||||
}
|
||||
@@ -319,15 +348,51 @@ impl Ports {
|
||||
}
|
||||
|
||||
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
||||
self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true))));
|
||||
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true)));
|
||||
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) {
|
||||
self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false))));
|
||||
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false)));
|
||||
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> {
|
||||
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||
}
|
||||
@@ -336,12 +401,37 @@ impl Ports {
|
||||
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> {
|
||||
self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
||||
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||
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> {
|
||||
self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
||||
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||
return Some(*anchor);
|
||||
}
|
||||
self.output_ports
|
||||
.iter()
|
||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -657,12 +747,16 @@ impl<T> TransientCache<T> {
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct NodeNetworkTransientMetadata {
|
||||
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
|
||||
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
|
||||
pub(crate) layout: TransientCache<NetworkLayout>,
|
||||
pub(crate) drag: Option<super::layout_pass::DragPreview>,
|
||||
/// The import and export connector click targets, with the generation of the layout they were placed by.
|
||||
pub(crate) import_export_ports: TransientCache<(u64, Ports)>,
|
||||
/// All export connector click targets
|
||||
pub(crate) import_export_ports: TransientCache<Ports>,
|
||||
|
||||
/// 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>,
|
||||
@@ -773,51 +867,11 @@ impl PartialEq for DocumentNodeMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NumberInputSettings {
|
||||
pub unit: Option<String>,
|
||||
pub min: Option<f64>,
|
||||
pub max: Option<f64>,
|
||||
pub step: Option<f64>,
|
||||
pub mode: NumberInputMode,
|
||||
pub range_min: Option<f64>,
|
||||
pub range_max: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for NumberInputSettings {
|
||||
fn default() -> Self {
|
||||
NumberInputSettings {
|
||||
unit: None,
|
||||
min: None,
|
||||
max: None,
|
||||
step: None,
|
||||
mode: NumberInputMode::default(),
|
||||
range_min: None,
|
||||
range_max: None,
|
||||
is_integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Vec2InputSettings {
|
||||
pub x: String,
|
||||
pub y: String,
|
||||
pub unit: String,
|
||||
pub min: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub enum WidgetOverride {
|
||||
None,
|
||||
Hidden,
|
||||
String(String),
|
||||
Number(NumberInputSettings),
|
||||
Vec2(Vec2InputSettings),
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
@@ -854,40 +908,6 @@ impl InputPersistentMetadata {
|
||||
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
|
||||
self.widget_override = Some("string".to_string());
|
||||
}
|
||||
WidgetOverride::Number(mut number_inspector) => {
|
||||
if let Some(unit) = number_inspector.unit.take() {
|
||||
self.input_data.insert("unit".to_string(), json!(unit));
|
||||
}
|
||||
if let Some(min) = number_inspector.min.take() {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
if let Some(max) = number_inspector.max.take() {
|
||||
self.input_data.insert("max".to_string(), json!(max));
|
||||
}
|
||||
if let Some(step) = number_inspector.step.take() {
|
||||
self.input_data.insert("step".to_string(), json!(step));
|
||||
}
|
||||
if let Some(range_min) = number_inspector.range_min.take() {
|
||||
self.input_data.insert("range_min".to_string(), json!(range_min));
|
||||
}
|
||||
if let Some(range_max) = number_inspector.range_max.take() {
|
||||
self.input_data.insert("range_max".to_string(), json!(range_max));
|
||||
}
|
||||
self.input_data.insert("mode".to_string(), json!(number_inspector.mode));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(number_inspector.is_integer));
|
||||
self.input_data.insert("blank_assist".to_string(), Value::Bool(number_inspector.blank_assist));
|
||||
self.widget_override = Some("number".to_string());
|
||||
}
|
||||
WidgetOverride::Vec2(vec2_inspector) => {
|
||||
self.input_data.insert("x".to_string(), json!(vec2_inspector.x));
|
||||
self.input_data.insert("y".to_string(), json!(vec2_inspector.y));
|
||||
self.input_data.insert("unit".to_string(), json!(vec2_inspector.unit));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_inspector.is_integer));
|
||||
if let Some(min) = vec2_inspector.min {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
self.widget_override = Some("vec2".to_string());
|
||||
}
|
||||
WidgetOverride::Custom(lambda_name) => {
|
||||
self.widget_override = Some(lambda_name);
|
||||
}
|
||||
@@ -1079,8 +1099,40 @@ 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.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct DocumentNodeTransientMetadata {
|
||||
/// 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, f64)>,
|
||||
/// 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.
|
||||
pub(crate) layer_width: TransientCache<u32>,
|
||||
}
|
||||
|
||||
#[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)]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
|
||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
|
||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, Point, Shape};
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
@@ -125,27 +125,23 @@ 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
|
||||
}
|
||||
|
||||
/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the
|
||||
/// 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, graph_wire_style: GraphWireStyle) -> BezPath {
|
||||
/// The center line that cleaves a thick layer-stack wire. Its ends reach past the wire (1.5px toward the 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 {
|
||||
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
|
||||
return BezPath::new();
|
||||
}
|
||||
|
||||
let wire = build_vector_wire(output_position, input_position, true, true, graph_wire_style);
|
||||
let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else {
|
||||
return BezPath::new();
|
||||
};
|
||||
|
||||
// The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead
|
||||
// The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots
|
||||
let sign = (input_position.y - output_position.y).signum();
|
||||
let output_trim = 1.5;
|
||||
let input_trim = 1.;
|
||||
let start = output_position + DVec2::new(0., output_trim * sign);
|
||||
let end = input_position - DVec2::new(0., input_trim * sign);
|
||||
|
||||
let mut center_line = BezPath::new();
|
||||
center_line.move_to(start - Vec2::new(0., 1.5 * sign));
|
||||
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.move_to(dvec2_to_point(start));
|
||||
center_line.line_to(dvec2_to_point(end));
|
||||
center_line
|
||||
}
|
||||
|
||||
@@ -584,7 +580,7 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use kurbo::{Affine, ParamCurveNearest};
|
||||
use kurbo::{Affine, Vec2};
|
||||
|
||||
#[test]
|
||||
fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() {
|
||||
@@ -607,30 +603,4 @@ 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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -472,9 +472,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
|
||||
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
// Old references (including these older aliases) are remapped here to `vec2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::vec2_value::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_math_nodes::Vec2ValueNode",
|
||||
"graphene_core::ops::ConstructVector2",
|
||||
@@ -484,7 +484,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER,
|
||||
aliases: &["math_nodes::CombineVec2Node"],
|
||||
},
|
||||
// ================================
|
||||
@@ -1576,8 +1576,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||
let split_wrapper_replacements = [
|
||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vec2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||
];
|
||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||
@@ -1641,7 +1641,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
|
||||
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
|
||||
if EXTRACT_XY.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||
} else {
|
||||
@@ -1901,13 +1901,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
continue;
|
||||
};
|
||||
|
||||
// The primary input comes before the Clip toggle where there is one, and the noise settings follow it in the current inputs' order
|
||||
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
|
||||
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() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
|
||||
}
|
||||
@@ -1919,11 +1914,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
|
||||
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,
|
||||
@@ -1996,9 +1986,6 @@ fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
|
||||
.cloned()
|
||||
.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 template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
|
||||
@@ -2100,48 +2087,6 @@ fn move_mandelbrot_to_old_origin(document: &mut DocumentMessageHandler, mandelbr
|
||||
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.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -2911,8 +2856,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
|
||||
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER);
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER);
|
||||
let mut node_template = resolve_document_node_type(&numbers_to_vec2_reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
@@ -5198,7 +5143,11 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node");
|
||||
let (&count_conversion_id, count_conversion) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. })))
|
||||
.expect("Blend should have a count conversion node");
|
||||
count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
|
||||
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
@@ -5215,7 +5164,7 @@ mod tests {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Blend", NodeId(3))].implementation,
|
||||
inner.nodes[&shipped_node_id("Blend", count_conversion_id)].implementation,
|
||||
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
|
||||
);
|
||||
}
|
||||
@@ -5232,7 +5181,11 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
|
||||
let (&edited_subtract_id, edited_subtract) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER))
|
||||
.expect("Blend should have an open-path denominator node");
|
||||
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
@@ -5242,7 +5195,7 @@ mod tests {
|
||||
let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
let edited_subtract = derived_node_id(*definition, NodeId(5));
|
||||
let edited_subtract = derived_node_id(*definition, edited_subtract_id);
|
||||
assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
|
||||
}
|
||||
|
||||
@@ -5324,8 +5277,15 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Regex Find should be a network node")
|
||||
};
|
||||
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
let inner_node_id = |identifier: graphene_std::ProtoNodeIdentifier| {
|
||||
let implementation = NodeTemplateImplementation::ProtoNode(identifier);
|
||||
network_template.nodes.iter().find(|(_, node)| node.implementation == implementation).map(|(&id, _)| id)
|
||||
};
|
||||
let find_id = inner_node_id(graphene_std::text_nodes::regex::regex_find::IDENTIFIER).expect("Regex Find should have a find node");
|
||||
let item_at_index_id = inner_node_id(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Regex Find should have an item-at-index node");
|
||||
|
||||
network_template.nodes.get_mut(&find_id).expect("the find node should exist").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&item_at_index_id).expect("the item-at-index node should exist").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
migrate(&mut document);
|
||||
@@ -5339,9 +5299,9 @@ mod tests {
|
||||
let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else {
|
||||
panic!("Regex Find should stay a network node")
|
||||
};
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", NodeId(0))].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", find_id)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Regex Find", NodeId(1))].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
inner.nodes[&shipped_node_id("Regex Find", item_at_index_id)].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::Integer(0))
|
||||
);
|
||||
}
|
||||
@@ -6466,9 +6426,6 @@ mod tests {
|
||||
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");
|
||||
}
|
||||
if pattern == noise {
|
||||
read = upstream(read, 0).expect("the Gamma Correction should read the pattern");
|
||||
}
|
||||
assert_eq!(read, pattern);
|
||||
}
|
||||
|
||||
@@ -6482,130 +6439,6 @@ 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
|
||||
#[tokio::test]
|
||||
async fn marbled_mandelbrot_renders_after_migration() {
|
||||
|
||||
@@ -27,7 +27,7 @@ mod recompile_tests;
|
||||
mod runtime;
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ExecutionRequest {
|
||||
execution_id: u64,
|
||||
render_config: RenderConfig,
|
||||
@@ -41,15 +41,6 @@ pub struct ExecutionResponse {
|
||||
dropped_thumbnails: Vec<NodeId>,
|
||||
/// The latest result of each observation.
|
||||
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.
|
||||
@@ -201,6 +192,18 @@ impl NodeGraphExecutor {
|
||||
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.
|
||||
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
|
||||
let execution_id = self.current_execution_id;
|
||||
@@ -250,6 +253,29 @@ impl NodeGraphExecutor {
|
||||
.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.
|
||||
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;
|
||||
@@ -501,8 +527,6 @@ impl NodeGraphExecutor {
|
||||
responses: existing_responses,
|
||||
dropped_thumbnails,
|
||||
mut observations,
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info,
|
||||
} = *execution_response;
|
||||
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
|
||||
|
||||
@@ -545,29 +569,6 @@ impl NodeGraphExecutor {
|
||||
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);
|
||||
|
||||
// A pending graph keeps the last frame, and the errors shown with it
|
||||
@@ -1035,6 +1036,11 @@ impl NodeGraphExecutor {
|
||||
responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use });
|
||||
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::Buffer { width, height, .. } => {
|
||||
log::error!("Invalid node graph output type: a {width}×{height} pixel buffer");
|
||||
@@ -1055,7 +1061,6 @@ impl NodeGraphExecutor {
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
effects_reach,
|
||||
effects_frames,
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
@@ -1072,7 +1077,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach, effects_frames });
|
||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
@@ -1200,6 +1205,15 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
||||
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.
|
||||
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
||||
DialogMessage::DisplayDialogError {
|
||||
@@ -1254,40 +1268,6 @@ mod test {
|
||||
use graphene_std::list::Item;
|
||||
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.
|
||||
#[derive(Default)]
|
||||
pub struct Instrumented {
|
||||
|
||||
@@ -20,7 +20,7 @@ use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Context, NodeError, Poll};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use observer::Observer;
|
||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||
use std::sync::Arc;
|
||||
@@ -94,7 +94,7 @@ enum ViewportArtwork {
|
||||
}
|
||||
|
||||
/// Messages passed from the editor thread to the node runtime thread.
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum GraphRuntimeRequest {
|
||||
GraphUpdate(GraphUpdate),
|
||||
ExecutionRequest(ExecutionRequest),
|
||||
@@ -114,7 +114,7 @@ pub enum GraphRuntimeRequest {
|
||||
RenderOverlays(OverlayContext),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GraphUpdate {
|
||||
pub(super) network: NodeNetwork,
|
||||
pub(super) resources: ResourceRegistry,
|
||||
@@ -302,7 +302,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
if let Some(viewport) = viewport {
|
||||
self.run_viewport(viewport).await;
|
||||
texture = self.run_viewport(viewport).await;
|
||||
}
|
||||
|
||||
// Overlays that changed without new artwork are drawn over the artwork already shown
|
||||
@@ -315,27 +315,63 @@ impl NodeRuntime {
|
||||
texture
|
||||
}
|
||||
|
||||
async fn run_viewport(&mut self, request: ExecutionRequest) {
|
||||
async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> {
|
||||
self.thumbnails.set_scale(request.render_config.scale);
|
||||
|
||||
let Some(mut result) = self.evaluate(request) else { return };
|
||||
let mut result = self.evaluate(request)?;
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
|
||||
if let Some(RenderOutput { data, metadata }) = result.render_output() {
|
||||
let content = match data {
|
||||
RenderOutputType::Texture(texture) => Some(ViewportArtwork::Texture(texture.clone())),
|
||||
RenderOutputType::Svg { .. } if request.render_config.export_format == ExportFormat::Raster => Some(ViewportArtwork::Svg),
|
||||
_ => None,
|
||||
};
|
||||
if content.is_some() {
|
||||
self.viewport_artwork = content;
|
||||
let path_contents = path_contents(&observations);
|
||||
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
|
||||
self.overlays_stale = true;
|
||||
}
|
||||
}
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
let resolution = request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale;
|
||||
|
||||
self.respond(request, result, observations).await;
|
||||
let texture = if let Some(RenderOutput { data, metadata }) = result.render_output()
|
||||
&& let RenderOutputType::Texture(texture) = data
|
||||
{
|
||||
self.viewport_artwork = Some(ViewportArtwork::Texture(texture.clone()));
|
||||
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"))]
|
||||
{
|
||||
*data = RenderOutputType::CanvasFrame {
|
||||
canvas_id: self.wasm_canvas_cache.id(),
|
||||
resolution,
|
||||
};
|
||||
}
|
||||
|
||||
frame
|
||||
} 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.
|
||||
@@ -395,7 +431,7 @@ impl NodeRuntime {
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
}
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.respond(request, result, observations).await;
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
}
|
||||
|
||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||
@@ -429,7 +465,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) {
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.output.node(), &context))) {
|
||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||
@@ -439,7 +475,7 @@ impl NodeRuntime {
|
||||
ExecutionResult::Fallback(value, 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.to_string()).error()), NodeErrorTrace::default())]))),
|
||||
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error).error()), NodeErrorTrace::default())]))),
|
||||
Err(payload) => {
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
@@ -447,8 +483,6 @@ impl NodeRuntime {
|
||||
responses: VecDeque::new(),
|
||||
dropped_thumbnails: Vec::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");
|
||||
return None;
|
||||
@@ -457,37 +491,18 @@ impl NodeRuntime {
|
||||
Some(result)
|
||||
}
|
||||
|
||||
async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
||||
async fn respond(&mut self, execution_id: u64, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
||||
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
|
||||
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 {
|
||||
execution_id: request.execution_id,
|
||||
execution_id,
|
||||
result,
|
||||
responses,
|
||||
dropped_thumbnails,
|
||||
observations,
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info,
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
}
|
||||
@@ -507,7 +522,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||
let mut scoped_network = wrap_network_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)) {
|
||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||
@@ -571,7 +586,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
impl ExecutionResult {
|
||||
pub(super) fn render_output(&mut self) -> Option<&mut RenderOutput> {
|
||||
fn render_output(&mut self) -> Option<&mut RenderOutput> {
|
||||
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -398,7 +398,8 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeTemplateImplementation, shipped_node_id};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -429,8 +430,20 @@ mod tests {
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
// The node adding Merge's content to the stack
|
||||
let Some(NodeTemplateImplementation::Network(merge_network)) = resolve_network_node_type("Merge").map(|merge| &merge.node_template.implementation) else {
|
||||
panic!("Merge should be a network node")
|
||||
};
|
||||
let Some((&extend_id, _)) = merge_network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER))
|
||||
else {
|
||||
panic!("Merge should extend the stack with its content")
|
||||
};
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", extend_id))]);
|
||||
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
|
||||
assert_eq!(
|
||||
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
||||
|
||||
@@ -520,18 +520,14 @@ fn init_test_logger() {
|
||||
});
|
||||
}
|
||||
|
||||
/// The GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
|
||||
/// 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.
|
||||
/// Panics if no adapter is found, since tests render on the GPU like the app does.
|
||||
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());
|
||||
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).",
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates application IO with the GPU executor every test shares (see [`gpu_executor`]).
|
||||
fn gpu_application_io() -> PlatformApplicationIo {
|
||||
PlatformApplicationIo::new_with_executor(gpu_executor())
|
||||
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(
|
||||
"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)
|
||||
}
|
||||
|
||||
/// Runs `operation`, returning its result along with the errors it logged.
|
||||
|
||||
@@ -538,6 +538,30 @@
|
||||
</div>
|
||||
{/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 -->
|
||||
<div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
|
||||
<svg>
|
||||
@@ -1287,6 +1311,46 @@
|
||||
}
|
||||
}
|
||||
|
||||
.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 {
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Writable } from "svelte/store";
|
||||
import type { IconName } from "/src/icons";
|
||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import type { MessageBody } from "/src/subscriptions-router";
|
||||
import type { NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { NodeGraphErrorDiagnostic, BoxSelection, FrontendClickTargets, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
|
||||
|
||||
@@ -13,6 +13,7 @@ export type ThumbnailCanvases = { layersPanelCanvasId: number; nodeGraphCanvasId
|
||||
|
||||
type NodeGraphStoreState = {
|
||||
box: BoxSelection | undefined;
|
||||
clickTargets: FrontendClickTargets | undefined;
|
||||
contextMenuInformation: ContextMenuInformation | undefined;
|
||||
errors: NodeGraphErrorDiagnostic[];
|
||||
layerWidths: Map<bigint, number>;
|
||||
@@ -35,6 +36,7 @@ type NodeGraphStoreState = {
|
||||
};
|
||||
const initialState: NodeGraphStoreState = {
|
||||
box: undefined,
|
||||
clickTargets: undefined,
|
||||
contextMenuInformation: undefined,
|
||||
errors: [],
|
||||
layerWidths: new Map(),
|
||||
@@ -134,6 +136,13 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateClickTargets", (data) => {
|
||||
update((state) => {
|
||||
state.clickTargets = data.clickTargets;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => {
|
||||
update((state) => {
|
||||
state.contextMenuInformation = data.contextMenuInformation;
|
||||
@@ -321,6 +330,7 @@ export function destroyNodeGraphStore() {
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateBox");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateClickTargets");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex");
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::mover::Mover;
|
||||
use crate::graph::LAYER_BOTTOM_GAP;
|
||||
use crate::per_node::PerNode;
|
||||
use crate::{NodeIndex, Placement};
|
||||
use glam::IVec2;
|
||||
use std::mem;
|
||||
|
||||
pub(super) struct Snapshot {
|
||||
placements: PerNode<Placement>,
|
||||
@@ -16,85 +16,38 @@ impl Mover {
|
||||
Snapshot { placements, positions }
|
||||
}
|
||||
|
||||
pub(super) fn restore_followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) {
|
||||
let followers = self.followers(before, kept);
|
||||
let mut pushed = PerNode::filled(&self.graph, None);
|
||||
for node in followers.indices().filter(|node| followers[*node]) {
|
||||
self.restore_follower(node, &followers, &before.positions, &mut pushed);
|
||||
}
|
||||
pub(super) fn restore_followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) {
|
||||
let followers = self.followers(before, moved);
|
||||
let mut restored = PerNode::filled(&self.graph, false);
|
||||
followers
|
||||
.indices()
|
||||
.filter(|node| followers[*node])
|
||||
.for_each(|node| self.restore_follower(node, &followers, &before.positions, &mut restored));
|
||||
}
|
||||
|
||||
fn followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) -> PerNode<bool> {
|
||||
fn followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) -> PerNode<bool> {
|
||||
let (graph, layout) = self.graph_and_layout();
|
||||
PerNode::from_fn(graph, |node| {
|
||||
let placement = graph[node].placement;
|
||||
let unchanged = placement == before.placements[node];
|
||||
let was_relative = matches!(before.placements[node], Placement::Relative(_));
|
||||
let is_relative = matches!(placement, Placement::Relative(_));
|
||||
kept[node] && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node]
|
||||
!moved.contains(&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>, pushed: &mut PerNode<Option<IVec2>>) -> IVec2 {
|
||||
if let Some(push) = pushed[node] {
|
||||
return push;
|
||||
fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, restored: &mut PerNode<bool>) {
|
||||
if mem::replace(&mut restored[node], true) {
|
||||
return;
|
||||
}
|
||||
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 pushed_by_readers = following_readers
|
||||
.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;
|
||||
}
|
||||
for reader in following_readers {
|
||||
self.restore_follower(reader, followers, positions_before, restored);
|
||||
}
|
||||
|
||||
let shift = positions_before[node] - self.position(node);
|
||||
let shifted = self.graph[node].placement.shifted(shift);
|
||||
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)))
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
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,12 +1,10 @@
|
||||
mod followers;
|
||||
mod kept;
|
||||
mod mover;
|
||||
mod shift;
|
||||
mod stack;
|
||||
|
||||
use crate::{Graph, Layout, NodeIndex, Placement};
|
||||
use glam::IVec2;
|
||||
use kept::UpstreamOfDragged;
|
||||
use mover::Mover;
|
||||
|
||||
/// Nodes dragged from where they are drawn, computing the graph for any offset from the start alone.
|
||||
@@ -14,7 +12,7 @@ use mover::Mover;
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Drag {
|
||||
dragged: Vec<NodeIndex>,
|
||||
upstream: Option<UpstreamOfDragged>,
|
||||
keep_upstream: bool,
|
||||
rows_up: Vec<Graph>,
|
||||
held_in_place: Vec<HeldInPlace>,
|
||||
}
|
||||
@@ -28,11 +26,8 @@ struct HeldInPlace {
|
||||
|
||||
impl Drag {
|
||||
/// 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]
|
||||
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 mut mover = Mover::new(start, Some(start_layout));
|
||||
mover.hold(&dragged);
|
||||
@@ -50,7 +45,7 @@ impl Drag {
|
||||
.collect();
|
||||
Self {
|
||||
dragged,
|
||||
upstream,
|
||||
keep_upstream,
|
||||
rows_up: vec![held],
|
||||
held_in_place,
|
||||
}
|
||||
@@ -79,7 +74,7 @@ impl Drag {
|
||||
[IVec2::new(0, offset.y.max(0)), IVec2::new(offset.x, 0)]
|
||||
.into_iter()
|
||||
.filter(|shift| *shift != IVec2::ZERO)
|
||||
.for_each(|shift| mover.shift_step(&self.dragged, shift, self.upstream.as_ref().map(|upstream| upstream.moving_by(shift))));
|
||||
.for_each(|shift| mover.shift_step(&self.dragged, shift, self.keep_upstream));
|
||||
mover.into_graph_and_layout()
|
||||
}
|
||||
|
||||
@@ -94,7 +89,7 @@ impl Drag {
|
||||
fn one_row_further_up(&self) -> Graph {
|
||||
let highest_so_far = self.rows_up.last().cloned().unwrap_or_default();
|
||||
let mut mover = Mover::new(highest_so_far, None);
|
||||
mover.shift_step(&self.dragged, IVec2::NEG_Y, self.upstream.as_ref().map(|upstream| upstream.moving_by(IVec2::NEG_Y)));
|
||||
mover.shift_step(&self.dragged, IVec2::NEG_Y, self.keep_upstream);
|
||||
mover.into_graph()
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,27 @@
|
||||
use super::kept::Upstream;
|
||||
use super::mover::Mover;
|
||||
use crate::NodeIndex;
|
||||
use glam::IVec2;
|
||||
|
||||
impl Mover {
|
||||
pub(super) fn shift_step(&mut self, dragged: &[NodeIndex], shift: IVec2, upstream: Option<&Upstream>) {
|
||||
let before = upstream.map(|upstream| (self.snapshot(), upstream));
|
||||
self.shift_nodes(dragged, shift);
|
||||
if let Some((before, upstream)) = before {
|
||||
self.restore_followers(&before, &upstream.kept);
|
||||
self.carry_along(&before, &upstream.carried);
|
||||
pub(super) fn shift_step(&mut self, dragged: &[NodeIndex], shift: IVec2, keep_upstream: bool) {
|
||||
let before = keep_upstream.then(|| self.snapshot());
|
||||
let shifted = self.shift_nodes(dragged, shift);
|
||||
if let Some(before) = before {
|
||||
let moved: Vec<NodeIndex> = dragged.iter().chain(&shifted).copied().collect();
|
||||
self.restore_followers(&before, &moved);
|
||||
}
|
||||
}
|
||||
|
||||
fn shift_nodes(&mut self, nodes: &[NodeIndex], shift: IVec2) {
|
||||
fn shift_nodes(&mut self, nodes: &[NodeIndex], shift: IVec2) -> Vec<NodeIndex> {
|
||||
let mut shifted = Vec::new();
|
||||
for node in self.moving_on_their_own(nodes) {
|
||||
self.shift_node(node, shift, &mut shifted);
|
||||
}
|
||||
shifted
|
||||
}
|
||||
|
||||
fn shift_node(&mut self, node: NodeIndex, shift: IVec2, shifted: &mut Vec<NodeIndex>) {
|
||||
let Some(moving) = self.node_moving_for(node, shift) else { return };
|
||||
let moving = self.node_moving_for(node, shift);
|
||||
if shifted.contains(&moving) {
|
||||
return;
|
||||
}
|
||||
@@ -34,12 +34,12 @@ impl Mover {
|
||||
self.place_at(moving, position + shift);
|
||||
}
|
||||
|
||||
fn node_moving_for(&mut self, node: NodeIndex, shift: IVec2) -> Option<NodeIndex> {
|
||||
fn node_moving_for(&mut self, node: NodeIndex, shift: IVec2) -> NodeIndex {
|
||||
let (stack, layout) = self.stack_and_layout();
|
||||
match shift {
|
||||
IVec2 { x: 0, y: -1 } => stack.lowest_layer_with_room_above(layout, node),
|
||||
IVec2 { x: 0, .. } => Some(node),
|
||||
_ => Some(stack.top(node)),
|
||||
IVec2 { x: 0, .. } => node,
|
||||
_ => stack.top(node),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,18 +14,8 @@ impl Stack<'_> {
|
||||
self.climb(node, |layer| self.layer_above(layer))
|
||||
}
|
||||
|
||||
pub(super) fn lowest_layer_with_room_above(&self, layout: &Layout, node: NodeIndex) -> Option<NodeIndex> {
|
||||
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))
|
||||
pub(super) fn lowest_layer_with_room_above(&self, layout: &Layout, node: NodeIndex) -> NodeIndex {
|
||||
self.climb(node, |layer| self.layer_above(layer).filter(|above| self.closed_up(layout, layer, *above)))
|
||||
}
|
||||
|
||||
fn closed_up(&self, layout: &Layout, layer: NodeIndex, above: NodeIndex) -> bool {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
mod common;
|
||||
|
||||
use common::{CHAINED, at, layer, node, stacked, wire};
|
||||
use common::{at, layer, stacked, wire};
|
||||
use glam::IVec2;
|
||||
use graph_layout::{Drag, Graph, Layout, Placement};
|
||||
|
||||
@@ -73,148 +73,3 @@ 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(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()
|
||||
);
|
||||
}
|
||||
+24
-2
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
|
||||
}
|
||||
```
|
||||
|
||||
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`.
|
||||
None of these definitions are written by hand. 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`. A built-in node made from a subgraph has its definition generated from the `graph` macro (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
|
||||
|
||||
## Inspector
|
||||
|
||||
@@ -127,7 +127,29 @@ fn opacity<T>(
|
||||
|
||||
## Additional Macro Options
|
||||
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `unit`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, while `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `step`, `display_decimal_places`, `unit`, `integer`, `labels`, `blank_assist`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, `#[display_decimal_places(2)]` sets how many decimal places a number's widget shows, `#[integer]` makes a number or Vec2 widget take only integers, `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[blank_assist(false)]` drops the space a widget leaves for its assist area. `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
|
||||
## Creating a node from a subgraph
|
||||
|
||||
A node built from other nodes uses the `graph` macro, which registers the subgraph as a catalog definition. It takes `category`, `icon`, `name`, and `version` as `node` does, plus `layer` for a node that starts as a layer. Unlike a proto node's, a graph's name (or the title derived from its function name) is also its catalog identifier, which documents store. The function's parameters are the subgraph's imports, which are parsed like a proto node's parameters and take the same value and widget attributes. On an import, `#[hard]` bounds the Inspector widget without clamping a value wired into it. `out!(...)` names the exports. In the body, `>>` feeds its left side into the primary input of the node on its right, every other parameter is named in the call, and a bare name feeds the binding or import of that name into the parameter of the same name. State methods after a call, each written once, set the node's position in grid units (`.at(x, y)`), its display name (`.named("…")`), its flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`), and its call argument (`.call_argument::<Footprint>()`, or `impl Any` for a generic one). An output's name after the call or a binding, like `.captures`, wires from that output instead of the primary one, and goes after any state methods. The body ends with one value per export, as a final expression or with `return`. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
|
||||
|
||||
```rs
|
||||
/// Loads an image from a given URL.
|
||||
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
|
||||
pub fn load_image(
|
||||
_: (),
|
||||
/// The web address or local asset path of the image to load.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
) -> out!(
|
||||
/// The loaded image.
|
||||
image,
|
||||
) {
|
||||
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
|
||||
}
|
||||
```
|
||||
|
||||
Each node, parameter, and output name resolves through the module the `node` or `graph` macro generates for that node, named after its function, so a misspelled one is reported where it's written. The module's `PARAMETER_COUNT` lets the macro reject `>>` into a node with no parameters. Proto nodes don't name their outputs in that module, so only a graph's outputs can be chosen by name. Every input a call leaves out keeps the default from the node's own definition.
|
||||
|
||||
## Executing a document `NodeNetwork`
|
||||
|
||||
|
||||
@@ -542,15 +542,9 @@ tagged_value! {
|
||||
GlowTechnique(graphic_types::GlowTechnique),
|
||||
GlowSource(graphic_types::GlowSource),
|
||||
MaskMode(graphic_types::MaskMode),
|
||||
MinimumMaximumMode(graphic_types::MinimumMaximumMode),
|
||||
BevelStyle(graphic_types::BevelStyle),
|
||||
BevelDirection(graphic_types::BevelDirection),
|
||||
BevelTechnique(graphic_types::BevelTechnique),
|
||||
NoiseDistribution(graphic_types::NoiseDistribution),
|
||||
RadialBlurMethod(graphic_types::RadialBlurMethod),
|
||||
EnvelopeStyle(graphic_types::EnvelopeStyle),
|
||||
WaveType(graphic_types::WaveType),
|
||||
DisplaceMode(graphic_types::DisplaceMode),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -685,24 +679,18 @@ impl TaggedValue {
|
||||
None
|
||||
}
|
||||
|
||||
// The Inspector's X, Y, W, H (e.g. "0., 0., 1000., 1000."), as a transform's translation and scale
|
||||
fn to_daffine2(input: &str) -> Option<DAffine2> {
|
||||
// The Inspector's X, Y, W, H (e.g. "0., 0., 1000., 1000."), rendered at 100% resolution
|
||||
fn to_footprint(input: &str) -> Option<Footprint> {
|
||||
let values: Option<Vec<f64>> = input.split(',').map(to_number).collect();
|
||||
let Some(&[x, y, width, height]) = values.as_deref() else {
|
||||
log::error!("Invalid default, which needs X, Y, W, H: {input}");
|
||||
log::error!("Invalid Footprint default, which needs X, Y, W, H: {input}");
|
||||
return None;
|
||||
};
|
||||
|
||||
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)?;
|
||||
let size = DVec2::new(width, height);
|
||||
|
||||
Some(Footprint {
|
||||
transform,
|
||||
resolution: transform.matrix2.diagonal().as_uvec2(),
|
||||
transform: DAffine2::from_scale_angle_translation(size, 0., DVec2::new(x, y)),
|
||||
resolution: size.as_uvec2(),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
@@ -726,22 +714,6 @@ impl TaggedValue {
|
||||
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> {
|
||||
use core_types::blending::BlendMode;
|
||||
|
||||
@@ -775,7 +747,6 @@ impl TaggedValue {
|
||||
() 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::<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::<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
|
||||
@@ -785,7 +756,6 @@ impl TaggedValue {
|
||||
() 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::<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::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
_ => {
|
||||
@@ -1004,6 +974,8 @@ pub enum RenderOutputType {
|
||||
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
|
||||
image_data: Vec<(u64, CanvasImage)>,
|
||||
},
|
||||
#[cfg(target_family = "wasm")]
|
||||
CanvasFrame { canvas_id: u64, resolution: DVec2 },
|
||||
}
|
||||
|
||||
impl CacheHash for RenderOutputType {
|
||||
@@ -1020,6 +992,11 @@ impl CacheHash for RenderOutputType {
|
||||
svg.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1151,13 +1128,6 @@ mod number_default_parsing {
|
||||
);
|
||||
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)]
|
||||
|
||||
@@ -14,7 +14,7 @@ use graphene_std::application_io::ApplicationIo;
|
||||
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
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.
|
||||
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);
|
||||
let mut network = wrap_network_with_render_node_in_scope(network, editor_api, runtime);
|
||||
let mut network = wrap_network_in_scope(network, editor_api, runtime);
|
||||
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
let preprocessed = match gdd {
|
||||
|
||||
@@ -5,7 +5,7 @@ use graph_craft::util::{DEMO_ART, compile};
|
||||
use graphene_std::application_io::EditorApi;
|
||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::path::Path;
|
||||
|
||||
pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork) {
|
||||
@@ -13,7 +13,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
|
||||
.unwrap()
|
||||
.network;
|
||||
let editor_api = std::sync::Arc::new(EditorApi::default());
|
||||
let mut network = wrap_network_with_render_node_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
||||
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
|
||||
@@ -21,7 +21,7 @@ use graphene_std::{Color, Context};
|
||||
use gungraun::prelude::*;
|
||||
use gungraun::{Callgrind, EntryPoint};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::hint::black_box;
|
||||
use std::sync::Arc;
|
||||
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.
|
||||
fn update(&mut self, document: NodeNetwork) {
|
||||
let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||
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;
|
||||
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
|
||||
|
||||
@@ -5,7 +5,6 @@ use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::RenderOutput;
|
||||
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphene_std::EnvelopeStyle;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::Stroke;
|
||||
@@ -29,8 +28,7 @@ use graphene_std::vector::misc::{
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -294,15 +292,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
GlowTechnique,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
NoiseDistribution,
|
||||
RadialBlurMethod,
|
||||
EnvelopeStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
|
||||
@@ -9,7 +9,7 @@ use graphene_std::RuntimeHandle;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn wrap_network_with_render_node_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
||||
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 {
|
||||
@@ -114,28 +114,10 @@ pub fn wrap_network_with_render_node_in_scope(mut network: NodeNetwork, editor_a
|
||||
..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
|
||||
let nodes = vec![
|
||||
inner_network,
|
||||
render_node,
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::EditorApi(editor_api), false)],
|
||||
@@ -148,12 +130,12 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
||||
},
|
||||
];
|
||||
let scope_injections = vec![
|
||||
("editor-api".to_string(), (NodeId(1), item!(Arc<PlatformEditorApi>))),
|
||||
("runtime".to_string(), (NodeId(2), item!(RuntimeHandle))),
|
||||
("editor-api".to_string(), (NodeId(2), item!(Arc<PlatformEditorApi>))),
|
||||
("runtime".to_string(), (NodeId(3), item!(RuntimeHandle))),
|
||||
];
|
||||
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(0), 0)],
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: nodes.into_iter().enumerate().map(|(id, node)| (NodeId(id as u64), node)).collect(),
|
||||
scope_injections: scope_injections.into_iter().collect(),
|
||||
definitions,
|
||||
|
||||
@@ -805,11 +805,6 @@ impl OwnedContextImpl {
|
||||
self.varargs = Some(Arc::new([value]));
|
||||
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 {
|
||||
self.generations = (!generations.is_empty()).then_some(generations);
|
||||
self
|
||||
|
||||
@@ -281,11 +281,11 @@ impl<'a, N> LazyInput<'a, N> {
|
||||
}
|
||||
|
||||
#[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
|
||||
N: Node<Input>,
|
||||
{
|
||||
self.status.record(self.index, self.node.eval(input))
|
||||
self.status.record(self.index, self.node.eval(&input))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,12 @@ pub struct FieldMetadata {
|
||||
pub progression: bool,
|
||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||
pub constant: bool,
|
||||
/// The X and Y labels of a Vec2 parameter's widget, from `#[labels("W", "H")]`.
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
/// Whether a number or Vec2 parameter's widget only takes integers, from `#[integer]`. Integer types always do.
|
||||
pub integer: bool,
|
||||
/// Whether the widget leaves room for the assist area beside it, which `#[blank_assist(false)]` turns off.
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -222,6 +228,167 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne
|
||||
|
||||
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// Every node defined as a subgraph by the `#[graph]` macro, in registration order.
|
||||
pub static GRAPH_METADATA: LazyLock<Mutex<Vec<GraphMetadata>>> = LazyLock::new(|| Mutex::new(Vec::new()));
|
||||
|
||||
/// A node defined as a subgraph by `#[graph]`, which the editor turns into a catalog definition alongside the proto nodes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphMetadata {
|
||||
/// The definition's identifier and display name.
|
||||
pub identifier: &'static str,
|
||||
pub category: &'static str,
|
||||
pub icon: Option<&'static str>,
|
||||
pub description: &'static str,
|
||||
/// The declaration version from `#[graph(version(N))]`, starting at 1.
|
||||
pub version: u32,
|
||||
/// Whether a new instance starts as a layer, from `#[graph(layer)]`.
|
||||
pub layer: bool,
|
||||
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
|
||||
/// Each one's `default_type` is the type it was declared with.
|
||||
pub imports: Vec<FieldMetadata>,
|
||||
pub exports: Vec<GraphExportMetadata>,
|
||||
/// The nodes inside the subgraph, where each node's position in this list is its ID.
|
||||
pub nodes: Vec<GraphNodeMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphExportMetadata {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub source: GraphInputSource,
|
||||
}
|
||||
|
||||
/// A node inside a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphNodeMetadata {
|
||||
pub implementation: GraphNodeImplementation,
|
||||
/// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition.
|
||||
pub inputs: Vec<(usize, GraphInputSource)>,
|
||||
/// The absolute position in grid units, from `.at(x, y)`.
|
||||
pub position: Option<(i32, i32)>,
|
||||
/// From `.layer()`.
|
||||
pub layer: bool,
|
||||
/// From `.named("…")`.
|
||||
pub display_name: Option<&'static str>,
|
||||
/// From `.hidden()`.
|
||||
pub hidden: bool,
|
||||
/// From `.locked()`.
|
||||
pub locked: bool,
|
||||
/// From `.pinned()`.
|
||||
pub pinned: bool,
|
||||
/// From `.call_argument::<T>()`.
|
||||
pub call_argument: Option<Type>,
|
||||
}
|
||||
|
||||
/// What a node inside a subgraph is an instance of.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GraphNodeImplementation {
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
/// Another node defined by `#[graph]`, named by its identifier.
|
||||
Graph(&'static str),
|
||||
}
|
||||
|
||||
impl From<ProtoNodeIdentifier> for GraphNodeImplementation {
|
||||
fn from(identifier: ProtoNodeIdentifier) -> Self {
|
||||
Self::ProtoNode(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for GraphNodeImplementation {
|
||||
fn from(identifier: &'static str) -> Self {
|
||||
Self::Graph(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// What feeds an input, or an export, of a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum GraphInputSource {
|
||||
/// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`].
|
||||
Node { node: usize, output: usize },
|
||||
/// One of the subgraph's imports, with the type its wire records.
|
||||
Import { index: usize, ty: Type },
|
||||
/// A value. Without an exposure, the input keeps the one from the node's own definition.
|
||||
Value { value: GraphValue, exposed: Option<bool> },
|
||||
/// A scope input, from `scope("…")`.
|
||||
Scope(&'static str),
|
||||
/// The document path of the node, from `reflect(NodePath)`.
|
||||
NodePath,
|
||||
/// The source ID of the node, from `reflect(SourceId)`.
|
||||
SourceId,
|
||||
}
|
||||
|
||||
/// A value written in a subgraph definition. The editor converts it to the type of the input it feeds.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GraphValue {
|
||||
/// A number written without a fractional part, which feeds an integer input as an integer and any other as a number.
|
||||
Integer(i64),
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
Vec2(glam::DVec2),
|
||||
Color(Color),
|
||||
}
|
||||
|
||||
impl GraphValue {
|
||||
pub fn vec2(x: f64, y: f64) -> Self {
|
||||
Self::Vec2(glam::DVec2::new(x, y))
|
||||
}
|
||||
|
||||
/// An opaque color from `rgb(0xRRGGBB)`.
|
||||
pub fn rgb(hex: u32) -> Self {
|
||||
let [_, red, green, blue] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, 255).into())
|
||||
}
|
||||
|
||||
/// A color with alpha from `rgba(0xRRGGBBAA)`.
|
||||
pub fn rgba(hex: u32) -> Self {
|
||||
let [red, green, blue, alpha] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, alpha).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for GraphValue {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::String(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for GraphValue {
|
||||
fn from(value: String) -> Self {
|
||||
Self::String(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> for GraphValue {
|
||||
fn from(value: bool) -> Self {
|
||||
Self::Bool(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f64> for GraphValue {
|
||||
fn from(value: f64) -> Self {
|
||||
Self::Number(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<i64> for GraphValue {
|
||||
fn from(value: i64) -> Self {
|
||||
Self::Integer(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<glam::DVec2> for GraphValue {
|
||||
fn from(value: glam::DVec2) -> Self {
|
||||
Self::Vec2(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Color> for GraphValue {
|
||||
fn from(value: Color) -> Self {
|
||||
Self::Color(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier.
|
||||
/// Snapshotted on first access, which must happen after startup registration of the node metadata completes.
|
||||
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
|
||||
|
||||
@@ -232,17 +232,6 @@ 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> {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
|
||||
@@ -82,7 +82,6 @@ pub enum Adjustment {
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
Solarize,
|
||||
}
|
||||
|
||||
impl Adjustment {
|
||||
@@ -108,7 +107,6 @@ impl Adjustment {
|
||||
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Solarize => EffectKind::Solarize,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +123,6 @@ impl Adjustment {
|
||||
| Self::Posterize { .. }
|
||||
| Self::Exposure { .. }
|
||||
| Self::ColorBalance(_)
|
||||
| Self::Solarize
|
||||
)
|
||||
}
|
||||
|
||||
@@ -137,7 +134,7 @@ impl Adjustment {
|
||||
visitor.parameter("gamma", gamma, 2.2);
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque | Self::Invert | Self::Solarize => {}
|
||||
Self::MakeOpaque | Self::Invert => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
|
||||
@@ -6,7 +6,6 @@ use crate::adjustment::Adjustment;
|
||||
use crate::effects::{BevelStyle, EffectCapture, EffectOperation, Effects, GlowFill, OutlineFill, outline_extents};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use std::borrow::Cow;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Which side of the content a piece of an effect draws on, and how.
|
||||
@@ -100,7 +99,9 @@ impl EffectLayers {
|
||||
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
|
||||
let last_pixel_filter = merged_into_content(&operations[..flattened]);
|
||||
let last_pixel_filter = (operations[..flattened].iter())
|
||||
.rposition(|operation| !operation.changes_nothing() && is_pixel_filter(operation))
|
||||
.map_or(0, |index| index + 1);
|
||||
let unmerged = pieces_from(last_pixel_filter, flattened);
|
||||
let mut pieces = pieces_from(flattened, operations.len());
|
||||
if has_beneath(&unmerged) && has_beneath(&pieces) {
|
||||
@@ -276,51 +277,18 @@ fn is_straight_along_backdrop(blend_mode: BlendMode) -> bool {
|
||||
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, a feather, or another filter 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, or a feather does.
|
||||
/// 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 {
|
||||
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: 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::MotionBlur { .. }
|
||||
| EffectOperation::RadialBlur { .. }
|
||||
| EffectOperation::Twirl { .. }
|
||||
| EffectOperation::Pinch { .. }
|
||||
| EffectOperation::Spherize { .. }
|
||||
| EffectOperation::PolarCoordinates { .. }
|
||||
| EffectOperation::EnvelopeWarp { .. }
|
||||
| EffectOperation::Ripple { .. }
|
||||
| EffectOperation::Wave { .. }
|
||||
| EffectOperation::Displace { .. }
|
||||
| EffectOperation::Mask { .. }
|
||||
| EffectOperation::Feather { .. } => true,
|
||||
operation if crate::filters::is_filter(operation) => true,
|
||||
EffectOperation::Blur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } => true,
|
||||
EffectOperation::Adjustment(adjustment) => !matches!(adjustment, Adjustment::ColorOverlay { .. }),
|
||||
_ => 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.
|
||||
/// 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]);
|
||||
if merged == trailing_masks.start {
|
||||
return Cow::Borrowed(effects);
|
||||
}
|
||||
|
||||
Cow::Owned(Effects((0..merged).chain(trailing_masks).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.
|
||||
fn trailing_masks(operations: &[EffectOperation]) -> Range<usize> {
|
||||
let no_rows = operations.len()..operations.len();
|
||||
@@ -391,28 +359,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
}
|
||||
EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)],
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)],
|
||||
EffectOperation::Blur { .. }
|
||||
| EffectOperation::MotionBlur { .. }
|
||||
| EffectOperation::RadialBlur { .. }
|
||||
| EffectOperation::Twirl { .. }
|
||||
| EffectOperation::Pinch { .. }
|
||||
| EffectOperation::Spherize { .. }
|
||||
| EffectOperation::PolarCoordinates { .. }
|
||||
| EffectOperation::EnvelopeWarp { .. }
|
||||
| EffectOperation::Ripple { .. }
|
||||
| EffectOperation::Wave { .. }
|
||||
| EffectOperation::Displace { .. }
|
||||
| EffectOperation::Mask { .. }
|
||||
| EffectOperation::Feather { .. }
|
||||
| EffectOperation::ConvolutionKernel { .. }
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
| EffectOperation::Adjustment(_) => Vec::new(),
|
||||
EffectOperation::Blur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } | EffectOperation::Adjustment(_) => Vec::new(),
|
||||
};
|
||||
pieces.into_iter().flatten().collect()
|
||||
}
|
||||
@@ -617,7 +564,6 @@ mod tests {
|
||||
#[test]
|
||||
fn rows_that_change_nothing_neither_flatten_nor_split_the_others() {
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -659,7 +605,6 @@ mod tests {
|
||||
#[test]
|
||||
fn trailing_masks_fade_each_layer_in_its_own_blend_mode() {
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -697,7 +642,6 @@ mod tests {
|
||||
#[test]
|
||||
fn effects_before_a_blur_or_a_mode_css_lacks_are_flattened() {
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -724,29 +668,6 @@ mod tests {
|
||||
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 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);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,814 +0,0 @@
|
||||
//! An envelope: 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 an envelope 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 EnvelopeStyle {
|
||||
/// 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,
|
||||
/// 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,
|
||||
/// 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,
|
||||
/// 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 [`EnvelopeMesh`] follows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Envelope {
|
||||
pub style: EnvelopeStyle,
|
||||
/// 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 Envelope {
|
||||
/// 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) -> EnvelopeMesh {
|
||||
use EnvelopeStyle::*;
|
||||
if !(size.cmpgt(DVec2::ZERO).all() && size.is_finite()) {
|
||||
return EnvelopeMesh::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 EnvelopeMesh(centered_mesh(DVec2::splat(bend), horizontal, vertical)),
|
||||
Squeeze if self.vertical => return EnvelopeMesh(centered_mesh(DVec2::new(bend, -bend), horizontal, vertical)),
|
||||
Squeeze => return EnvelopeMesh(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 EnvelopeMesh(mesh);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// A vertical envelope 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);
|
||||
EnvelopeMesh(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 EnvelopeMesh(pub [[DVec2; 4]; 4]);
|
||||
|
||||
impl EnvelopeMesh {
|
||||
/// 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: EnvelopeStyle, bend: f64, size: DVec2) -> [[DVec2; 4]; 4] {
|
||||
let mut mesh = EnvelopeMesh::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 {
|
||||
EnvelopeStyle::Arc => arc_mesh(bend, size),
|
||||
EnvelopeStyle::ArcLower => rows_between(identity_top, edge_arc(bend, size, false)),
|
||||
EnvelopeStyle::ArcUpper => rows_between(edge_arc(bend, size, true), identity_bottom),
|
||||
EnvelopeStyle::Arch => {
|
||||
let top = edge_arc(bend, size, true);
|
||||
std::array::from_fn(|row| top.map(|point| point + DVec2::new(0., row as f64 / 3.)))
|
||||
}
|
||||
EnvelopeStyle::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
|
||||
EnvelopeStyle::ShellLower => {
|
||||
let arc = arc_mesh(-bend, size);
|
||||
mesh[3] = arc[3];
|
||||
mesh[2][0] = arc[2][0];
|
||||
mesh[2][3] = arc[2][3];
|
||||
mesh
|
||||
}
|
||||
EnvelopeStyle::ShellUpper => {
|
||||
let arc = arc_mesh(bend, size);
|
||||
mesh[0] = arc[0];
|
||||
mesh[1][0] = arc[1][0];
|
||||
mesh[1][3] = arc[1][3];
|
||||
mesh
|
||||
}
|
||||
EnvelopeStyle::Flag => {
|
||||
for row in 0..4 {
|
||||
nudge(row, 1, DVec2::new(0., 2. * bend));
|
||||
nudge(row, 2, DVec2::new(0., -2. * bend));
|
||||
}
|
||||
mesh
|
||||
}
|
||||
EnvelopeStyle::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
|
||||
}
|
||||
EnvelopeStyle::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
|
||||
}
|
||||
EnvelopeStyle::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
|
||||
EnvelopeStyle::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)
|
||||
EnvelopeStyle::Inflate => centered_mesh(DVec2::splat(bend), 0., 0.),
|
||||
EnvelopeStyle::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
|
||||
EnvelopeStyle::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 = EnvelopeStyle> {
|
||||
use EnvelopeStyle::*;
|
||||
[Arc, ArcLower, ArcUpper, Arch, Bulge, ShellLower, ShellUpper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist].into_iter()
|
||||
}
|
||||
|
||||
fn envelope(style: EnvelopeStyle, bend: f64) -> Envelope {
|
||||
Envelope {
|
||||
style,
|
||||
bend,
|
||||
horizontal_distortion: 0.,
|
||||
vertical_distortion: 0.,
|
||||
vertical: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn envelopes_without_bend_or_distortion_change_nothing() {
|
||||
for style in every_style() {
|
||||
for vertical in [false, true] {
|
||||
let mesh = Envelope { vertical, ..envelope(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!(envelope(EnvelopeStyle::Arc, 0.5).mesh(size), EnvelopeMesh::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 = envelope(EnvelopeStyle::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 = envelope(EnvelopeStyle::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 EnvelopeStyle::*;
|
||||
|
||||
// For PSD interop, points measured on warped boxes: each case's style, bend, distortions, orientation, and size, then points (u, v) and where they land from the box's corner
|
||||
let cases = [
|
||||
(
|
||||
Arc,
|
||||
46.,
|
||||
-46.,
|
||||
63.,
|
||||
false,
|
||||
(137., 291.),
|
||||
[((0.125, 0.875), (-18.2693, 273.7009)), ((0.5, 0.5), (68.5, 142.5221)), ((0.875, 0.25), (147.3426, 129.4578))],
|
||||
),
|
||||
(
|
||||
ArcLower,
|
||||
-10.,
|
||||
40.,
|
||||
-17.,
|
||||
false,
|
||||
(137., 291.),
|
||||
[((0.125, 0.875), (21.154, 220.248)), ((0.5, 0.5), (68.5, 143.2627)), ((0.875, 0.25), (125.9035, 50.4845))],
|
||||
),
|
||||
(
|
||||
ArcUpper,
|
||||
72.,
|
||||
83.,
|
||||
-82.,
|
||||
false,
|
||||
(137., 291.),
|
||||
[((0.125, 0.875), (21.7839, 179.6745)), ((0.5, 0.5), (68.5, 105.941)), ((0.875, 0.25), (164.3882, -0.2931))],
|
||||
),
|
||||
(
|
||||
Arch,
|
||||
60.,
|
||||
-12.,
|
||||
21.,
|
||||
false,
|
||||
(137., 291.),
|
||||
[((0.125, 0.875), (4.7147, 246.6993)), ((0.5, 0.5), (68.5, 110.5975)), ((0.875, 0.25), (117.7196, 65.5829))],
|
||||
),
|
||||
(
|
||||
Bulge,
|
||||
-5.,
|
||||
92.,
|
||||
-7.,
|
||||
false,
|
||||
(137., 291.),
|
||||
[((0.125, 0.875), (17.4618, 178.7312)), ((0.5, 0.5), (68.5, 145.6884)), ((0.875, 0.25), (123.2537, 23.3591))],
|
||||
),
|
||||
(
|
||||
ShellLower,
|
||||
-11.,
|
||||
-32.,
|
||||
81.,
|
||||
false,
|
||||
(250., 250.),
|
||||
[((0.125, 0.875), (-47.7217, 235.6717)), ((0.5, 0.5), (124.4881, 122.5727)), ((0.875, 0.25), (193.4388, 77.0996))],
|
||||
),
|
||||
(
|
||||
ShellUpper,
|
||||
28.,
|
||||
22.,
|
||||
79.,
|
||||
false,
|
||||
(250., 250.),
|
||||
[((0.125, 0.875), (-15.6586, 205.5381)), ((0.5, 0.5), (125.4301, 129.278)), ((0.875, 0.25), (198.9814, 66.0233))],
|
||||
),
|
||||
(
|
||||
Flag,
|
||||
-34.,
|
||||
96.,
|
||||
-71.,
|
||||
false,
|
||||
(400., 120.),
|
||||
[((0.125, 0.875), (57.455, 58.6496)), ((0.5, 0.5), (200., 60.)), ((0.875, 0.25), (451.53, 38.6517))],
|
||||
),
|
||||
(
|
||||
Wave,
|
||||
-68.,
|
||||
64.,
|
||||
-81.,
|
||||
false,
|
||||
(400., 120.),
|
||||
[((0.125, 0.875), (86.045, 77.1135)), ((0.5, 0.5), (200., 73.056)), ((0.875, 0.25), (447.47, 34.9449))],
|
||||
),
|
||||
(
|
||||
Fish,
|
||||
-74.,
|
||||
37.,
|
||||
83.,
|
||||
false,
|
||||
(300., 200.),
|
||||
[((0.125, 0.875), (-8.0592, 48.0784)), ((0.5, 0.5), (150., 100.)), ((0.875, 0.25), (199.4978, 54.1741))],
|
||||
),
|
||||
(
|
||||
Rise,
|
||||
21.,
|
||||
-41.,
|
||||
3.,
|
||||
false,
|
||||
(400., 120.),
|
||||
[((0.125, 0.875), (45.3181, 167.7718)), ((0.5, 0.5), (200., 85.2)), ((0.875, 0.25), (348.6213, 41.6151))],
|
||||
),
|
||||
(
|
||||
Fisheye,
|
||||
-41.,
|
||||
9.,
|
||||
9.,
|
||||
false,
|
||||
(400., 120.),
|
||||
[((0.125, 0.875), (49.4018, 99.2699)), ((0.5, 0.5), (198.155, 59.4465)), ((0.875, 0.25), (327.1722, 30.8844))],
|
||||
),
|
||||
(
|
||||
Inflate,
|
||||
-44.,
|
||||
-1.,
|
||||
-25.,
|
||||
false,
|
||||
(137., 291.),
|
||||
[((0.125, 0.875), (31.8545, 247.6754)), ((0.5, 0.5), (68.5753, 149.5012)), ((0.875, 0.25), (117.8414, 82.486))],
|
||||
),
|
||||
(
|
||||
Squeeze,
|
||||
-100.,
|
||||
-23.,
|
||||
-76.,
|
||||
false,
|
||||
(300., 200.),
|
||||
[((0.125, 0.875), (86.4829, 184.5195)), ((0.5, 0.5), (141.375, 119.)), ((0.875, 0.25), (327.0879, 79.9531))],
|
||||
),
|
||||
(
|
||||
Twist,
|
||||
-50.,
|
||||
24.,
|
||||
26.,
|
||||
false,
|
||||
(300., 200.),
|
||||
[((0.125, 0.875), (32.6476, 161.1075)), ((0.5, 0.5), (150.2812, 95.3125)), ((0.875, 0.25), (227.5034, 37.7156))],
|
||||
),
|
||||
(
|
||||
Arc,
|
||||
-62.,
|
||||
57.,
|
||||
-4.,
|
||||
true,
|
||||
(400., 120.),
|
||||
[((0.125, 0.875), (51.7769, 143.6624)), ((0.5, 0.5), (281.6909, 62.3381)), ((0.875, 0.25), (414.7634, -239.3584))],
|
||||
),
|
||||
(
|
||||
ArcLower,
|
||||
-34.,
|
||||
27.,
|
||||
97.,
|
||||
true,
|
||||
(250., 250.),
|
||||
[((0.125, 0.875), (-13.9043, 199.8505)), ((0.5, 0.5), (103.2855, 125.2042)), ((0.875, 0.25), (130.5268, 48.473))],
|
||||
),
|
||||
(
|
||||
ArcUpper,
|
||||
9.,
|
||||
-83.,
|
||||
-59.,
|
||||
true,
|
||||
(200., 300.),
|
||||
[((0.125, 0.875), (88.0162, 332.7032)), ((0.5, 0.5), (90.2822, 149.9693)), ((0.875, 0.25), (170.7866, 121.653))],
|
||||
),
|
||||
(
|
||||
Arch,
|
||||
-85.,
|
||||
-53.,
|
||||
82.,
|
||||
true,
|
||||
(137., 291.),
|
||||
[((0.125, 0.875), (33.3319, 318.7345)), ((0.5, 0.5), (183.2029, 145.5)), ((0.875, 0.25), (165.5277, 91.453))],
|
||||
),
|
||||
(
|
||||
Bulge,
|
||||
1.,
|
||||
-29.,
|
||||
26.,
|
||||
true,
|
||||
(200., 300.),
|
||||
[((0.125, 0.875), (4.1491, 286.9706)), ((0.5, 0.5), (99.6583, 150.)), ((0.875, 0.25), (169.4088, 91.3111))],
|
||||
),
|
||||
(
|
||||
ShellLower,
|
||||
59.,
|
||||
77.,
|
||||
23.,
|
||||
true,
|
||||
(137., 291.),
|
||||
[((0.125, 0.875), (14.9208, 183.6004)), ((0.5, 0.5), (89.0674, 140.4151)), ((0.875, 0.25), (185.5401, -57.6605))],
|
||||
),
|
||||
(
|
||||
ShellUpper,
|
||||
-48.,
|
||||
-13.,
|
||||
69.,
|
||||
true,
|
||||
(400., 120.),
|
||||
[((0.125, 0.875), (-40.7272, 140.8086)), ((0.5, 0.5), (200.408, 64.7486)), ((0.875, 0.25), (305.3843, 32.0372))],
|
||||
),
|
||||
(
|
||||
Flag,
|
||||
12.,
|
||||
57.,
|
||||
-90.,
|
||||
true,
|
||||
(200., 300.),
|
||||
[((0.125, 0.875), (30.3873, 214.4063)), ((0.5, 0.5), (100., 150.)), ((0.875, 0.25), (253.6712, 42.9375))],
|
||||
),
|
||||
(
|
||||
Wave,
|
||||
47.,
|
||||
80.,
|
||||
36.,
|
||||
true,
|
||||
(200., 300.),
|
||||
[((0.125, 0.875), (9.8851, 195.)), ((0.5, 0.5), (91.54, 150.)), ((0.875, 0.25), (159.0405, 30.))],
|
||||
),
|
||||
(
|
||||
Fish,
|
||||
-65.,
|
||||
80.,
|
||||
86.,
|
||||
true,
|
||||
(137., 291.),
|
||||
[((0.125, 0.875), (22.3632, 189.15)), ((0.5, 0.5), (99.1332, 145.5)), ((0.875, 0.25), (41.0932, 29.1))],
|
||||
),
|
||||
(
|
||||
Rise,
|
||||
26.,
|
||||
-84.,
|
||||
45.,
|
||||
true,
|
||||
(400., 120.),
|
||||
[((0.125, 0.875), (-108.2769, 133.35)), ((0.5, 0.5), (304., 60.)), ((0.875, 0.25), (484.505, 48.9))],
|
||||
),
|
||||
(
|
||||
Fisheye,
|
||||
-59.,
|
||||
85.,
|
||||
44.,
|
||||
true,
|
||||
(300., 200.),
|
||||
[((0.125, 0.875), (36.7591, 121.2068)), ((0.5, 0.5), (131.1938, 93.51)), ((0.875, 0.25), (197.0264, 24.3454))],
|
||||
),
|
||||
(
|
||||
Inflate,
|
||||
-25.,
|
||||
-87.,
|
||||
-38.,
|
||||
true,
|
||||
(200., 300.),
|
||||
[((0.125, 0.875), (73.5647, 332.1892)), ((0.5, 0.5), (105.4375, 153.5625)), ((0.875, 0.25), (175.6768, 129.9873))],
|
||||
),
|
||||
(
|
||||
Squeeze,
|
||||
92.,
|
||||
-36.,
|
||||
24.,
|
||||
true,
|
||||
(200., 300.),
|
||||
[((0.125, 0.875), (-14.3164, 264.5742)), ((0.5, 0.5), (91.72, 141.72)), ((0.875, 0.25), (185.5469, 105.8156))],
|
||||
),
|
||||
(
|
||||
Twist,
|
||||
-69.,
|
||||
35.,
|
||||
4.,
|
||||
true,
|
||||
(300., 200.),
|
||||
[((0.125, 0.875), (50.1306, 154.89)), ((0.5, 0.5), (143.9841, 94.9544)), ((0.875, 0.25), (232.9504, 32.6515))],
|
||||
),
|
||||
];
|
||||
for (style, bend, horizontal_distortion, vertical_distortion, vertical, (width, height), points) in cases {
|
||||
let envelope = Envelope {
|
||||
style,
|
||||
bend: bend / 100.,
|
||||
horizontal_distortion: horizontal_distortion / 100.,
|
||||
vertical_distortion: vertical_distortion / 100.,
|
||||
vertical,
|
||||
};
|
||||
let size = DVec2::new(width, height);
|
||||
let mesh = envelope.mesh(size);
|
||||
for ((u, v), (x, y)) in points {
|
||||
let landed = mesh.point(DVec2::new(u, v)) * size;
|
||||
assert!(landed.distance(DVec2::new(x, y)) < 1e-3, "{envelope:?} carries ({u}, {v}) to {landed}, not ({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_envelopes_bend_the_sides() {
|
||||
// Built vertically, an Arch bends its columns across, leaving the top and bottom edges' heights alone at the corners
|
||||
let mesh = Envelope {
|
||||
vertical: true,
|
||||
..envelope(EnvelopeStyle::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 = envelope(EnvelopeStyle::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 = envelope(EnvelopeStyle::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 = envelope(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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,489 +0,0 @@
|
||||
//! 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::AddNoise { .. }
|
||||
| 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::AddNoise { .. } | 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 Add Noise 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 {
|
||||
/// Add Noise'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,
|
||||
}
|
||||
|
||||
impl RandomField {
|
||||
/// The value hashed with each cell for this field of the `seed`.
|
||||
pub fn seed(self, seed: i64) -> u32 {
|
||||
(seed as u32).wrapping_mul(4).wrapping_add(self as u32)
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest offset Add Noise 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,21 +315,3 @@ impl GeneratorPattern {
|
||||
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 raster_types::{CPU, GPU, Raster};
|
||||
pub use vector_types::Vector;
|
||||
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
|
||||
use vector_types::vector::{Path, paths_from_item_attributes, paths_from_list_row_attributes};
|
||||
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.
|
||||
@@ -630,11 +630,10 @@ impl Graphic {
|
||||
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
||||
match self {
|
||||
Graphic::Vector(item) => {
|
||||
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))
|
||||
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))
|
||||
}
|
||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing)
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none()
|
||||
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
||||
}),
|
||||
_ => false,
|
||||
@@ -743,22 +742,6 @@ impl Graphic {
|
||||
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>`.
|
||||
@@ -874,20 +857,6 @@ 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`.
|
||||
pub fn vector_list_bounding_box(list: &List<Vector>, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
let mut combined_bounds: Option<[DVec2; 2]> = None;
|
||||
|
||||
@@ -3,13 +3,10 @@ pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod effect_layers;
|
||||
pub mod effects;
|
||||
pub mod envelope;
|
||||
pub mod filters;
|
||||
pub mod generator;
|
||||
pub mod graphic;
|
||||
pub mod masks;
|
||||
pub(crate) mod parameters;
|
||||
pub mod resampling;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
pub use core_types;
|
||||
@@ -21,15 +18,12 @@ pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use effects::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||
stamp_effect, stamped_transform,
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, fitted_paint, linked_to_content, paint_with_envelope_effects, stamp_effect,
|
||||
stamped_transform,
|
||||
};
|
||||
pub use envelope::EnvelopeStyle;
|
||||
pub use filters::NoiseDistribution;
|
||||
pub use generator::Generator;
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
pub use masks::MaskMode;
|
||||
pub use resampling::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
|
||||
pub mod migrations {
|
||||
use crate::Vector;
|
||||
|
||||
@@ -60,63 +60,3 @@ pub fn feather_parts(distance: f64) -> (f64, f64) {
|
||||
let distance = distance.max(0.);
|
||||
(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::Luminance) * 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,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -25,6 +25,5 @@ vector-types = { workspace = true }
|
||||
# Workspace dependencies
|
||||
fastnoise-lite = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
half = { workspace = true }
|
||||
log = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -29,12 +29,11 @@ pub enum StepKind {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
ColorOverlay,
|
||||
Solarize,
|
||||
}
|
||||
|
||||
impl StepKind {
|
||||
/// Every kind, in the order of their codes.
|
||||
pub const ALL: [StepKind; 21] = [
|
||||
pub const ALL: [StepKind; 20] = [
|
||||
StepKind::Desaturate,
|
||||
StepKind::GammaCorrection,
|
||||
StepKind::MakeOpaque,
|
||||
@@ -55,7 +54,6 @@ impl StepKind {
|
||||
StepKind::PhotoFilter,
|
||||
StepKind::ColorLookup,
|
||||
StepKind::ColorOverlay,
|
||||
StepKind::Solarize,
|
||||
];
|
||||
|
||||
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
||||
@@ -268,7 +266,6 @@ mod tests {
|
||||
blend_mode: Default::default(),
|
||||
opacity: 50.,
|
||||
},
|
||||
Adjustment::Solarize,
|
||||
];
|
||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||
|
||||
|
||||
@@ -223,7 +223,6 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
||||
})
|
||||
}
|
||||
Adjustment::Invert => visitor.visit(Invert),
|
||||
Adjustment::Solarize => visitor.visit(Solarize),
|
||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||
min_luminance: (min_luminance / 100.) as f32,
|
||||
max_luminance: (max_luminance / 100.) as f32,
|
||||
@@ -1098,19 +1097,6 @@ 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 {
|
||||
min_luminance: f32,
|
||||
max_luminance: f32,
|
||||
|
||||
@@ -86,10 +86,11 @@ impl BlurKernel {
|
||||
let reach = ((3. * sigma).ceil() as usize).min(MAX_KERNEL_REACH);
|
||||
(0..=reach).map(|i| (-((i * i) as f64) / (2. * sigma * sigma)).exp()).collect()
|
||||
}
|
||||
// The texels at the ends weigh only the fraction of them the box covers, so the blur grows smoothly with its radius
|
||||
Self::Box { radius } => {
|
||||
let radius = radius / level_scale;
|
||||
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
||||
(0..=reach).map(|i| box_weight(radius, i)).collect()
|
||||
(0..=reach).map(|i| (radius + 1. - i as f64).clamp(0., 1.)).collect()
|
||||
}
|
||||
Self::Tent { radius } => {
|
||||
let radius = radius / level_scale;
|
||||
@@ -107,22 +108,6 @@ impl BlurKernel {
|
||||
}
|
||||
}
|
||||
|
||||
/// How much a box of half width `radius` weighs the texel `distance` from its center, before normalizing: all of it within the box,
|
||||
/// and at each end the fraction of it the box covers, so the blur grows smoothly with its radius.
|
||||
pub fn box_weight(radius: f64, distance: usize) -> f64 {
|
||||
(radius + 1. - distance as f64).clamp(0., 1.)
|
||||
}
|
||||
|
||||
/// The greatest channel value a variable box blur counts, past 1 to keep bright high dynamic range values, which `vello_masks.wgsl` matches.
|
||||
pub const VARIABLE_BOX_MAX_VALUE: f32 = 16.;
|
||||
|
||||
/// How many steps from 0 to 1 a variable box blur counts each channel of an image of `pixels` in, up to [`VARIABLE_BOX_MAX_VALUE`].
|
||||
/// The GPU's running sums of those counts then stay exact in f32 digits (see `RUNNING_SUM_DIGIT` in `vello_masks.wgsl`): 2^12 up to 8192 by 8192 pixels, halving for each doubling past it.
|
||||
pub fn variable_box_scale(pixels: usize) -> f64 {
|
||||
let pixel_bits = (pixels.max(1) as f64).log2().ceil();
|
||||
2_f64.powf((38. - pixel_bits).clamp(0., 12.))
|
||||
}
|
||||
|
||||
/// A pixel value the operations can weigh, sum, and compare: one coverage channel, or premultiplied color channels.
|
||||
pub trait Sample: Copy + Default + Send + Sync {
|
||||
fn scaled(self, factor: f32) -> Self;
|
||||
@@ -193,7 +178,7 @@ impl<T: Sample> Plane<T> {
|
||||
}
|
||||
|
||||
/// The plane with its rows and columns swapped, so a horizontal operation can work vertically. O(width × height).
|
||||
pub(crate) fn transposed(&self) -> Self {
|
||||
fn transposed(&self) -> Self {
|
||||
let mut transposed = Self::new(self.height, self.width);
|
||||
fill_rows(&mut transposed.data, self.height, |x, row| {
|
||||
row.iter_mut().enumerate().for_each(|(y, target)| *target = self.data[y * self.width + x]);
|
||||
|
||||
@@ -1,684 +0,0 @@
|
||||
//! The envelope warp on the CPU, drawing the triangles of its tessellated patch in the order the GPU's mesh pass does.
|
||||
|
||||
use crate::effect_kernels::Plane;
|
||||
use crate::resample_kernels::{pixel_area_within, sample_bilinear_within};
|
||||
use glam::DVec2;
|
||||
use graphic_types::envelope::EnvelopeMesh;
|
||||
use graphic_types::resampling::{EffectFrame, EnvelopeFragment, EnvelopeTessellation};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// A triangle of the tessellation, as its corners in the texels and their parameters (s, t), wound clockwise on screen.
|
||||
struct Triangle {
|
||||
corners: [DVec2; 3],
|
||||
parameters: [DVec2; 3],
|
||||
/// Twice its area.
|
||||
area: f64,
|
||||
/// Whether the patch turns its sheet over here, as where it folds over itself.
|
||||
reversed: bool,
|
||||
/// The part of the warp it draws.
|
||||
fragment: EnvelopeFragment,
|
||||
}
|
||||
|
||||
impl Triangle {
|
||||
/// The triangle drawing a `fragment` with these corners, wound clockwise on screen, or `None` if it covers no area.
|
||||
/// It's reversed where its winding disagrees with the square's `orientation` (the sign of its placement's determinant), which is 0 for the fringe.
|
||||
fn new(mut corners: [(DVec2, DVec2); 3], orientation: f64, fragment: EnvelopeFragment) -> Option<Self> {
|
||||
let area = |corners: &[(DVec2, DVec2); 3]| (corners[1].1 - corners[0].1).perp_dot(corners[2].1 - corners[0].1);
|
||||
let reversed = area(&corners) * orientation < 0.;
|
||||
if area(&corners) < 0. {
|
||||
corners.swap(1, 2);
|
||||
}
|
||||
let area = area(&corners);
|
||||
(area > 0. && area.is_finite()).then(|| Self {
|
||||
corners: corners.map(|(_, texel)| texel),
|
||||
parameters: corners.map(|(parameters, _)| parameters),
|
||||
area,
|
||||
reversed,
|
||||
fragment,
|
||||
})
|
||||
}
|
||||
|
||||
/// The parameters (s, t) interpolated at a `point` in the texels, if the triangle covers it.
|
||||
/// A point on an edge belongs to the triangle only along its top or left edges, so the triangles sharing it cover it once.
|
||||
fn interpolated(&self, point: DVec2) -> Option<DVec2> {
|
||||
let mut weights = [0.; 3];
|
||||
for edge in 0..3 {
|
||||
let (start, end) = (self.corners[(edge + 1) % 3], self.corners[(edge + 2) % 3]);
|
||||
|
||||
// Measured from the same end of the edge for both triangles sharing it, so roundoff can't leave a point on it outside both
|
||||
let side = match (start.x, start.y) < (end.x, end.y) {
|
||||
true => (end - start).perp_dot(point - start),
|
||||
false => -(start - end).perp_dot(point - end),
|
||||
};
|
||||
|
||||
// On screen, clockwise winding puts the top edge heading right and the left edges heading up
|
||||
let top_or_left = (start.y == end.y && end.x > start.x) || end.y < start.y;
|
||||
if side < 0. || (side == 0. && !top_or_left) {
|
||||
return None;
|
||||
}
|
||||
weights[edge] = side / self.area;
|
||||
}
|
||||
Some(self.parameters[0] * weights[0] + self.parameters[1] * weights[1] + self.parameters[2] * weights[2])
|
||||
}
|
||||
}
|
||||
|
||||
/// An envelope warp of the `mesh` (as fractions of its square) prepared for planes of one size, matching the GPU's mesh pass, so several planes warp through it with the work shared.
|
||||
/// The fringe past the square's sides and corners is drawn first, then each triangle of the tessellation paints over those before it the content within the square that its texels' polished sources read,
|
||||
/// leaving clear all that the bent square doesn't cover. For PSD interop, where it folds, the sheet turned over shows on top, like a flap of paper folded toward the viewer, so its triangles are drawn after the rest.
|
||||
pub struct EnvelopeRasterizer {
|
||||
square: EffectFrame,
|
||||
tessellation: Option<EnvelopeTessellation>,
|
||||
triangles: Vec<Option<Triangle>>,
|
||||
/// The triangles each row of pixel centers may cross, in the order they're drawn.
|
||||
crossing: Vec<Vec<u32>>,
|
||||
width: usize,
|
||||
}
|
||||
|
||||
impl EnvelopeRasterizer {
|
||||
/// The warp of the `mesh` within the `square` (see [`graphic_types::resampling::warp_frame`]) for planes `width` by `height`. O(triangles and the rows they cross).
|
||||
pub fn new(mesh: &EnvelopeMesh, square: &EffectFrame, width: usize, height: usize) -> Self {
|
||||
let tessellation = EnvelopeTessellation::new(mesh, square, DVec2::new(width as f64, height as f64));
|
||||
let mut triangles = Vec::new();
|
||||
let mut crossing: Vec<Vec<u32>> = vec![Vec::new(); height];
|
||||
|
||||
if let Some(tessellation) = &tessellation {
|
||||
// The fringe's quads along the left, right, top, and bottom sides, then past the corners where both sides meet, each split into two triangles as the GPU draws them
|
||||
let [columns, rows] = tessellation.cells;
|
||||
let quad = |[first, second, third, fourth]: [(DVec2, DVec2); 4], fragment| [Triangle::new([first, second, third], 0., fragment), Triangle::new([first, third, fourth], 0., fragment)];
|
||||
for side in (0..4).filter(|&side| tessellation.sides[side]) {
|
||||
let segments = if side < 2 { rows } else { columns };
|
||||
for along in 0..segments {
|
||||
let corners = [(along, false), (along + 1, false), (along + 1, true), (along, true)].map(|(along, outer)| tessellation.fringe_vertex(side, along, outer));
|
||||
triangles.extend(quad(corners, EnvelopeFragment::PastSide(side)));
|
||||
}
|
||||
}
|
||||
for corner in (0..4).filter(|&corner| tessellation.sides[corner % 2] && tessellation.sides[2 + corner / 2]) {
|
||||
let corners = [[false, false], [true, false], [true, true], [false, true]].map(|outer| tessellation.corner_vertex(corner, outer));
|
||||
triangles.extend(quad(corners, EnvelopeFragment::PastCorner(corner)));
|
||||
}
|
||||
|
||||
// Each cell's two triangles, cell by cell across each row of cells and row by row down, as the GPU draws them
|
||||
let vertices: Vec<(DVec2, DVec2)> = (0..=rows)
|
||||
.flat_map(|row| (0..=columns).map(move |column| (column, row)))
|
||||
.map(|index| tessellation.vertex(index.into()))
|
||||
.collect();
|
||||
let corner = |column: u32, row: u32| vertices[(row * (columns + 1) + column) as usize];
|
||||
let orientation = tessellation.source.matrix2.determinant().signum();
|
||||
triangles.reserve(2 * (columns * rows) as usize);
|
||||
for row in 0..rows {
|
||||
for column in 0..columns {
|
||||
let [top_left, top_right, bottom_left, bottom_right] = [corner(column, row), corner(column + 1, row), corner(column, row + 1), corner(column + 1, row + 1)];
|
||||
triangles.extend([
|
||||
Triangle::new([top_left, top_right, bottom_right], orientation, EnvelopeFragment::Within),
|
||||
Triangle::new([top_left, bottom_right, bottom_left], orientation, EnvelopeFragment::Within),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// Those turned over are drawn after the rest
|
||||
let drawn = [false, true]
|
||||
.into_iter()
|
||||
.flat_map(|reversed| (triangles.iter().enumerate()).filter_map(move |(index, triangle)| Some((index, triangle.as_ref().filter(|triangle| triangle.reversed == reversed)?))));
|
||||
for (index, triangle) in drawn {
|
||||
let (top, bottom) = triangle
|
||||
.corners
|
||||
.iter()
|
||||
.fold((f64::INFINITY, f64::NEG_INFINITY), |(top, bottom), corner| (top.min(corner.y), bottom.max(corner.y)));
|
||||
let first = (top - 0.5).ceil().max(0.);
|
||||
let last = (bottom - 0.5).floor().min(height as f64 - 1.);
|
||||
if first <= last {
|
||||
(first as usize..=last as usize).for_each(|y| crossing[y].push(index as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
square: *square,
|
||||
tessellation,
|
||||
triangles,
|
||||
crossing,
|
||||
width,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `plane` (of the size the warp was prepared for) carried through the warp. O(width × height).
|
||||
pub fn warped(&self, plane: &Plane<[f32; 4]>) -> Plane<[f32; 4]> {
|
||||
if plane.width != self.width || plane.height != self.crossing.len() {
|
||||
log::error!(
|
||||
"An envelope warp prepared for {} by {} pixels was given a plane {} by {}",
|
||||
self.width,
|
||||
self.crossing.len(),
|
||||
plane.width,
|
||||
plane.height
|
||||
);
|
||||
return plane.clone();
|
||||
}
|
||||
|
||||
let mut result = Plane::<[f32; 4]>::new(plane.width, plane.height);
|
||||
let Some(tessellation) = &self.tessellation else { return result };
|
||||
let area_within = pixel_area_within(&self.square);
|
||||
|
||||
// The triangles paint over each other from clear
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
let center_y = y as f64 + 0.5;
|
||||
for triangle in self.crossing[y].iter().filter_map(|&index| self.triangles[index as usize].as_ref()) {
|
||||
let (left, right) = triangle
|
||||
.corners
|
||||
.iter()
|
||||
.fold((f64::INFINITY, f64::NEG_INFINITY), |(left, right), corner| (left.min(corner.x), right.max(corner.x)));
|
||||
let first = (left - 0.5).ceil().max(0.);
|
||||
let last = (right - 0.5).floor().min(plane.width as f64 - 1.);
|
||||
if first > last {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (x, pixel) in row.iter_mut().enumerate().take(last as usize + 1).skip(first as usize) {
|
||||
let target = DVec2::new(x as f64 + 0.5, center_y);
|
||||
let Some(seed) = triangle.interpolated(target) else { continue };
|
||||
let parameters = match triangle.fragment {
|
||||
EnvelopeFragment::Within => tessellation.polished(seed, target),
|
||||
_ => seed,
|
||||
};
|
||||
|
||||
// The content within the square there, faded by how much of the pixel the warped square covers, painted over what earlier triangles left
|
||||
let shade = tessellation.shade(triangle.fragment, parameters, target);
|
||||
let coverage = shade.coverage as f32;
|
||||
if coverage <= 0. {
|
||||
continue;
|
||||
}
|
||||
let color = sample_bilinear_within(plane, tessellation.source.transform_point2(shade.read), &area_within);
|
||||
let painted = color.map(|channel| channel * coverage);
|
||||
*pixel = std::array::from_fn(|channel| painted[channel] + pixel[channel] * (1. - painted[3]));
|
||||
}
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graphic_types::envelope::{Envelope, EnvelopeStyle};
|
||||
use graphic_types::resampling::{envelope_half_fade, warp_frame};
|
||||
|
||||
/// The plane carried through the envelope warp of the `mesh` (as fractions of the `square`).
|
||||
fn envelope_warped(plane: &Plane<[f32; 4]>, mesh: &EnvelopeMesh, square: &EffectFrame) -> Plane<[f32; 4]> {
|
||||
EnvelopeRasterizer::new(mesh, square, plane.width, plane.height).warped(plane)
|
||||
}
|
||||
|
||||
/// A plane 60 by 40 of colors ramping across and down, with the warp's square its middle 40 by 20 pixels.
|
||||
fn ramps() -> (Plane<[f32; 4]>, EffectFrame) {
|
||||
let mut plane = Plane::<[f32; 4]>::new(60, 40);
|
||||
plane.data = (0..60 * 40).map(|index| [(index % 60) as f32 / 60., (index / 60) as f32 / 40., 0.5, 1.]).collect();
|
||||
let square = warp_frame(DAffine2::from_translation(DVec2::new(30., 20.)) * DAffine2::from_scale(DVec2::new(40., 20.)), DAffine2::IDENTITY).unwrap();
|
||||
(plane, square)
|
||||
}
|
||||
|
||||
fn envelope(style: EnvelopeStyle, bend: f64) -> Envelope {
|
||||
Envelope {
|
||||
style,
|
||||
bend,
|
||||
horizontal_distortion: 0.,
|
||||
vertical_distortion: 0.,
|
||||
vertical: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_envelope_without_bend_leaves_every_pixel_within_its_square_as_it_is_and_clears_the_rest() {
|
||||
let (plane, square) = ramps();
|
||||
let warped = envelope_warped(&plane, &envelope(EnvelopeStyle::Twist, 0.).mesh(square.size), &square);
|
||||
|
||||
// The square's sides run along the pixels' edges, so each pixel lies wholly within or past it
|
||||
for (index, (warped, original)) in warped.data.iter().zip(&plane.data).enumerate() {
|
||||
let within = (10..50).contains(&(index % 60)) && (10..30).contains(&(index / 60));
|
||||
let expected = if within { *original } else { [0.; 4] };
|
||||
let difference = warped.iter().zip(expected).map(|(a, b)| (a - b).abs()).fold(0., f32::max);
|
||||
assert!(difference < 1e-4, "pixel {index} became {warped:?} rather than {expected:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_pixel_shows_the_content_where_the_patch_carries_it_from() {
|
||||
let (plane, square) = ramps();
|
||||
let mesh = envelope(EnvelopeStyle::Flag, 0.3).mesh(square.size);
|
||||
let warped = envelope_warped(&plane, &mesh, &square);
|
||||
|
||||
// The ramps read back where each point of the square lands
|
||||
for uv in [DVec2::new(0.2, 0.3), DVec2::new(0.5, 0.5), DVec2::new(0.85, 0.6)] {
|
||||
let landed = square.to_pixels.transform_point2(mesh.point(uv));
|
||||
let pixel = landed.floor();
|
||||
let color = warped.data[pixel.y as usize * 60 + pixel.x as usize];
|
||||
|
||||
// The pixel's center reads from near the point, which the ramps show to within a pixel
|
||||
let source = square.to_pixels.transform_point2(uv);
|
||||
assert!((color[0] * 60. - source.x as f32).abs() < 1.5, "{uv} reads across from {}, not {}", color[0] * 60., source.x);
|
||||
assert!((color[1] * 40. - source.y as f32).abs() < 1.5, "{uv} reads down from {}, not {}", color[1] * 40., source.y);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_lies_outside_the_square_and_what_the_bend_leaves_of_it_clear() {
|
||||
// A flag only raises and lowers the square's content, lowering its top edge on the left and raising it on the right
|
||||
let (plane, square) = ramps();
|
||||
let mesh = envelope(EnvelopeStyle::Flag, 0.2).mesh(square.size);
|
||||
let warped = envelope_warped(&plane, &mesh, &square);
|
||||
|
||||
// Beside the square, and above it where the flag lowers its top edge, all is clear
|
||||
for (x, y) in [(55, 20), (3, 35), (20, 3)] {
|
||||
assert_eq!(warped.data[y * 60 + x], [0.; 4], "({x}, {y}) isn't clear");
|
||||
}
|
||||
|
||||
// Where it lowers the top edge, what it leaves of the square is clear, and where it raises it, the square's top row shows above the square
|
||||
assert!(warped.data[10 * 60 + 20][3] < 1e-3, "the square's top left shows {:?}", warped.data[10 * 60 + 20]);
|
||||
let raised = warped.data[8 * 60 + 40];
|
||||
assert!((raised[1] * 40. - 10.5).abs() < 1.5 && raised[3] > 0.99, "above the square's top right shows {raised:?}");
|
||||
}
|
||||
|
||||
/// Whether the patch of the `mesh` turns over anywhere within its unit square, so parts of it overlap, by the sign of its Jacobian across a dense grid.
|
||||
fn folds(mesh: &EnvelopeMesh) -> bool {
|
||||
(0..65 * 65).any(|index| {
|
||||
let [_, along_u, along_v] = mesh.point_and_tangents(DVec2::new((index % 65) as f64, (index / 65) as f64) / 64.);
|
||||
along_u.perp_dot(along_v) <= 1e-9
|
||||
})
|
||||
}
|
||||
|
||||
/// How many points of the unit square the patch of `mesh` (in pixels) carries onto `point`, found by splitting the square until its parts are small, then polishing each part's middle onto it.
|
||||
/// A part whose polish settles outside it, or nowhere, splits further, as beside a fold's crease, and the points found from several parts count once.
|
||||
fn preimages(mesh: &EnvelopeMesh, point: DVec2) -> usize {
|
||||
let mut found: Vec<DVec2> = Vec::new();
|
||||
let mut parts = vec![(DVec2::ZERO, DVec2::ONE)];
|
||||
while let Some((start, end)) = parts.pop() {
|
||||
let [min, max] = mesh.over(start, end).hull_bounds();
|
||||
if point.cmplt(min).any() || point.cmpgt(max).any() {
|
||||
continue;
|
||||
}
|
||||
let middle = (start + end) / 2.;
|
||||
let split = [
|
||||
(start, middle),
|
||||
(DVec2::new(middle.x, start.y), DVec2::new(end.x, middle.y)),
|
||||
(DVec2::new(start.x, middle.y), DVec2::new(middle.x, end.y)),
|
||||
(middle, end),
|
||||
];
|
||||
let size = (end - start).max_element();
|
||||
if size > 1. / 64. {
|
||||
parts.extend(split);
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut uv = middle;
|
||||
for _ in 0..16 {
|
||||
let [landed, along_u, along_v] = mesh.point_and_tangents(uv);
|
||||
let (residual, determinant) = (landed - point, along_u.perp_dot(along_v));
|
||||
if determinant.abs() < 1e-12 {
|
||||
break;
|
||||
}
|
||||
uv -= DVec2::new(residual.perp_dot(along_v), along_u.perp_dot(residual)) / determinant;
|
||||
}
|
||||
|
||||
let settled = (mesh.point(uv) - point).length() < 1e-6;
|
||||
if settled && uv.cmpge(DVec2::ZERO).all() && uv.cmple(DVec2::ONE).all() && found.iter().all(|other| other.distance(uv) > 1e-7) {
|
||||
found.push(uv);
|
||||
}
|
||||
let within_part = uv.cmpge(start - 1e-9).all() && uv.cmple(end + 1e-9).all();
|
||||
if !(settled && within_part) && size > 1. / 4096. {
|
||||
parts.extend(split);
|
||||
}
|
||||
}
|
||||
found.len()
|
||||
}
|
||||
|
||||
/// How many layers of content show at each of 8 by 8 samples across `pixel` (its corner) after the envelope warp of the `mesh` (as fractions of the `square`):
|
||||
/// one for each point of the square the patch carries onto it.
|
||||
fn supersampled_layers(mesh: &EnvelopeMesh, square: &EffectFrame, pixel: DVec2) -> [usize; 64] {
|
||||
let in_pixels = mesh.transformed(square.to_pixels);
|
||||
std::array::from_fn(|index| preimages(&in_pixels, pixel + (DVec2::new((index % 8) as f64, (index / 8) as f64) + 0.5) / 8.))
|
||||
}
|
||||
|
||||
/// How much of the pixel with its corner at `pixel` the `square` itself covers, fading across its sides as a side the warp keeps in place does.
|
||||
fn square_coverage(square: &EffectFrame, pixel: DVec2) -> f32 {
|
||||
let (local, half, half_fade) = (square.pixels_to_local().transform_point2(pixel + 0.5), square.size / 2., envelope_half_fade(square));
|
||||
(0.5 + (half - local.abs()) / (2. * half_fade)).clamp(DVec2::ZERO, DVec2::ONE).element_product() as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sides_a_bend_keeps_in_place_match_the_content_at_any_squeeze_and_offset() {
|
||||
use EnvelopeStyle::*;
|
||||
|
||||
// Content of one color reaching past a square 39 by 19 at quarter-pixel offsets and scaled between pixels (its corners on the reference's samples), and past squares slanted and turned off the grid,
|
||||
// which fisheyes, waves, and twists bend across their range while keeping all four sides in place
|
||||
let bends = (-25..=25)
|
||||
.map(|step| step as f64 * 0.04)
|
||||
.chain([0.58, 0.59, 0.6, 0.61, 0.66, 0.67, 0.68, 0.75, 0.76, 0.77, -0.59, -0.6, -0.76]);
|
||||
let placements = [
|
||||
DAffine2::from_cols_array(&[39., 0., 0., 19., 30., 20.]),
|
||||
DAffine2::from_cols_array(&[39., 0., 0., 19., 30.25, 20.5]),
|
||||
DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]),
|
||||
DAffine2::from_cols_array(&[39., 0., 0., 19., 30.75, 20.75]),
|
||||
DAffine2::from_cols_array(&[42.5, 0., 0., 20.75, 30.25, 20.375]),
|
||||
DAffine2::from_cols_array(&[24., 0., 16., 14., 30.3, 20.6]),
|
||||
DAffine2::from_translation(DVec2::new(30.4, 20.15)) * DAffine2::from_angle(0.5) * DAffine2::from_scale(DVec2::new(30., 14.)),
|
||||
];
|
||||
for (style, bend, placement) in [Fisheye, Wave, Twist]
|
||||
.into_iter()
|
||||
.flat_map(|style| bends.clone().flat_map(move |bend| placements.map(|placement| (style, bend, placement))))
|
||||
{
|
||||
let square = warp_frame(placement, DAffine2::IDENTITY).unwrap();
|
||||
let mesh = envelope(style, bend).mesh(square.size);
|
||||
let folding = folds(&mesh);
|
||||
let offset = placement.translation;
|
||||
|
||||
// The 3 by 3 pixels around each corner of an upright square, where its coverage is its area, with the layers a supersampled reference counts across them.
|
||||
// A slanted square's edge fades by its coverage along its axes instead, as the square's own edge does, which the check of every pixel below holds it to.
|
||||
let upright = placement.matrix2.x_axis.y == 0. && placement.matrix2.y_axis.x == 0.;
|
||||
let corners = [DVec2::splat(-0.5), DVec2::new(0.5, -0.5), DVec2::new(-0.5, 0.5), DVec2::splat(0.5)].map(|corner| placement.transform_point2(corner));
|
||||
let around_corners: Vec<(DVec2, [usize; 64])> = corners
|
||||
.into_iter()
|
||||
.filter(|_| upright)
|
||||
.flat_map(|corner| (0..9).map(move |index| (corner - 1.5).floor() + DVec2::new((index % 3) as f64, (index / 3) as f64)))
|
||||
.map(|pixel| (pixel, supersampled_layers(&mesh, &square, pixel)))
|
||||
.collect();
|
||||
|
||||
for alpha in [1., 0.5] {
|
||||
let plane = Plane {
|
||||
data: vec![[alpha; 4]; 60 * 40],
|
||||
..Plane::<[f32; 4]>::new(60, 40)
|
||||
};
|
||||
let warped = envelope_warped(&plane, &mesh, &square);
|
||||
|
||||
// Where the patch doesn't fold, it shows the content within the square, clear past it, and the content faded by the square's coverage across its sides.
|
||||
// Where it folds, the layers of opaque content cover at least that much.
|
||||
for (index, pixel) in warped.data.iter().enumerate() {
|
||||
let expected = alpha * square_coverage(&square, DVec2::new((index % 60) as f64, (index / 60) as f64));
|
||||
let error = pixel.iter().map(|channel| (channel - expected).abs()).fold(0., f32::max);
|
||||
let (x, y) = (index % 60, index / 60);
|
||||
if !folding {
|
||||
assert!(
|
||||
error < 1e-4,
|
||||
"{style:?} at {bend} placed at {offset}, alpha {alpha}, shows {pixel:?} rather than {expected} at ({x}, {y})"
|
||||
);
|
||||
} else if alpha == 1. {
|
||||
assert!(pixel[3] > expected - 1e-4, "{style:?} at {bend} placed at {offset} shows {pixel:?}, short of {expected} at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
// Around each corner, it matches the reference
|
||||
for (pixel, layers) in &around_corners {
|
||||
let reference = layers.iter().map(|&layers| 1. - (1. - alpha).powi(layers as i32)).sum::<f32>() / 64.;
|
||||
let shown = warped.data[pixel.y as usize * 60 + pixel.x as usize][3];
|
||||
assert!(
|
||||
(shown - reference).abs() < 1e-3,
|
||||
"{style:?} at {bend} placed at {offset}, alpha {alpha}, shows {shown} at {pixel} rather than {reference}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strongly_bent_styles_keep_opaque_content_opaque_within_their_patch_at_any_scale() {
|
||||
use EnvelopeStyle::*;
|
||||
|
||||
// Opaque content past squares 120 by 90 at non-integer scales, which fish (whose sides curve back near each other) and other styles bend far, both ways and turned, and fish within smaller squares
|
||||
let styles = [Fish, Arch, Bulge, Flag, Wave, Fisheye, Squeeze, Twist];
|
||||
let cases = |styles: Vec<EnvelopeStyle>, square: DVec2| {
|
||||
styles.into_iter().flat_map(move |style| {
|
||||
[-1., -0.6, 0.6, 1.].into_iter().flat_map(move |bend| {
|
||||
[false, true]
|
||||
.into_iter()
|
||||
.flat_map(move |vertical| [0.91, 1.09, 1.37].map(move |scale| (style, bend, vertical, square * scale)))
|
||||
})
|
||||
})
|
||||
};
|
||||
for (style, bend, vertical, size) in cases(styles.to_vec(), DVec2::new(120., 90.)).chain(cases(vec![Fish], DVec2::new(60., 40.))) {
|
||||
let (width, height) = ((size.x * 3.) as usize, (size.y * 3.) as usize);
|
||||
let plane = Plane {
|
||||
data: vec![[1.; 4]; width * height],
|
||||
..Plane::<[f32; 4]>::new(width, height)
|
||||
};
|
||||
let center = DVec2::new(width as f64, height as f64) / 2. + DVec2::new(0.3, 0.2);
|
||||
let square = warp_frame(DAffine2::from_translation(center) * DAffine2::from_scale(size), DAffine2::IDENTITY).unwrap();
|
||||
let mesh = Envelope { vertical, ..envelope(style, bend) }.mesh(square.size);
|
||||
let warped = envelope_warped(&plane, &mesh, &square);
|
||||
|
||||
// Each pixel the patch carries a point of the square onto, which lies at least a pixel within the patch and two from the curves its sides bend into, is opaque
|
||||
let in_pixels = mesh.transformed(square.to_pixels);
|
||||
let sides: Vec<DVec2> = (0..=400)
|
||||
.flat_map(|index| {
|
||||
let t = index as f64 / 400.;
|
||||
[DVec2::new(0., t), DVec2::new(1., t), DVec2::new(t, 0.), DVec2::new(t, 1.)]
|
||||
})
|
||||
.map(|uv| in_pixels.point(uv))
|
||||
.collect();
|
||||
for index in 0..101 * 101 {
|
||||
let uv = DVec2::new((index % 101) as f64, (index / 101) as f64) / 100.;
|
||||
let pixel = in_pixels.point(uv).floor();
|
||||
let within_plane = pixel.cmpge(DVec2::ZERO).all() && pixel.x < width as f64 && pixel.y < height as f64;
|
||||
if !within_plane || sides.iter().any(|side| side.distance(pixel + 0.5) < 2.) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let alpha = warped.data[pixel.y as usize * width + pixel.x as usize][3];
|
||||
let within_patch = || {
|
||||
[DVec2::ZERO, DVec2::X, -DVec2::X, DVec2::Y, -DVec2::Y]
|
||||
.iter()
|
||||
.all(|&offset| preimages(&in_pixels, pixel + 0.5 + offset) > 0)
|
||||
};
|
||||
assert!(
|
||||
alpha > 0.99 || !within_patch(),
|
||||
"{style:?} at {bend}, vertical {vertical}, within a square {size}, shows {alpha} at {pixel} from {uv}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sides_curving_sharply_toward_a_pixel_fade_it() {
|
||||
// Opaque content past a square 10 by 200 that a flag waves far, so its top side's crest curves tightly past the pixel (28, 87), a third of a pixel within it
|
||||
let plane = Plane {
|
||||
data: vec![[1.; 4]; 80 * 500],
|
||||
..Plane::<[f32; 4]>::new(80, 500)
|
||||
};
|
||||
let square = warp_frame(DAffine2::from_cols_array(&[10., 0., 0., 200., 25.625, 300.75]), DAffine2::IDENTITY).unwrap();
|
||||
let warped = envelope_warped(&plane, &envelope(EnvelopeStyle::Flag, 1.).mesh(square.size), &square);
|
||||
|
||||
// It fades by the third of a pixel, as two thirds past the pixel's middle, though the curve's tangent where the pixel's source lies passes two pixels away
|
||||
let alpha = warped.data[87 * 80 + 28][3];
|
||||
assert!((alpha - 0.83).abs() < 0.02, "the pixel shows alpha {alpha}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fisheyes_squeezing_the_content_nearly_flat_against_a_side_keep_it_seamless() {
|
||||
// Opaque content past a square with its top side three quarters of the way down a row of pixels, against which fisheyes squeeze the content nearly flat
|
||||
for bend in [0.59, 0.6] {
|
||||
let plane = Plane {
|
||||
data: vec![[1.; 4]; 60 * 40],
|
||||
..Plane::<[f32; 4]>::new(60, 40)
|
||||
};
|
||||
let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]), DAffine2::IDENTITY).unwrap();
|
||||
let warped = envelope_warped(&plane, &envelope(EnvelopeStyle::Fisheye, bend).mesh(square.size), &square);
|
||||
for (index, pixel) in warped.data.iter().enumerate() {
|
||||
let expected = square_coverage(&square, DVec2::new((index % 60) as f64, (index / 60) as f64));
|
||||
assert!(
|
||||
(pixel[3] - expected).abs() < 1e-4,
|
||||
"bent {bend}, ({}, {}) shows {pixel:?} rather than {expected}",
|
||||
index % 60,
|
||||
index / 60
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slanted_squares_keep_the_content_as_it_is_past_corners_they_keep_in_place() {
|
||||
// Opaque content past a square slanted to corners an eighth of a turn sharp, off the pixel grid, within which a fisheye keeps the sides in place
|
||||
let plane = Plane {
|
||||
data: vec![[1.; 4]; 120 * 80],
|
||||
..Plane::<[f32; 4]>::new(120, 80)
|
||||
};
|
||||
let square = warp_frame(DAffine2::from_cols_array(&[40., 0., 40., 40., 61., 40.75]), DAffine2::IDENTITY).unwrap();
|
||||
let warped = envelope_warped(&plane, &envelope(EnvelopeStyle::Fisheye, 0.4).mesh(square.size), &square);
|
||||
for (index, pixel) in warped.data.iter().enumerate() {
|
||||
let expected = square_coverage(&square, DVec2::new((index % 120) as f64, (index / 120) as f64));
|
||||
assert!((pixel[3] - expected).abs() < 1e-4, "({}, {}) shows {pixel:?} rather than {expected}", index % 120, index / 120);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folds_returning_over_a_side_change_smoothly_as_the_side_moves() {
|
||||
// Clear rows down through the one a square's top side runs through the middle of, and opaque rows below, which a fisheye folds out over the clear rows and back
|
||||
let alpha_at = |down: f64| {
|
||||
let mut plane = Plane::<[f32; 4]>::new(60, 40);
|
||||
plane.data[11 * 60..].fill([1.; 4]);
|
||||
let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, down]), DAffine2::IDENTITY).unwrap();
|
||||
envelope_warped(&plane, &envelope(EnvelopeStyle::Fisheye, 1.).mesh(square.size), &square).data[10 * 60 + 30][3]
|
||||
};
|
||||
|
||||
// Moving the side a fiftieth of a pixel across the pixel's center moves its fade only as far
|
||||
let (above, below) = (alpha_at(19.99), alpha_at(20.01));
|
||||
assert!((above - below).abs() < 0.03, "the pixel's alpha jumps from {above} to {below}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folds_out_past_a_side_clear_what_lies_outside_the_square_beneath_them() {
|
||||
// Opaque rows down to just above a square's top side, and clear rows below, which a fisheye folds out over the rows above
|
||||
let mut plane = Plane::<[f32; 4]>::new(60, 40);
|
||||
plane.data[..10 * 60].fill([1.; 4]);
|
||||
let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.]), DAffine2::IDENTITY).unwrap();
|
||||
let warped = envelope_warped(&plane, &envelope(EnvelopeStyle::Fisheye, 1.).mesh(square.size), &square);
|
||||
|
||||
// The fold carries only the square's clear content, and the rows above clear
|
||||
for (index, pixel) in warped.data.iter().enumerate() {
|
||||
assert!(pixel[3] < 1e-4, "({}, {}) shows {pixel:?}", index % 60, index / 60);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_well_outside_the_bent_square_clears() {
|
||||
// Opaque content 80 by 60 pixels, within which a flag bends a square 30 by 20 at its middle
|
||||
let plane = Plane {
|
||||
data: vec![[1.; 4]; 80 * 60],
|
||||
..Plane::<[f32; 4]>::new(80, 60)
|
||||
};
|
||||
let square = warp_frame(DAffine2::from_cols_array(&[30., 0., 0., 20., 40., 30.]), DAffine2::IDENTITY).unwrap();
|
||||
let mesh = envelope(EnvelopeStyle::Flag, 0.4).mesh(square.size);
|
||||
let warped = envelope_warped(&plane, &mesh, &square);
|
||||
|
||||
// The pixels within two and a half of where the patch carries the square, past which its edge's fade and its fringe's miters reach nothing
|
||||
let in_pixels = mesh.transformed(square.to_pixels);
|
||||
let mut near = vec![false; 80 * 60];
|
||||
for index in 0..201 * 201 {
|
||||
let point = in_pixels.point(DVec2::new((index % 201) as f64, (index / 201) as f64) / 200.);
|
||||
for (x, y) in (-3..=3).flat_map(|y| (-3..=3).map(move |x| (x, y))) {
|
||||
let pixel = (point - 0.5).round() + DVec2::new(x as f64, y as f64);
|
||||
if (pixel + 0.5).distance(point) <= 2.5 && pixel.cmpge(DVec2::ZERO).all() && pixel.x < 80. && pixel.y < 60. {
|
||||
near[pixel.y as usize * 80 + pixel.x as usize] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// All else is clear, though the content was opaque there
|
||||
let far: Vec<usize> = (0..80 * 60).filter(|&index| !near[index]).collect();
|
||||
assert!(far.len() > 2000, "only {} pixels lie far from the patch", far.len());
|
||||
for index in far {
|
||||
assert_eq!(warped.data[index], [0.; 4], "({}, {}) shows {:?}", index % 80, index / 80, warped.data[index]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_wholly_outside_a_slanted_or_turned_square_is_carried_through_it() {
|
||||
// Clear content but for an opaque pixel just above the top side of a slanted square, which an upper arc raises past where the pixel lies,
|
||||
// or just above the top corner of a square turned an eighth, which an arc bends far around
|
||||
let cases = [
|
||||
(UVec2::new(80, 40), UVec2::new(30, 9), EnvelopeStyle::ArcUpper, 0.5, [40., 0., 40., 4., 50., 12.]),
|
||||
(UVec2::new(80, 60), UVec2::new(40, 9), EnvelopeStyle::Arc, 0.8, [20., 20., -20., 20., 40.5, 30.01]),
|
||||
];
|
||||
for (size, opaque, style, bend, transform) in cases {
|
||||
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
||||
plane.data[(opaque.y * size.x + opaque.x) as usize] = [1.; 4];
|
||||
let square = warp_frame(DAffine2::from_cols_array(&transform), DAffine2::IDENTITY).unwrap();
|
||||
let warped = envelope_warped(&plane, &envelope(style, bend).mesh(square.size), &square);
|
||||
|
||||
// The patch carries none of the pixel anywhere, and the pixel clears where it lies
|
||||
for (index, pixel) in warped.data.iter().enumerate() {
|
||||
assert!(pixel[3] < 1e-3, "{style:?} shows {pixel:?} at ({}, {})", index % plane.width, index / plane.width);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn squares_far_smaller_than_a_pixel_paint_nothing_past_the_content() {
|
||||
// Opaque content 25 pixels across at a hundredth of a pixel per unit, twisted within a square one unit across at its middle, which its reach keeps within the content
|
||||
let mut plane = Plane::<[f32; 4]>::new(64, 64);
|
||||
for y in 0..25 {
|
||||
plane.data[y * 64..y * 64 + 25].fill([1.; 4]);
|
||||
}
|
||||
let square = warp_frame(DAffine2::from_translation(DVec2::splat(1275.)), DAffine2::from_scale(DVec2::splat(0.01))).unwrap();
|
||||
let warped = envelope_warped(&plane, &envelope(EnvelopeStyle::Twist, 0.8).mesh(square.size), &square);
|
||||
|
||||
for (index, pixel) in warped.data.iter().enumerate() {
|
||||
let (x, y) = (index % 64, index / 64);
|
||||
assert!((x < 25 && y < 25) || pixel[3] < 1e-3, "({x}, {y}) past the content shows {pixel:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folds_show_the_sheet_turned_over_on_top() {
|
||||
// Columns that double back across the middle, so it's covered by the left and right of the content and by the sheet between them turned over
|
||||
let (plane, square) = ramps();
|
||||
let mesh = EnvelopeMesh(std::array::from_fn(|row| [0., 1.5, -0.5, 1.].map(|x| DVec2::new(x, row as f64 / 3.))));
|
||||
let warped = envelope_warped(&plane, &mesh, &square);
|
||||
|
||||
// For PSD interop, the middle shows the turned sheet, which reads near the content's middle rather than a quarter in from either side
|
||||
let red = warped.data[20 * 60 + 30][0];
|
||||
assert!((red - 0.49).abs() < 0.03, "the middle shows red {red}");
|
||||
assert!(warped.data[20 * 60 + 30][3] > 0.999);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirrored_squares_fold_as_the_mirror_of_upright_ones() {
|
||||
// The fold above in the square and content mirrored left to right, where the turned sheet winds the other way on screen
|
||||
let (plane, square) = ramps();
|
||||
let mesh = EnvelopeMesh(std::array::from_fn(|row| [0., 1.5, -0.5, 1.].map(|x| DVec2::new(x, row as f64 / 3.))));
|
||||
let mirror = |index: usize| index - index % 60 + 59 - index % 60;
|
||||
let mirrored_plane = Plane {
|
||||
data: (0..60 * 40).map(|index| plane.data[mirror(index)]).collect(),
|
||||
..plane.clone()
|
||||
};
|
||||
let mirrored_square = square.placed(DAffine2::from_translation(DVec2::new(60., 0.)) * DAffine2::from_scale(DVec2::new(-1., 1.)));
|
||||
|
||||
let upright = envelope_warped(&plane, &mesh, &square);
|
||||
let mirrored = envelope_warped(&mirrored_plane, &mesh, &mirrored_square);
|
||||
for (index, color) in upright.data.iter().enumerate() {
|
||||
let difference = color.iter().zip(mirrored.data[mirror(index)]).map(|(a, b)| (a - b).abs()).fold(0., f32::max);
|
||||
assert!(difference < 1e-3, "pixel {index} shows {color:?} upright but {:?} mirrored", mirrored.data[mirror(index)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_style_at_its_extremes_paints_colors_within_range() {
|
||||
use EnvelopeStyle::*;
|
||||
let (plane, square) = ramps();
|
||||
|
||||
for style in [Arc, ArcLower, ArcUpper, Arch, Bulge, ShellLower, ShellUpper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist] {
|
||||
for (bend, horizontal_distortion, vertical_distortion) in [(1., 0., 0.), (-1., 0., 0.), (1., 1., 1.), (-1., -1., 1.), (1., -1., -1.), (0., 1., -1.)] {
|
||||
for vertical in [false, true] {
|
||||
let envelope = Envelope {
|
||||
style,
|
||||
bend,
|
||||
horizontal_distortion,
|
||||
vertical_distortion,
|
||||
vertical,
|
||||
};
|
||||
let warped = envelope_warped(&plane, &envelope.mesh(square.size), &square);
|
||||
|
||||
// Premultiplied, each color lies within its alpha, which lies within 0 to 1
|
||||
let within = |pixel: &[f32; 4]| pixel.iter().all(|channel| channel.is_finite() && (0.0..=pixel[3] + 1e-4).contains(channel)) && pixel[3] <= 1. + 1e-4;
|
||||
assert!(warped.data.iter().all(within), "{envelope:?} paints colors out of range");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,912 +0,0 @@
|
||||
//! The pixel filters on the CPU, which mirror the renderer's GPU passes on premultiplied gamma-encoded channels.
|
||||
|
||||
use crate::effect_kernels::{BlurKernel, Plane};
|
||||
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use graphic_types::filters::{
|
||||
Convolution, FieldSampling, GAUSSIAN_NOISE_LIMIT, HIGH_PASS_GRAY, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, average_weight,
|
||||
edge_gain, fill_shifts, neighborhood_radii, noise_extent, unsharp, unsharp_change,
|
||||
};
|
||||
use graphic_types::generator::pcg3d;
|
||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// Carries out a filter effect on premultiplied gamma-encoded pixels, which `pixels_to_effect` places in the effect space, or returns them as they are for any other operation.
|
||||
/// The pixels visible in the `full`-strength content (the plane itself for `None`) are those whose colors the filter reads.
|
||||
pub fn filter(plane: Plane<[f32; 4]>, full: Option<&Plane<[f32; 4]>>, operation: &EffectOperation, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||
let document_to_pixels = pixels_to_effect.matrix2.inverse();
|
||||
if let Some(convolution) = operation.convolution() {
|
||||
return convolve(&plane, full.unwrap_or(&plane), &convolution, document_to_pixels);
|
||||
}
|
||||
|
||||
if let Some((blur, sharpening)) = unsharp(operation) {
|
||||
let sharpening = sharpening.map(|[amount, threshold]| (amount as f32, threshold as f32));
|
||||
return unsharp_mask(&plane, full.unwrap_or(&plane), blur, sharpening, document_to_pixels);
|
||||
}
|
||||
|
||||
match *operation {
|
||||
EffectOperation::FindEdges => find_edges(&plane, document_to_pixels),
|
||||
EffectOperation::MinimumMaximum { radius, mode } => neighborhood_extreme(&plane, radius, mode == MinimumMaximumMode::Maximum, document_to_pixels),
|
||||
EffectOperation::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
seed,
|
||||
} => add_noise(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect),
|
||||
EffectOperation::Dissolve { opacity, seed } => dissolve(&plane, opacity / 100., seed, pixels_to_effect),
|
||||
_ => plane,
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole-pixel shifts, nearest first, that a faint pixel looks along for a visible one within `reach` document pixels, measured through `document_to_pixels`. O(reach² log reach).
|
||||
pub fn pixel_fill_shifts(reach: f64, document_to_pixels: DMat2) -> Vec<[isize; 2]> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let pixel_shift = |[x, y]: [i32; 2]| (document_to_pixels * DVec2::new(x as f64, y as f64)).round();
|
||||
(fill_shifts(reach.ceil() as i32).into_iter().map(pixel_shift))
|
||||
.map(|shift| [shift.x as isize, shift.y as isize])
|
||||
.filter(|&shift| seen.insert(shift))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each pixel's straight color, as the filters read it, with an alpha of 1 where there is one: its own if it's visible in the `full`-strength content, otherwise that of the first visible pixel along `shifts`,
|
||||
/// or failing that its own if it has any coverage. O(width × height × shifts) for the faint pixels.
|
||||
pub(crate) fn visible_colors(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, shifts: &[[isize; 2]]) -> Plane<[f32; 4]> {
|
||||
let (columns, rows) = (plane.width as isize, plane.height as isize);
|
||||
let covered = |x: isize, y: isize, least_alpha: f32| {
|
||||
let index = (x >= 0 && y >= 0 && x < columns && y < rows).then_some((y * columns + x) as usize)?;
|
||||
let [red, green, blue, alpha] = plane.data[index];
|
||||
(alpha > 0. && full.data[index][3] >= least_alpha).then(|| [red / alpha, green / alpha, blue / alpha, 1.])
|
||||
};
|
||||
|
||||
let mut colors = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut colors.data, plane.width, |y, row| {
|
||||
for (x, color) in row.iter_mut().enumerate() {
|
||||
let (x, y) = (x as isize, y as isize);
|
||||
let nearest_visible = shifts.iter().find_map(|&[shift_x, shift_y]| covered(x + shift_x, y + shift_y, VISIBLE_ALPHA));
|
||||
*color = nearest_visible.or_else(|| covered(x, y, 0.)).unwrap_or_default();
|
||||
}
|
||||
});
|
||||
colors
|
||||
}
|
||||
|
||||
/// A weighted copy of a plane shifted by a fixed fraction of a pixel, read as the four pixels around each position with their bilinear weights.
|
||||
struct BilinearTap {
|
||||
/// The whole-pixel part of the shift.
|
||||
whole: [isize; 2],
|
||||
/// The bilinear weights of the pixels at the whole shift and one past it along x, then the same one past it along y.
|
||||
bilinear: [f32; 4],
|
||||
weight: f32,
|
||||
}
|
||||
|
||||
impl BilinearTap {
|
||||
fn new(shift: DVec2, weight: f32) -> Self {
|
||||
let whole = shift.floor();
|
||||
let [x, y] = (shift - whole).as_vec2().to_array();
|
||||
Self {
|
||||
whole: [whole.x as isize, whole.y as isize],
|
||||
bilinear: [(1. - x) * (1. - y), x * (1. - y), (1. - x) * y, x * y],
|
||||
weight,
|
||||
}
|
||||
}
|
||||
|
||||
/// The weighted color between the four `corners` (straight colors with an alpha of 1 where there is one), interpolated among those with a color, matching the GPU's `color_between`.
|
||||
/// Leaving out those without one continues the colors past the edges between pixels too, rather than fading toward black.
|
||||
fn weighted(&self, corners: [[f32; 4]; 4]) -> [f32; 3] {
|
||||
let (mut color, mut covered) = ([0.; 3], 0.);
|
||||
for (corner, bilinear) in corners.into_iter().zip(self.bilinear) {
|
||||
(0..3).for_each(|channel| color[channel] += corner[channel] * bilinear);
|
||||
covered += corner[3] * bilinear;
|
||||
}
|
||||
if covered > 0. { color.map(|channel| channel / covered * self.weight) } else { [0.; 3] }
|
||||
}
|
||||
}
|
||||
|
||||
/// The opaque colors a filter reads, as its surroundings describe, with the color it reads beyond their edges.
|
||||
struct SurroundedColors {
|
||||
colors: Plane<[f32; 4]>,
|
||||
beyond: [f32; 4],
|
||||
}
|
||||
|
||||
impl SurroundedColors {
|
||||
/// The colors of the premultiplied pixels that a filter reading within `reach` document pixels sees, measured through `document_to_pixels`, those visible judged by the `full`-strength content.
|
||||
fn new(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, surroundings: Surroundings, reach: f64, document_to_pixels: DMat2) -> Self {
|
||||
match surroundings {
|
||||
Surroundings::Continued => Self {
|
||||
colors: visible_colors(plane, full, &pixel_fill_shifts(reach, document_to_pixels)),
|
||||
beyond: [0.; 4],
|
||||
},
|
||||
Surroundings::Matted(gray) => {
|
||||
let gray = gray as f32;
|
||||
let over_gray = |channel: f32, alpha: f32| channel + gray * (1. - alpha);
|
||||
Self {
|
||||
colors: plane.map(|[red, green, blue, alpha]| [over_gray(red, alpha), over_gray(green, alpha), over_gray(blue, alpha), 1.]),
|
||||
beyond: [gray, gray, gray, 1.],
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The coverage of the premultiplied pixels in each channel, read with none beyond the plane's edges and every pixel counted when reading between them.
|
||||
fn coverage(plane: &Plane<[f32; 4]>) -> Self {
|
||||
Self {
|
||||
colors: plane.map(|[.., alpha]| [alpha, alpha, alpha, 1.]),
|
||||
beyond: [0., 0., 0., 1.],
|
||||
}
|
||||
}
|
||||
|
||||
fn at(&self, x: isize, y: isize) -> [f32; 4] {
|
||||
let (columns, rows) = (self.colors.width as isize, self.colors.height as isize);
|
||||
match x >= 0 && y >= 0 && x < columns && y < rows {
|
||||
true => self.colors.data[(y * columns + x) as usize],
|
||||
false => self.beyond,
|
||||
}
|
||||
}
|
||||
|
||||
/// The weighted sum of the colors that the `taps` read around a pixel.
|
||||
fn sum(&self, x: isize, y: isize, taps: &[BilinearTap]) -> [f32; 3] {
|
||||
let mut sum = [0.; 3];
|
||||
for tap in taps {
|
||||
let [shift_x, shift_y] = [x + tap.whole[0], y + tap.whole[1]];
|
||||
let corners = [
|
||||
self.at(shift_x, shift_y),
|
||||
self.at(shift_x + 1, shift_y),
|
||||
self.at(shift_x, shift_y + 1),
|
||||
self.at(shift_x + 1, shift_y + 1),
|
||||
];
|
||||
let weighted = tap.weighted(corners);
|
||||
(0..3).for_each(|channel| sum[channel] += weighted[channel]);
|
||||
}
|
||||
sum
|
||||
}
|
||||
}
|
||||
|
||||
/// A filtered pixel as a premultiplied color: its straight `colors` given the coverage of `alpha`, or for matted surroundings, colors filtered over the gray and lifted back off it within that coverage.
|
||||
fn uncovered(colors: [f32; 3], alpha: f32, surroundings: Surroundings) -> [f32; 4] {
|
||||
let [red, green, blue] = match surroundings {
|
||||
Surroundings::Continued => colors.map(|channel| channel.clamp(0., 1.) * alpha),
|
||||
Surroundings::Matted(gray) => colors.map(|channel| (channel.clamp(0., 1.) - gray as f32 * (1. - alpha)).max(0.).min(alpha)),
|
||||
};
|
||||
[red, green, blue, alpha]
|
||||
}
|
||||
|
||||
/// The premultiplied pixels with each one's color replaced by the weighted sum `convolution` describes, with its shifts measured through `document_to_pixels`.
|
||||
/// It reads the colors as the convolution's surroundings describe, those visible judged by the `full`-strength content, then divides, raises, and clamps the sum, keeping each pixel's coverage unless it weighs that too. O(width × height × taps).
|
||||
pub fn convolve(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, convolution: &Convolution, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
let taps: Vec<BilinearTap> = convolution
|
||||
.taps
|
||||
.iter()
|
||||
.map(|&(shift, weight)| BilinearTap::new(document_to_pixels * shift, (weight / convolution.divisor) as f32))
|
||||
.collect();
|
||||
let offset = convolution.offset as f32;
|
||||
let colors = SurroundedColors::new(plane, full, convolution.surroundings, convolution.reach(), document_to_pixels);
|
||||
let coverage = convolution.weighs_coverage.then(|| SurroundedColors::coverage(plane));
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let (x, y) = (x as isize, y as isize);
|
||||
let alpha = match &coverage {
|
||||
Some(coverage) => coverage.sum(x, y, &taps)[0].clamp(0., 1.),
|
||||
None => plane.data[y as usize * plane.width + x as usize][3],
|
||||
};
|
||||
if alpha <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
let sum = colors.sum(x, y, &taps).map(|channel| channel + offset);
|
||||
*pixel = uncovered(sum, alpha, convolution.surroundings);
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// Each pixel's share of the full-strength content's coverage that the faded fill left, which a filter sharpening the coverage fades its result by. O(width × height).
|
||||
pub fn fill_shares(full: &Plane<[f32; 4]>, filled: &Plane<[f32; 4]>) -> Plane<f32> {
|
||||
full.zip(filled, |full, filled| if full[3] > 0. { (filled[3] / full[3]).min(1.) } else { 0. })
|
||||
}
|
||||
|
||||
/// The fill's filtered straight colors at the coverage of the full-strength content's filtered result, scaled by each pixel's share of it from [`fill_shares`],
|
||||
/// so the fill fades the result as if after the filter. O(width × height).
|
||||
pub fn faded_by_shares(filtered_filled: &Plane<[f32; 4]>, filtered_full: &Plane<[f32; 4]>, shares: &Plane<f32>) -> Plane<[f32; 4]> {
|
||||
let straight = |[red, green, blue, alpha]: [f32; 4]| [red / alpha, green / alpha, blue / alpha];
|
||||
let colors = filtered_filled.zip(filtered_full, |filled, full| {
|
||||
let [red, green, blue] = if filled[3] > 0. {
|
||||
straight(filled)
|
||||
} else if full[3] > 0. {
|
||||
straight(full)
|
||||
} else {
|
||||
[0.; 3]
|
||||
};
|
||||
[red, green, blue, full[3]]
|
||||
});
|
||||
colors.zip(shares, |[red, green, blue, full_alpha], share| {
|
||||
let alpha = full_alpha * share;
|
||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||
})
|
||||
}
|
||||
|
||||
/// For PSD interop, each straight color and the coverage sharpened against the `blur` around it, measured through `document_to_pixels`, by the `amount` and `threshold` fractions [`unsharp_change`] takes.
|
||||
/// The colors are compared against the average of those visible in the `full`-strength content alone (or where too few are, the pixel's own color), so the content's surroundings take no part.
|
||||
/// With no amount and threshold, it's a high pass instead: the colors' difference from their blur around middle gray, with the coverage kept. O(width × height) per blur pass.
|
||||
pub fn unsharp_mask(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, blur: UnsharpBlur, sharpening: Option<(f32, f32)>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
// The visible colors made opaque among the others left out, so dividing their blur by its alpha averages the visible colors alone
|
||||
let visible = plane.zip(full, |[red, green, blue, alpha], [.., full_alpha]| match alpha > 0. && full_alpha >= VISIBLE_ALPHA {
|
||||
true => [red / alpha, green / alpha, blue / alpha, 1.],
|
||||
false => [0.; 4],
|
||||
});
|
||||
|
||||
// A high pass keeps the coverage, so only unsharp masking blurs it
|
||||
let (blurred_colors, blurred_coverage) = match blur {
|
||||
UnsharpBlur::Gaussian(radius) => {
|
||||
let sigma = radius.max(0.) * spans_along_axes(document_to_pixels);
|
||||
let kernels = (BlurKernel::Gaussian { sigma: sigma.x }, BlurKernel::Gaussian { sigma: sigma.y });
|
||||
let blurred_coverage = sharpening.is_some().then(|| plane.map(|[.., alpha]| alpha).blurred(kernels.0, kernels.1));
|
||||
(visible.blurred(kernels.0, kernels.1), blurred_coverage)
|
||||
}
|
||||
UnsharpBlur::EdgeNeighbors => {
|
||||
let blurred_coverage = sharpening.is_some().then(|| neighbors_average(plane, document_to_pixels).map(|[.., alpha]| alpha));
|
||||
(neighbors_average(&visible, document_to_pixels), blurred_coverage)
|
||||
}
|
||||
};
|
||||
let gains = (blur == UnsharpBlur::EdgeNeighbors).then(|| edge_gains(plane, full, document_to_pixels));
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let index = y * plane.width + x;
|
||||
let [red, green, blue, alpha] = plane.data[index];
|
||||
if alpha <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Where too little of the blur lands on visible colors to know their average, the pixel eases into being compared against its own color.
|
||||
// Edges Only moves each channel only its gain's share of the way toward the average.
|
||||
let own = [red / alpha, green / alpha, blue / alpha, alpha];
|
||||
let blurred = blurred_colors.data[index];
|
||||
let weight = average_weight(blurred[3]);
|
||||
let gain = gains.as_ref().map_or([1.; 4], |gains| gains.data[index]);
|
||||
let average: [f32; 3] = std::array::from_fn(|channel| {
|
||||
if weight > 0. {
|
||||
own[channel] + (blurred[channel] / blurred[3] - own[channel]) * weight * gain[channel]
|
||||
} else {
|
||||
own[channel]
|
||||
}
|
||||
});
|
||||
let coverage_average = blurred_coverage.as_ref().map_or(alpha, |blurred_coverage| alpha + (blurred_coverage.data[index] - alpha) * gain[3]);
|
||||
let difference: [f32; 4] = std::array::from_fn(|channel| own[channel] - if channel == 3 { coverage_average } else { average[channel] });
|
||||
|
||||
let sharpened: [f32; 4] = match sharpening {
|
||||
Some((amount, threshold)) => std::array::from_fn(|channel| (own[channel] + unsharp_change(difference[channel], amount, threshold)).clamp(0., 1.)),
|
||||
None => std::array::from_fn(|channel| if channel == 3 { alpha } else { (difference[channel] + HIGH_PASS_GRAY).clamp(0., 1.) }),
|
||||
};
|
||||
let alpha = sharpened[3];
|
||||
*pixel = [sharpened[0] * alpha, sharpened[1] * alpha, sharpened[2] * alpha, alpha];
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// The average of each pixel's four nearest neighbors ([`SHARPEN_NEIGHBORS`], measured through `document_to_pixels`) in every channel, read between pixels with none beyond the plane's edges,
|
||||
/// as Edges Only compares against, matching the GPU's `neighbors_average`. O(width × height).
|
||||
fn neighbors_average(plane: &Plane<[f32; 4]>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
let taps = SHARPEN_NEIGHBORS.map(|shift| BilinearTap::new(document_to_pixels * shift, 0.25));
|
||||
let (columns, rows) = (plane.width as isize, plane.height as isize);
|
||||
let at = |x: isize, y: isize| match x >= 0 && y >= 0 && x < columns && y < rows {
|
||||
true => plane.data[(y * columns + x) as usize],
|
||||
false => [0.; 4],
|
||||
};
|
||||
|
||||
let mut average = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut average.data, plane.width, |y, row: &mut [[f32; 4]]| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
for tap in &taps {
|
||||
let [x, y] = [x as isize + tap.whole[0], y as isize + tap.whole[1]];
|
||||
let corners = [at(x, y), at(x + 1, y), at(x, y + 1), at(x + 1, y + 1)];
|
||||
for (corner, bilinear) in corners.into_iter().zip(tap.bilinear) {
|
||||
(0..4).for_each(|channel| pixel[channel] += corner[channel] * bilinear * tap.weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
average
|
||||
}
|
||||
|
||||
/// For PSD interop, the share of its change Edges Only makes in each channel of each pixel, the [`edge_gain`] of the channel's Sobel gradient there, matching the GPU's `edge_gains`.
|
||||
/// The colors are read continued past those visible in the `full`-strength content, and the coverage with none beyond it. O(width × height).
|
||||
fn edge_gains(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
// A faint pixel the gradient reads finds its nearest visible color within the square of a pixel around it
|
||||
let colors = SurroundedColors::new(plane, full, Surroundings::Continued, 1., document_to_pixels);
|
||||
let coverage = SurroundedColors::coverage(plane);
|
||||
let taps = |axis: usize| SOBEL_TAPS.map(|(shift, weights)| BilinearTap::new(document_to_pixels * shift, weights[axis] as f32));
|
||||
let (across, down) = (taps(0), taps(1));
|
||||
|
||||
let mut gains = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut gains.data, plane.width, |y, row: &mut [[f32; 4]]| {
|
||||
for (x, gain) in row.iter_mut().enumerate() {
|
||||
let (x, y) = (x as isize, y as isize);
|
||||
let [colors_across, colors_down] = [colors.sum(x, y, &across), colors.sum(x, y, &down)];
|
||||
let [coverage_across, coverage_down] = [coverage.sum(x, y, &across)[0], coverage.sum(x, y, &down)[0]];
|
||||
|
||||
*gain = std::array::from_fn(|channel| match channel {
|
||||
3 => edge_gain(coverage_across.hypot(coverage_down)),
|
||||
_ => edge_gain(colors_across[channel].hypot(colors_down[channel])),
|
||||
});
|
||||
}
|
||||
});
|
||||
gains
|
||||
}
|
||||
|
||||
/// For PSD interop, each channel darkened by how steeply it changes, the length of its Sobel gradient, so edges show dark over white.
|
||||
/// The content is matted over white, so its silhouette shows as an edge too. O(width × height).
|
||||
pub fn find_edges(plane: &Plane<[f32; 4]>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
let surroundings = Surroundings::Matted(1.);
|
||||
let colors = SurroundedColors::new(plane, plane, surroundings, 1., document_to_pixels);
|
||||
let taps = |axis: usize| SOBEL_TAPS.map(|(shift, weights)| BilinearTap::new(document_to_pixels * shift, weights[axis] as f32));
|
||||
let (across, down) = (taps(0), taps(1));
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let alpha = plane.data[y * plane.width + x][3];
|
||||
if alpha <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (x, y) = (x as isize, y as isize);
|
||||
let [across, down] = [colors.sum(x, y, &across), colors.sum(x, y, &down)];
|
||||
let edges = std::array::from_fn(|channel| 1. - across[channel].hypot(down[channel]));
|
||||
*pixel = uncovered(edges, alpha, surroundings);
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// For PSD interop, each pixel's color is the lightest in the square of `radius` document pixels around it (or with `maximum` false, the darkest), and its coverage the opposite extreme.
|
||||
/// The maximum spreads every covered pixel's straight color. The minimum spreads the darkest colors matted over white, lifted back off within the grown coverage, so faint pixels darken only as much as they cover.
|
||||
/// A fractional radius mixes the whole radii around it. O(width × height).
|
||||
pub fn neighborhood_extreme(plane: &Plane<[f32; 4]>, radius: f64, maximum: bool, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
let spans = spans_along_axes(document_to_pixels);
|
||||
let ([near_x, far_x], fraction) = neighborhood_radii(radius, spans.x);
|
||||
let ([near_y, far_y], _) = neighborhood_radii(radius, spans.y);
|
||||
if near_x.max(near_y) == 0 && (fraction <= 0. || far_x.max(far_y) == 0) {
|
||||
return plane.clone();
|
||||
}
|
||||
|
||||
// Colors and coverage in the form the filter takes the extremes of, with uncovered pixels' colors (and those beyond the edges) at the identity of their extreme
|
||||
let (prepared, beyond) = match maximum {
|
||||
true => (
|
||||
plane.map(|[red, green, blue, alpha]| match alpha > 0. {
|
||||
true => [red / alpha, green / alpha, blue / alpha, alpha],
|
||||
false => [0.; 4],
|
||||
}),
|
||||
[0.; 4],
|
||||
),
|
||||
false => (
|
||||
plane.map(|[red, green, blue, alpha]| [red + 1. - alpha, green + 1. - alpha, blue + 1. - alpha, alpha]),
|
||||
[1., 1., 1., 0.],
|
||||
),
|
||||
};
|
||||
let extreme = move |first: [f32; 4], second: [f32; 4]| -> [f32; 4] {
|
||||
std::array::from_fn(|channel| match (channel == 3) != maximum {
|
||||
true => first[channel].max(second[channel]),
|
||||
false => first[channel].min(second[channel]),
|
||||
})
|
||||
};
|
||||
// Back to premultiplied colors, which for the minimum lifts white back off within the grown coverage
|
||||
let premultiplied = move |[red, green, blue, alpha]: [f32; 4]| {
|
||||
let channel = |channel: f32| match maximum {
|
||||
true => channel * alpha,
|
||||
false => (channel - (1. - alpha)).max(0.).min(alpha),
|
||||
};
|
||||
[channel(red), channel(green), channel(blue), alpha]
|
||||
};
|
||||
|
||||
// The larger square's extremes grow from the smaller one's, as a square widened by another is the square of their radii summed
|
||||
let near = extremes_in_squares(prepared, [near_x, near_y], beyond, extreme);
|
||||
if fraction <= 0. {
|
||||
return near.map(premultiplied);
|
||||
}
|
||||
let far = extremes_in_squares(near.clone(), [far_x - near_x, far_y - near_y], beyond, extreme);
|
||||
near.zip(&far, |near, far| {
|
||||
let (near, far) = (premultiplied(near), premultiplied(far));
|
||||
std::array::from_fn(|channel| near[channel] + (far[channel] - near[channel]) * fraction as f32)
|
||||
})
|
||||
}
|
||||
|
||||
/// The `extreme` of each rectangle reaching `across` and `down` pixels from each pixel, with `beyond` read past the edges, along the rows then the columns. O(width × height).
|
||||
fn extremes_in_squares(plane: Plane<[f32; 4]>, [across, down]: [u32; 2], beyond: [f32; 4], extreme: impl Fn([f32; 4], [f32; 4]) -> [f32; 4] + Copy + Sync) -> Plane<[f32; 4]> {
|
||||
let along_rows = |plane: Plane<[f32; 4]>, radius: u32| {
|
||||
if radius == 0 {
|
||||
return plane;
|
||||
}
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
window_extremes(&plane.data[y * plane.width..(y + 1) * plane.width], row, radius as usize, beyond, extreme)
|
||||
});
|
||||
result
|
||||
};
|
||||
|
||||
let plane = along_rows(plane, across);
|
||||
match down {
|
||||
0 => plane,
|
||||
_ => along_rows(plane.transposed(), down).transposed(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `extreme` of each window of `2 × radius + 1` values along a row, with `beyond` read past its ends, by van Herk and Gil-Werman's blocks of extremes running from each block's start and to its end.
|
||||
/// O(length) whatever the radius, since a window as wide as the row already holds all of it.
|
||||
fn window_extremes(source: &[[f32; 4]], target: &mut [[f32; 4]], radius: usize, beyond: [f32; 4], extreme: impl Fn([f32; 4], [f32; 4]) -> [f32; 4]) {
|
||||
let radius = radius.min(source.len());
|
||||
let window = 2 * radius + 1;
|
||||
let padded: Vec<[f32; 4]> = std::iter::repeat_n(beyond, radius).chain(source.iter().copied()).chain(std::iter::repeat_n(beyond, radius)).collect();
|
||||
|
||||
let mut from_start = padded.clone();
|
||||
let mut to_end = padded.clone();
|
||||
for index in 1..padded.len() {
|
||||
if index % window != 0 {
|
||||
from_start[index] = extreme(from_start[index - 1], padded[index]);
|
||||
}
|
||||
}
|
||||
for index in (0..padded.len() - 1).rev() {
|
||||
if (index + 1) % window != 0 {
|
||||
to_end[index] = extreme(to_end[index + 1], padded[index]);
|
||||
}
|
||||
}
|
||||
|
||||
// Each window spans the end of one block and the start of the next
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
*value = extreme(to_end[index], from_start[index + window - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A value strictly between 0 and 1 from the top 23 bits of a hash, which an f32 holds exactly with the half added, matching the GPU's.
|
||||
fn unit_interval(hash: u32) -> f32 {
|
||||
((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32
|
||||
}
|
||||
|
||||
/// The three random values one field of the `seed` holds at a cell of the effect space.
|
||||
fn field_values(cell: IVec2, seed: u32) -> [f32; 3] {
|
||||
pcg3d([cell.x as u32, cell.y as u32, seed]).map(unit_interval)
|
||||
}
|
||||
|
||||
/// The noise each of a pixel's colors takes before the amount scales it, averaged over the pixel's samples of the field: uniform from -1 to 1, or Gaussian with a deviation of 1 cut off at [`GAUSSIAN_NOISE_LIMIT`].
|
||||
fn noise_at(sampling: &FieldSampling, pixel: [usize; 2], distribution: NoiseDistribution, monochromatic: bool, seed: i64) -> [f32; 3] {
|
||||
let (offsets_seed, angles_seed) = (RandomField::NoiseOffsets.seed(seed), RandomField::NoiseAngles.seed(seed));
|
||||
|
||||
let mut sum = [0.; 3];
|
||||
let mut count = 0.;
|
||||
for cell in sampling.sample_cells(pixel) {
|
||||
let offsets = field_values(cell, offsets_seed);
|
||||
let noise = match distribution {
|
||||
NoiseDistribution::Uniform => offsets.map(|value| 2. * value - 1.),
|
||||
// The Box-Muller transform of two uniform values into one with a normal distribution
|
||||
NoiseDistribution::Gaussian => {
|
||||
let angles = field_values(cell, angles_seed);
|
||||
std::array::from_fn(|channel| ((-2. * offsets[channel].ln()).sqrt() * (std::f32::consts::TAU * angles[channel]).cos()).clamp(-GAUSSIAN_NOISE_LIMIT, GAUSSIAN_NOISE_LIMIT))
|
||||
}
|
||||
};
|
||||
(0..3).for_each(|channel| sum[channel] += noise[channel]);
|
||||
count += 1.;
|
||||
}
|
||||
|
||||
let average = sum.map(|channel| channel / count);
|
||||
if monochromatic { [average[0]; 3] } else { average }
|
||||
}
|
||||
|
||||
/// For PSD interop, each straight color offset by noise of `amount` (a fraction of full brightness) with its `distribution`, the same for every color of a pixel if it's `monochromatic`, and clamped.
|
||||
/// The coverage is kept. The noise is fixed to the cells of the effect space, which `pixels_to_effect` places the plane's pixels among. O(width × height × samples per pixel).
|
||||
pub fn add_noise(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||
let sampling = FieldSampling::new(pixels_to_effect);
|
||||
let extent = noise_extent(amount, distribution) as f32;
|
||||
let scale = (amount * sampling.deviation_scale) as f32;
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let [red, green, blue, alpha] = plane.data[y * plane.width + x];
|
||||
if alpha <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
let noise = noise_at(&sampling, [x, y], distribution, monochromatic, seed);
|
||||
let noisy = |channel: f32, noise: f32| (channel / alpha + (noise * scale).clamp(-extent, extent)).clamp(0., 1.) * alpha;
|
||||
*pixel = [noisy(red, noise[0]), noisy(green, noise[1]), noisy(blue, noise[2]), alpha];
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// For PSD interop, how much of a pixel Dissolve shows, from 0 to 1: the share of its samples passing the `opacity` (a fraction), and the threshold level from 0 to 254 its coverage must pass.
|
||||
/// For pixels spanning more cells than they sample, the share deviates from the opacity less, as it would over them all.
|
||||
fn dissolve_field(sampling: &FieldSampling, pixel: [usize; 2], opacity: f32, seed: i64) -> (f32, f32) {
|
||||
let seed = RandomField::Dissolve.seed(seed);
|
||||
|
||||
let (mut shown, mut count) = (0., 0.);
|
||||
for cell in sampling.sample_cells(pixel) {
|
||||
shown += if field_values(cell, seed)[0] < opacity { 1. } else { 0. };
|
||||
count += 1.;
|
||||
}
|
||||
let share = (opacity + (shown / count - opacity) * sampling.deviation_scale as f32).clamp(0., 1.);
|
||||
|
||||
let threshold = (field_values(sampling.center_cell(pixel), seed)[1] * 255.).floor();
|
||||
(share, threshold)
|
||||
}
|
||||
|
||||
/// For PSD interop, the content shown fully opaque where the `opacity` (a fraction) and the coverage each pass a threshold of their own, random for each cell of the effect space, and hidden elsewhere.
|
||||
/// The thresholds are fixed to those cells, which `pixels_to_effect` places the plane's pixels among, and pixels spanning several show the share of them passing. O(width × height × samples per pixel).
|
||||
pub fn dissolve(plane: &Plane<[f32; 4]>, opacity: f64, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||
let sampling = FieldSampling::new(pixels_to_effect);
|
||||
let opacity = opacity as f32;
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let [red, green, blue, alpha] = plane.data[y * plane.width + x];
|
||||
if alpha <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The coverage passes a threshold level when it's at least one 8-bit level above it, a half level counting as the level below as browsers truncate it
|
||||
let (share, threshold) = dissolve_field(&sampling, [x, y], opacity, seed);
|
||||
let shown = if alpha * 255. > threshold + 0.5 { share } else { 0. };
|
||||
*pixel = [red / alpha * shown, green / alpha * shown, blue / alpha * shown, shown];
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn plane(width: usize, height: usize, data: Vec<[f32; 4]>) -> Plane<[f32; 4]> {
|
||||
Plane { width, height, data }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernels_of_any_shape_read_around_their_center() {
|
||||
let (black, white) = ([0., 0., 0., 1.], [1.; 4]);
|
||||
|
||||
// An even row centers on its second weight, so its first reads the pixel to the left, moving the colors right
|
||||
let line = plane(3, 1, vec![white, black, black]);
|
||||
let even = convolve(&line, &line, &Convolution::custom(&[1., 0.], 2, 1., 0.), DMat2::IDENTITY);
|
||||
assert_eq!(&even.data[1..], &[white, black]);
|
||||
|
||||
// A column reads the pixels above and below
|
||||
let column = plane(1, 3, vec![white, black, black]);
|
||||
let down = convolve(&column, &column, &Convolution::custom(&[1., 0., 0.], 1, 1., 0.), DMat2::IDENTITY);
|
||||
assert_eq!(&down.data[1..], &[white, black]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kernel_of_one_weight_shifts_the_colors_within_the_coverage() {
|
||||
let (black, white) = ([0., 0., 0., 1.], [1.; 4]);
|
||||
let line = plane(4, 1, vec![black, white, black, [0.; 4]]);
|
||||
|
||||
// The weight right of the center reads the pixel to the right, moving the colors left
|
||||
let right = [0., 0., 0., 0., 0., 1., 0., 0., 0.];
|
||||
let shifted = convolve(&line, &line, &Convolution::custom(&right, 3, 1., 0.), DMat2::IDENTITY);
|
||||
assert_eq!(shifted.data, vec![white, black, black, [0.; 4]]);
|
||||
|
||||
// A shift of half a pixel splits between two
|
||||
let halved = convolve(&line, &line, &Convolution::custom(&right, 3, 1., 0.), DMat2::from_diagonal(DVec2::splat(0.5)));
|
||||
assert_eq!(halved.data, vec![[0.5, 0.5, 0.5, 1.], [0.5, 0.5, 0.5, 1.], black, [0.; 4]]);
|
||||
|
||||
// A shift past the edge reads between the colors continued past it and none further, which it leaves out rather than darkening toward
|
||||
let edge = plane(5, 1, vec![white, white, [0.; 4], [0.; 4], [0.; 4]]);
|
||||
let past_edge = convolve(&edge, &edge, &Convolution::custom(&right, 3, 1., 0.), DMat2::from_diagonal(DVec2::splat(1.25)));
|
||||
assert_eq!(past_edge.data[1], white);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sums_are_divided_raised_and_clamped() {
|
||||
let gray = [0.25, 0.25, 0.25, 0.5];
|
||||
let line = plane(3, 1, vec![gray; 3]);
|
||||
|
||||
// Doubled to full brightness, then raised past it
|
||||
let raised = convolve(&line, &line, &Convolution::custom(&[2.], 1, 1., 255. / 4.), DMat2::IDENTITY);
|
||||
assert_eq!(raised.data[1], [0.5; 4]);
|
||||
|
||||
// The difference across a flat color is nothing, which the offset lifts to middle gray
|
||||
let difference = convolve(&line, &line, &Convolution::custom(&[-1., 0., 1.], 3, 2., 255. / 2.), DMat2::IDENTITY);
|
||||
assert_eq!(difference.data[1], [0.25, 0.25, 0.25, 0.5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_continue_past_the_edges_from_the_nearest_visible_pixel() {
|
||||
let red = [1., 0., 0., 1.];
|
||||
let faint_blue = [0., 0., 0.01, 0.01];
|
||||
let line = plane(5, 1, vec![[0.; 4], [0.; 4], red, faint_blue, [0.; 4]]);
|
||||
|
||||
// Averaging three neighbors at the edge reads the red beyond it rather than black, leaving the red as it is
|
||||
let averaged = convolve(&line, &line, &Convolution::custom(&[1., 1., 1.], 3, 3., 0.), DMat2::IDENTITY);
|
||||
assert!((averaged.data[2][0] - 1.).abs() < 1e-6, "{:?}", averaged.data[2]);
|
||||
// The faint pixel reads red rather than its own blue, keeping its own coverage
|
||||
let faint = averaged.data[3];
|
||||
assert!(faint[0] > 0. && faint[2] == 0. && faint[3] == 0.01, "{faint:?}");
|
||||
}
|
||||
|
||||
/// A white square of `inner` pixels in the middle of a transparent square of `outer` pixels.
|
||||
fn white_square(outer: usize, inner: std::ops::Range<usize>) -> Plane<[f32; 4]> {
|
||||
let mut square = Plane::new(outer, outer);
|
||||
for y in inner.clone() {
|
||||
square.data[y * outer + inner.start..y * outer + inner.end].fill([1.; 4]);
|
||||
}
|
||||
square
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emboss_grays_flat_colors_and_shows_the_silhouette_in_relief() {
|
||||
let square = white_square(16, 4..12);
|
||||
let embossed = convolve(&square, &square, &Convolution::emboss(0., 2., 100.), DMat2::IDENTITY);
|
||||
let at = |x: usize| embossed.data[8 * 16 + x];
|
||||
|
||||
// The inside is flat, so it's middle gray
|
||||
assert_eq!(at(8), [0.5, 0.5, 0.5, 1.]);
|
||||
// Lit from the right, the right edge's white falls off to the gray beyond it, and the left edge rises from it
|
||||
assert!(at(11)[0] < 0.5 && at(4)[0] > 0.5, "{:?} {:?}", at(11), at(4));
|
||||
assert_eq!(at(2), [0.; 4], "nothing outside");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_edges_whitens_flat_colors_and_darkens_the_silhouette() {
|
||||
let square = white_square(16, 4..12);
|
||||
let edges = find_edges(&square, DMat2::IDENTITY);
|
||||
let at = |x: usize, y: usize| edges.data[y * 16 + x];
|
||||
|
||||
assert_eq!(at(8, 8), [1.; 4]);
|
||||
// Over white, the white square's edge has no contrast, so it stays white
|
||||
assert_eq!(at(4, 8), [1.; 4]);
|
||||
|
||||
// A black square's edge against the white it's matted over is dark
|
||||
let black = white_square(16, 4..12).map(|[_, _, _, alpha]| [0., 0., 0., alpha]);
|
||||
let edges = find_edges(&black, DMat2::IDENTITY);
|
||||
assert_eq!(edges.data[8 * 16 + 4], [0., 0., 0., 1.]);
|
||||
assert_eq!(edges.data[8 * 16 + 8], [1.; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighborhood_maximum_spreads_light_colors_as_coverage_shrinks() {
|
||||
let mut square = white_square(16, 2..14);
|
||||
square.data[8 * 16 + 8] = [0., 0., 0., 1.];
|
||||
|
||||
let maximum = neighborhood_extreme(&square, 1., true, DMat2::IDENTITY);
|
||||
assert_eq!(maximum.data[8 * 16 + 8], [1.; 4], "the dark pixel takes its lighter neighbors' color");
|
||||
assert_eq!(maximum.data[8 * 16 + 2], [0.; 4], "the coverage shrinks by the radius");
|
||||
assert_eq!(maximum.data[8 * 16 + 3], [1.; 4]);
|
||||
|
||||
let minimum = neighborhood_extreme(&square, 1., false, DMat2::IDENTITY);
|
||||
assert_eq!(minimum.data[9 * 16 + 9], [0., 0., 0., 1.], "the dark pixel spreads");
|
||||
assert_eq!(minimum.data[8 * 16 + 1], [1.; 4], "the coverage grows by the radius, with the colors beyond taking no part");
|
||||
|
||||
// Half a radius more mixes halfway toward the next
|
||||
let between = neighborhood_extreme(&square, 1.5, false, DMat2::IDENTITY);
|
||||
assert_eq!(between.data[9 * 16 + 9], [0., 0., 0., 1.]);
|
||||
assert_eq!(between.data[10 * 16 + 10], [0.5, 0.5, 0.5, 1.]);
|
||||
assert_eq!(between.data[8 * 16], [0.5; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighborhood_extremes_keep_faint_colors_and_a_zero_radius_changes_nothing() {
|
||||
// A faint red block keeps its color at its own coverage, rather than taking either extreme's identity
|
||||
let mut faint = plane(7, 7, vec![[0.; 4]; 49]);
|
||||
for y in 1..6 {
|
||||
faint.data[y * 7 + 1..y * 7 + 6].fill([0.04, 0., 0., 0.04]);
|
||||
}
|
||||
for maximum in [true, false] {
|
||||
let extreme = neighborhood_extreme(&faint, 1., maximum, DMat2::IDENTITY);
|
||||
let [red, green, blue, alpha] = extreme.data[3 * 7 + 3];
|
||||
assert!(
|
||||
(red - 0.04).abs() < 1e-6 && green.abs() < 1e-6 && blue.abs() < 1e-6 && (alpha - 0.04).abs() < 1e-6,
|
||||
"{:?}",
|
||||
extreme.data[3 * 7 + 3]
|
||||
);
|
||||
|
||||
assert_eq!(neighborhood_extreme(&faint, 0., maximum, DMat2::IDENTITY).data, faint.data);
|
||||
}
|
||||
|
||||
// At twice the zoom, a radius of one document pixel reaches two pixels
|
||||
let mut dot = plane(9, 9, vec![[1.; 4]; 81]);
|
||||
dot.data[4 * 9 + 4] = [0., 0., 0., 1.];
|
||||
let spread = neighborhood_extreme(&dot, 1., false, DMat2::from_diagonal(DVec2::splat(2.)));
|
||||
assert_eq!(spread.data[2 * 9 + 6], [0., 0., 0., 1.]);
|
||||
assert_eq!(spread.data[9 + 4], [1.; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_fades_sharpened_coverage_evenly() {
|
||||
// Sharpening the faded square alone would overshoot at its edge, where the full-strength square's clamp at full coverage hides it
|
||||
let square = white_square(16, 4..12);
|
||||
let faded = square.map(|pixel| pixel.map(|channel| channel * 0.5));
|
||||
let sharpen = |plane: &Plane<[f32; 4]>| unsharp_mask(plane, plane, UnsharpBlur::EdgeNeighbors, Some((1., 0.)), DMat2::IDENTITY);
|
||||
assert!(sharpen(&faded).data.iter().any(|pixel| pixel[3] > 0.5));
|
||||
|
||||
let result = faded_by_shares(&sharpen(&faded), &sharpen(&square), &fill_shares(&square, &faded));
|
||||
assert!(result.data.iter().all(|pixel| pixel[3] == 0. || pixel[3] == 0.5), "{:?}", result.data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_extremes_match_a_direct_search() {
|
||||
let values: Vec<[f32; 4]> = (0..37).map(|index| [((index * 7919) % 31) as f32; 4]).collect();
|
||||
for radius in [1, 2, 5, 40] {
|
||||
let mut fast = vec![[0.; 4]; values.len()];
|
||||
window_extremes(&values, &mut fast, radius, [-1.; 4], |first, second| std::array::from_fn(|channel| first[channel].max(second[channel])));
|
||||
|
||||
for (index, value) in fast.iter().enumerate() {
|
||||
let window = (index as isize - radius as isize)..=(index as isize + radius as isize);
|
||||
let direct = window.map(|at| values.get(at as usize).filter(|_| at >= 0).map_or(-1., |value| value[0])).fold(f32::MIN, f32::max);
|
||||
assert_eq!(value[0], direct, "radius {radius} at {index}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsharp_masking_exaggerates_differences_past_its_threshold() {
|
||||
// A gray line with a lighter middle, a step the blur softens
|
||||
let mut line = plane(9, 1, vec![[0.5, 0.5, 0.5, 1.]; 9]);
|
||||
line.data[4] = [0.6, 0.6, 0.6, 1.];
|
||||
|
||||
let gaussian = UnsharpBlur::Gaussian(1.);
|
||||
let sharpened = unsharp_mask(&line, &line, gaussian, Some((1., 0.)), DMat2::IDENTITY);
|
||||
assert!(sharpened.data[4][0] > 0.6 && sharpened.data[3][0] < 0.5, "{:?}", sharpened.data);
|
||||
assert_eq!(sharpened.data[4][3], 1., "full coverage stays full");
|
||||
|
||||
// A threshold past the exaggerated difference leaves every pixel as it is
|
||||
let untouched = unsharp_mask(&line, &line, gaussian, Some((1., 0.2)), DMat2::IDENTITY);
|
||||
assert_eq!(untouched.data, line.data);
|
||||
|
||||
// A high pass of a flat color is middle gray
|
||||
let flat = plane(5, 1, vec![[0.3, 0.3, 0.3, 1.]; 5]);
|
||||
assert_eq!(
|
||||
unsharp_mask(&flat, &flat, UnsharpBlur::Gaussian(2.), None, DMat2::IDENTITY).data[2],
|
||||
[HIGH_PASS_GRAY, HIGH_PASS_GRAY, HIGH_PASS_GRAY, 1.]
|
||||
);
|
||||
|
||||
// A fill faint enough to fall below the visible threshold still averages the colors the full-strength content shows
|
||||
let faint = line.map(|pixel| pixel.map(|channel| channel * 0.05));
|
||||
let faint_sharpened = unsharp_mask(&faint, &line, gaussian, Some((1., 0.)), DMat2::IDENTITY);
|
||||
let straight = |pixel: [f32; 4]| pixel[0] / pixel[3];
|
||||
assert!((straight(faint_sharpened.data[4]) - straight(sharpened.data[4])).abs() < 1e-4, "{:?}", faint_sharpened.data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_only_sharpens_against_the_neighbors_as_far_as_an_edge_runs_through() {
|
||||
// A gray step up by `height` between columns, across which the Sobel gradient is four times as long, read along the middle row
|
||||
let step = |height: f32| {
|
||||
let mut columns = plane(6, 3, vec![[0.4, 0.4, 0.4, 1.]; 18]);
|
||||
(0..3).for_each(|y| (3..6).for_each(|x| columns.data[y * 6 + x] = [0.4 + height, 0.4 + height, 0.4 + height, 1.]));
|
||||
columns
|
||||
};
|
||||
let sharpen = |plane: &Plane<[f32; 4]>, amount: f32, threshold: f32| unsharp_mask(plane, plane, UnsharpBlur::EdgeNeighbors, Some((amount, threshold)), DMat2::IDENTITY).data;
|
||||
let close = |actual: f32, expected: f32| (actual - expected).abs() < 1e-5;
|
||||
|
||||
// A strong step sharpens fully, each side moving by its difference from its four neighbors' average, a quarter of the step, while flat areas stay
|
||||
let strong = sharpen(&step(0.4), 1., 0.);
|
||||
assert!(close(strong[8][0], 0.3) && close(strong[9][0], 0.9) && close(strong[7][0], 0.4), "{strong:?}");
|
||||
|
||||
// A step under a sixteenth of full contrast stays as it is, and one of an eighth sharpens a third as much
|
||||
assert!(close(sharpen(&step(0.05), 1., 0.)[8][0], 0.4));
|
||||
assert!(close(sharpen(&step(0.125), 1., 0.)[8][0], 0.4 - 0.125 / 4. / 3.));
|
||||
|
||||
// The threshold softens the change, which half the amount halves
|
||||
assert!(close(sharpen(&step(0.4), 1., 0.05)[8][0], 0.35));
|
||||
assert!(close(sharpen(&step(0.4), 0.5, 0.)[8][0], 0.35));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kernel_applied_to_alpha_weighs_the_coverage_too() {
|
||||
let mut line = plane(5, 1, vec![[0.; 4]; 5]);
|
||||
line.data[2] = [0.6, 0.3, 0., 1.];
|
||||
let average = Convolution::custom(&[1., 1., 1.], 3, 3., 0.);
|
||||
|
||||
// Averaged with its neighbors, the coverage of a lone pixel spreads a third of itself to each side
|
||||
let spread = convolve(
|
||||
&line,
|
||||
&line,
|
||||
&Convolution {
|
||||
weighs_coverage: true,
|
||||
..average.clone()
|
||||
},
|
||||
DMat2::IDENTITY,
|
||||
);
|
||||
let alphas: Vec<f32> = spread.data.iter().map(|pixel| pixel[3]).collect();
|
||||
assert!(alphas.iter().zip([0., 1., 1., 1., 0.]).all(|(alpha, thirds)| (alpha - thirds / 3.).abs() < 1e-6), "{alphas:?}");
|
||||
|
||||
// Otherwise, the coverage stays as it is
|
||||
let kept = convolve(&line, &line, &average, DMat2::IDENTITY);
|
||||
assert!(kept.data.iter().zip(&line.data).all(|(kept, line)| kept[3] == line[3]));
|
||||
}
|
||||
|
||||
/// The mean and standard deviation of each color's offset from middle gray, and the correlation between the first two colors' offsets.
|
||||
fn offset_statistics(noisy: &Plane<[f32; 4]>) -> ([f64; 3], [f64; 3], f64) {
|
||||
let count = noisy.data.len() as f64;
|
||||
let offsets: Vec<[f64; 3]> = noisy.data.iter().map(|pixel| std::array::from_fn(|channel| pixel[channel] as f64 / pixel[3] as f64 - 0.5)).collect();
|
||||
let mean: [f64; 3] = std::array::from_fn(|channel| offsets.iter().map(|offset| offset[channel]).sum::<f64>() / count);
|
||||
let deviation: [f64; 3] = std::array::from_fn(|channel| (offsets.iter().map(|offset| (offset[channel] - mean[channel]).powi(2)).sum::<f64>() / count).sqrt());
|
||||
let covariance = offsets.iter().map(|offset| (offset[0] - mean[0]) * (offset[1] - mean[1])).sum::<f64>() / count;
|
||||
(mean, deviation, covariance / (deviation[0] * deviation[1]))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_follows_its_distribution_independently_for_each_color() {
|
||||
let gray = plane(256, 256, vec![[0.5, 0.5, 0.5, 1.]; 256 * 256]);
|
||||
let amount = 0.2;
|
||||
|
||||
// Uniform noise spreads evenly up to the amount, with a deviation of the amount over √3
|
||||
let uniform = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY);
|
||||
let (mean, deviation, correlation) = offset_statistics(&uniform);
|
||||
for channel in 0..3 {
|
||||
assert!(
|
||||
mean[channel].abs() < 0.002 && (deviation[channel] / (amount / 3_f64.sqrt()) - 1.).abs() < 0.02,
|
||||
"{mean:?} {deviation:?}"
|
||||
);
|
||||
}
|
||||
assert!(correlation.abs() < 0.02, "{correlation}");
|
||||
assert!(uniform.data.iter().all(|pixel| (pixel[0] - 0.5).abs() <= amount as f32 && pixel[3] == 1.));
|
||||
|
||||
// Gaussian noise deviates by the amount, cut off at its limit
|
||||
let gaussian = add_noise(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY);
|
||||
let (_, deviation, _) = offset_statistics(&gaussian);
|
||||
assert!((deviation[0] / amount - 1.).abs() < 0.03, "{deviation:?}");
|
||||
|
||||
// Monochromatic noise shifts every color of a pixel together, and another seed gives other noise
|
||||
let monochromatic = add_noise(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
|
||||
assert!(monochromatic.data.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
|
||||
let reseeded = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY);
|
||||
assert_ne!(reseeded.data[..64], uniform.data[..64]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_is_fixed_to_the_effect_spaces_cells_and_averages_where_pixels_span_several() {
|
||||
let gray = |size: usize| plane(size, size, vec![[0.5, 0.5, 0.5, 1.]; size * size]);
|
||||
let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| add_noise(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect);
|
||||
|
||||
// A plane placed three cells right and five down holds the same noise at the same cells
|
||||
let placed = noise(&gray(16), DAffine2::IDENTITY);
|
||||
let moved = noise(&gray(16), DAffine2::from_translation(DVec2::new(3., 5.)));
|
||||
assert_eq!(moved.data[0], placed.data[5 * 16 + 3]);
|
||||
assert_eq!(moved.data[16 + 2], placed.data[6 * 16 + 5]);
|
||||
|
||||
// Pixels spanning eight cells each deviate as an average over all 64 would, an eighth as much
|
||||
let zoomed_out = noise(&gray(128), DAffine2::from_scale(DVec2::splat(8.)));
|
||||
let (_, deviation, _) = offset_statistics(&zoomed_out);
|
||||
assert!((deviation[0] / (0.3 / 3_f64.sqrt() / 8.) - 1.).abs() < 0.05, "{deviation:?}");
|
||||
|
||||
// Pixels at exactly one cell each take one sample, like zoomed in
|
||||
assert_eq!(FieldSampling::new(DAffine2::IDENTITY).counts, glam::UVec2::ONE);
|
||||
assert_eq!(FieldSampling::new(DAffine2::from_scale(DVec2::splat(0.25))).counts, glam::UVec2::ONE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dissolve_shows_opaque_pixels_by_the_opacity_and_the_coverage() {
|
||||
let shown_share = |plane: &Plane<[f32; 4]>| plane.data.iter().filter(|pixel| pixel[3] > 0.).count() as f64 / plane.data.len() as f64;
|
||||
let red = |alpha: f32| plane(256, 256, vec![[alpha, 0., 0., alpha]; 256 * 256]);
|
||||
|
||||
// Where the content is opaque, the opacity's share shows, and a larger opacity shows those and more
|
||||
let some = dissolve(&red(1.), 0.3, 0, DAffine2::IDENTITY);
|
||||
let more = dissolve(&red(1.), 0.6, 0, DAffine2::IDENTITY);
|
||||
assert!((shown_share(&some) - 0.3).abs() < 0.01 && (shown_share(&more) - 0.6).abs() < 0.01);
|
||||
assert!(some.data.iter().zip(&more.data).all(|(some, more)| some[3] <= more[3]));
|
||||
|
||||
// Half-covered content shows half as much, each shown pixel fully opaque in its straight color
|
||||
let half = dissolve(&red(0.5), 1., 0, DAffine2::IDENTITY);
|
||||
assert!((shown_share(&half) - 127. / 255.).abs() < 0.01, "{}", shown_share(&half));
|
||||
assert!(half.data.iter().all(|pixel| *pixel == [0.; 4] || *pixel == [1., 0., 0., 1.]));
|
||||
|
||||
// Pixels spanning several cells show the share of them passing the opacity
|
||||
let zoomed_out = dissolve(&red(1.), 0.3, 0, DAffine2::from_scale(DVec2::splat(2.)));
|
||||
let average = zoomed_out.data.iter().map(|pixel| pixel[3] as f64).sum::<f64>() / zoomed_out.data.len() as f64;
|
||||
assert!((average - 0.3).abs() < 0.01 && zoomed_out.data.iter().any(|pixel| pixel[3] == 0.5), "{average}");
|
||||
|
||||
// For PSD interop, the opacity and the coverage pass thresholds of their own, so equal products show different pixels, neither set holding the other
|
||||
let quarter = dissolve(&red(64. / 255.), 1., 0, DAffine2::IDENTITY);
|
||||
let half_at_half = dissolve(&red(128. / 255.), 0.5, 0, DAffine2::IDENTITY);
|
||||
let only_in = |first: &Plane<[f32; 4]>, second: &Plane<[f32; 4]>| first.data.iter().zip(&second.data).filter(|(first, second)| first[3] > 0. && second[3] <= 0.).count();
|
||||
assert!(only_in(&quarter, &half_at_half) > 1000 && only_in(&half_at_half, &quarter) > 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_values_lie_strictly_between_zero_and_one() {
|
||||
assert!(unit_interval(u32::MAX) < 1. && unit_interval(0) > 0.);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::mandelbrot::{MandelbrotSetup, resolves_in_32_bits};
|
||||
use core_types::Color;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType, hash_fraction, pcg3d};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{Image, ImageError};
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32,
|
||||
let interior_test = setup.has_interior_test() && resolves_in_32_bits(plane_area, plane_texel);
|
||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| {
|
||||
*pixel = pattern_gray(setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test));
|
||||
*pixel = mandelbrot_gray(setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -60,18 +60,18 @@ pub fn pattern_sampler(pattern: &GeneratorPattern) -> impl Fn(DVec2) -> Color +
|
||||
};
|
||||
|
||||
move |point| match &sampler {
|
||||
Sampler::Noise(noise) => pattern_gray(noise.sample(point)),
|
||||
Sampler::Mandelbrot(setup) => pattern_gray(setup.sample(setup.plane_point(point), None, false)),
|
||||
Sampler::Noise(noise) => Color::from_luminance(noise.sample(point)),
|
||||
Sampler::Mandelbrot(setup) => mandelbrot_gray(setup.sample(setup.plane_point(point), None, false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern's value from 0 to 1 as the gray at that gamma-encoded level, so middle values show as middle gray and a Gradient Map takes the value as the position along its gradient.
|
||||
fn pattern_gray(value: f32) -> Color {
|
||||
let value = value.clamp(0., 1.);
|
||||
/// The Mandelbrot brightness as a gray, gamma-encoded so a Gradient Map takes it as the position along its gradient.
|
||||
fn mandelbrot_gray(brightness: f32) -> Color {
|
||||
let value = brightness.clamp(0., 1.);
|
||||
Color::from_gamma_srgb_channels(value, value, value, 1.)
|
||||
}
|
||||
|
||||
/// Samples a noise pattern's value, from 0 to 1, at positions in its space.
|
||||
/// Samples a noise pattern's luminance, from 0 to 1, at positions in its space.
|
||||
struct NoiseSampler {
|
||||
noise: fastnoise_lite::FastNoiseLite,
|
||||
white_noise_seed: Option<i32>,
|
||||
@@ -170,7 +170,22 @@ impl NoiseSampler {
|
||||
/// A random value from 0 to 1 for each cell of a grid, the same for the same seed and cell. In 32-bit math, which a GPU can match.
|
||||
fn white_noise(seed: i32, cell: IVec2) -> f32 {
|
||||
let [hash, _, _] = pcg3d([cell.x as u32, cell.y as u32, seed as u32]);
|
||||
hash_fraction(hash)
|
||||
|
||||
// The top 24 bits, which an f32 holds exactly
|
||||
(hash >> 8) as f32 / (1_u32 << 24) as f32
|
||||
}
|
||||
|
||||
/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result.
|
||||
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)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -206,18 +221,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_values_show_as_the_gray_at_that_level() {
|
||||
for value in [0., 0.25, 0.5, 0.75, 1.] {
|
||||
let [red, green, blue, alpha] = pattern_gray(value).to_gamma_srgb_channels();
|
||||
assert!([red, green, blue].iter().all(|channel| (channel - value).abs() < 1e-5) && alpha == 1., "{value} shows as {red}");
|
||||
}
|
||||
|
||||
// Values out of range clamp
|
||||
assert_eq!(pattern_gray(1.5).to_gamma_srgb_channels()[0], 1.);
|
||||
assert_eq!(pattern_gray(-0.5).to_gamma_srgb_channels()[0], 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn white_noise_is_the_same_wherever_and_however_finely_it_is_sampled() {
|
||||
let white_noise = |seed| {
|
||||
|
||||
@@ -5,15 +5,12 @@ pub mod adjustments;
|
||||
mod blending;
|
||||
pub mod color_lookup_table;
|
||||
pub mod effect_kernels;
|
||||
pub mod envelope_kernels;
|
||||
pub mod filter_kernels;
|
||||
pub mod generators;
|
||||
mod kernel;
|
||||
pub mod layer_blending;
|
||||
pub mod mandelbrot;
|
||||
pub mod masks;
|
||||
mod masks;
|
||||
pub mod raster_effects;
|
||||
pub mod resample_kernels;
|
||||
pub mod value_effects;
|
||||
|
||||
pub use kernel::*;
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
//! The CPU twins of the GPU passes that mask, feather, and blur content by a radius mask.
|
||||
//! The CPU twins of the GPU passes that mask content by another graphic and feather it toward its edges.
|
||||
|
||||
use crate::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, Plane, VARIABLE_BOX_MAX_VALUE, variable_box_scale};
|
||||
use crate::raster_effects::{blur, premultiplied_gamma_channels, transferred};
|
||||
use crate::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, Plane};
|
||||
use crate::raster_effects::premultiplied_gamma_channels;
|
||||
use core_types::Color;
|
||||
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
||||
use glam::DVec2;
|
||||
use graphic_types::masks::{FEATHER_FOOTPRINT_ALPHA, MaskMode, feather_parts, mask_coverage, mask_density_line, mask_feather_sigma, masked_radius_blur_code, masked_radius_blur_interpolation};
|
||||
use graphic_types::masks::{FEATHER_FOOTPRINT_ALPHA, MaskMode, feather_parts, mask_coverage, mask_density_line, mask_feather_sigma};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// How much the mask shows the content at each pixel, from 0 to 1, given the `colors` its graphic draws over a plane of `width` by `height` pixels.
|
||||
@@ -74,170 +73,9 @@ pub(crate) fn feather_strength(full: &Plane<[f32; 4]>, distance: f64) -> Plane<f
|
||||
}
|
||||
}
|
||||
|
||||
/// A masked radius blur map's color in 8-bit channels as the GPU renders the map: straight, then premultiplied.
|
||||
fn map_channels(color: Color) -> [f32; 4] {
|
||||
let eight_bit = |channel: f32| (channel.clamp(0., 1.) * 255.).round() / 255.;
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels().map(eight_bit);
|
||||
[eight_bit(red * alpha), eight_bit(green * alpha), eight_bit(blue * alpha), alpha]
|
||||
}
|
||||
|
||||
/// The 8-bit luminance code of each of a masked radius blur map's `colors` (see [`map_channels`]).
|
||||
pub(crate) fn masked_radius_blur_codes(colors: &[Color]) -> Vec<u8> {
|
||||
colors.iter().map(|&color| masked_radius_blur_code(map_channels(color))).collect()
|
||||
}
|
||||
|
||||
/// The luminance from 0 to 1 of each of a masked box blur map's `colors`, unrounded like the GPU's precise map texture, in the half floats the GPU keeps it in, which size the boxes finer than 8-bit codes could.
|
||||
pub(crate) fn masked_box_blur_luminances(colors: &[Color]) -> Vec<f32> {
|
||||
let luminance = |color: Color| {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::Luminance).clamp(0., 1.)
|
||||
};
|
||||
colors.iter().map(|&color| half::f16::from_f32(luminance(color)).to_f32()).collect()
|
||||
}
|
||||
|
||||
/// The premultiplied gamma-encoded `image` blurred by the interpolation between Gaussian `levels` (from `masked_radius_blur_levels`, here in pixels along each axis) each pixel's map luminance `codes` picks,
|
||||
/// matching the GPU's `masked_radius_blur`, blurring in linear light if `linear`. O(width × height) for each of the levels.
|
||||
pub(crate) fn masked_radius_blur(image: &Plane<[f32; 4]>, codes: &[u8], levels: &[DVec2], linear: bool) -> Plane<[f32; 4]> {
|
||||
// Each code's level below and share of the level above, the same for every level and at any scale
|
||||
let lengths: Vec<f64> = levels.iter().map(|level| level.max_element()).collect();
|
||||
let interpolations: Vec<(usize, f32)> = (0..=255_u8)
|
||||
.map(|code| {
|
||||
let (below, above_parts) = masked_radius_blur_interpolation(code, &lengths);
|
||||
(below, above_parts as f32 / 255.)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Only the levels some pixel takes a share of are blurred, so a map of one luminance blurs once or twice
|
||||
let mut weighed = vec![false; levels.len()];
|
||||
for &code in codes {
|
||||
let (below, above_share) = interpolations[code as usize];
|
||||
weighed[below] |= above_share < 1.;
|
||||
if let Some(above) = weighed.get_mut(below + 1) {
|
||||
*above |= above_share > 0.;
|
||||
}
|
||||
}
|
||||
|
||||
let mut sum = Plane::<[f32; 4]>::new(image.width, image.height);
|
||||
for (index, &length) in levels.iter().enumerate().filter(|&(index, _)| weighed[index]) {
|
||||
let blurred = match length.max_element() >= NEGLIGIBLE_LENGTH {
|
||||
true => blur(image.clone(), (BlurKernel::Gaussian { sigma: length.x }, BlurKernel::Gaussian { sigma: length.y }), linear),
|
||||
false => image.clone(),
|
||||
};
|
||||
|
||||
let weight = |(below, above_share): (usize, f32)| match index {
|
||||
_ if index == below => 1. - above_share,
|
||||
_ if index == below + 1 => above_share,
|
||||
_ => 0.,
|
||||
};
|
||||
// Summed in gamma on purpose (see `masked_radius_blur_interpolation`)
|
||||
for ((sum, pixel), &code) in sum.data.iter_mut().zip(&blurred.data).zip(codes) {
|
||||
let weight = weight(interpolations[code as usize]);
|
||||
*sum = std::array::from_fn(|channel| sum[channel] + pixel[channel] * weight);
|
||||
}
|
||||
}
|
||||
sum
|
||||
}
|
||||
|
||||
/// The premultiplied gamma-encoded `image` box blurred at each pixel by its own half width along each axis, the fraction of the `radius` in pixels its map's `luminances` give,
|
||||
/// matching the GPU's `variable_box_blur`. Each box weighs pixels like [`BlurKernel::Box`], holding the edge pixels past the edges, in linear light if `linear`.
|
||||
/// It sums each box from running sums (a summed-area table) of whole-number counts, exact at any size, so O(width × height) at any radius.
|
||||
pub fn variable_box_blur(image: &Plane<[f32; 4]>, luminances: &[f32], radius: DVec2, linear: bool) -> Plane<[f32; 4]> {
|
||||
let (width, height) = (image.width, image.height);
|
||||
let summed = match linear {
|
||||
true => std::borrow::Cow::Owned(image.map(transferred(srgb_to_linear))),
|
||||
false => std::borrow::Cow::Borrowed(image),
|
||||
};
|
||||
let scale = variable_box_scale(width * height);
|
||||
let count = |value: f32| (value.clamp(0., VARIABLE_BOX_MAX_VALUE) * scale as f32).round_ties_even() as u64;
|
||||
|
||||
// Two channels at a time, as the GPU sums them, keeping the running sums to 16 bytes a pixel
|
||||
let mut averages = Plane::<[f32; 4]>::new(width, height);
|
||||
for first in [0, 2] {
|
||||
// Each channel counted in whole steps, summed over the pixels above and left of each corner between pixels, in rows of one more corner than pixels
|
||||
let corners = width + 1;
|
||||
let mut sums = vec![[0_u64; 2]; corners * (height + 1)];
|
||||
for y in 0..height {
|
||||
let mut row = [0_u64; 2];
|
||||
for x in 0..width {
|
||||
let pixel = summed.data[y * width + x];
|
||||
row = [row[0] + count(pixel[first]), row[1] + count(pixel[first + 1])];
|
||||
|
||||
let above = sums[y * corners + x + 1];
|
||||
sums[(y + 1) * corners + x + 1] = [above[0] + row[0], above[1] + row[1]];
|
||||
}
|
||||
}
|
||||
let sum_at = |x: usize, y: usize| sums[y * corners + x];
|
||||
|
||||
// The counts over the pixels from `start` up to `end`, with those past the edges repeating the nearest edge pixel
|
||||
let counts_continued = |start: [i64; 2], end: [i64; 2]| -> [f64; 2] {
|
||||
let spans = |axis: usize, size: usize| {
|
||||
let size = size as i64;
|
||||
let (inner_start, inner_end) = (start[axis].clamp(0, size), end[axis].clamp(0, size));
|
||||
[(0, 1, inner_start - start[axis]), (inner_start, inner_end, 1), (size - 1, size, end[axis] - inner_end)]
|
||||
};
|
||||
|
||||
let mut sum = [0.; 2];
|
||||
for (start_x, end_x, count_x) in spans(0, width) {
|
||||
for (start_y, end_y, count_y) in spans(1, height) {
|
||||
if count_x <= 0 || count_y <= 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let [start_x, end_x, start_y, end_y] = [start_x, end_x, start_y, end_y].map(|corner| corner as usize);
|
||||
let [top_left, top_right] = [sum_at(start_x, start_y), sum_at(end_x, start_y)];
|
||||
let [bottom_left, bottom_right] = [sum_at(start_x, end_y), sum_at(end_x, end_y)];
|
||||
let count = (count_x * count_y) as f64;
|
||||
sum = std::array::from_fn(|channel| sum[channel] + count * ((bottom_right[channel] + top_left[channel]) - (bottom_left[channel] + top_right[channel])) as f64);
|
||||
}
|
||||
}
|
||||
sum
|
||||
};
|
||||
|
||||
fill_rows(&mut averages.data, width, |y, row| {
|
||||
for (x, target) in row.iter_mut().enumerate() {
|
||||
let index = y * width + x;
|
||||
if luminances[index] <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
// A box of a fractional half width is the mix of the boxes of the whole half widths either side, weighed by that fraction along each axis
|
||||
let half_width = radius * luminances[index] as f64;
|
||||
let (whole, fraction) = (half_width.floor(), half_width - half_width.floor());
|
||||
let mut sum = [0.; 2];
|
||||
for wider in [[false, false], [true, false], [false, true], [true, true]] {
|
||||
let along = |axis: usize| if wider[axis] { fraction[axis] } else { 1. - fraction[axis] };
|
||||
let weight = along(0) * along(1);
|
||||
if weight <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
let reach = [0, 1].map(|axis| whole[axis] as i64 + wider[axis] as i64);
|
||||
let rectangle = counts_continued([x as i64 - reach[0], y as i64 - reach[1]], [x as i64 + reach[0] + 1, y as i64 + reach[1] + 1]);
|
||||
sum = std::array::from_fn(|channel| sum[channel] + weight * rectangle[channel]);
|
||||
}
|
||||
|
||||
let total = (2. * half_width.x + 1.) * (2. * half_width.y + 1.) * scale;
|
||||
target[first..first + 2].copy_from_slice(&sum.map(|channel| (channel / total) as f32));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Pixels not blurred keep their color, and the rest return to gamma from linear light
|
||||
let encode = transferred(linear_to_srgb);
|
||||
for ((average, &original), &luminance) in averages.data.iter_mut().zip(&image.data).zip(luminances) {
|
||||
*average = match luminance > 0. {
|
||||
false => original,
|
||||
true if linear => encode(*average),
|
||||
true => *average,
|
||||
};
|
||||
}
|
||||
averages
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::effect_kernels::box_weight;
|
||||
|
||||
/// The standard normal cumulative distribution, from the Abramowitz and Stegun approximation of the error function, accurate to 1e-7.
|
||||
fn normal_cdf(x: f64) -> f64 {
|
||||
@@ -322,87 +160,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Premultiplied colors varying across the plane up to its edges, every seventh pixel transparent and some translucent.
|
||||
fn colorful(width: usize, height: usize) -> Plane<[f32; 4]> {
|
||||
let data = (0..width * height)
|
||||
.map(|index| {
|
||||
let (x, y) = ((index % width) as f32 / width as f32, (index / width) as f32 / height as f32);
|
||||
let alpha = [0., 0.5, 0.5, 1., 1., 1., 1.][index % 7];
|
||||
[x * alpha, y * alpha, (1. - x * y) * alpha, alpha]
|
||||
})
|
||||
.collect();
|
||||
Plane { width, height, data }
|
||||
}
|
||||
|
||||
/// The box of `half_width` along each axis around a pixel of the plane, summed pixel by pixel with the edge pixels held past the edges.
|
||||
fn summed_box(plane: &Plane<[f32; 4]>, x: usize, y: usize, half_width: DVec2) -> [f32; 4] {
|
||||
let reach = half_width.ceil().as_i64vec2();
|
||||
let (mut sum, mut total) = ([0.; 4], 0.);
|
||||
for offset_y in -reach.y..=reach.y {
|
||||
for offset_x in -reach.x..=reach.x {
|
||||
let weight = box_weight(half_width.x, offset_x.unsigned_abs() as usize) * box_weight(half_width.y, offset_y.unsigned_abs() as usize);
|
||||
let source_x = (x as i64 + offset_x).clamp(0, plane.width as i64 - 1) as usize;
|
||||
let source_y = (y as i64 + offset_y).clamp(0, plane.height as i64 - 1) as usize;
|
||||
let pixel = plane.data[source_y * plane.width + source_x];
|
||||
|
||||
sum = std::array::from_fn(|channel| sum[channel] + weight * pixel[channel] as f64);
|
||||
total += weight;
|
||||
}
|
||||
}
|
||||
sum.map(|channel| (channel / total) as f32)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_box_blurs_box_each_pixel_by_its_own_fraction_of_the_radius() {
|
||||
let image = colorful(37, 29);
|
||||
// Luminances finer than 8-bit codes, with every 41st pixel unblurred
|
||||
let luminances: Vec<f32> = (0..37 * 29).map(|index| if index % 41 == 0 { 0. } else { ((index * 37) % 1000) as f32 / 1000. }).collect();
|
||||
let radius = DVec2::new(9.3, 6.);
|
||||
|
||||
for linear in [false, true] {
|
||||
let blurred = variable_box_blur(&image, &luminances, radius, linear);
|
||||
let decoded = if linear { image.map(transferred(srgb_to_linear)) } else { image.clone() };
|
||||
|
||||
// Counting in 4096 steps rounds by up to half a step, which gamma encoding stretches up to 13 times near black
|
||||
let tolerance = if linear { 2e-3 } else { 2e-4 };
|
||||
|
||||
for (index, &luminance) in luminances.iter().enumerate() {
|
||||
// A luminance of 0 leaves its pixel exactly as it is
|
||||
if luminance <= 0. {
|
||||
assert_eq!(blurred.data[index], image.data[index]);
|
||||
continue;
|
||||
}
|
||||
|
||||
let summed = summed_box(&decoded, index % 37, index / 37, radius * luminance as f64);
|
||||
let expected = if linear { transferred(linear_to_srgb)(summed) } else { summed };
|
||||
for channel in 0..4 {
|
||||
let difference = (blurred.data[index][channel] - expected[channel]).abs();
|
||||
assert!(
|
||||
difference < tolerance,
|
||||
"pixel {index} of luminance {luminance} differs by {difference} in channel {channel} (linear: {linear})"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_box_blurs_of_one_fraction_of_the_radius_are_the_box_blur_of_that_half_width() {
|
||||
let image = colorful(48, 40);
|
||||
let luminances = vec![0.6; 48 * 40];
|
||||
let radius = DVec2::new(20., 12.5);
|
||||
let half_width = radius * 0.6_f32 as f64;
|
||||
|
||||
for linear in [false, true] {
|
||||
let variable = variable_box_blur(&image, &luminances, radius, linear);
|
||||
let even = blur(image.clone(), (BlurKernel::Box { radius: half_width.x }, BlurKernel::Box { radius: half_width.y }), linear);
|
||||
for (index, (variable, even)) in variable.data.iter().zip(&even.data).enumerate() {
|
||||
for channel in 0..4 {
|
||||
let difference = (variable[channel] - even[channel]).abs();
|
||||
assert!(difference < 2e-4, "pixel {index} differs by {difference} in channel {channel} (linear: {linear})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -5,9 +5,7 @@
|
||||
|
||||
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, render_raster_cpu_image_svg};
|
||||
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::transform::Footprint;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
@@ -114,17 +112,11 @@ fn map_markers(id: u64) -> (String, String) {
|
||||
(format!("<!--effect-map-{id}-->"), format!("<!--/effect-map-{id}-->"))
|
||||
}
|
||||
|
||||
/// The filter primitive standing for the map `id` names until it's resolved, flooding the region with `flood`, which leaves the effect out.
|
||||
/// Coverage that is added leaves the effect out when transparent, coverage the content is multiplied by leaves it out when opaque, and data a filter combines in other ways takes whatever value is neutral for it.
|
||||
pub(crate) fn map_placeholder(id: u64, result: &str, flood: Color) -> String {
|
||||
let color = SRGBA8::from(flood.with_alpha(1.)).to_rgb_hex();
|
||||
map_placeholder_primitive(id, &format!(r##"<feFlood flood-color="#{color}" flood-opacity="{}" result="{result}" />"##, flood.a()))
|
||||
}
|
||||
|
||||
/// The filter `primitive` standing for the map `id` names until it's resolved, which gives the result the map stands for.
|
||||
pub(crate) fn map_placeholder_primitive(id: u64, primitive: &str) -> String {
|
||||
/// The filter primitive standing for the map `id` names until it's resolved, covering everything to the `coverage` from 0 to 1.
|
||||
/// Coverage that is added leaves the effect out at 0, and coverage the content is multiplied by leaves it out at 1.
|
||||
pub(crate) fn map_placeholder(id: u64, result: &str, coverage: f64) -> String {
|
||||
let (opening, closing) = map_markers(id);
|
||||
format!("{opening}{primitive}{closing}")
|
||||
format!(r#"{opening}<feFlood flood-opacity="{coverage}" result="{result}" />{closing}"#)
|
||||
}
|
||||
|
||||
impl EffectMap {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,833 +0,0 @@
|
||||
//! The SVG filter primitives carrying out the filter effects like the GPU passes do.
|
||||
|
||||
use super::SvgFilterPrimitives;
|
||||
use core_types::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use glam::DVec2;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::filters::{AVERAGE_VISIBILITY_RAMP, Convolution, HIGH_PASS_GRAY, Surroundings, UnsharpBlur, fill_shifts, noise_extent, unsharp, unsharp_change};
|
||||
use graphic_types::{EffectOperation, Effects, MinimumMaximumMode};
|
||||
use raster_kernels::effect_kernels::{MAX_DIRECT_BOX_RADIUS, box_weight};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The most weights an `feConvolveMatrix` kernel holds before browsers carry it out with less precision.
|
||||
const MAX_PRECISE_KERNEL_AREA: usize = 25;
|
||||
|
||||
/// A convolution's kernel on the user space's lattice, its weights listed as the matrix of an `feConvolveMatrix` of `order` weights across and down, with the `target` cell on the pixel being found.
|
||||
struct LatticeKernel {
|
||||
order: [usize; 2],
|
||||
target: [usize; 2],
|
||||
matrix: Vec<f64>,
|
||||
}
|
||||
|
||||
impl LatticeKernel {
|
||||
/// The kernel of `convolution`, its shifts in whole units of the user space, one to a pixel, or `None` if it holds more weights than browsers carry out precisely.
|
||||
fn new(convolution: &Convolution) -> Option<Self> {
|
||||
let mut weights: BTreeMap<(i64, i64), f64> = BTreeMap::new();
|
||||
for &(shift, weight) in &convolution.taps {
|
||||
*weights.entry((shift.x.round() as i64, shift.y.round() as i64)).or_default() += weight / convolution.divisor;
|
||||
}
|
||||
|
||||
// The faint pixels' colors stack a copy for each shift within the square the kernel reaches across, which must stay small too
|
||||
let reach = weights.keys().map(|&(x, y)| x.abs().max(y.abs())).max().unwrap_or(0);
|
||||
let side = 2 * reach.unsigned_abs() as usize + 1;
|
||||
if side * side > MAX_PRECISE_KERNEL_AREA {
|
||||
return None;
|
||||
}
|
||||
|
||||
// The matrix spans the weights and the pixel being found, and is applied turned halfway around, so it lists the weights from the last shift to the first
|
||||
let extent = |axis: fn(&(i64, i64)) -> i64| weights.keys().map(axis).fold((0, 0), |(least, most), value| (least.min(value), most.max(value)));
|
||||
let [(least_x, most_x), (least_y, most_y)] = [extent(|&(x, _)| x), extent(|&(_, y)| y)];
|
||||
let order = [(most_x - least_x + 1) as usize, (most_y - least_y + 1) as usize];
|
||||
let mut matrix = vec![0.; order[0] * order[1]];
|
||||
for (&(x, y), &weight) in &weights {
|
||||
let cell = (y - least_y) as usize * order[0] + (x - least_x) as usize;
|
||||
matrix[order[0] * order[1] - 1 - cell] = weight;
|
||||
}
|
||||
|
||||
// The target is how far the kernel reads left of and above the pixel being found
|
||||
let target = [-least_x as usize, -least_y as usize];
|
||||
Some(Self { order, target, matrix })
|
||||
}
|
||||
}
|
||||
|
||||
/// How much farther than the effects reach an SVG filter's region must extend, in document pixels, since a minimum's erosion of the colors reads past the region as black.
|
||||
pub(super) fn svg_region_reach_beyond(effects: &Effects) -> f64 {
|
||||
effects
|
||||
.operations()
|
||||
.map(|operation| match operation {
|
||||
EffectOperation::MinimumMaximum {
|
||||
radius,
|
||||
mode: MinimumMaximumMode::Minimum,
|
||||
} => radius.max(0.).ceil(),
|
||||
_ => 0.,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
impl SvgFilterPrimitives {
|
||||
/// The image with a filter effect carried out on it, in a user space of one unit to a pixel of its effect space, or as it is for any other operation.
|
||||
/// A filter on the pixel lattice runs natively only where one user unit is one device pixel (`pixel_exact`), and otherwise takes its result as the map the GPU renders for `capture`.
|
||||
/// Where the fill `forked` the content into two planes, no filter reading its input many times runs natively, since the filter can't split to keep chains of them from multiplying.
|
||||
pub(super) fn filter(&mut self, image: &str, operation: &EffectOperation, pixel_exact: bool, forked: bool, capture: EffectCapture) -> String {
|
||||
let native = pixel_exact && !forked;
|
||||
|
||||
if let Some(convolution) = operation.convolution() {
|
||||
return match native.then(|| LatticeKernel::new(&convolution)).flatten() {
|
||||
Some(kernel) => {
|
||||
let coverage = convolution.weighs_coverage.then(|| self.convolve_coverage(image, &kernel));
|
||||
let convolved = self.convolve(image, &convolution, &kernel);
|
||||
self.uncover(&convolved, coverage.as_deref().unwrap_or(image), convolution.surroundings)
|
||||
}
|
||||
// A kernel weighing the coverage too gives the colors the coverage it weighs, so the whole result comes as the map
|
||||
None if convolution.weighs_coverage => self.map_showing(capture, image),
|
||||
None => self.uncovered_map(image, capture, convolution.surroundings),
|
||||
};
|
||||
}
|
||||
|
||||
// Edges Only needs the length of each channel's gradient, which loses too much precision through the 8-bit results between primitives
|
||||
if let Some((blur, sharpening)) = unsharp(operation) {
|
||||
return match blur {
|
||||
UnsharpBlur::Gaussian(radius) if !forked => self.unsharp_mask(image, radius, sharpening),
|
||||
_ => self.map_showing(capture, image),
|
||||
};
|
||||
}
|
||||
|
||||
match *operation {
|
||||
// The Euclidean length of the gradient loses too much precision through the 8-bit results between primitives
|
||||
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
||||
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
|
||||
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
|
||||
EffectOperation::AddNoise { amount, distribution, .. } => self.add_noise(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
||||
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
|
||||
_ => image.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The map the GPU renders for `capture` given the image's coverage, matching the GPU's `uncover`, or the image as it is until the map resolves.
|
||||
/// It reads the image only once, so chains of filters taking maps stay linear in a browser that redoes a filter's input for each read.
|
||||
/// Continued colors' maps are opaque and placed atop the image, while matted ones hold the whole result, since lifting off the gray isn't a composite.
|
||||
fn uncovered_map(&mut self, image: &str, capture: EffectCapture, surroundings: Surroundings) -> String {
|
||||
match surroundings {
|
||||
Surroundings::Continued => {
|
||||
let map = self.map(capture);
|
||||
self.push("feComposite", &format!(r#"in="{map}" in2="{image}" operator="atop""#), "")
|
||||
}
|
||||
Surroundings::Matted(_) => self.map_showing(capture, image),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the filter reads its input more than a few times (natively, for those on the pixel lattice), so a chain of them in one filter would multiply their cost.
|
||||
pub(super) fn reads_input_often(&self, operation: &EffectOperation, native: bool) -> bool {
|
||||
match operation.convolution() {
|
||||
Some(convolution) => native && LatticeKernel::new(&convolution).is_some(),
|
||||
None => matches!(
|
||||
operation,
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Sharpen { .. } | EffectOperation::HighPass { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. }
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The image's straight colors as the filters read them, opaque where there's one, with faint pixels taking the nearest visible color within `reach` document pixels.
|
||||
/// Copies with the visible pixels made opaque and the rest left out stack nearest on top, so each pixel shows the first visible one exactly.
|
||||
fn visible_colors(&mut self, image: &str, reach: f64) -> String {
|
||||
// The alpha row raises 16 levels and up to full and leaves out 15 and below, matching the GPU's threshold, and beneath it all the covered pixels made opaque
|
||||
let opaque = |primitives: &mut Self, alpha_row: &str| {
|
||||
let values = format!("1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 {alpha_row}");
|
||||
primitives.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="{values}""#), "")
|
||||
};
|
||||
let visible = opaque(self, "0 0 0 255 -15");
|
||||
let covered = opaque(self, "0 0 0 255 0");
|
||||
|
||||
let mut layers = Vec::new();
|
||||
for [x, y] in fill_shifts(reach.ceil() as i32).into_iter().skip(1) {
|
||||
// Each copy moves against its shift, so the pixel it lands on reads the one the shift points to, written without negative zeros
|
||||
let shift = -DVec2::new(x as f64, y as f64) + DVec2::ZERO;
|
||||
layers.push(self.push("feOffset", &format!(r#"in="{visible}" dx="{}" dy="{}""#, shift.x, shift.y), ""));
|
||||
}
|
||||
let layers = [vec![covered], layers.into_iter().rev().collect(), vec![visible]].concat();
|
||||
|
||||
let nodes: String = layers.iter().map(|layer| format!(r#"<feMergeNode in="{layer}" />"#)).collect();
|
||||
self.push("feMerge", "", &nodes)
|
||||
}
|
||||
|
||||
/// The opaque colors of the image convolved by an `feConvolveMatrix` of the `kernel` over the colors its surroundings describe, as the GPU's `convolve` does.
|
||||
fn convolve(&mut self, image: &str, convolution: &Convolution, kernel: &LatticeKernel) -> String {
|
||||
let colors = match convolution.surroundings {
|
||||
Surroundings::Continued => self.visible_colors(image, convolution.reach()),
|
||||
Surroundings::Matted(gray) => self.over_gray(image, gray),
|
||||
};
|
||||
|
||||
let ([columns, rows], [target_x, target_y]) = (kernel.order, kernel.target);
|
||||
let matrix = kernel.matrix.iter().map(f64::to_string).collect::<Vec<_>>().join(" ");
|
||||
let attributes = format!(
|
||||
r#"in="{colors}" order="{columns} {rows}" kernelMatrix="{matrix}" divisor="1" bias="{}" targetX="{target_x}" targetY="{target_y}" kernelUnitLength="1 1" edgeMode="none" preserveAlpha="true""#,
|
||||
convolution.offset
|
||||
);
|
||||
self.push("feConvolveMatrix", &attributes, "")
|
||||
}
|
||||
|
||||
/// The image's coverage weighed by the `kernel`, clamped, as the alpha of an `feConvolveMatrix` over every channel.
|
||||
fn convolve_coverage(&mut self, image: &str, kernel: &LatticeKernel) -> String {
|
||||
let ([columns, rows], [target_x, target_y]) = (kernel.order, kernel.target);
|
||||
let matrix = kernel.matrix.iter().map(f64::to_string).collect::<Vec<_>>().join(" ");
|
||||
let attributes = format!(r#"in="{image}" order="{columns} {rows}" kernelMatrix="{matrix}" divisor="1" targetX="{target_x}" targetY="{target_y}" kernelUnitLength="1 1" edgeMode="none""#);
|
||||
self.push("feConvolveMatrix", &attributes, "")
|
||||
}
|
||||
|
||||
/// The image composited over an opaque gray of level `gray`.
|
||||
fn over_gray(&mut self, image: &str, gray: f64) -> String {
|
||||
let percent = gray * 100.;
|
||||
let flood = self.push("feFlood", &format!(r#"flood-color="rgb({percent}%, {percent}%, {percent}%)" flood-opacity="1""#), "");
|
||||
self.push("feComposite", &format!(r#"in="{image}" in2="{flood}" operator="over""#), "")
|
||||
}
|
||||
|
||||
/// Filtered opaque `colors` given the image's coverage, as their `surroundings` describe, matching the GPU's `uncover`.
|
||||
fn uncover(&mut self, colors: &str, image: &str, surroundings: Surroundings) -> String {
|
||||
let Surroundings::Matted(gray) = surroundings else {
|
||||
return self.push("feComposite", &format!(r#"in="{colors}" in2="{image}" operator="in""#), "");
|
||||
};
|
||||
// The gray over the share the image leaves uncovered, taken off the opaque colors, which leaves the image's coverage as alpha and clamps as the GPU does
|
||||
let values = format!("0 0 0 0 {gray} 0 0 0 0 {gray} 0 0 0 0 {gray} 0 0 0 -1 1");
|
||||
let uncovered_gray = self.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="{values}""#), "");
|
||||
self.push("feComposite", &format!(r#"in="{colors}" in2="{uncovered_gray}" operator="arithmetic" k2="1" k3="-1""#), "")
|
||||
}
|
||||
|
||||
/// The image with each straight color and its coverage sharpened against a Gaussian blur of `radius` document pixels, by the amount and threshold fractions in `sharpening`,
|
||||
/// or with none, a high pass of its colors, matching the GPU's `unsharp_mask`.
|
||||
fn unsharp_mask(&mut self, image: &str, radius: f64, sharpening: Option<[f64; 2]>) -> String {
|
||||
let sigma = radius.max(0.);
|
||||
let blur = |primitives: &mut Self, input: &str| primitives.push("feGaussianBlur", &format!(r#"in="{input}" stdDeviation="{sigma} {sigma}""#), "");
|
||||
let matrix = |primitives: &mut Self, input: &str, values: &str| primitives.push("feColorMatrix", &format!(r#"in="{input}" type="matrix" values="{values}""#), "");
|
||||
let arithmetic = |primitives: &mut Self, first: &str, second: &str, [k2, k3, k4]: [f64; 3]| {
|
||||
primitives.push("feComposite", &format!(r#"in="{first}" in2="{second}" operator="arithmetic" k2="{k2}" k3="{k3}" k4="{k4}""#), "")
|
||||
};
|
||||
// Linear transfers stay exact through the truncation browsers round their results by
|
||||
let inverted = |primitives: &mut Self, input: &str| {
|
||||
let functions = ["R", "G", "B"].map(|channel| format!(r#"<feFunc{channel} type="linear" slope="-1" intercept="1" />"#)).concat();
|
||||
primitives.push("feComponentTransfer", &format!(r#"in="{input}""#), &functions)
|
||||
};
|
||||
|
||||
// The average of the visible colors alone, as the blur of them made opaque among the rest left out, divided by its alpha.
|
||||
// Where too little of the blur lands on visible colors to know their average, it eases into the pixel's own color.
|
||||
let visible = matrix(self, image, "1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 -15");
|
||||
let blurred = blur(self, &visible);
|
||||
let [start, end] = AVERAGE_VISIBILITY_RAMP.map(f64::from);
|
||||
let weighted = matrix(self, &blurred, &format!("1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 {} {}", 1. / (end - start), -start / (end - start)));
|
||||
let own = matrix(self, image, "1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0");
|
||||
let average = self.push("feComposite", &format!(r#"in="{weighted}" in2="{own}" operator="over""#), "");
|
||||
|
||||
// A high pass is the colors less their average, around middle gray, which adding the inverted average reaches with an alpha clamped back to full
|
||||
let Some([amount, threshold]) = sharpening else {
|
||||
let inverted_average = inverted(self, &average);
|
||||
let detail = arithmetic(self, &own, &inverted_average, [1., 1., HIGH_PASS_GRAY as f64 - 1.]);
|
||||
return self.push("feComposite", &format!(r#"in="{detail}" in2="{image}" operator="in""#), "");
|
||||
};
|
||||
|
||||
// The coverage sharpens the same way against its own blur, carried as an opaque gray then returned to alpha
|
||||
let coverage_gray = matrix(self, image, "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1");
|
||||
let blurred_coverage = blur(self, image);
|
||||
let blurred_gray = matrix(self, &blurred_coverage, "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1");
|
||||
let to_alpha = |primitives: &mut Self, gray: &str| matrix(primitives, gray, "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0");
|
||||
|
||||
// Without a threshold, the change is the difference scaled by the amount, so one composite adds it back with nothing rounded between
|
||||
if threshold <= 0. {
|
||||
let colors = arithmetic(self, &own, &average, [1. + amount, -amount, 0.]);
|
||||
let sharpened_gray = arithmetic(self, &coverage_gray, &blurred_gray, [1. + amount, -amount, 0.]);
|
||||
let coverage = to_alpha(self, &sharpened_gray);
|
||||
return self.push("feComposite", &format!(r#"in="{colors}" in2="{coverage}" operator="in""#), "");
|
||||
}
|
||||
|
||||
// The difference from the average, centered on level 128 and widened as far as it can be before the change it makes saturates, then mapped through the change by tables and added back.
|
||||
// Each table value lies a quarter level above the level it means, which the browser's truncation keeps.
|
||||
// Its scale is whole 128ths and its offset whole levels, as Firefox rounds them, with a zero difference landing under half a level above 128.
|
||||
let ideal_count = ((amount / (1. + threshold)).max(1.) * 127. / 255. * 128.).floor() as i64;
|
||||
let count = (65..=ideal_count.max(65)).rev().find(|count| count % 128 == 0 || count % 128 > 64).unwrap_or(65);
|
||||
let scale = count as f64 / 128.;
|
||||
let widening = scale * 255. / 127.;
|
||||
let offset = (128. - (255. * scale).floor()) / 255.;
|
||||
let table: String = (0..256)
|
||||
.map(|level| {
|
||||
let difference = (level as f64 - 128.) / 127. / widening;
|
||||
let change = unsharp_change(difference as f32, amount as f32, threshold as f32).clamp(-1., 1.) as f64;
|
||||
format!("{:.5}", ((128. + change * 127.).round() + 0.25) / 255.)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let sharpen = |primitives: &mut Self, own: &str, inverted_average: &str, channels: &[&str]| {
|
||||
let difference = arithmetic(primitives, own, inverted_average, [scale, scale, offset]);
|
||||
let functions = channels.iter().map(|channel| format!(r#"<feFunc{channel} type="table" tableValues="{table}" />"#)).collect::<String>();
|
||||
let change = primitives.push("feComponentTransfer", &format!(r#"in="{difference}""#), &functions);
|
||||
arithmetic(primitives, own, &change, [1., 255. / 127., -128. / 127.])
|
||||
};
|
||||
let inverted_average = inverted(self, &average);
|
||||
let colors = sharpen(self, &own, &inverted_average, &["R", "G", "B"]);
|
||||
let inverted_blurred_gray = inverted(self, &blurred_gray);
|
||||
let sharpened_gray = sharpen(self, &coverage_gray, &inverted_blurred_gray, &["R"]);
|
||||
let coverage = to_alpha(self, &sharpened_gray);
|
||||
|
||||
self.push("feComposite", &format!(r#"in="{colors}" in2="{coverage}" operator="in""#), "")
|
||||
}
|
||||
|
||||
/// The image's straight colors made opaque, for composites that combine colors without their coverage.
|
||||
fn opaque_colors(&mut self, image: &str) -> String {
|
||||
self.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), "")
|
||||
}
|
||||
|
||||
/// The image with each straight color offset by the noise in the GPU's map for `capture`, which holds offsets up to `extent` either way around middle gray, matching the GPU's `add_noise`.
|
||||
/// Until the map is resolved, its middle gray offsets nothing.
|
||||
fn add_noise(&mut self, image: &str, extent: f64, capture: EffectCapture) -> String {
|
||||
let colors = self.opaque_colors(image);
|
||||
let noise = self.map_unresolved_as(capture, Color::from(SRGBA8::new(128, 128, 128, 255)));
|
||||
let attributes = format!(r#"in="{colors}" in2="{noise}" operator="arithmetic" k2="1" k3="{}" k4="{}""#, 2. * extent, -extent);
|
||||
let noisy = self.push("feComposite", &attributes, "");
|
||||
self.push("feComposite", &format!(r#"in="{noisy}" in2="{image}" operator="in""#), "")
|
||||
}
|
||||
|
||||
/// The image shown fully opaque where its coverage passes the threshold level of the GPU's map for `capture` (its gray), by the share of it (its alpha), matching the GPU's `dissolve`.
|
||||
/// Until the map is resolved, its opaque black shows every covered pixel.
|
||||
fn dissolve(&mut self, image: &str, capture: EffectCapture) -> String {
|
||||
let field = self.map_unresolved_as(capture, Color::BLACK);
|
||||
let thresholds = self.push("feColorMatrix", &format!(r#"in="{field}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0""#), "");
|
||||
|
||||
// The coverage less the threshold, which passes at one 8-bit level or more
|
||||
let above = self.push("feComposite", &format!(r#"in="{image}" in2="{thresholds}" operator="arithmetic" k2="1" k3="-1""#), "");
|
||||
let passing = ["0"].into_iter().chain(std::iter::repeat_n("1", 255)).collect::<Vec<_>>().join(" ");
|
||||
let passed = self.push("feComponentTransfer", &format!(r#"in="{above}""#), &format!(r#"<feFuncA type="discrete" tableValues="{passing}" />"#));
|
||||
|
||||
let shown = self.push("feComposite", &format!(r#"in="{passed}" in2="{field}" operator="in""#), "");
|
||||
let colors = self.opaque_colors(image);
|
||||
self.push("feComposite", &format!(r#"in="{colors}" in2="{shown}" operator="in""#), "")
|
||||
}
|
||||
|
||||
/// The image with each pixel's color the lightest (or with `maximum` false, the darkest) in the square of `radius` document pixels around it,
|
||||
/// and its coverage the opposite extreme, matching the GPU's `neighborhood_extreme`, by `feMorphology` of the opaque colors and of the coverage.
|
||||
fn neighborhood_extreme(&mut self, image: &str, radius: f64, maximum: bool) -> String {
|
||||
let radius = radius.max(0.);
|
||||
let (colors_operator, coverage_operator) = if maximum { ("dilate", "erode") } else { ("erode", "dilate") };
|
||||
|
||||
let extreme_within = |primitives: &mut Self, whole_radius: f64| {
|
||||
if whole_radius <= 0. {
|
||||
return image.to_string();
|
||||
}
|
||||
let radius = format!(r#"radius="{whole_radius} {whole_radius}""#);
|
||||
|
||||
// The maximum spreads every covered pixel's straight color made opaque, and the minimum the colors matted over white, lifted back off within the grown coverage
|
||||
let colors = match maximum {
|
||||
true => primitives.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), ""),
|
||||
false => primitives.over_gray(image, 1.),
|
||||
};
|
||||
let colors = primitives.push("feMorphology", &format!(r#"in="{colors}" operator="{colors_operator}" {radius}"#), "");
|
||||
let coverage = primitives.push("feMorphology", &format!(r#"in="{image}" operator="{coverage_operator}" {radius}"#), "");
|
||||
match maximum {
|
||||
true => primitives.push("feComposite", &format!(r#"in="{colors}" in2="{coverage}" operator="in""#), ""),
|
||||
false => primitives.uncover(&colors, &coverage, Surroundings::Matted(1.)),
|
||||
}
|
||||
};
|
||||
|
||||
let near = extreme_within(self, radius.floor());
|
||||
let fraction = radius.fract();
|
||||
if fraction <= 0. {
|
||||
return near;
|
||||
}
|
||||
let far = extreme_within(self, radius.ceil());
|
||||
self.push("feComposite", &format!(r#"in="{near}" in2="{far}" operator="arithmetic" k2="{}" k3="{fraction}""#, 1. - fraction), "")
|
||||
}
|
||||
|
||||
/// The image box blurred by a half width of `radius` user units in the color `space` ("sRGB" or "linearRGB"), weighing pixels as the GPU's box does (see [`box_weight`]).
|
||||
/// Where one user unit is one device pixel (`native`), it's a row then a column of `feConvolveMatrix` weights, and otherwise the GPU's result as the map for `capture`,
|
||||
/// with the Gaussian of the same variance standing in until the map resolves.
|
||||
pub(super) fn box_blur(&mut self, image: &str, radius: f64, space: &str, native: bool, capture: EffectCapture) -> String {
|
||||
// Past this the GPU halves the image before its box, which the map follows, and the kernels' markup stays short
|
||||
if !native || radius > MAX_DIRECT_BOX_RADIUS {
|
||||
let sigma = (radius * (radius + 1.) / 3.).sqrt();
|
||||
let attributes = format!(r#"in="{image}" stdDeviation="{sigma} {sigma}" color-interpolation-filters="{space}""#);
|
||||
return self.map_standing_in(capture, "feGaussianBlur", &attributes);
|
||||
}
|
||||
|
||||
// The weights from one end to the other, which read the same turned around, summing to the divisor.
|
||||
// Unlike other kernels, they stay precise past `MAX_PRECISE_KERNEL_AREA`, since browsers quantize between a kernel's least and greatest weights, a box's only two.
|
||||
let reach = radius.ceil() as usize;
|
||||
let weights: Vec<f64> = (0..=2 * reach).map(|index| box_weight(radius, index.abs_diff(reach))).collect();
|
||||
let divisor: f64 = weights.iter().sum();
|
||||
let matrix = weights.iter().map(f64::to_string).collect::<Vec<_>>().join(" ");
|
||||
|
||||
let mut pass = |input: &str, order: [usize; 2], [target_x, target_y]: [usize; 2]| {
|
||||
let attributes = format!(
|
||||
r#"in="{input}" order="{} {}" kernelMatrix="{matrix}" divisor="{divisor}" targetX="{target_x}" targetY="{target_y}" kernelUnitLength="1 1" edgeMode="none" preserveAlpha="false" color-interpolation-filters="{space}""#,
|
||||
order[0], order[1]
|
||||
);
|
||||
self.push("feConvolveMatrix", &attributes, "")
|
||||
};
|
||||
let row = pass(image, [weights.len(), 1], [reach, 0]);
|
||||
pass(&row, [1, weights.len()], [0, reach])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::{write_svg_effects_filter, write_svg_effects_filter_on_lattice};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::Item;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effect_layers::EffectLayers;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::filters::NoiseDistribution;
|
||||
use graphic_types::{EffectOperation, Effects, MinimumMaximumMode};
|
||||
|
||||
fn convolution_kernel(text: &str, scale: f64, offset: f64) -> EffectOperation {
|
||||
EffectOperation::convolution_kernel(text, Some(scale), offset, false)
|
||||
}
|
||||
|
||||
/// The one layer that filters alone draw, with the content.
|
||||
fn one_layer(effects: &Effects) -> EffectLayers {
|
||||
EffectLayers::plan(effects, BlendMode::Normal, 1., true)
|
||||
}
|
||||
|
||||
fn filter(operations: Vec<EffectOperation>, pixel_exact: bool) -> (String, usize) {
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations(operations);
|
||||
let filter = write_svg_effects_filter_on_lattice(
|
||||
&mut defs,
|
||||
&effects,
|
||||
&one_layer(&effects),
|
||||
0,
|
||||
1.,
|
||||
1.,
|
||||
[DVec2::ZERO, DVec2::splat(10.)],
|
||||
0,
|
||||
&[],
|
||||
0..effects.len(),
|
||||
1.,
|
||||
pixel_exact,
|
||||
)
|
||||
.unwrap();
|
||||
(defs, filter.maps.len())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convolution_kernels_turn_their_kernels_around_over_the_visible_colors() {
|
||||
let (defs, maps) = filter(vec![convolution_kernel("0 0 0\n0 0 2\n0 0 0", 2., 51.)], true);
|
||||
assert_eq!(maps, 0);
|
||||
|
||||
// The matrix spans the weight reading the pixel to the right and the pixel itself, turned around, after the stack of the nearest visible colors, nearest on top
|
||||
assert!(
|
||||
defs.contains(r#"<feColorMatrix in="SourceGraphic" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 -15""#),
|
||||
"{defs}"
|
||||
);
|
||||
assert!(defs.contains(r#"<feMerge result="effect-11"><feMergeNode in="effect-2" /><feMergeNode in="effect-10" />"#), "{defs}");
|
||||
assert!(defs.contains(r#"<feMergeNode in="effect-3" /><feMergeNode in="effect-1" /></feMerge>"#), "{defs}");
|
||||
assert!(defs.contains(r#"order="2 1" kernelMatrix="1 0" divisor="1" bias="0.2" targetX="0" targetY="0""#), "{defs}");
|
||||
assert!(defs.contains(r#"in2="SourceGraphic" operator="in""#), "{defs}");
|
||||
assert!(!defs.contains("-0\""), "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convolution_kernels_target_their_center_in_any_shape() {
|
||||
// The order, the turned matrix, and the target of the `feConvolveMatrix` carrying out a kernel
|
||||
let matrix_of = |text: &str| {
|
||||
let (defs, _) = filter(vec![convolution_kernel(text, 1., 0.)], true);
|
||||
let attribute = |name: &str| defs.split(&format!(r#" {name}=""#)).nth(1).and_then(|rest| rest.split('"').next()).unwrap_or_default().to_string();
|
||||
["order", "kernelMatrix", "targetX", "targetY"].map(attribute)
|
||||
};
|
||||
|
||||
// A row lists its weights from the last, centered on its middle, as a column does down, and an even count centers after its middle
|
||||
assert_eq!(matrix_of("1 2 3"), ["3 1", "3 2 1", "1", "0"]);
|
||||
assert_eq!(matrix_of("1\n2\n3"), ["1 3", "3 2 1", "0", "1"]);
|
||||
assert_eq!(matrix_of("1 2\n3 4"), ["2 2", "4 3 2 1", "1", "1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convolution_kernels_take_the_gpus_map_off_the_pixel_lattice_or_past_precise_kernels() {
|
||||
// Where a user unit isn't a device pixel, or the kernel holds more weights than browsers keep precise, the colors come from the GPU, given the live coverage
|
||||
let (defs, maps) = filter(vec![convolution_kernel("0 0 0\n0 0 2\n0 0 0", 2., 51.)], false);
|
||||
assert_eq!(maps, 1);
|
||||
// The map lies atop the content, which shows as it is until the map resolves
|
||||
assert!(!defs.contains("feConvolveMatrix") && defs.contains(r#"in2="SourceGraphic" operator="atop""#), "{defs}");
|
||||
let (defs, maps) = filter(
|
||||
vec![convolution_kernel(
|
||||
&"1 1 1 1 1 1 1
|
||||
"
|
||||
.repeat(7),
|
||||
49.,
|
||||
0.,
|
||||
)],
|
||||
true,
|
||||
);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(!defs.contains("feConvolveMatrix"), "{defs}");
|
||||
|
||||
// A fill forks the content into two, which take a map each
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([convolution_kernel("2", 1., 0.)]);
|
||||
let faded = write_svg_effects_filter(&mut defs, &effects, &one_layer(&effects), 0, 0.5, 1., [DVec2::ZERO, DVec2::ONE], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
assert_eq!(faded.maps.len(), 2);
|
||||
}
|
||||
|
||||
fn box_blur(radius: f64, gamma: bool) -> EffectOperation {
|
||||
EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius,
|
||||
box_blur: true,
|
||||
gamma,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the attribute `name` of each `feConvolveMatrix` in the `defs`, in order.
|
||||
fn attribute_values(defs: &str, name: &str) -> Vec<String> {
|
||||
let primitives = defs.split("<feConvolveMatrix ").skip(1).filter_map(|rest| rest.split("/>").next());
|
||||
let value = |primitive: &str| primitive.split(&format!(r#"{name}=""#)).nth(1)?.split('"').next().map(str::to_string);
|
||||
primitives.filter_map(value).collect()
|
||||
}
|
||||
|
||||
/// The filter of a run of `operations` drawing one layer at `fill`, with whether one user unit is one device pixel, and the captures of its maps.
|
||||
fn filter_at(operations: Vec<EffectOperation>, fill: f32, pixel_exact: bool) -> (String, Vec<EffectCapture>) {
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations(operations);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, true);
|
||||
let filter = write_svg_effects_filter_on_lattice(&mut defs, &effects, &layers, 0, fill, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1., pixel_exact).unwrap();
|
||||
(defs, filter.maps.iter().map(|map| map.capture).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_blurs_on_the_pixel_lattice_convolve_a_row_then_a_column_of_the_gpus_weights() {
|
||||
// A whole half width weighs its pixels evenly, a row centered on each pixel and then a column of the row's result, in linear light
|
||||
let (defs, maps) = filter_at(vec![box_blur(2., false)], 1., true);
|
||||
assert!(maps.is_empty(), "{defs}");
|
||||
assert_eq!(attribute_values(&defs, "order"), ["5 1", "1 5"]);
|
||||
assert_eq!(attribute_values(&defs, "kernelMatrix"), ["1 1 1 1 1"; 2]);
|
||||
assert_eq!(attribute_values(&defs, "divisor"), ["5"; 2]);
|
||||
assert_eq!([attribute_values(&defs, "targetX"), attribute_values(&defs, "targetY")], [["2", "0"], ["0", "2"]]);
|
||||
assert!(
|
||||
defs.contains(r#"<feConvolveMatrix in="SourceGraphic""#) && defs.contains(r#"<feConvolveMatrix in="effect-1""#),
|
||||
"{defs}"
|
||||
);
|
||||
assert_eq!(attribute_values(&defs, "color-interpolation-filters"), ["linearRGB"; 2]);
|
||||
assert!(defs.contains(r#"edgeMode="none" preserveAlpha="false""#), "{defs}");
|
||||
|
||||
// A fractional half width weighs the pixels at its ends by the fraction of them it covers, here in gamma
|
||||
let (defs, _) = filter_at(vec![box_blur(2.5, true)], 1., true);
|
||||
assert_eq!(attribute_values(&defs, "order"), ["7 1", "1 7"]);
|
||||
assert_eq!(attribute_values(&defs, "kernelMatrix"), ["0.5 1 1 1 1 1 0.5"; 2]);
|
||||
assert_eq!(attribute_values(&defs, "divisor"), ["6"; 2]);
|
||||
assert_eq!(attribute_values(&defs, "color-interpolation-filters"), ["sRGB"; 2]);
|
||||
|
||||
// Up to the widest box the GPU runs without halving the image, and on the faded fill as well as the content
|
||||
let (defs, maps) = filter_at(vec![box_blur(24., false)], 0.5, true);
|
||||
assert!(maps.is_empty(), "{defs}");
|
||||
assert_eq!(attribute_values(&defs, "order"), ["49 1", "1 49", "49 1", "1 49"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_blurs_off_the_pixel_lattice_or_wider_than_the_gpus_direct_box_take_the_gpus_map() {
|
||||
// The GPU's result stands in place of the content's, with a Gaussian of the box's variance until it resolves
|
||||
let (defs, maps) = filter_at(vec![box_blur(2., false)], 1., false);
|
||||
assert_eq!(maps, [EffectCapture { index: 0, plane: 0 }]);
|
||||
assert!(!defs.contains("feConvolveMatrix"), "{defs}");
|
||||
assert!(
|
||||
defs.contains(r#"<!--effect-map-"#) && defs.contains(r#"<feGaussianBlur in="SourceGraphic" stdDeviation="1.4142135623730951 1.4142135623730951""#),
|
||||
"{defs}"
|
||||
);
|
||||
|
||||
// A box the GPU blurs on a halved image is that box, and a fill forks the content into two maps
|
||||
let (defs, maps) = filter_at(vec![box_blur(24.5, true)], 0.5, true);
|
||||
assert_eq!(maps, [EffectCapture { index: 0, plane: 1 }, EffectCapture { index: 0, plane: 0 }]);
|
||||
assert!(!defs.contains("feConvolveMatrix"), "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chained_native_convolutions_each_start_a_filter_of_their_own() {
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let sharpen = convolution_kernel("0 -1 0\n-1 5 -1\n0 -1 0", 1., 0.);
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([blur, sharpen.clone(), sharpen]);
|
||||
let filter = write_svg_effects_filter(&mut defs, &effects, &one_layer(&effects), 0, 1., 1., [DVec2::ZERO, DVec2::ONE], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
|
||||
// Each convolution reads the result before it as the source of a filter later in the list
|
||||
assert_eq!(filter.ids.len(), 3);
|
||||
assert_eq!(defs.matches(r#"<feColorMatrix in="SourceGraphic""#).count(), 4, "{defs}");
|
||||
}
|
||||
|
||||
/// How many primitives in the `defs` read the result read most.
|
||||
fn most_reads_of_a_result(defs: &str) -> usize {
|
||||
let results = defs.split(r#"result=""#).skip(1).filter_map(|rest| rest.split('"').next());
|
||||
let reads = |result: &str| defs.matches(&format!(r#"in="{result}""#)).count() + defs.matches(&format!(r#"in2="{result}""#)).count();
|
||||
results.map(reads).max().unwrap_or(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chained_convolutions_taking_maps_read_each_result_once() {
|
||||
// A browser works out a filter's input again for each read, so a chain reading any result twice would double its work at each stage
|
||||
let sharpen = || convolution_kernel("0 -1 0\n-1 5 -1\n0 -1 0", 1., 0.);
|
||||
for (fill, pixel_exact) in [(0.5, true), (1., false)] {
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([sharpen(), sharpen(), sharpen(), sharpen()]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, true);
|
||||
let filter = write_svg_effects_filter_on_lattice(&mut defs, &effects, &layers, 0, fill, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1., pixel_exact).unwrap();
|
||||
assert!(!filter.maps.is_empty(), "{defs}");
|
||||
assert_eq!(most_reads_of_a_result(&defs), 1, "{defs}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chained_minimums_and_maximums_read_each_result_once_where_the_fill_forks_the_content() {
|
||||
// Natively each reads its input twice, or four times for a fractional radius, so where the fill keeps the filter from splitting they take the GPU's results
|
||||
let minimum_maximum = |radius, mode| EffectOperation::MinimumMaximum { radius, mode };
|
||||
let operations = [1.5, 1., 2.5].map(|radius| minimum_maximum(radius, MinimumMaximumMode::Minimum));
|
||||
let effects = Effects::from_operations(operations.into_iter().chain([minimum_maximum(1.5, MinimumMaximumMode::Maximum)]));
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
let mut defs = String::new();
|
||||
let filter = write_svg_effects_filter_on_lattice(&mut defs, &effects, &layers, 0, 0.5, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1., true).unwrap();
|
||||
assert_eq!(filter.maps.len(), 8, "both planes of each take a map: {defs}");
|
||||
assert_eq!(most_reads_of_a_result(&defs), 1, "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chained_unsharp_masks_and_high_passes_read_each_result_once_where_the_fill_forks_the_content() {
|
||||
let unsharp = |threshold| EffectOperation::Sharpen {
|
||||
amount: 200.,
|
||||
radius: 2.,
|
||||
threshold,
|
||||
edges_only: false,
|
||||
};
|
||||
let effects = Effects::from_operations([EffectOperation::HighPass { radius: 2. }, unsharp(10.), EffectOperation::HighPass { radius: 1. }, unsharp(0.)]);
|
||||
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
let mut defs = String::new();
|
||||
let filter = write_svg_effects_filter_on_lattice(&mut defs, &effects, &layers, 0, 0.5, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1., true).unwrap();
|
||||
assert_eq!(filter.maps.len(), 8, "both planes of each take a map: {defs}");
|
||||
assert_eq!(most_reads_of_a_result(&defs), 1, "{defs}");
|
||||
|
||||
// Without the fork, each runs natively in its own filter reading the one before
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
let mut defs = String::new();
|
||||
let filter = write_svg_effects_filter_on_lattice(&mut defs, &effects, &layers, 0, 1., 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1., true).unwrap();
|
||||
assert!(filter.maps.is_empty(), "{defs}");
|
||||
assert_eq!(filter.ids.len(), 4, "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stylize_filters_matte_morph_and_map_where_svg_cant_reach() {
|
||||
// Emboss convolves the content over middle gray, then lifts the gray back off within the coverage in one step
|
||||
let (emboss, _) = filter(vec![EffectOperation::Emboss { angle: 0., height: 2., amount: 100. }], true);
|
||||
assert!(emboss.contains(r#"flood-color="rgb(50%, 50%, 50%)""#), "{emboss}");
|
||||
assert!(emboss.contains(r#"order="3 1" kernelMatrix="1 0 -1" divisor="1" bias="0.5" targetX="1" targetY="0""#), "{emboss}");
|
||||
assert!(emboss.contains(r#"values="0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 -1 1""#), "{emboss}");
|
||||
assert!(emboss.contains(r#"operator="arithmetic" k2="1" k3="-1""#), "{emboss}");
|
||||
|
||||
// Off the pixel lattice, its whole result comes from the GPU, with the content standing in as it is until the map resolves
|
||||
let (emboss, maps) = filter(vec![EffectOperation::Emboss { angle: 0., height: 2., amount: 100. }], false);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(!emboss.contains("feConvolveMatrix") && emboss.contains(r#"--><feOffset in="SourceGraphic""#), "{emboss}");
|
||||
|
||||
// Find Edges takes its whole result as a map too, for the fill and the content each
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([EffectOperation::FindEdges]);
|
||||
let find_edges = write_svg_effects_filter(&mut defs, &effects, &one_layer(&effects), 0, 0.5, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
let planes: Vec<usize> = find_edges.maps.iter().map(|map| map.capture.plane).collect();
|
||||
assert_eq!(planes, [1, 0], "the fill and the content each take their own");
|
||||
assert!(!defs.contains("-1 1\""), "nothing lifts white off the maps: {defs}");
|
||||
|
||||
// A fractional radius mixes the morphologies of the whole radii around it
|
||||
let maximum = EffectOperation::MinimumMaximum {
|
||||
radius: 1.25,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
};
|
||||
let (maximum, _) = filter(vec![maximum], true);
|
||||
assert!(
|
||||
maximum.contains(r#"operator="dilate" radius="1 1""#) && maximum.contains(r#"operator="erode" radius="2 2""#),
|
||||
"{maximum}"
|
||||
);
|
||||
assert!(maximum.contains(r#"operator="arithmetic" k2="0.75" k3="0.25""#), "{maximum}");
|
||||
|
||||
// The maximum spreads every covered pixel's color, and the minimum lifts white back off its colors within the grown coverage, in a region grown for its erosion
|
||||
assert!(maximum.contains(r#"values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), "{maximum}");
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([EffectOperation::MinimumMaximum {
|
||||
radius: 2.,
|
||||
mode: MinimumMaximumMode::Minimum,
|
||||
}]);
|
||||
let minimum = write_svg_effects_filter(&mut defs, &effects, &one_layer(&effects), 0, 1., 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
assert!(
|
||||
defs.contains(r#"operator="dilate" radius="2 2""#) && defs.contains(r#"values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 -1 1""#),
|
||||
"{defs}"
|
||||
);
|
||||
assert_eq!(minimum.region, [DVec2::splat(-5.), DVec2::splat(15.)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sharpening_blurs_natively_and_maps_its_coverage_off_the_lattice() {
|
||||
// Without a threshold, unsharp masking adds the scaled difference from a blur of the visible colors back in one composite, and sharpens the coverage the same way
|
||||
let unsharp = |threshold| EffectOperation::Sharpen {
|
||||
amount: 200.,
|
||||
radius: 2.,
|
||||
threshold,
|
||||
edges_only: false,
|
||||
};
|
||||
let (defs, maps) = filter(vec![unsharp(0.)], false);
|
||||
assert_eq!(maps, 0);
|
||||
assert_eq!(defs.matches("feGaussianBlur").count(), 2, "{defs}");
|
||||
assert_eq!(defs.matches(r#"operator="arithmetic" k2="3" k3="-2" k4="0""#).count(), 2, "{defs}");
|
||||
assert!(!defs.contains("tableValues"), "{defs}");
|
||||
|
||||
// With one, the difference maps through a table of the change it makes, where no change is level 128 written a quarter level up
|
||||
let (defs, _) = filter(vec![unsharp(10.)], false);
|
||||
assert_eq!(defs.matches(r#"<feFuncR type="table" tableValues=""#).count(), 2, "{defs}");
|
||||
assert!(defs.contains(" 0.50294 ") && defs.contains(r#"type="linear" slope="-1" intercept="1""#), "{defs}");
|
||||
|
||||
// The widening is whole 128ths and its offset whole levels, putting a zero difference at 128.04
|
||||
assert_eq!(defs.matches(r#"k2="0.953125" k3="0.953125" k4="-0.45098"#).count(), 2, "{defs}");
|
||||
|
||||
// Edges Only takes its whole result as one map even on the pixel lattice, as unsharp masking does for both planes where the fill forks
|
||||
let edges_only = EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 1.,
|
||||
threshold: 0.,
|
||||
edges_only: true,
|
||||
};
|
||||
let (defs, maps) = filter(vec![edges_only], true);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(!defs.contains("feGaussianBlur") && !defs.contains("feConvolveMatrix"), "{defs}");
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([unsharp(0.)]);
|
||||
let faded = write_svg_effects_filter(&mut defs, &effects, &one_layer(&effects), 0, 0.5, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
let planes: Vec<usize> = faded.maps.iter().map(|map| map.capture.plane).collect();
|
||||
assert_eq!(planes, [1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kernel_applied_to_alpha_convolves_the_coverage_on_the_lattice_and_maps_its_result_off_it() {
|
||||
let sharpen = EffectOperation::convolution_kernel("0 -1 0\n-1 8 -1\n0 -1 0", None, 0., true);
|
||||
|
||||
// The colors convolve straight, and the coverage alongside them as the alpha of a convolution over every channel
|
||||
let (defs, maps) = filter(vec![sharpen.clone()], true);
|
||||
assert_eq!(maps, 0);
|
||||
assert_eq!(defs.matches("<feConvolveMatrix").count(), 2, "{defs}");
|
||||
assert_eq!(defs.matches(r#"preserveAlpha="true""#).count(), 1, "{defs}");
|
||||
|
||||
// Off the lattice, the colors take the coverage they weigh, so the whole result comes as the map
|
||||
let (defs, maps) = filter(vec![sharpen], false);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(!defs.contains("feConvolveMatrix"), "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_fields_come_from_the_gpu_combined_with_the_live_content() {
|
||||
// Add Noise adds the map's offsets, scaled out from middle gray to their extent, to the opaque colors within the live coverage
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 40.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
seed: 0,
|
||||
};
|
||||
let (defs, maps) = filter(vec![noise], true);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(defs.contains(r#"operator="arithmetic" k2="1" k3="0.8" k4="-0.4""#), "{defs}");
|
||||
assert!(defs.contains(r#"in2="SourceGraphic" operator="in""#), "{defs}");
|
||||
// Until the map is resolved, its middle gray offsets nothing
|
||||
assert!(defs.contains(r##"<feFlood flood-color="#808080" flood-opacity="1""##), "{defs}");
|
||||
|
||||
// Dissolve shows the opaque colors where the coverage is at least a level above the map's threshold (its gray), by the share the map gives (its alpha)
|
||||
let (defs, maps) = filter(vec![EffectOperation::Dissolve { opacity: 50., seed: 0 }], true);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(defs.contains(r#"in="SourceGraphic" in2="effect-2" operator="arithmetic" k2="1" k3="-1""#), "{defs}");
|
||||
assert!(defs.contains(r#"in2="effect-1" operator="in""#), "{defs}");
|
||||
// Until the map is resolved, its opaque black shows every covered pixel
|
||||
assert!(defs.contains(r##"<feFlood flood-color="#000000" flood-opacity="1""##), "{defs}");
|
||||
|
||||
// Where the fill forks the content, each plane takes its whole result as a map, so chains of them don't multiply their reads
|
||||
let mut faded = String::new();
|
||||
let effects = Effects::from_operations([EffectOperation::Dissolve { opacity: 50., seed: 0 }]);
|
||||
let filter = write_svg_effects_filter(&mut faded, &effects, &one_layer(&effects), 0, 0.5, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
assert_eq!(filter.maps.len(), 2);
|
||||
let table = defs
|
||||
.split(r#"<feFuncA type="discrete" tableValues=""#)
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('"').next())
|
||||
.unwrap_or_default();
|
||||
assert_eq!(table.split(' ').collect::<Vec<_>>(), [vec!["0"], vec!["1"; 255]].concat(), "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_fields_change_endless_colors_within_the_view() {
|
||||
use crate::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use core_types::list::{ATTR_EFFECTS, List};
|
||||
use core_types::transform::Footprint;
|
||||
|
||||
// A color with Add Noise after Levels draws through a filter over the view, with the noise's map and the Levels within it
|
||||
let levels = graphic_types::Adjustment::Exposure {
|
||||
exposure: 1.,
|
||||
offset: 0.,
|
||||
gamma_correction: 1.,
|
||||
};
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 20.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
seed: 0,
|
||||
};
|
||||
let effects = Effects::from_operations([noise, EffectOperation::Adjustment(levels)]);
|
||||
let color = Item::new_from_element(core_types::Color::BLUE).with_attribute(ATTR_EFFECTS, effects);
|
||||
let params = RenderParams {
|
||||
view: Some(Footprint {
|
||||
transform: DAffine2::IDENTITY,
|
||||
resolution: glam::UVec2::splat(32),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut render = SvgRender::new();
|
||||
List::new_from_item(color).render_svg(&mut render, ¶ms);
|
||||
assert_eq!(render.effect_maps.len(), 1);
|
||||
assert!(render.svg.to_svg_string().contains(r#"filter="url(#"#), "{}", render.svg.to_svg_string());
|
||||
assert!(render.svg_defs.contains(r#"x="0" y="0" width="32" height="32""#), "{}", render.svg_defs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_fields_leave_a_mask_on_endless_colors_in_its_own_place() {
|
||||
use crate::{Render, RenderParams, SvgRender};
|
||||
use core_types::list::{ATTR_EFFECTS, List};
|
||||
use core_types::transform::Footprint;
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||||
use graphic_types::{Graphic, MaskMode};
|
||||
|
||||
// A gradient mask without a transform lies across the color's own unit square, as on the GPU, rather than across the view
|
||||
let stops = [(0., core_types::Color::BLACK), (1., core_types::Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 20.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
seed: 0,
|
||||
};
|
||||
let mask = EffectOperation::Mask {
|
||||
mask: Graphic::from(Gradient::new(stops)),
|
||||
mode: MaskMode::Luminance,
|
||||
density: 100.,
|
||||
feather: 0.,
|
||||
invert: false,
|
||||
};
|
||||
let color = Item::new_from_element(core_types::Color::BLUE).with_attribute(ATTR_EFFECTS, Effects::from_operations([noise, mask]));
|
||||
|
||||
let params = RenderParams {
|
||||
view: Some(Footprint {
|
||||
transform: DAffine2::IDENTITY,
|
||||
resolution: glam::UVec2::splat(64),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let mut render = SvgRender::new();
|
||||
List::new_from_item(color).render_svg(&mut render, ¶ms);
|
||||
|
||||
// The gradient spans its own unit square rather than the 64 units in view
|
||||
let defs = &render.svg_defs;
|
||||
assert!(defs.contains("<mask") && defs.contains(r#"x1="0" y1="0" x2="1" y2="0">"#), "{defs}");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! SVG masks of content by another graphic: SVG's own `<mask>` for the masks before and after the other effects, and filter primitives for those between them.
|
||||
//! Both forms run the same steps as the GPU's passes: the coverage, its feather, then its density. Also the masked radius blur's filter primitives.
|
||||
//! Both forms run the same steps as the GPU's passes: the coverage, its feather, then its density.
|
||||
|
||||
use super::{ENDLESS_EXTENT, Render, RenderParams, RenderSvgSegmentList, SvgFilterPrimitives, SvgRender, drawn_bounding_box, nested_effects_reach, svg_drawn_paint, svg_effects_region};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
@@ -8,7 +8,7 @@ use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effects::{EffectOperation, Effects, spans_along_axes};
|
||||
use graphic_types::masks::{MaskMode, mask_density_line, mask_feather_sigma, masked_radius_blur_weight};
|
||||
use graphic_types::masks::{MaskMode, mask_density_line, mask_feather_sigma};
|
||||
use graphic_types::{Appearance, Graphic};
|
||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||
use std::fmt::Write;
|
||||
@@ -74,23 +74,6 @@ pub(super) fn holds_effects(graphic: &Graphic) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the graphic or anything nested in it is a GPU image, which SVG markup can't draw.
|
||||
fn holds_gpu_image(graphic: &Graphic) -> bool {
|
||||
match graphic {
|
||||
Graphic::RasterGPU(_) => true,
|
||||
Graphic::RasterGPUList(list) => !list.is_empty(),
|
||||
Graphic::Graphic(item) => holds_gpu_image(item.element()),
|
||||
Graphic::GraphicList(list) => list.iter_element_values().any(holds_gpu_image),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether SVG draws a blur's `radius_mask` as markup in its filter, keeping the blur resolution-independent, rather than taking its luminance as the GPU's map.
|
||||
/// Markup embedded as an image reaches no maps of the radius mask's own effects.
|
||||
pub(super) fn radius_mask_draws_as_markup(radius_mask: &Graphic) -> bool {
|
||||
!holds_effects(radius_mask) && !holds_gpu_image(radius_mask)
|
||||
}
|
||||
|
||||
/// A mask's graphic placed by its content's `placement`, which it follows.
|
||||
pub(super) fn placed(mask: &Graphic, placement: DAffine2) -> Graphic {
|
||||
Graphic::Graphic(Box::new(Item::new_from_element(mask.clone()).with_attribute(ATTR_TRANSFORM, placement)))
|
||||
@@ -144,7 +127,7 @@ pub(super) fn masked_extent(effects: &Effects, placement: DAffine2) -> Option<[D
|
||||
break;
|
||||
}
|
||||
|
||||
let reach = 3. * svg_feather_sigma(feather, length_scale) + nested_effects_reach(&mask, placement, |_| true);
|
||||
let reach = 3. * svg_feather_sigma(feather, length_scale) + nested_effects_reach(&mask, placement, EffectOperation::painted_reach);
|
||||
let [min, max] = [min - reach, max + reach];
|
||||
extent = Some(match extent {
|
||||
// Masks that don't overlap leave an empty extent at the first one's corner
|
||||
@@ -194,7 +177,7 @@ pub(super) fn write_endless_content_mask(render: &mut SvgRender, effects: &Effec
|
||||
let sigma = svg_feather_sigma(feather, length_scale);
|
||||
let region = match drawn_bounding_box(&mask, DAffine2::IDENTITY) {
|
||||
RenderBoundingBox::Rectangle([min, max]) => {
|
||||
let reach = 3. * sigma + nested_effects_reach(&mask, DAffine2::IDENTITY, |_| true);
|
||||
let reach = 3. * sigma + nested_effects_reach(&mask, DAffine2::IDENTITY, EffectOperation::painted_reach);
|
||||
[min - reach, max + reach]
|
||||
}
|
||||
_ => [DVec2::splat(-ENDLESS_EXTENT), DVec2::splat(ENDLESS_EXTENT)],
|
||||
@@ -266,46 +249,6 @@ fn write_combined_mask(svg_defs: &mut String, masks: &[&NativeMask], endless: bo
|
||||
}
|
||||
|
||||
impl SvgFilterPrimitives {
|
||||
/// Each level's parts of a masked radius blur's interpolation, in the alpha of its result, from the radius mask's 8-bit `luminance` (in alpha) for the `levels` of its radius, matching `masked_radius_blur_interpolation`.
|
||||
pub(super) fn masked_radius_blur_weights(&mut self, luminance: &str, levels: &[f64]) -> Vec<String> {
|
||||
(0..levels.len())
|
||||
.map(|level| {
|
||||
// A quarter of a level past each whole one lands on it whether a browser rounds or truncates, and none stays exactly none for one that doesn't
|
||||
let table = (0..=255_u8)
|
||||
.map(|code| {
|
||||
let weight = masked_radius_blur_weight(level, code, levels) as f64;
|
||||
let biased = if weight > 0. { weight + 0.25 } else { 0. };
|
||||
format!("{:.6}", (biased / 255.).min(1.))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
self.push("feComponentTransfer", &format!(r#"in="{luminance}""#), &format!(r#"<feFuncA type="table" tableValues="{table}" />"#))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `image` blurred by each of a masked radius blur's Gaussian `levels` (in user units) weighed by its `weights` and summed, matching the GPU's `masked_radius_blur`.
|
||||
/// The levels blur in gamma if `gamma` and in linear light otherwise.
|
||||
pub(super) fn masked_radius_blur(&mut self, image: &str, weights: &[String], levels: &[f64], gamma: bool) -> String {
|
||||
let space = if gamma { "sRGB" } else { "linearRGB" };
|
||||
|
||||
let mut sum: Option<String> = None;
|
||||
for (&sigma, weight) in levels.iter().zip(weights) {
|
||||
let blurred = match sigma >= NEGLIGIBLE_LENGTH {
|
||||
true => self.push("feGaussianBlur", &format!(r#"in="{image}" stdDeviation="{sigma} {sigma}" color-interpolation-filters="{space}""#), ""),
|
||||
false => image.to_string(),
|
||||
};
|
||||
// Weighed and summed in gamma, the filter's own space, on purpose (see `masked_radius_blur_interpolation`)
|
||||
let weighted = self.push("feComposite", &format!(r#"in="{blurred}" in2="{weight}" operator="in""#), "");
|
||||
|
||||
sum = Some(match sum {
|
||||
Some(sum) => self.add(&sum, &weighted),
|
||||
None => weighted,
|
||||
});
|
||||
}
|
||||
sum.unwrap_or_else(|| image.to_string())
|
||||
}
|
||||
|
||||
/// The `mode`'s coverage of a mask graphic's `image`, in the alpha of the result, matching the GPU's `mask_coverage`.
|
||||
pub(super) fn mask_coverage(&mut self, image: &str, mode: MaskMode) -> String {
|
||||
match mode {
|
||||
|
||||
@@ -5,7 +5,6 @@ use graphic_types::effect_layers::EffectLayers;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use graphic_types::raster_types::{CPU, Raster, Texture};
|
||||
use graphic_types::resampling::EffectFrame;
|
||||
use graphic_types::{Adjustment, EffectOperation, Effects};
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
|
||||
use std::borrow::Cow;
|
||||
@@ -57,7 +56,6 @@ pub trait EffectsRenderer: Send {
|
||||
/// Renders the content `draw` draws, and each of the effects' drawn paints `draw_paint` draws by index, placed by `view` in premultiplied textures of `size`,
|
||||
/// returning one for each of the `layers` that `effects` carried out on it draw, with the mode it blends by.
|
||||
/// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers.
|
||||
/// The `frame`, in the texture's pixels, is what effects relative to the content's extent take as their own.
|
||||
/// With a `capture`, the only texture instead holds that effect's coverage, as black with it in alpha.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_effects(
|
||||
@@ -69,7 +67,6 @@ pub trait EffectsRenderer: Send {
|
||||
fill: f32,
|
||||
opacity: f32,
|
||||
effect_to_pixels: DAffine2,
|
||||
frame: Option<EffectFrame>,
|
||||
capture: Option<EffectCapture>,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
@@ -379,8 +376,6 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
/// Draws the content `draw` draws with `effects` carried out on it in their `effect_space` (placed in the space of the drawn content), within `bounds` in that space (or everywhere for `None`),
|
||||
/// drawing again for each part of a split render. `draw_paint` draws each of the effects' drawn paints by its index among them, and `fill` fades the content but not the shadows and glows cast from it.
|
||||
/// The content blends by `blend_mode` and the effects by their own modes, each faded by `opacity`, onto what lies beneath, or with every effect flattened into the content's image if not `layered`.
|
||||
/// The `frame` places the unit square on the content's bounds in its own space, carried through its transform into the space of the drawn content, for effects relative to the content's extent.
|
||||
/// It comes with how far the content already paints past it in document units (its overhang), as a group's nested effects do, which those effects carry along.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn draw_effects(
|
||||
&mut self,
|
||||
@@ -391,16 +386,12 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
layered: bool,
|
||||
bounds: Option<Rect>,
|
||||
effect_space: DAffine2,
|
||||
frame: Option<(DAffine2, f64)>,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) {
|
||||
let capture = self.effect_capture.take();
|
||||
let effect_to_device = DAffine2::from_cols_array(&self.view.as_coeffs()) * effect_space;
|
||||
|
||||
// The effect space is tested alone too, since a tilted view can leave a rounding residue in the product where its own determinant is 0
|
||||
let collapsed = !effect_to_device.matrix2.determinant().is_normal() || !effect_space.matrix2.determinant().is_normal();
|
||||
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) || collapsed {
|
||||
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) || !effect_to_device.matrix2.determinant().is_normal() {
|
||||
self.push_viewport_layer(peniko::BlendMode::new(blend_mode.to_peniko(), peniko::Compose::SrcOver), opacity * fill);
|
||||
draw(self);
|
||||
self.pop_layer();
|
||||
@@ -409,12 +400,11 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
let layers = EffectLayers::plan(effects, blend_mode, fill, layered);
|
||||
|
||||
// The texture follows the viewport's axes if the effect space only turns and evenly scales, or else its own axes, scaled evenly to keep every direction's detail.
|
||||
// A box blur or a minimum or maximum, whose square neighborhoods aren't round, turns with its space only along that space's axes.
|
||||
let has_square_kernel = effects.operations().any(|operation| {
|
||||
let square = matches!(operation, EffectOperation::Blur { box_blur: true, .. } | EffectOperation::MinimumMaximum { .. });
|
||||
square && !operation.changes_nothing()
|
||||
});
|
||||
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
|
||||
// A box blur, which isn't round, turns with its space only along that space's axes.
|
||||
let has_box_blur = effects
|
||||
.operations()
|
||||
.any(|operation| matches!(operation, EffectOperation::Blur { box_blur: true, .. }) && !operation.changes_nothing());
|
||||
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_box_blur || is_axis_aligned(effect_to_device.matrix2));
|
||||
let (frame_to_device, lengths_to_frame) = match follows_viewport {
|
||||
true => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
||||
false => {
|
||||
@@ -424,54 +414,22 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
};
|
||||
let device_to_frame = frame_to_device.inverse();
|
||||
let document_to_frame = Affine::new(device_to_frame.to_cols_array()) * self.view;
|
||||
|
||||
// Effects relative to the content's extent paint farther from larger content, measured in their effect space, and others read past what they paint, like a kernel or a mask's feather
|
||||
let (effect_frame, overhang) = (frame.map(|(frame, _)| frame), frame.map_or(0., |(_, overhang)| overhang));
|
||||
let read_beyond_painted = effects.required_reach() - effects.reach();
|
||||
let reach = match bounds {
|
||||
Some(bounds) => effects.run_reach_around(effect_space, [DVec2::new(bounds.x0, bounds.y0), DVec2::new(bounds.x1, bounds.y1)], overhang) + read_beyond_painted,
|
||||
None => effects.required_reach(),
|
||||
};
|
||||
let length_scale = lengths_to_frame.determinant().abs().sqrt();
|
||||
let (reach, working_reach) = (reach * length_scale, (reach + effects.working_reach() - effects.required_reach()) * length_scale);
|
||||
let (reach, working_reach) = (effects.reach() * length_scale, effects.working_reach() * length_scale);
|
||||
|
||||
// Effects relative to the content's extent take its frame, measured in their effect space
|
||||
let effect_to_frame = device_to_frame * effect_to_device;
|
||||
let effect_frame = effect_frame.and_then(|frame| EffectFrame::new(effect_space.inverse() * frame, effect_to_frame));
|
||||
|
||||
// The content and what its effects read past it, reaching into the viewport and rounded out to whole pixels of the frame, and its effect frame where effects paint anywhere in it.
|
||||
// Past the view, what they read without painting or reading around each pixel (like a mask's feather) is kept as far as it fits without lowering the resolution.
|
||||
// The content and what its effects read past it, reaching into the viewport and rounded out to whole pixels of the frame.
|
||||
// Past the view, what they read without painting (like a mask's feather) is kept as far as it fits without lowering the resolution.
|
||||
let viewport = Rect::new(0., 0., self.width() as f64, self.height() as f64);
|
||||
let viewport_in_frame = Affine::new(device_to_frame.to_cols_array()).transform_rect_bbox(viewport);
|
||||
let mut content_bounds = bounds.map_or(viewport_in_frame, |bounds| document_to_frame.transform_rect_bbox(bounds));
|
||||
if let Some(frame) = effect_frame.filter(|_| bounds.is_some() && effects.paint_across_frame()) {
|
||||
let [min, max] = frame.pixel_bounds();
|
||||
content_bounds = content_bounds.union(Rect::new(min.x, min.y, max.x, max.y));
|
||||
}
|
||||
let content_bounds = bounds.map_or(viewport_in_frame, |bounds| document_to_frame.transform_rect_bbox(bounds));
|
||||
let max_size = self.max_texture_size.min(u16::MAX as u32);
|
||||
let max_area = MAX_EFFECTS_AREA_PER_VIEWPORT_AREA * viewport.area();
|
||||
let painted_region = content_bounds.inflate(working_reach, working_reach).intersect(viewport_in_frame.inflate(reach, reach));
|
||||
let read_past_view = reach + growth_that_fits(painted_region, max_area, max_size as f64).min(working_reach - reach).max(0.);
|
||||
let mut region = content_bounds
|
||||
let region = content_bounds
|
||||
.inflate(working_reach, working_reach)
|
||||
.intersect(viewport_in_frame.inflate(read_past_view, read_past_view))
|
||||
.expand();
|
||||
|
||||
// Some read beyond the region, like a radial blur along its arcs, and content without bounds lies wherever they read
|
||||
let visible = content_bounds.inflate(reach, reach).intersect(viewport_in_frame);
|
||||
let corners = |rect: Rect| [DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)];
|
||||
if let Some([min, max]) = effects.source_region(corners(visible), effect_frame.as_ref(), effect_to_frame) {
|
||||
if !(visible.width() > 0. && visible.height() > 0.) {
|
||||
return;
|
||||
}
|
||||
let source = Rect::new(min.x, min.y, max.x, max.y);
|
||||
region = match bounds {
|
||||
Some(_) => source.intersect(content_bounds.inflate(working_reach, working_reach)),
|
||||
None => source,
|
||||
}
|
||||
.expand();
|
||||
}
|
||||
|
||||
if !(region.width() > 0. && region.height() > 0.) {
|
||||
return;
|
||||
}
|
||||
@@ -483,12 +441,10 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
||||
let origin = region.origin().to_vec2();
|
||||
|
||||
let frame_to_pixels = Affine::scale(resolution) * Affine::translate(-origin);
|
||||
let content_view = frame_to_pixels * document_to_frame;
|
||||
let content_view = Affine::scale(resolution) * Affine::translate(-origin) * document_to_frame;
|
||||
let effect_to_pixels = DAffine2::from_cols_array(&content_view.as_coeffs()) * effect_space;
|
||||
let effect_frame = effect_frame.map(|frame| frame.placed(DAffine2::from_cols_array(&frame_to_pixels.as_coeffs())));
|
||||
let Some(renderer) = self.effects_renderer.as_deref_mut() else { return };
|
||||
let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, effect_frame, capture, draw_paint, draw);
|
||||
let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, capture, draw_paint, draw);
|
||||
|
||||
// Draw each layer where the content was, blended onto what lies beneath, except a captured coverage, which is drawn as it is
|
||||
let area = Rect::new(0., 0., size.x as f64, size.y as f64);
|
||||
|
||||
@@ -29,7 +29,6 @@ fn operation(primitives: &[Primitive]) -> Option<EffectOperation> {
|
||||
|
||||
match primitive.kind() {
|
||||
Kind::GaussianBlur(blur) if *blur.input() == Input::SourceGraphic => Some(EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: standard_deviation(blur.std_dev_x().get(), blur.std_dev_y().get()),
|
||||
box_blur: false,
|
||||
gamma: primitive.color_interpolation() == ColorInterpolation::SRGB,
|
||||
|
||||
@@ -314,7 +314,6 @@ fn a_gaussian_blur_filter_becomes_a_blur_of_the_geometric_mean_of_its_standard_d
|
||||
assert_eq!(
|
||||
effects,
|
||||
Some(&Effects::from_operations([EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false
|
||||
|
||||
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user