mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71e0099edd | ||
|
|
f3dafd9dc2 | ||
|
|
6f4ef1fe3d | ||
|
|
7469ecce35 | ||
|
|
d69b21f035 | ||
|
|
7e2e1fe028 | ||
|
|
12daaf8ab0 | ||
|
|
c465a3ebea | ||
|
|
8bcafc9dec | ||
|
|
0fbc09eabd | ||
|
|
017234b15b | ||
|
|
5f48595604 | ||
|
|
7aba423a2e | ||
|
|
16774db9c2 | ||
|
|
a4c0cb5c31 |
No files matched your search
Generated
+4
-2
@@ -2675,7 +2675,6 @@ dependencies = [
|
|||||||
"math-nodes",
|
"math-nodes",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"path-bool-nodes",
|
"path-bool-nodes",
|
||||||
"raster-kernels",
|
|
||||||
"raster-nodes",
|
"raster-nodes",
|
||||||
"rendering",
|
"rendering",
|
||||||
"repeat-nodes",
|
"repeat-nodes",
|
||||||
@@ -5437,9 +5436,11 @@ dependencies = [
|
|||||||
"glam",
|
"glam",
|
||||||
"graph-craft",
|
"graph-craft",
|
||||||
"graphene-std",
|
"graphene-std",
|
||||||
|
"graphic-types",
|
||||||
"interpreted-executor",
|
"interpreted-executor",
|
||||||
"log",
|
"log",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
|
"wgpu-executor",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -5772,12 +5773,14 @@ dependencies = [
|
|||||||
"node-macro",
|
"node-macro",
|
||||||
"raster-kernels",
|
"raster-kernels",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
|
"rendering",
|
||||||
"serde",
|
"serde",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tsify",
|
"tsify",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
|
"wgpu-executor",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -8076,7 +8079,6 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"ollev",
|
"ollev",
|
||||||
"raster-kernels",
|
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -6,5 +6,6 @@ mod mandelbrot_v2;
|
|||||||
mod mix_colors_from_mix_node;
|
mod mix_colors_from_mix_node;
|
||||||
mod noise_pattern_v1;
|
mod noise_pattern_v1;
|
||||||
mod noise_pattern_v2;
|
mod noise_pattern_v2;
|
||||||
|
mod passthrough_from_extend_image_to_bounds;
|
||||||
mod pattern_square;
|
mod pattern_square;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
use migration_core::{Inputs, migration};
|
||||||
|
|
||||||
|
/// 'Extend Image to Bounds' is gone, and the transparent pixels it padded an image with drew nothing, so it passes its image on and drops its bounds.
|
||||||
|
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
||||||
|
pub fn passthrough_from_extend_image_to_bounds(inputs: &mut Inputs) {
|
||||||
|
inputs.truncate(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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(2, |random, _slot| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&PassthroughFromExtendImageToBounds, &contract());
|
||||||
|
check_undo(&PassthroughFromExtendImageToBounds, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_image_and_drops_the_bounds() {
|
||||||
|
let (image, bounds) = (literal(1.), literal(2.));
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&PassthroughFromExtendImageToBounds);
|
||||||
|
let extend = fixture.add(decl!("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1), vec![image.clone(), bounds]);
|
||||||
|
let migrated = fixture.migrate(&PassthroughFromExtendImageToBounds).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, extend), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, extend), [image]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,3 +4,12 @@ use migration_core::rename;
|
|||||||
|
|
||||||
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
|
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
|
||||||
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
|
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
|
||||||
|
|
||||||
|
// 'Image to Channels' became 'Into Channels', taking and giving graphics, whose stored input and channel outputs keep their places
|
||||||
|
rename!("raster_nodes::adjustments::ImageToChannelsNode"@1 => "raster_nodes::channels::IntoChannelsNode"@2);
|
||||||
|
|
||||||
|
// 'Channels to Image' became 'From Channels', taking and giving graphics, whose stored inputs and output keep their places
|
||||||
|
rename!("raster_nodes::std_nodes::ChannelsToImageNode"@1 => "raster_nodes::channels::FromChannelsNode"@2);
|
||||||
|
|
||||||
|
// 'Median Filter' became an effect taking any graphic, whose stored image and radius keep their places
|
||||||
|
rename!("raster_nodes::filter::MedianFilterNode"@1 => @2);
|
||||||
@@ -37,6 +37,7 @@ impl FrontendGraphDataType {
|
|||||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||||
// A generator draws pixels like an image, at whatever resolution is needed
|
// A generator draws pixels like an image, at whatever resolution is needed
|
||||||
"Generator" => Self::Raster,
|
"Generator" => Self::Raster,
|
||||||
|
"Pixels" => Self::Raster,
|
||||||
raster if raster.starts_with("Raster") => Self::Raster,
|
raster if raster.starts_with("Raster") => Self::Raster,
|
||||||
_ => Self::General,
|
_ => Self::General,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,6 +121,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
"graphene_std::raster::SampleImageNode",
|
"graphene_std::raster::SampleImageNode",
|
||||||
"graphene_std::raster::SampleNode",
|
"graphene_std::raster::SampleNode",
|
||||||
"raster_nodes::std_nodes::SampleImageNode",
|
"raster_nodes::std_nodes::SampleImageNode",
|
||||||
|
// The deleted Extend Image to Bounds passes its image through, since the transparent pixels it padded with drew nothing
|
||||||
|
"graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
||||||
|
"graphene_std::raster::ExtendImageToBoundsNode",
|
||||||
|
"raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
@@ -545,8 +549,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
node: graphene_std::raster_nodes::channels::into_channels::IDENTIFIER,
|
||||||
|
aliases: &["raster_nodes::adjustments::ImageToChannelsNode"],
|
||||||
|
},
|
||||||
|
NodeReplacement {
|
||||||
|
node: graphene_std::raster_nodes::channels::from_channels::IDENTIFIER,
|
||||||
aliases: &[
|
aliases: &[
|
||||||
|
"raster_nodes::std_nodes::ChannelsToImageNode",
|
||||||
"raster_nodes::std_nodes::CombineChannelsNode",
|
"raster_nodes::std_nodes::CombineChannelsNode",
|
||||||
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
||||||
"graphene_std::raster::CombineChannelsNode",
|
"graphene_std::raster::CombineChannelsNode",
|
||||||
@@ -564,10 +573,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
"graphene_core::raster::ExposureNode",
|
"graphene_core::raster::ExposureNode",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
NodeReplacement {
|
|
||||||
node: graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
|
||||||
aliases: &["graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode", "graphene_std::raster::ExtendImageToBoundsNode"],
|
|
||||||
},
|
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||||
@@ -1564,13 +1569,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `image_to_channels` proto nodes.
|
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `into_channels` proto nodes.
|
||||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
// 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.
|
// 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 = [
|
let split_wrapper_replacements = [
|
||||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
("Split Channels", graphene_std::raster_nodes::channels::into_channels::IDENTIFIER),
|
||||||
];
|
];
|
||||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||||
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||||
@@ -1616,7 +1621,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Image to Channels" nodes.
|
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Into Channels" nodes.
|
||||||
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
||||||
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
||||||
const EXTRACT_CHANNEL: [&str; 4] = [
|
const EXTRACT_CHANNEL: [&str; 4] = [
|
||||||
@@ -1635,7 +1640,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
if EXTRACT_XY.contains(&name) {
|
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::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
Some((*node_id, path, graphene_std::raster_nodes::channels::into_channels::IDENTIFIER, "Extract Channel"))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -3247,9 +3252,17 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sample Image nodes, now passthroughs, drop their old title
|
// Sample Image and Extend Image to Bounds nodes, now passthroughs, drop their old titles and any inputs past the first, like Extend Image to Bounds's bounds
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) {
|
||||||
reset_default_display_name(document, node_id, network_path, "Sample Image");
|
reset_default_display_name(document, node_id, network_path, "Sample Image");
|
||||||
|
reset_default_display_name(document, node_id, network_path, "Extend Image to Bounds");
|
||||||
|
|
||||||
|
if inputs_count > 1 {
|
||||||
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
|
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||||
|
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Serialize became As String, whose input converts a wired value to text, while a stored value keeps the JSON text Serialize made of it
|
// Serialize became As String, whose input converts a wired value to text, while a stored value keeps the JSON text Serialize made of it
|
||||||
@@ -6318,6 +6331,35 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn extend_image_to_bounds_opens_as_a_passthrough_of_its_image() {
|
||||||
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
use glam::DAffine2;
|
||||||
|
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||||
|
|
||||||
|
let (image, extend) = (NodeId(1), NodeId(2));
|
||||||
|
let image_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
||||||
|
.expect("the Image definition should exist")
|
||||||
|
.default_node_template();
|
||||||
|
let extend_template = NodeTemplate {
|
||||||
|
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("raster_nodes::std_nodes::ExtendImageToBoundsNode")),
|
||||||
|
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::DAffine2(DAffine2::IDENTITY), false)],
|
||||||
|
display_name: "Extend Image to Bounds".to_string(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut document = DocumentMessageHandler::default();
|
||||||
|
document.network_interface.insert_node(image, image_template, &[]);
|
||||||
|
document.network_interface.insert_node(extend, extend_template, &[]);
|
||||||
|
document.network_interface.set_input(&InputConnector::node_at_index(extend, 0), NodeInput::node(image, 0), &[]);
|
||||||
|
|
||||||
|
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||||
|
let node = opened.network_interface.document_node(&extend, &[]).expect("the node should still exist");
|
||||||
|
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||||
|
assert!(matches!(node.inputs[..], [NodeInput::Node { node_id, output_index: 0, .. }] if node_id == image), "{:?}", node.inputs);
|
||||||
|
assert_ne!(opened.network_interface.display_name(&extend, &[]), "Extend Image to Bounds");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
|||||||
use graphene_animation::AnimationCurve;
|
use graphene_animation::AnimationCurve;
|
||||||
use graphene_application_io::resource::ResourceHash;
|
use graphene_application_io::resource::ResourceHash;
|
||||||
use graphene_application_io::resource::ResourceId;
|
use graphene_application_io::resource::ResourceId;
|
||||||
use graphic_types::raster_types::{CPU, Image, Raster};
|
use graphic_types::raster_types::{CPU, Image, Pixels, Raster};
|
||||||
use graphic_types::vector_types::vector::misc::BoxCorners;
|
use graphic_types::vector_types::vector::misc::BoxCorners;
|
||||||
use graphic_types::vector_types::vector::style::DashPattern;
|
use graphic_types::vector_types::vector::style::DashPattern;
|
||||||
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
|
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
|
||||||
@@ -400,6 +400,11 @@ macro_rules! tagged_value {
|
|||||||
Type::Fn(_, output) => TaggedValue::from_type(output),
|
Type::Fn(_, output) => TaggedValue::from_type(output),
|
||||||
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
|
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
|
||||||
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
|
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
|
||||||
|
// Pixels are read back from an image, so a `Pixels` input holds the empty image
|
||||||
|
if **element == concrete!(Pixels) {
|
||||||
|
return Some(TaggedValue::TypeDefault(item!(Raster<CPU>)));
|
||||||
|
}
|
||||||
|
|
||||||
macro_rules! check {
|
macro_rules! check {
|
||||||
($type_default:ty) => {
|
($type_default:ty) => {
|
||||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||||
@@ -416,6 +421,9 @@ macro_rules! tagged_value {
|
|||||||
if **element == concrete!(Stroke) {
|
if **element == concrete!(Stroke) {
|
||||||
return Some(TaggedValue::Strokes(Vec::new()));
|
return Some(TaggedValue::Strokes(Vec::new()));
|
||||||
}
|
}
|
||||||
|
if **element == concrete!(Pixels) {
|
||||||
|
return Some(TaggedValue::TypeDefault(list!(Raster<CPU>)));
|
||||||
|
}
|
||||||
macro_rules! check {
|
macro_rules! check {
|
||||||
($type_default:ty) => {
|
($type_default:ty) => {
|
||||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||||
|
|||||||
@@ -440,6 +440,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
node_types.extend(ranked_value_types!(cache_chain_nodes));
|
node_types.extend(ranked_value_types!(cache_chain_nodes));
|
||||||
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
|
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
|
||||||
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
|
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
|
||||||
|
// Context nullification can wrap the read-back adapter's output
|
||||||
|
node_types.extend(cache_chain_nodes!(Pixels));
|
||||||
// A position wire may feed a ranked vector connector, each position becoming a single-anchor vector
|
// A position wire may feed a ranked vector connector, each position becoming a single-anchor vector
|
||||||
node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector));
|
node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector));
|
||||||
// A string wire may feed the ranked `Item<DashPattern>` dash connector by parsing each element into a dash pattern
|
// A string wire may feed the ranked `Item<DashPattern>` dash connector by parsing each element into a dash pattern
|
||||||
@@ -496,6 +498,20 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
|
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
|
||||||
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
|
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
|
||||||
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
|
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
|
||||||
|
// An image wire feeds a `Pixels` connector through its GPU readback, an async node taking the executor, runtime, and source ID after the wire.
|
||||||
|
// These rows have no one-input passthrough siblings, which type resolution would match by their first input alone.
|
||||||
|
macro_rules! read_back_node {
|
||||||
|
($node:ty, wire: $wire:ty) => {
|
||||||
|
async_node!(
|
||||||
|
identifier: graphene_std::read_back::INPUT_ADAPTER,
|
||||||
|
$node,
|
||||||
|
input: Context,
|
||||||
|
fn_params: [Context => $wire, Context => Item<wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::RuntimeHandle>, Context => Item<graphene_std::SourceId>]
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
node_types.push(read_back_node!(graphene_std::read_back::ReadBackNode<_, _, _, _>, wire: Item<Raster<CPU>>));
|
||||||
|
node_types.push(read_back_node!(graphene_std::read_back::ReadBackListNode<_, _, _, _>, wire: List<Raster<CPU>>));
|
||||||
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
||||||
macro_rules! attribute_value_node {
|
macro_rules! attribute_value_node {
|
||||||
(Item<$element:ty>) => {
|
(Item<$element:ty>) => {
|
||||||
|
|||||||
@@ -86,6 +86,8 @@ pub enum Adjustment {
|
|||||||
opacity: f64,
|
opacity: f64,
|
||||||
},
|
},
|
||||||
Solarize,
|
Solarize,
|
||||||
|
/// Shows the alpha as a gray of the same gamma-encoded level, keeping the alpha, so a luminance mask of the gray shows as much as the alpha.
|
||||||
|
AlphaToGray,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Adjustment {
|
impl Adjustment {
|
||||||
@@ -112,6 +114,17 @@ impl Adjustment {
|
|||||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||||
Self::Solarize => EffectKind::Solarize,
|
Self::Solarize => EffectKind::Solarize,
|
||||||
|
Self::AlphaToGray => EffectKind::AlphaToGray,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the adjustment might change a color's alpha, which only Make Opaque and the alpha records of Levels and Curves do.
|
||||||
|
pub fn may_change_alpha(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::MakeOpaque { .. } => true,
|
||||||
|
Self::Levels(settings) => !settings.alpha.is_identity(),
|
||||||
|
Self::Curves(settings) => settings.alpha != TransferCurve::default(),
|
||||||
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,7 +154,7 @@ impl Adjustment {
|
|||||||
visitor.parameter("inverse", inverse, false);
|
visitor.parameter("inverse", inverse, false);
|
||||||
}
|
}
|
||||||
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
||||||
Self::Invert | Self::Solarize => {}
|
Self::Invert | Self::Solarize | Self::AlphaToGray => {}
|
||||||
Self::BrightnessContrast {
|
Self::BrightnessContrast {
|
||||||
brightness,
|
brightness,
|
||||||
contrast,
|
contrast,
|
||||||
@@ -486,6 +499,20 @@ fn grouped_key(group: &str, parameter: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl LevelsRecord {
|
impl LevelsRecord {
|
||||||
|
/// The record leaving every value as it is, as its node's defaults do.
|
||||||
|
pub const IDENTITY: Self = Self {
|
||||||
|
shadows: 0.,
|
||||||
|
midtones: 1.,
|
||||||
|
highlights: 100.,
|
||||||
|
output_minimums: 0.,
|
||||||
|
output_maximums: 100.,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Whether the record leaves every value as it is.
|
||||||
|
pub fn is_identity(&self) -> bool {
|
||||||
|
*self == Self::IDENTITY
|
||||||
|
}
|
||||||
|
|
||||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||||
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
||||||
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
||||||
|
|||||||
@@ -490,6 +490,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
|||||||
| EffectOperation::Emboss { .. }
|
| EffectOperation::Emboss { .. }
|
||||||
| EffectOperation::FindEdges
|
| EffectOperation::FindEdges
|
||||||
| EffectOperation::MinimumMaximum { .. }
|
| EffectOperation::MinimumMaximum { .. }
|
||||||
|
| EffectOperation::Median { .. }
|
||||||
| EffectOperation::Sharpen { .. }
|
| EffectOperation::Sharpen { .. }
|
||||||
| EffectOperation::HighPass { .. }
|
| EffectOperation::HighPass { .. }
|
||||||
| EffectOperation::Speckle { .. }
|
| EffectOperation::Speckle { .. }
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ use core_types::Color;
|
|||||||
use core_types::blending::BlendMode;
|
use core_types::blending::BlendMode;
|
||||||
use core_types::color::SRGBA8;
|
use core_types::color::SRGBA8;
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, List};
|
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, ItemAttributeValues, List};
|
||||||
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||||
@@ -60,6 +60,8 @@ pub enum EffectKind {
|
|||||||
FindEdges,
|
FindEdges,
|
||||||
/// Spreads each pixel's darkest or lightest neighboring colors.
|
/// Spreads each pixel's darkest or lightest neighboring colors.
|
||||||
MinimumMaximum,
|
MinimumMaximum,
|
||||||
|
/// Gives each pixel the middle value of each channel among those around it, removing specks while keeping edges.
|
||||||
|
Median,
|
||||||
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
||||||
Sharpen,
|
Sharpen,
|
||||||
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
||||||
@@ -117,6 +119,8 @@ pub enum EffectKind {
|
|||||||
PhotoFilter,
|
PhotoFilter,
|
||||||
ColorLookup,
|
ColorLookup,
|
||||||
Solarize,
|
Solarize,
|
||||||
|
/// Shows the content's alpha as a gray, as 'Into Channels' does for its alpha output.
|
||||||
|
AlphaToGray,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display for EffectKind {
|
impl std::fmt::Display for EffectKind {
|
||||||
@@ -137,6 +141,7 @@ impl std::fmt::Display for EffectKind {
|
|||||||
Self::Emboss => "Emboss",
|
Self::Emboss => "Emboss",
|
||||||
Self::FindEdges => "Find Edges",
|
Self::FindEdges => "Find Edges",
|
||||||
Self::MinimumMaximum => "Minimum/Maximum",
|
Self::MinimumMaximum => "Minimum/Maximum",
|
||||||
|
Self::Median => "Median",
|
||||||
Self::Sharpen => "Sharpen",
|
Self::Sharpen => "Sharpen",
|
||||||
Self::HighPass => "High Pass",
|
Self::HighPass => "High Pass",
|
||||||
Self::Speckle => "Speckle",
|
Self::Speckle => "Speckle",
|
||||||
@@ -175,6 +180,7 @@ impl std::fmt::Display for EffectKind {
|
|||||||
Self::PhotoFilter => "Photo Filter",
|
Self::PhotoFilter => "Photo Filter",
|
||||||
Self::ColorLookup => "Color Lookup",
|
Self::ColorLookup => "Color Lookup",
|
||||||
Self::Solarize => "Solarize",
|
Self::Solarize => "Solarize",
|
||||||
|
Self::AlphaToGray => "Alpha to Gray",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -218,6 +224,9 @@ pub enum MinimumMaximumMode {
|
|||||||
Maximum,
|
Maximum,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The most pixels a median's square reaches out from its center on its grid, whose cost grows with the square's area. Past it, the grid coarsens instead.
|
||||||
|
pub const MAX_MEDIAN_GRID_RADIUS: f64 = 16.;
|
||||||
|
|
||||||
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
pub struct EffectCapture {
|
pub struct EffectCapture {
|
||||||
@@ -454,6 +463,17 @@ impl Effects {
|
|||||||
self.operations().all(|operation| operation.changes_nothing())
|
self.operations().all(|operation| operation.changes_nothing())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether the effects might change the content's alpha, as any but an adjustment keeping it (see [`Adjustment::may_change_alpha`]) can unless it changes nothing.
|
||||||
|
pub fn may_change_alpha(&self) -> bool {
|
||||||
|
self.operations().any(|operation| {
|
||||||
|
!operation.changes_nothing()
|
||||||
|
&& match &operation {
|
||||||
|
EffectOperation::Adjustment(adjustment) => adjustment.may_change_alpha(),
|
||||||
|
_ => true,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// The effects of the given range of rows decoded into operations, in order.
|
/// The effects of the given range of rows decoded into operations, in order.
|
||||||
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
|
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
|
||||||
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
|
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
|
||||||
@@ -475,17 +495,30 @@ impl Effects {
|
|||||||
self.operations().map(|operation| operation.required_reach()).sum()
|
self.operations().map(|operation| operation.required_reach()).sum()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How many pixels per unit of their effect space a run of these effects renders at, at most, if any of them works on the content's own grid (see [`EffectOperation::works_on_content_grid`]).
|
||||||
|
/// It's one, except that a median reaching past [`MAX_MEDIAN_GRID_RADIUS`] whole units coarsens the grid to bound its cost.
|
||||||
|
pub fn content_grid_resolution(&self) -> Option<f64> {
|
||||||
|
let grid_resolution = |operation: EffectOperation| match operation {
|
||||||
|
EffectOperation::Median { radius } => (MAX_MEDIAN_GRID_RADIUS / radius.floor()).min(1.),
|
||||||
|
_ => 1.,
|
||||||
|
};
|
||||||
|
self.operations().filter(EffectOperation::works_on_content_grid).map(grid_resolution).reduce(f64::min)
|
||||||
|
}
|
||||||
|
|
||||||
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
||||||
/// A transform applied between two effects starts a new run, which renders around the result of those before it.
|
/// A transform applied between two effects, or an effect on the content's own grid (which runs alone at its grid's resolution), starts a new run around the result of those before it.
|
||||||
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
||||||
pub fn runs(&self) -> Vec<(DAffine2, Range<usize>)> {
|
pub fn runs(&self) -> Vec<(DAffine2, Range<usize>)> {
|
||||||
let mut runs: Vec<(DAffine2, Range<usize>)> = Vec::new();
|
let mut runs: Vec<(DAffine2, Range<usize>)> = Vec::new();
|
||||||
let mut run_changes_something = false;
|
let (mut run_changes_something, mut run_on_content_grid) = (false, false);
|
||||||
for (index, effect) in self.effects().enumerate() {
|
for (index, effect) in self.effects().enumerate() {
|
||||||
let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||||
let changes_something = !effect.operation().changes_nothing();
|
let operation = effect.operation();
|
||||||
|
let (changes_something, on_content_grid) = (!operation.changes_nothing(), operation.works_on_content_grid());
|
||||||
|
|
||||||
|
let shares_grid = !(on_content_grid && run_changes_something) && !(run_on_content_grid && changes_something);
|
||||||
if let Some((transform, rows)) = runs.last_mut()
|
if let Some((transform, rows)) = runs.last_mut()
|
||||||
|
&& shares_grid
|
||||||
&& (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2))
|
&& (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2))
|
||||||
{
|
{
|
||||||
if changes_something && !run_changes_something {
|
if changes_something && !run_changes_something {
|
||||||
@@ -493,9 +526,10 @@ impl Effects {
|
|||||||
}
|
}
|
||||||
rows.end = index + 1;
|
rows.end = index + 1;
|
||||||
run_changes_something |= changes_something;
|
run_changes_something |= changes_something;
|
||||||
|
run_on_content_grid |= on_content_grid;
|
||||||
} else {
|
} else {
|
||||||
runs.push((stamped_transform, index..index + 1));
|
runs.push((stamped_transform, index..index + 1));
|
||||||
run_changes_something = changes_something;
|
(run_changes_something, run_on_content_grid) = (changes_something, on_content_grid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
runs
|
runs
|
||||||
@@ -835,8 +869,14 @@ pub fn contour_gradient_position(distance: f32, start: f32, span: f32) -> f32 {
|
|||||||
/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point.
|
/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point.
|
||||||
/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect.
|
/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect.
|
||||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||||
let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM));
|
stamp_effect_on(item.attributes_mut(), effect);
|
||||||
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS)
|
}
|
||||||
|
|
||||||
|
/// Like [`stamp_effect`], given the item's attributes.
|
||||||
|
pub fn stamp_effect_on(attributes: &mut ItemAttributeValues, effect: Effect) {
|
||||||
|
let transform = stamped_transform(attributes.get::<DAffine2>(ATTR_TRANSFORM).copied().unwrap_or_default());
|
||||||
|
attributes
|
||||||
|
.get_or_insert_default_mut::<Effects>(ATTR_EFFECTS)
|
||||||
.0
|
.0
|
||||||
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
||||||
}
|
}
|
||||||
@@ -1086,6 +1126,11 @@ pub enum EffectOperation {
|
|||||||
radius: f64,
|
radius: f64,
|
||||||
mode: MinimumMaximumMode,
|
mode: MinimumMaximumMode,
|
||||||
},
|
},
|
||||||
|
/// Carried out on the content's own grid of pixels (see [`Self::works_on_content_grid`]), then resampled to the view.
|
||||||
|
Median {
|
||||||
|
/// How many pixels the square neighborhood reaches out from its center, of which the whole pixels count.
|
||||||
|
radius: f64,
|
||||||
|
},
|
||||||
Sharpen {
|
Sharpen {
|
||||||
/// Percent.
|
/// Percent.
|
||||||
amount: f64,
|
amount: f64,
|
||||||
@@ -1287,6 +1332,7 @@ impl EffectOperation {
|
|||||||
Self::Emboss { .. } => EffectKind::Emboss,
|
Self::Emboss { .. } => EffectKind::Emboss,
|
||||||
Self::FindEdges => EffectKind::FindEdges,
|
Self::FindEdges => EffectKind::FindEdges,
|
||||||
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
||||||
|
Self::Median { .. } => EffectKind::Median,
|
||||||
Self::Sharpen { .. } => EffectKind::Sharpen,
|
Self::Sharpen { .. } => EffectKind::Sharpen,
|
||||||
Self::HighPass { .. } => EffectKind::HighPass,
|
Self::HighPass { .. } => EffectKind::HighPass,
|
||||||
Self::Speckle { .. } => EffectKind::Speckle,
|
Self::Speckle { .. } => EffectKind::Speckle,
|
||||||
@@ -1387,6 +1433,8 @@ impl EffectOperation {
|
|||||||
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
||||||
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
||||||
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
||||||
|
// Only whole pixels count, so one of less than a pixel reads the pixel alone
|
||||||
|
Self::Median { radius } => *radius < 1.,
|
||||||
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
|
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1413,7 +1461,7 @@ impl EffectOperation {
|
|||||||
Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => {
|
Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Median { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||||
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
|
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
|
||||||
Self::DropShadow { .. }
|
Self::DropShadow { .. }
|
||||||
| Self::InnerShadow { .. }
|
| Self::InnerShadow { .. }
|
||||||
@@ -1427,6 +1475,12 @@ impl EffectOperation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether this operation is carried out on the content's own grid of pixels, one to each unit of its effect space, and the result resampled to the view, since it doesn't commute with resampling.
|
||||||
|
/// So it looks the same at every zoom, and on an image at its own size when stamped, it reads the image's pixels.
|
||||||
|
pub fn works_on_content_grid(&self) -> bool {
|
||||||
|
matches!(self, Self::Median { .. }) && !self.changes_nothing()
|
||||||
|
}
|
||||||
|
|
||||||
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
||||||
pub fn painted_reach(&self) -> f64 {
|
pub fn painted_reach(&self) -> f64 {
|
||||||
let keeps_coverage = matches!(
|
let keeps_coverage = matches!(
|
||||||
@@ -1440,6 +1494,8 @@ impl EffectOperation {
|
|||||||
mode: MinimumMaximumMode::Maximum,
|
mode: MinimumMaximumMode::Maximum,
|
||||||
..
|
..
|
||||||
}
|
}
|
||||||
|
// Its coverage is the window's middle one, which past the content's bounds comes from a window at least half beyond them
|
||||||
|
| Self::Median { .. }
|
||||||
| Self::Sharpen { .. }
|
| Self::Sharpen { .. }
|
||||||
| Self::HighPass { .. }
|
| Self::HighPass { .. }
|
||||||
);
|
);
|
||||||
@@ -1482,6 +1538,7 @@ impl EffectOperation {
|
|||||||
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
||||||
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
||||||
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
||||||
|
Self::Median { radius } => radius.max(0.).floor() + 1.,
|
||||||
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
||||||
Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3.,
|
Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3.,
|
||||||
// They reach as far as `Effects::reach_around` measures from where the content lies
|
// They reach as far as `Effects::reach_around` measures from where the content lies
|
||||||
@@ -1576,7 +1633,7 @@ impl EffectOperation {
|
|||||||
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
||||||
Self::Feather { distance } => finite(distance),
|
Self::Feather { distance } => finite(distance),
|
||||||
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
||||||
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
|
Self::MinimumMaximum { radius, .. } | Self::Median { radius } | Self::HighPass { radius } => finite(radius),
|
||||||
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
||||||
Self::Speckle { amount, .. } => finite(amount),
|
Self::Speckle { amount, .. } => finite(amount),
|
||||||
Self::Dissolve { opacity, .. } => finite(opacity),
|
Self::Dissolve { opacity, .. } => finite(opacity),
|
||||||
@@ -1747,6 +1804,7 @@ impl EffectOperation {
|
|||||||
radius: 0.,
|
radius: 0.,
|
||||||
mode: MinimumMaximumMode::default(),
|
mode: MinimumMaximumMode::default(),
|
||||||
},
|
},
|
||||||
|
EffectKind::Median => Self::Median { radius: 0. },
|
||||||
EffectKind::Sharpen => Self::Sharpen {
|
EffectKind::Sharpen => Self::Sharpen {
|
||||||
amount: 0.,
|
amount: 0.,
|
||||||
radius: 0.,
|
radius: 0.,
|
||||||
@@ -1875,6 +1933,7 @@ impl EffectOperation {
|
|||||||
}),
|
}),
|
||||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||||
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
||||||
|
EffectKind::AlphaToGray => Self::Adjustment(Adjustment::AlphaToGray),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2088,6 +2147,7 @@ impl EffectOperation {
|
|||||||
visitor.parameter("radius", radius, 1.);
|
visitor.parameter("radius", radius, 1.);
|
||||||
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
||||||
}
|
}
|
||||||
|
Self::Median { radius } => visitor.parameter("radius", radius, 0.),
|
||||||
Self::Sharpen {
|
Self::Sharpen {
|
||||||
amount,
|
amount,
|
||||||
radius,
|
radius,
|
||||||
@@ -2390,6 +2450,7 @@ mod tests {
|
|||||||
radius: 7.,
|
radius: 7.,
|
||||||
mode: MinimumMaximumMode::Maximum,
|
mode: MinimumMaximumMode::Maximum,
|
||||||
},
|
},
|
||||||
|
EffectOperation::Median { radius: 3.5 },
|
||||||
EffectOperation::Adjustment(Adjustment::Solarize),
|
EffectOperation::Adjustment(Adjustment::Solarize),
|
||||||
EffectOperation::Sharpen {
|
EffectOperation::Sharpen {
|
||||||
amount: 180.,
|
amount: 180.,
|
||||||
@@ -2888,6 +2949,7 @@ mod tests {
|
|||||||
PhotoFilter,
|
PhotoFilter,
|
||||||
ColorLookup,
|
ColorLookup,
|
||||||
Solarize,
|
Solarize,
|
||||||
|
AlphaToGray,
|
||||||
PaintOverlay,
|
PaintOverlay,
|
||||||
];
|
];
|
||||||
for kind in kinds {
|
for kind in kinds {
|
||||||
@@ -2987,6 +3049,7 @@ mod tests {
|
|||||||
radius: 3.,
|
radius: 3.,
|
||||||
mode: MinimumMaximumMode::Maximum,
|
mode: MinimumMaximumMode::Maximum,
|
||||||
},
|
},
|
||||||
|
EffectOperation::Median { radius: 3.5 },
|
||||||
EffectOperation::Sharpen {
|
EffectOperation::Sharpen {
|
||||||
amount: 100.,
|
amount: 100.,
|
||||||
radius: 3.,
|
radius: 3.,
|
||||||
@@ -3010,6 +3073,28 @@ mod tests {
|
|||||||
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_median_works_on_the_content_grid_coarsened_past_its_largest_radius() {
|
||||||
|
let median = |radius| Effects::from_operations([EffectOperation::Median { radius }]);
|
||||||
|
assert_eq!(median(0.5).content_grid_resolution(), None, "less than a whole pixel changes nothing");
|
||||||
|
assert_eq!(median(5.9).content_grid_resolution(), Some(1.));
|
||||||
|
assert_eq!(median(64.).content_grid_resolution(), Some(MAX_MEDIAN_GRID_RADIUS / 64.));
|
||||||
|
assert_eq!(Effects::from_operations([EffectOperation::FindEdges]).content_grid_resolution(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_median_runs_alone_at_its_own_grid_resolution() {
|
||||||
|
let median = |radius| EffectOperation::Median { radius };
|
||||||
|
let nothing = median(0.);
|
||||||
|
let effects = Effects::from_operations([nothing.clone(), median(1.), median(64.), nothing, EffectOperation::FindEdges, median(2.)]);
|
||||||
|
|
||||||
|
// Effects changing nothing join a median's run, but nothing else does
|
||||||
|
let runs: Vec<_> = effects.runs().into_iter().map(|(_, rows)| rows).collect();
|
||||||
|
assert_eq!(runs, vec![0..2, 2..4, 4..5, 5..6]);
|
||||||
|
let resolutions: Vec<_> = runs.into_iter().map(|rows| effects.run(rows).content_grid_resolution()).collect();
|
||||||
|
assert_eq!(resolutions, [Some(1.), Some(MAX_MEDIAN_GRID_RADIUS / 64.), None, Some(1.)]);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn baking_the_content_placement_into_its_geometry_keeps_its_mask_in_place() {
|
fn baking_the_content_placement_into_its_geometry_keeps_its_mask_in_place() {
|
||||||
fn nested_placement(graphic: &Graphic) -> DAffine2 {
|
fn nested_placement(graphic: &Graphic) -> DAffine2 {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! 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.
|
//! 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 crate::effects::EffectOperation;
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
||||||
@@ -164,6 +164,7 @@ pub fn is_filter(operation: &EffectOperation) -> bool {
|
|||||||
| EffectOperation::Emboss { .. }
|
| EffectOperation::Emboss { .. }
|
||||||
| EffectOperation::FindEdges
|
| EffectOperation::FindEdges
|
||||||
| EffectOperation::MinimumMaximum { .. }
|
| EffectOperation::MinimumMaximum { .. }
|
||||||
|
| EffectOperation::Median { .. }
|
||||||
| EffectOperation::Sharpen { .. }
|
| EffectOperation::Sharpen { .. }
|
||||||
| EffectOperation::HighPass { .. }
|
| EffectOperation::HighPass { .. }
|
||||||
| EffectOperation::Speckle { .. }
|
| EffectOperation::Speckle { .. }
|
||||||
@@ -181,12 +182,6 @@ pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
|
|||||||
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
|
|
||||||
/// The random field filters change endless content without its neighbors (see [`is_random_field_filter`]).
|
|
||||||
pub fn has_filters(effects: &Effects) -> bool {
|
|
||||||
effects.operations().any(|operation| reads_neighbors(&operation) && !operation.changes_nothing())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
|
/// 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] = [
|
pub const SOBEL_TAPS: [(DVec2, [f64; 2]); 8] = [
|
||||||
(DVec2::new(-1., -1.), [-1., -1.]),
|
(DVec2::new(-1., -1.), [-1., -1.]),
|
||||||
|
|||||||
@@ -630,16 +630,17 @@ impl Graphic {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn can_reduce_to_clip_path(&self) -> bool {
|
/// Whether this graphic clips as its outline would, with `inherited_appearance` cascading from an ancestor to vectors lacking their own.
|
||||||
|
pub fn can_reduce_to_clip_path(&self, inherited_appearance: Option<&Appearance>) -> bool {
|
||||||
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
||||||
match self {
|
match self {
|
||||||
Graphic::Vector(item) => {
|
Graphic::Vector(item) => {
|
||||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing)
|
let appearance = Appearance::cascade(item.attribute(ATTR_APPEARANCE), inherited_appearance);
|
||||||
&& vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
|
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), appearance)
|
||||||
}
|
}
|
||||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing)
|
let appearance = Appearance::cascade(list.attribute(ATTR_APPEARANCE, index), inherited_appearance);
|
||||||
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), appearance)
|
||||||
}),
|
}),
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
@@ -648,16 +649,22 @@ impl Graphic {
|
|||||||
pub fn is_guaranteed_fully_opaque(&self) -> bool {
|
pub fn is_guaranteed_fully_opaque(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => false,
|
Graphic::None(_) | Graphic::NoneList(_) => false,
|
||||||
// The group's own opacity scales whatever it wraps, so full alpha there is a precondition
|
// The group's own opacity and effects act on whatever it wraps, so they must keep it at full alpha
|
||||||
Graphic::Graphic(item) => item_opacity_is_full(item) && item.element().is_guaranteed_fully_opaque(),
|
Graphic::Graphic(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_opaque(),
|
||||||
Graphic::GraphicList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque),
|
Graphic::GraphicList(list) => {
|
||||||
Graphic::Vector(item) => vector_is_guaranteed_fully_opaque(
|
!list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque)
|
||||||
|
}
|
||||||
|
Graphic::Vector(item) => {
|
||||||
|
!item_effects_may_change_alpha(item)
|
||||||
|
&& vector_is_guaranteed_fully_opaque(
|
||||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||||
),
|
)
|
||||||
|
}
|
||||||
Graphic::VectorList(list) => {
|
Graphic::VectorList(list) => {
|
||||||
!list.is_empty()
|
!list.is_empty()
|
||||||
|
&& !list_effects_may_change_alpha(list)
|
||||||
&& (0..list.len()).all(|index| {
|
&& (0..list.len()).all(|index| {
|
||||||
vector_is_guaranteed_fully_opaque(
|
vector_is_guaranteed_fully_opaque(
|
||||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||||
@@ -669,11 +676,12 @@ impl Graphic {
|
|||||||
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
||||||
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
||||||
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
||||||
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
|
Graphic::Color(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_opaque(),
|
||||||
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
||||||
// A `Clear` spread cuts off to transparency past the ends, and curved contours may leave gaps, leaving the rest of the region unpainted
|
// A `Clear` spread cuts off to transparency past the ends, and curved contours may leave gaps, leaving the rest of the region unpainted
|
||||||
Graphic::Gradient(item) => {
|
Graphic::Gradient(item) => {
|
||||||
item_opacity_is_full(item)
|
item_opacity_is_full(item)
|
||||||
|
&& !item_effects_may_change_alpha(item)
|
||||||
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
|
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
|
||||||
&& gradient_paints_everywhere(&|key| item.attributes().get_any(key))
|
&& gradient_paints_everywhere(&|key| item.attributes().get_any(key))
|
||||||
&& item.element().iter().all(|stop| stop.color.is_opaque())
|
&& item.element().iter().all(|stop| stop.color.is_opaque())
|
||||||
@@ -681,6 +689,7 @@ impl Graphic {
|
|||||||
Graphic::GradientList(list) => {
|
Graphic::GradientList(list) => {
|
||||||
!list.is_empty()
|
!list.is_empty()
|
||||||
&& every_item_has_full_opacity(list)
|
&& every_item_has_full_opacity(list)
|
||||||
|
&& !list_effects_may_change_alpha(list)
|
||||||
&& (0..list.len()).all(|index| {
|
&& (0..list.len()).all(|index| {
|
||||||
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
|
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
|
||||||
&& gradient_paints_everywhere(&|key| list.attribute_any(key, index))
|
&& gradient_paints_everywhere(&|key| list.attribute_any(key, index))
|
||||||
@@ -693,27 +702,41 @@ impl Graphic {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_guaranteed_fully_transparent(&self) -> bool {
|
pub fn is_guaranteed_fully_transparent(&self) -> bool {
|
||||||
|
// An effect that might change alpha, like Make Opaque or a shadow, can show content its paints leave transparent, so only its opacity can hide it
|
||||||
match self {
|
match self {
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => true,
|
Graphic::None(_) | Graphic::NoneList(_) => true,
|
||||||
Graphic::Graphic(item) => item_opacity_is_zero(item) || item.element().is_guaranteed_fully_transparent(),
|
Graphic::Graphic(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_transparent()),
|
||||||
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent),
|
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent)),
|
||||||
Graphic::Vector(item) => vector_is_guaranteed_fully_transparent(
|
Graphic::Vector(item) => {
|
||||||
|
item_opacity_is_zero(item)
|
||||||
|
|| (!item_effects_may_change_alpha(item)
|
||||||
|
&& vector_is_guaranteed_fully_transparent(
|
||||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||||
),
|
item.attribute::<Effects>(ATTR_EFFECTS),
|
||||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
))
|
||||||
|
}
|
||||||
|
Graphic::VectorList(list) => {
|
||||||
|
every_item_has_zero_opacity(list)
|
||||||
|
|| (!list_effects_may_change_alpha(list)
|
||||||
|
&& (0..list.len()).all(|index| {
|
||||||
vector_is_guaranteed_fully_transparent(
|
vector_is_guaranteed_fully_transparent(
|
||||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||||
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
||||||
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
||||||
|
list.attribute::<Effects>(ATTR_EFFECTS, index),
|
||||||
)
|
)
|
||||||
}),
|
}))
|
||||||
Graphic::Color(item) => item_opacity_is_zero(item) || item.element().a() == 0.,
|
}
|
||||||
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|color| color.a() == 0.),
|
Graphic::Color(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().a() == 0.),
|
||||||
|
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.a() == 0.)),
|
||||||
// A stopless ramp paints as solid black, matching `Gradient::evaluate`, so it counts as transparent only once it has stops
|
// A stopless ramp paints as solid black, matching `Gradient::evaluate`, so it counts as transparent only once it has stops
|
||||||
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && !item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
||||||
Graphic::GradientList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)),
|
Graphic::GradientList(list) => {
|
||||||
|
every_item_has_zero_opacity(list)
|
||||||
|
|| (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)))
|
||||||
|
}
|
||||||
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
||||||
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
||||||
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
||||||
@@ -806,12 +829,13 @@ fn vector_is_guaranteed_fully_opaque(opacity: f64, opacity_fill: f64, appearance
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a vector object draws nothing visible, either through its opacity or through its paint.
|
/// Whether a vector object draws nothing visible, either through its opacity or through its paint.
|
||||||
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>) -> bool {
|
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>, effects: Option<&Effects>) -> bool {
|
||||||
if opacity <= f64::EPSILON {
|
if opacity <= f64::EPSILON {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
let fills_invisible = opacity_fill <= f64::EPSILON
|
// Fill opacity fades the paints but not what effects paint at full strength, like overlays and shadows
|
||||||
|
let fills_invisible = (opacity_fill <= f64::EPSILON && effects.is_none_or(Effects::change_nothing))
|
||||||
|| appearance.is_none_or(|appearance| {
|
|| appearance.is_none_or(|appearance| {
|
||||||
appearance
|
appearance
|
||||||
.covers_with_paints()
|
.covers_with_paints()
|
||||||
@@ -829,6 +853,16 @@ fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appea
|
|||||||
fills_invisible && strokes_invisible
|
fills_invisible && strokes_invisible
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a lone item's effects might change its alpha, so its element's own alpha can't vouch for it being opaque or transparent.
|
||||||
|
fn item_effects_may_change_alpha<T>(item: &Item<T>) -> bool {
|
||||||
|
item.attribute::<Effects>(ATTR_EFFECTS).is_some_and(Effects::may_change_alpha)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the effects of any item of a list might change its alpha (see [`item_effects_may_change_alpha`]).
|
||||||
|
fn list_effects_may_change_alpha<T>(list: &List<T>) -> bool {
|
||||||
|
(0..list.len()).any(|index| list.attribute::<Effects>(ATTR_EFFECTS, index).is_some_and(Effects::may_change_alpha))
|
||||||
|
}
|
||||||
|
|
||||||
/// Whether a lone item's opacity zeroes it out, independent of what its element holds.
|
/// Whether a lone item's opacity zeroes it out, independent of what its element holds.
|
||||||
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
|
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
|
||||||
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) <= f64::EPSILON
|
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) <= f64::EPSILON
|
||||||
@@ -1308,4 +1342,64 @@ mod graphic_is_opaque_tests {
|
|||||||
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
|
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
|
||||||
assert!(!Graphic::Graphic(Box::new(reduced)).is_guaranteed_fully_opaque());
|
assert!(!Graphic::Graphic(Box::new(reduced)).is_guaranteed_fully_opaque());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effects_that_might_change_alpha_leave_content_neither_known_opaque_nor_known_transparent() {
|
||||||
|
use crate::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
|
||||||
|
use crate::effects::EffectOperation;
|
||||||
|
use crate::vector_types::vector::style::Stroke;
|
||||||
|
|
||||||
|
let effected = |graphic: Graphic, operation: EffectOperation| Item::new_from_element(graphic).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]));
|
||||||
|
let colors = |alpha: f64, operation: EffectOperation| {
|
||||||
|
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
|
||||||
|
Graphic::ColorList(List::new_from_item(Item::new_from_element(color).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]))))
|
||||||
|
};
|
||||||
|
let make_opaque = || EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
|
||||||
|
let dissolve = || EffectOperation::Dissolve { opacity: 50., seed: 0 };
|
||||||
|
let levels = |record: LevelsRecord, alpha: LevelsRecord| {
|
||||||
|
EffectOperation::Adjustment(Adjustment::Levels(Box::new(LevelsSettings {
|
||||||
|
composite: record,
|
||||||
|
red: LevelsRecord::IDENTITY,
|
||||||
|
green: LevelsRecord::IDENTITY,
|
||||||
|
blue: LevelsRecord::IDENTITY,
|
||||||
|
alpha,
|
||||||
|
})))
|
||||||
|
};
|
||||||
|
let identity = LevelsRecord::IDENTITY;
|
||||||
|
let darkened = LevelsRecord { output_maximums: 50., ..identity };
|
||||||
|
|
||||||
|
// Adjustments keeping alpha leave paints as opaque or transparent as their colors
|
||||||
|
assert!(colors(1., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_opaque());
|
||||||
|
assert!(colors(0., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_transparent());
|
||||||
|
assert!(colors(1., levels(darkened, identity)).is_guaranteed_fully_opaque());
|
||||||
|
|
||||||
|
// Effects that might fade a paint, or show a transparent one, leave it unknown
|
||||||
|
assert!(!colors(1., dissolve()).is_guaranteed_fully_opaque());
|
||||||
|
assert!(!colors(1., levels(identity, darkened)).is_guaranteed_fully_opaque());
|
||||||
|
assert!(!colors(0., make_opaque()).is_guaranteed_fully_transparent());
|
||||||
|
assert!(!colors(0., make_opaque()).is_guaranteed_to_cover_opaquely());
|
||||||
|
|
||||||
|
// A group's own effects act on all it wraps, though its zero opacity still hides it
|
||||||
|
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(1.), dissolve()))).is_guaranteed_fully_opaque());
|
||||||
|
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()))).is_guaranteed_fully_transparent());
|
||||||
|
assert!(Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()).with_attribute(ATTR_OPACITY, 0.))).is_guaranteed_fully_transparent());
|
||||||
|
|
||||||
|
// A vector's own effects, like a shadow cast by a shape with no visible paint, do too
|
||||||
|
let mut shape = Item::new_from_element(Vector::default());
|
||||||
|
shape.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_stroke(&Stroke::new(4.)), color_graphic(0.)));
|
||||||
|
assert!(Graphic::Vector(Box::new(shape.clone())).is_guaranteed_fully_transparent());
|
||||||
|
let shadowed = shape
|
||||||
|
.clone()
|
||||||
|
.with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::default_for(crate::effects::EffectKind::DropShadow)]));
|
||||||
|
assert!(!Graphic::Vector(Box::new(shadowed)).is_guaranteed_fully_transparent());
|
||||||
|
|
||||||
|
// Zero fill opacity hides a vector's paints but not an overlay its effects paint over them, though that keeps alpha
|
||||||
|
let mut filled = Item::new_from_element(Vector::default()).with_attribute(ATTR_OPACITY_FILL, 0.);
|
||||||
|
filled.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), color_graphic(1.)));
|
||||||
|
assert!(Graphic::Vector(Box::new(filled.clone())).is_guaranteed_fully_transparent());
|
||||||
|
let overlay = EffectOperation::default_for(crate::effects::EffectKind::PaintOverlay);
|
||||||
|
assert!(matches!(overlay, EffectOperation::Adjustment(Adjustment::ColorOverlay { .. })), "{overlay:?}");
|
||||||
|
let overlaid = filled.with_attribute(ATTR_EFFECTS, Effects::from_operations([overlay]));
|
||||||
|
assert!(!Graphic::Vector(Box::new(overlaid)).is_guaranteed_fully_transparent());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@ pub use artboard::Artboard;
|
|||||||
pub use blend_if::BlendIfChannel;
|
pub use blend_if::BlendIfChannel;
|
||||||
pub use effects::{
|
pub use effects::{
|
||||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||||
stamp_effect, stamped_transform,
|
stamp_effect, stamp_effect_on, stamped_transform,
|
||||||
};
|
};
|
||||||
pub use filters::NoiseDistribution;
|
pub use filters::NoiseDistribution;
|
||||||
pub use generator::Generator;
|
pub use generator::Generator;
|
||||||
|
|||||||
@@ -1715,10 +1715,10 @@ impl EffectOperation {
|
|||||||
FrameWarp::of(self).is_some() || warp_of(self).is_some()
|
FrameWarp::of(self).is_some() || warp_of(self).is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether this operation takes the content's frame, which displacements and lattices measure from, unless it changes nothing.
|
/// Whether this operation takes the content's frame, which displacements and lattices measure from and a median reads within, unless it changes nothing.
|
||||||
pub fn takes_frame(&self) -> bool {
|
pub fn takes_frame(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } => !self.changes_nothing(),
|
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } | Self::Median { .. } => !self.changes_nothing(),
|
||||||
Self::Twirl { .. }
|
Self::Twirl { .. }
|
||||||
| Self::Pinch { .. }
|
| Self::Pinch { .. }
|
||||||
| Self::Spherize { .. }
|
| Self::Spherize { .. }
|
||||||
|
|||||||
@@ -30,11 +30,12 @@ pub enum StepKind {
|
|||||||
ColorLookup,
|
ColorLookup,
|
||||||
ColorOverlay,
|
ColorOverlay,
|
||||||
Solarize,
|
Solarize,
|
||||||
|
AlphaToGray,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StepKind {
|
impl StepKind {
|
||||||
/// Every kind, in the order of their codes.
|
/// Every kind, in the order of their codes.
|
||||||
pub const ALL: [StepKind; 21] = [
|
pub const ALL: [StepKind; 22] = [
|
||||||
StepKind::Desaturate,
|
StepKind::Desaturate,
|
||||||
StepKind::GammaCorrection,
|
StepKind::GammaCorrection,
|
||||||
StepKind::MakeOpaque,
|
StepKind::MakeOpaque,
|
||||||
@@ -56,6 +57,7 @@ impl StepKind {
|
|||||||
StepKind::ColorLookup,
|
StepKind::ColorLookup,
|
||||||
StepKind::ColorOverlay,
|
StepKind::ColorOverlay,
|
||||||
StepKind::Solarize,
|
StepKind::Solarize,
|
||||||
|
StepKind::AlphaToGray,
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
||||||
@@ -269,6 +271,7 @@ mod tests {
|
|||||||
opacity: 50.,
|
opacity: 50.,
|
||||||
},
|
},
|
||||||
Adjustment::Solarize,
|
Adjustment::Solarize,
|
||||||
|
Adjustment::AlphaToGray,
|
||||||
];
|
];
|
||||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||||
|
|
||||||
|
|||||||
@@ -226,6 +226,7 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
|||||||
}
|
}
|
||||||
Adjustment::Invert => visitor.visit(Invert),
|
Adjustment::Invert => visitor.visit(Invert),
|
||||||
Adjustment::Solarize => visitor.visit(Solarize),
|
Adjustment::Solarize => visitor.visit(Solarize),
|
||||||
|
Adjustment::AlphaToGray => visitor.visit(AlphaToGray),
|
||||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||||
min_luminance: (min_luminance / 100.) as f32,
|
min_luminance: (min_luminance / 100.) as f32,
|
||||||
max_luminance: (max_luminance / 100.) as f32,
|
max_luminance: (max_luminance / 100.) as f32,
|
||||||
@@ -1121,6 +1122,20 @@ impl MapColor for Solarize {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Grays each color to the gamma-encoded level of its alpha, keeping the alpha.
|
||||||
|
struct AlphaToGray;
|
||||||
|
|
||||||
|
impl MapColor for AlphaToGray {
|
||||||
|
fn map_cpu(&self, color: Color) -> Color {
|
||||||
|
let gray = srgb_to_linear(color.a());
|
||||||
|
color.map_rgb(|_| gray)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
||||||
|
steps.push(StepKind::AlphaToGray, []);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct Threshold {
|
struct Threshold {
|
||||||
min_luminance: f32,
|
min_luminance: f32,
|
||||||
max_luminance: f32,
|
max_luminance: f32,
|
||||||
@@ -2007,4 +2022,69 @@ mod tests {
|
|||||||
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
|
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn adjustments_changing_alpha_are_known_to_without_running_their_kernels() {
|
||||||
|
use core_types::transfer_curve::TransferCurve;
|
||||||
|
use glam::DVec2;
|
||||||
|
use graphic_types::effects::{EffectKind, EffectOperation};
|
||||||
|
|
||||||
|
let kinds = [
|
||||||
|
EffectKind::Desaturate,
|
||||||
|
EffectKind::GammaCorrection,
|
||||||
|
EffectKind::MakeOpaque,
|
||||||
|
EffectKind::BrightnessContrast,
|
||||||
|
EffectKind::Levels,
|
||||||
|
EffectKind::Curves,
|
||||||
|
EffectKind::BlackAndWhite,
|
||||||
|
EffectKind::HueSaturation,
|
||||||
|
EffectKind::Invert,
|
||||||
|
EffectKind::Threshold,
|
||||||
|
EffectKind::GradientMap,
|
||||||
|
EffectKind::Vibrance,
|
||||||
|
EffectKind::ChannelMixer,
|
||||||
|
EffectKind::SelectiveColor,
|
||||||
|
EffectKind::Posterize,
|
||||||
|
EffectKind::Exposure,
|
||||||
|
EffectKind::ColorBalance,
|
||||||
|
EffectKind::PhotoFilter,
|
||||||
|
EffectKind::ColorLookup,
|
||||||
|
EffectKind::Solarize,
|
||||||
|
];
|
||||||
|
let defaults = kinds.map(|kind| match EffectOperation::default_for(kind) {
|
||||||
|
EffectOperation::Adjustment(adjustment) => adjustment,
|
||||||
|
operation => panic!("{kind} isn't an adjustment: {operation:?}"),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Levels and Curves change alpha by their alpha records and curves, and nothing else of theirs
|
||||||
|
let identity = settings::LevelsRecord::IDENTITY;
|
||||||
|
let darkened = settings::LevelsRecord { output_maximums: 50., ..identity };
|
||||||
|
let levels = |composite, alpha| {
|
||||||
|
Adjustment::Levels(Box::new(settings::LevelsSettings {
|
||||||
|
composite,
|
||||||
|
red: identity,
|
||||||
|
green: identity,
|
||||||
|
blue: identity,
|
||||||
|
alpha,
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
let curve = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(1., 0.5)]);
|
||||||
|
let curves = |composite: TransferCurve, alpha: TransferCurve| {
|
||||||
|
Adjustment::Curves(Box::new(settings::CurvesSettings {
|
||||||
|
composite,
|
||||||
|
alpha,
|
||||||
|
..Default::default()
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
let settings = [
|
||||||
|
levels(darkened, identity),
|
||||||
|
levels(identity, darkened),
|
||||||
|
curves(curve.clone(), TransferCurve::default()),
|
||||||
|
curves(TransferCurve::default(), curve),
|
||||||
|
];
|
||||||
|
|
||||||
|
for adjustment in defaults.iter().chain(&settings) {
|
||||||
|
assert_eq!(adjustment.may_change_alpha(), !preserves_alpha(adjustment), "{adjustment:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
//! The pixel filters on the CPU, which mirror the renderer's GPU passes on premultiplied gamma-encoded channels.
|
//! 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 crate::effect_kernels::{BlurKernel, Plane};
|
||||||
|
use crate::resample_kernels::sample_bilinear;
|
||||||
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
||||||
use graphic_types::effects::spans_along_axes;
|
use graphic_types::effects::{MAX_MEDIAN_GRID_RADIUS, spans_along_axes};
|
||||||
use graphic_types::filters::{
|
use graphic_types::filters::{
|
||||||
Convolution, FieldSampling, GAUSSIAN_NOISE_LIMIT, HIGH_PASS_GRAY, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, average_weight,
|
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,
|
edge_gain, fill_shifts, neighborhood_radii, noise_extent, unsharp, unsharp_change,
|
||||||
@@ -10,6 +11,7 @@ use graphic_types::filters::{
|
|||||||
use graphic_types::generator::pcg3d;
|
use graphic_types::generator::pcg3d;
|
||||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||||
use raster_types::parallel_rows::fill_rows;
|
use raster_types::parallel_rows::fill_rows;
|
||||||
|
use std::ops::Range;
|
||||||
|
|
||||||
/// 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.
|
/// 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.
|
/// The pixels visible in the `full`-strength content (the plane itself for `None`) are those whose colors the filter reads.
|
||||||
@@ -475,6 +477,105 @@ fn window_extremes(source: &[[f32; 4]], target: &mut [[f32; 4]], radius: usize,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The GPU's median of `radius` whole effect-space units, which `pixels_per_length` makes pixels along each axis, on a grid of a pixel to each unit coarsened past [`MAX_MEDIAN_GRID_RADIUS`] as the GPU's is.
|
||||||
|
/// The `image` is the range of pixels along each axis holding the image, whose own pixels read only each other, and `origin` its corner, where the coarse grid starts.
|
||||||
|
pub fn median_on_content_grid(plane: &Plane<[f32; 4]>, radius: f64, pixels_per_length: DVec2, origin: DVec2, image: [Range<usize>; 2]) -> Plane<[f32; 4]> {
|
||||||
|
let whole = radius.max(0.).floor();
|
||||||
|
let coarsening = (MAX_MEDIAN_GRID_RADIUS / whole).min(1.);
|
||||||
|
if coarsening >= 1. {
|
||||||
|
let radii = (pixels_per_length * whole).round().min(DVec2::new(plane.width as f64, plane.height as f64));
|
||||||
|
return match radii == DVec2::ZERO {
|
||||||
|
true => plane.clone(),
|
||||||
|
false => median(plane, [radii.x as usize, radii.y as usize], image),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// The coarse grid's texels, each spanning this many pixels, lie on a lattice from the image's corner, as the GPU's lattice lies from the content's origin
|
||||||
|
let texel = pixels_per_length / coarsening;
|
||||||
|
let first = ((DVec2::ZERO - origin) / texel).floor();
|
||||||
|
let end = ((DVec2::new(plane.width as f64, plane.height as f64) - origin) / texel).ceil();
|
||||||
|
let size = (end - first).max(DVec2::ONE);
|
||||||
|
let texel_center = |index: DVec2| origin + (first + index + 0.5) * texel;
|
||||||
|
|
||||||
|
// The content drawn onto the coarse grid by sampling it at each texel's center, as the GPU draws it
|
||||||
|
let (coarse_width, coarse_height) = (size.x as usize, size.y as usize);
|
||||||
|
let mut coarse = Plane::new(coarse_width, coarse_height);
|
||||||
|
fill_rows(&mut coarse.data, coarse_width, |y, row| {
|
||||||
|
for (x, texel) in row.iter_mut().enumerate() {
|
||||||
|
*texel = sample_bilinear(plane, texel_center(DVec2::new(x as f64, y as f64)));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// The texels whose centers lie within the image, and the median over a window of the radius in texels, then resampled back onto the pixels
|
||||||
|
let within = |axis: usize, count: usize| {
|
||||||
|
let inside = |index: usize| image[axis].contains(&(texel_center(DVec2::splat(index as f64))[axis].floor().max(0.) as usize));
|
||||||
|
let start = (0..count).find(|&index| inside(index)).unwrap_or(count);
|
||||||
|
let end = (start..count).find(|&index| !inside(index)).unwrap_or(count);
|
||||||
|
start..end
|
||||||
|
};
|
||||||
|
let radius_in_texels = (coarsening * whole).round() as usize;
|
||||||
|
let medians = median(&coarse, [radius_in_texels; 2], [within(0, coarse_width), within(1, coarse_height)]);
|
||||||
|
|
||||||
|
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 center = DVec2::new(x as f64, y as f64) + 0.5;
|
||||||
|
*pixel = sample_bilinear(&medians, (center - origin) / texel - first);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The median of each pixel's window reaching `across` and `down` pixels, as the GPU's median finds it: the alpha's among the window's pixels, with those past the plane's edges transparent,
|
||||||
|
/// and each straight color's among those with coverage, taking the upper median of an even count. A pixel within the `within` range along each axis reads only pixels within it. O(width × height × across × down).
|
||||||
|
pub fn median(plane: &Plane<[f32; 4]>, [across, down]: [usize; 2], within: [Range<usize>; 2]) -> Plane<[f32; 4]> {
|
||||||
|
let inside = |x: isize, y: isize| x >= 0 && y >= 0 && within[0].contains(&(x as usize)) && within[1].contains(&(y as usize));
|
||||||
|
let upper_median = |values: &mut [f32]| *values.select_nth_unstable_by(values.len() / 2, f32::total_cmp).1;
|
||||||
|
let window_capacity = (2 * across + 1) * (2 * down + 1);
|
||||||
|
|
||||||
|
let mut result = Plane::new(plane.width, plane.height);
|
||||||
|
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||||
|
// Allocated once for the row and reused for each of its pixels
|
||||||
|
let mut alphas: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||||
|
let mut colors: [Vec<f32>; 3] = std::array::from_fn(|_| Vec::with_capacity(window_capacity));
|
||||||
|
|
||||||
|
let y = y as isize;
|
||||||
|
for (x, pixel) in row.iter_mut().enumerate() {
|
||||||
|
let x = x as isize;
|
||||||
|
alphas.clear();
|
||||||
|
colors.iter_mut().for_each(Vec::clear);
|
||||||
|
|
||||||
|
let clips = inside(x, y);
|
||||||
|
for read_y in y - down as isize..=y + down as isize {
|
||||||
|
for read_x in x - across as isize..=x + across as isize {
|
||||||
|
if clips && !inside(read_x, read_y) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let on_plane = read_x >= 0 && read_y >= 0 && (read_x as usize) < plane.width && (read_y as usize) < plane.height;
|
||||||
|
let [red, green, blue, alpha] = if on_plane { plane.data[read_y as usize * plane.width + read_x as usize] } else { [0.; 4] };
|
||||||
|
alphas.push(alpha.min(1.));
|
||||||
|
if alpha > 0. {
|
||||||
|
// Kept within the finite range of the GPU's half floats
|
||||||
|
let straight = |channel: f32| (channel / alpha).max(0.).min(65504.);
|
||||||
|
colors.iter_mut().zip([red, green, blue]).for_each(|(values, channel)| values.push(straight(channel)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let alpha = upper_median(&mut alphas);
|
||||||
|
*pixel = match colors[0].is_empty() || !(alpha > 0.) {
|
||||||
|
true => [0.; 4],
|
||||||
|
false => {
|
||||||
|
let [red, green, blue] = colors.each_mut().map(|values| upper_median(values));
|
||||||
|
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
/// 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.
|
/// 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 {
|
fn unit_interval(hash: u32) -> f32 {
|
||||||
((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32
|
((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32
|
||||||
|
|||||||
@@ -18,4 +18,4 @@ pub mod warp_kernels;
|
|||||||
|
|
||||||
pub use kernel::*;
|
pub use kernel::*;
|
||||||
pub use raster_effects::evaluate_raster_effects;
|
pub use raster_effects::evaluate_raster_effects;
|
||||||
pub use value_effects::{evaluate_color_effects, evaluate_gradient_effects};
|
pub use value_effects::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
|
||||||
@@ -550,6 +550,16 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
|||||||
}
|
}
|
||||||
// An image of its own has nothing beneath it to blur, or for Blend If to read, which fades the content where it acts
|
// An image of its own has nothing beneath it to blur, or for Blend If to read, which fades the content where it acts
|
||||||
EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => {}
|
EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => {}
|
||||||
|
EffectOperation::Median { radius } => {
|
||||||
|
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||||
|
let origin = DVec2::new(margin_x as f64, margin_y as f64);
|
||||||
|
let median = |plane: &Plane<[f32; 4]>| {
|
||||||
|
let image = [margin_x..margin_x + width, margin_y..margin_y + height];
|
||||||
|
crate::filter_kernels::median_on_content_grid(plane, radius, pixels_per_length, origin, image)
|
||||||
|
};
|
||||||
|
full = median(&full);
|
||||||
|
filled = filled.map(|filled| median(&filled));
|
||||||
|
}
|
||||||
// A solid paint overlay paints within the content alone, like any other paint overlay
|
// A solid paint overlay paints within the content alone, like any other paint overlay
|
||||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => {
|
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => {
|
||||||
let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32));
|
let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32));
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use crate::adjustments::{PreparedAdjustment, adjust_color};
|
|||||||
use crate::blending::overlay_paint;
|
use crate::blending::overlay_paint;
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
|
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_OPACITY, ATTR_OPACITY_FILL, Item};
|
||||||
use graphic_types::adjustment::Adjustment;
|
use graphic_types::adjustment::Adjustment;
|
||||||
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
|
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
|
||||||
use graphic_types::effects::{EffectOperation, Effects};
|
use graphic_types::effects::{EffectOperation, Effects};
|
||||||
@@ -258,9 +258,24 @@ pub fn adjusted_gradient_with_blend_ifs(
|
|||||||
Some((resampled, resampled_settings))
|
Some((resampled, resampled_settings))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether [`color_after_effects`] and [`gradient_after_effects`] carry out every one of the effects, since each changes every color on its own:
|
||||||
|
/// an adjustment, a Blend If reading only the value's own colors, or an effect that changes nothing.
|
||||||
|
pub fn carries_out_every_effect(effects: &Effects) -> bool {
|
||||||
|
effects.operations().all(|operation| match operation {
|
||||||
|
EffectOperation::Adjustment(_) => true,
|
||||||
|
EffectOperation::BlendIf(ranges) => ranges.underlying.show_everything(),
|
||||||
|
_ => operation.changes_nothing(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
|
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
|
||||||
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
|
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
|
||||||
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), 1.)
|
filled_color_after_effects(color, effects, 1.)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`color_after_effects`], carried out over the color faded by a `fill`, which leaves the paint overlays among them at full strength, as the renderers fade content.
|
||||||
|
pub fn filled_color_after_effects(color: Color, effects: &Effects, fill: f32) -> Color {
|
||||||
|
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), fill)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
|
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
|
||||||
@@ -270,10 +285,15 @@ pub fn prepared_color_after_effects(effects: &Effects) -> Box<dyn Fn(Color) -> C
|
|||||||
|
|
||||||
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
|
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
|
||||||
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
|
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
|
||||||
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), 1.)
|
filled_gradient_after_effects(gradient, settings, effects, 1.)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The color with its effects carried out as [`color_after_effects`] does and consumed, for nodes that read the color.
|
/// Like [`gradient_after_effects`], carried out along the ramp faded by a `fill` as [`filled_color_after_effects`] carries them out on a color.
|
||||||
|
pub fn filled_gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects, fill: f32) -> Option<(Gradient, GradientSettings)> {
|
||||||
|
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), fill)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The color with its effects carried out as [`color_after_effects`] does and consumed, though not its opacity (see [`evaluate_color_parameter`]).
|
||||||
/// A color without the effects attribute is returned as it is.
|
/// A color without the effects attribute is returned as it is.
|
||||||
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
||||||
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
|
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
|
||||||
@@ -286,6 +306,27 @@ pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
|||||||
item
|
item
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The color as the renderers show it, for a node reading it as a parameter: its effects carried out over it faded by its fill, then its opacity fading it all, each consumed.
|
||||||
|
/// Every node reading one color goes through this, so those attributes mean the same to all of them.
|
||||||
|
pub fn evaluate_color_parameter(item: Item<Color>) -> Item<Color> {
|
||||||
|
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||||
|
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
|
||||||
|
let (adjustments, blend_ifs) = item
|
||||||
|
.attribute::<Effects>(ATTR_EFFECTS)
|
||||||
|
.map(|effects| (adjustments(effects), content_blend_ifs(effects)))
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let shown = filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill);
|
||||||
|
let mut item = item;
|
||||||
|
*item.element_mut() = shown.with_alpha(shown.a() * opacity);
|
||||||
|
|
||||||
|
// Consumed so a node passing the item on doesn't get them carried out twice where it's drawn
|
||||||
|
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||||
|
item.remove_attribute::<f64>(ATTR_OPACITY);
|
||||||
|
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
|
||||||
|
item
|
||||||
|
}
|
||||||
|
|
||||||
/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors.
|
/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors.
|
||||||
/// A gradient without the effects attribute is returned as it is.
|
/// A gradient without the effects attribute is returned as it is.
|
||||||
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
||||||
@@ -351,6 +392,21 @@ mod tests {
|
|||||||
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
|
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_color_parameters_fill_fades_it_beneath_its_paint_overlays_and_its_opacity_over_them() {
|
||||||
|
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||||
|
color: Color::RED,
|
||||||
|
blend_mode: BlendMode::Normal,
|
||||||
|
opacity: 100.,
|
||||||
|
});
|
||||||
|
let unfilled = Item::new_from_element(Color::BLACK)
|
||||||
|
.with_attribute(ATTR_EFFECTS, Effects::from_operations([red]))
|
||||||
|
.with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||||||
|
|
||||||
|
assert!(close(gamma(*evaluate_color_parameter(unfilled.clone()).element()), [1., 0., 0., 1.]));
|
||||||
|
assert!(close(gamma(*evaluate_color_parameter(unfilled.with_attribute(ATTR_OPACITY, 0.5_f64)).element()), [1., 0., 0., 0.5]));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
|
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
|
||||||
use graphic_types::blend_if::BlendIfRanges;
|
use graphic_types::blend_if::BlendIfRanges;
|
||||||
|
|||||||
@@ -312,6 +312,29 @@ mod cpu {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An image's pixels as it's drawn, with its effects and fill carried out on its own pixel grid.
|
||||||
|
/// A node input of this type has the compiler read them back from the image wired into it, which carries its effects as attributes until then.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, DynAny, core_types::CacheHash)]
|
||||||
|
pub struct Pixels(Raster<CPU>);
|
||||||
|
|
||||||
|
impl Pixels {
|
||||||
|
pub fn new(raster: Raster<CPU>) -> Self {
|
||||||
|
Self(raster)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn into_raster(self) -> Raster<CPU> {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for Pixels {
|
||||||
|
type Target = Image<Color>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
self.0.data()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub use gpu::GPU;
|
pub use gpu::GPU;
|
||||||
#[cfg(feature = "wgpu")]
|
#[cfg(feature = "wgpu")]
|
||||||
pub use gpu::{Texture, TextureWeakRef};
|
pub use gpu::{Texture, TextureWeakRef};
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::renderer::{
|
use crate::renderer::{
|
||||||
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, painted_gradient, spread_adjusted_samples,
|
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, paint_draws_by_its_colors, painted_gradient,
|
||||||
svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
|
spread_adjusted_samples, svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
|
||||||
};
|
};
|
||||||
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||||
use core_types::color::SRGBA8;
|
use core_types::color::SRGBA8;
|
||||||
@@ -88,7 +88,7 @@ impl RenderExt for List<Color> {
|
|||||||
|
|
||||||
/// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing.
|
/// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing.
|
||||||
/// One painted through a mask fills a pattern spanning `bounds`, which `stroke_transform` places in the painted element's space.
|
/// One painted through a mask fills a pattern spanning `bounds`, which `stroke_transform` places in the painted element's space.
|
||||||
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
|
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_fill_and_opacity`] explains.
|
||||||
fn render_gradient_paint(
|
fn render_gradient_paint(
|
||||||
item: Option<ItemRef<'_, Gradient>>,
|
item: Option<ItemRef<'_, Gradient>>,
|
||||||
svg_defs: &mut String,
|
svg_defs: &mut String,
|
||||||
@@ -101,14 +101,13 @@ fn render_gradient_paint(
|
|||||||
let mut stop = String::new();
|
let mut stop = String::new();
|
||||||
|
|
||||||
let item = item?;
|
let item = item?;
|
||||||
let (stops, settings) = painted_gradient(item)?;
|
let (stops, settings, paint_opacity) = painted_gradient(item, for_mask)?;
|
||||||
let shape = gradient_shape(item);
|
let shape = gradient_shape(item);
|
||||||
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
|
|
||||||
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
|
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
|
||||||
with_two_stops_at_least(shape, &mut samples);
|
with_two_stops_at_least(shape, &mut samples);
|
||||||
|
|
||||||
let paint_opacity = item.paint_opacity(for_mask);
|
|
||||||
if paint_opacity < 1. {
|
if paint_opacity < 1. {
|
||||||
for (_, color, _) in &mut samples {
|
for (_, color, _) in &mut samples {
|
||||||
*color = color.with_alpha(color.a() * paint_opacity);
|
*color = color.with_alpha(color.a() * paint_opacity);
|
||||||
@@ -303,10 +302,11 @@ impl RenderExt for Graphic {
|
|||||||
target: PaintTarget,
|
target: PaintTarget,
|
||||||
) -> Self::Output {
|
) -> Self::Output {
|
||||||
let paint_attr = target.paint_attr();
|
let paint_attr = target.paint_attr();
|
||||||
|
let by_colors = paint_draws_by_its_colors(self);
|
||||||
|
|
||||||
match self {
|
match self {
|
||||||
Graphic::Color(item) => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
||||||
Graphic::ColorList(color_list) => color_list.render(
|
Graphic::ColorList(color_list) if by_colors => color_list.render(
|
||||||
svg_defs,
|
svg_defs,
|
||||||
user_to_document,
|
user_to_document,
|
||||||
paint_reach,
|
paint_reach,
|
||||||
@@ -317,11 +317,11 @@ impl RenderExt for Graphic {
|
|||||||
render_params,
|
render_params,
|
||||||
target,
|
target,
|
||||||
),
|
),
|
||||||
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
|
Graphic::Gradient(item) if by_colors => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
|
||||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||||
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
|
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
|
||||||
Graphic::GradientList(gradient_list) if gradient_list.len() <= 1 => gradient_list
|
Graphic::GradientList(gradient_list) if by_colors => gradient_list
|
||||||
.render(
|
.render(
|
||||||
svg_defs,
|
svg_defs,
|
||||||
user_to_document,
|
user_to_document,
|
||||||
@@ -336,7 +336,10 @@ impl RenderExt for Graphic {
|
|||||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
|
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
|
||||||
Graphic::Graphic(_)
|
Graphic::Color(_)
|
||||||
|
| Graphic::ColorList(_)
|
||||||
|
| Graphic::Gradient(_)
|
||||||
|
| Graphic::Graphic(_)
|
||||||
| Graphic::Vector(_)
|
| Graphic::Vector(_)
|
||||||
| Graphic::RasterCPU(_)
|
| Graphic::RasterCPU(_)
|
||||||
| Graphic::RasterGPU(_)
|
| Graphic::RasterGPU(_)
|
||||||
|
|||||||
@@ -51,7 +51,8 @@ use num_traits::Zero;
|
|||||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||||
use raster_kernels::raster_effects::adjusted_raster;
|
use raster_kernels::raster_effects::adjusted_raster;
|
||||||
use raster_kernels::value_effects::{
|
use raster_kernels::value_effects::{
|
||||||
BlendIfStep, adjusted_color, adjusted_gradient, adjusted_gradient_with_blend_ifs, blend_ifs_span_runs, color_after_effects, filled_color_with_blend_ifs, gradient_after_effects,
|
BlendIfStep, adjusted_color, adjusted_gradient, adjusted_gradient_with_blend_ifs, blend_ifs_span_runs, carries_out_every_effect, filled_color_after_effects, filled_color_with_blend_ifs,
|
||||||
|
filled_gradient_after_effects,
|
||||||
};
|
};
|
||||||
use skrifa::instance::{LocationRef, NormalizedCoord, Size};
|
use skrifa::instance::{LocationRef, NormalizedCoord, Size};
|
||||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||||
@@ -120,12 +121,12 @@ impl<'a, T> ItemRef<'a, T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The alpha multiplier this item's opacity attributes apply when it serves as a paint.
|
/// The fill and opacity this item's opacity attributes fade it by when it serves as a paint, the fill before its effects and the opacity after them, as for any content.
|
||||||
/// Fill opacity fades a paint just as opacity does, but a masker drops it so it cannot reach the content clipped to it.
|
/// A masker drops the fill so it cannot reach the content clipped to it.
|
||||||
pub(crate) fn paint_opacity(self, for_mask: bool) -> f32 {
|
pub(crate) fn paint_fill_and_opacity(self, for_mask: bool) -> (f32, f32) {
|
||||||
let opacity_fill = if for_mask { 1. } else { self.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) };
|
let fill = if for_mask { 1. } else { self.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) };
|
||||||
|
|
||||||
(self.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) * opacity_fill) as f32
|
(fill as f32, self.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How the item's opacity attributes and effects apply as it renders, with `content_transform` placing its content in the space it's drawn in.
|
/// How the item's opacity attributes and effects apply as it renders, with `content_transform` placing its content in the space it's drawn in.
|
||||||
@@ -539,6 +540,7 @@ impl ItemCompositing<'_> {
|
|||||||
// The color a solid paint draws, which is `None` for no paint, or no color at all for a paint that isn't solid
|
// The color a solid paint draws, which is `None` for no paint, or no color at all for a paint that isn't solid
|
||||||
let solid_color = |paint: Option<&Graphic>| match paint {
|
let solid_color = |paint: Option<&Graphic>| match paint {
|
||||||
None | Some(Graphic::None(_) | Graphic::NoneList(_)) => Some(None),
|
None | Some(Graphic::None(_) | Graphic::NoneList(_)) => Some(None),
|
||||||
|
Some(paint) if !paint_draws_by_its_colors(paint) => None,
|
||||||
Some(Graphic::Color(item)) => Some(faded_paint_color(ItemRef::Item(item), for_mask)),
|
Some(Graphic::Color(item)) => Some(faded_paint_color(ItemRef::Item(item), for_mask)),
|
||||||
Some(Graphic::ColorList(list)) => Some(composite_paint_colors(list, for_mask)),
|
Some(Graphic::ColorList(list)) => Some(composite_paint_colors(list, for_mask)),
|
||||||
Some(_) => None,
|
Some(_) => None,
|
||||||
@@ -1753,7 +1755,7 @@ fn svg_expresses_adjustment(adjustment: &Adjustment) -> bool {
|
|||||||
use graphic_types::adjustment::DesaturateMethod;
|
use graphic_types::adjustment::DesaturateMethod;
|
||||||
|
|
||||||
match adjustment {
|
match adjustment {
|
||||||
Adjustment::Threshold { .. } | Adjustment::GradientMap { .. } | Adjustment::ChannelMixer(_) | Adjustment::ColorOverlay { .. } => true,
|
Adjustment::Threshold { .. } | Adjustment::GradientMap { .. } | Adjustment::ChannelMixer(_) | Adjustment::ColorOverlay { .. } | Adjustment::AlphaToGray => true,
|
||||||
Adjustment::Desaturate { method } => matches!(
|
Adjustment::Desaturate { method } => matches!(
|
||||||
method,
|
method,
|
||||||
DesaturateMethod::LuminanceRec709 | DesaturateMethod::ChannelsAverage | DesaturateMethod::LumaRec709 | DesaturateMethod::LumaRec601
|
DesaturateMethod::LuminanceRec709 | DesaturateMethod::ChannelsAverage | DesaturateMethod::LumaRec709 | DesaturateMethod::LumaRec601
|
||||||
@@ -2093,6 +2095,10 @@ impl SvgFilterPrimitives {
|
|||||||
};
|
};
|
||||||
self.push("feColorMatrix", &format!(r#"in="{image}" color-interpolation-filters="{space}" {}"#, matrix([weights; 3])), "")
|
self.push("feColorMatrix", &format!(r#"in="{image}" color-interpolation-filters="{space}" {}"#, matrix([weights; 3])), "")
|
||||||
}
|
}
|
||||||
|
Adjustment::AlphaToGray => {
|
||||||
|
let values = "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0";
|
||||||
|
self.push("feColorMatrix", &format!(r#"{} type="matrix" values="{values}""#, in_gamma(image)), "")
|
||||||
|
}
|
||||||
// TODO: Express the other cross-channel adjustments, which no SVG primitive covers exactly
|
// TODO: Express the other cross-channel adjustments, which no SVG primitive covers exactly
|
||||||
_ => image.to_string(),
|
_ => image.to_string(),
|
||||||
}
|
}
|
||||||
@@ -2470,6 +2476,7 @@ fn write_svg_effects_filter_on_lattice(
|
|||||||
| EffectOperation::Emboss { .. }
|
| EffectOperation::Emboss { .. }
|
||||||
| EffectOperation::FindEdges
|
| EffectOperation::FindEdges
|
||||||
| EffectOperation::MinimumMaximum { .. }
|
| EffectOperation::MinimumMaximum { .. }
|
||||||
|
| EffectOperation::Median { .. }
|
||||||
| EffectOperation::Sharpen { .. }
|
| EffectOperation::Sharpen { .. }
|
||||||
| EffectOperation::HighPass { .. }
|
| EffectOperation::HighPass { .. }
|
||||||
| EffectOperation::Speckle { .. }
|
| EffectOperation::Speckle { .. }
|
||||||
@@ -2480,7 +2487,8 @@ fn write_svg_effects_filter_on_lattice(
|
|||||||
primitives.merge_beneath(&mut full, &mut filled, beneath.take());
|
primitives.merge_beneath(&mut full, &mut filled, beneath.take());
|
||||||
|
|
||||||
// Those keeping the content's coverage leave alone all a layer cutting its pieces within the content reads
|
// Those keeping the content's coverage leave alone all a layer cutting its pieces within the content reads
|
||||||
let changes_coverage = matches!(operation, EffectOperation::MinimumMaximum { .. } | EffectOperation::Dissolve { .. }) || graphic_types::filters::sharpens_coverage(&operation);
|
let changes_coverage = matches!(operation, EffectOperation::MinimumMaximum { .. } | EffectOperation::Median { .. } | EffectOperation::Dissolve { .. })
|
||||||
|
|| graphic_types::filters::sharpens_coverage(&operation);
|
||||||
if !shows_content && !changes_coverage {
|
if !shows_content && !changes_coverage {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -2630,25 +2638,60 @@ fn rect_bounds(rect: kurbo::Rect) -> RenderBoundingBox {
|
|||||||
RenderBoundingBox::Rectangle([DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)])
|
RenderBoundingBox::Rectangle([DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The color one paint item contributes, with its effects carried out (see [`color_after_effects`]) and faded by its opacity attributes.
|
/// Whether a solid or gradient paint draws by its colors, with each item's effects carried out on them (see [`faded_paint_color`] and [`painted_gradient`]), which is exact
|
||||||
pub(crate) fn faded_paint_color(item: ItemRef<'_, Color>, for_mask: bool) -> Option<Color> {
|
/// only where every effect changes each color on its own. Any other paint renders as content with its whole effect stack, clipped to the shape.
|
||||||
let mut color = *item.element()?;
|
pub(crate) fn paint_draws_by_its_colors(paint: &Graphic) -> bool {
|
||||||
if let Some(effects) = item.attribute::<Effects>(ATTR_EFFECTS) {
|
match paint {
|
||||||
color = color_after_effects(color, effects);
|
// Stacked gradients can't composite into one brush
|
||||||
|
Graphic::GradientList(list) if list.len() > 1 => false,
|
||||||
|
Graphic::Color(_) | Graphic::ColorList(_) | Graphic::Gradient(_) | Graphic::GradientList(_) => !paint_has_effects_beyond_its_colors(paint),
|
||||||
|
_ => false,
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(color.with_alpha(color.a() * item.paint_opacity(for_mask)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The ramp one gradient paint item contributes, with its effects carried out along it (see [`gradient_after_effects`]), and the settings to read it with.
|
/// Whether an item of a solid or gradient paint has an effect that doesn't change each color on its own (see [`carries_out_every_effect`]).
|
||||||
pub(crate) fn painted_gradient(item: ItemRef<'_, Gradient>) -> Option<(Cow<'_, Gradient>, GradientSettings)> {
|
fn paint_has_effects_beyond_its_colors(paint: &Graphic) -> bool {
|
||||||
|
fn beyond_colors(effects: Option<&Effects>) -> bool {
|
||||||
|
effects.is_some_and(|effects| !carries_out_every_effect(effects))
|
||||||
|
}
|
||||||
|
fn list_beyond_colors<T>(list: &List<T>) -> bool {
|
||||||
|
(0..list.len()).any(|index| beyond_colors(list.attribute(ATTR_EFFECTS, index)))
|
||||||
|
}
|
||||||
|
|
||||||
|
match paint {
|
||||||
|
Graphic::Color(item) => beyond_colors(item.attribute(ATTR_EFFECTS)),
|
||||||
|
Graphic::Gradient(item) => beyond_colors(item.attribute(ATTR_EFFECTS)),
|
||||||
|
Graphic::ColorList(list) => list_beyond_colors(list),
|
||||||
|
Graphic::GradientList(list) => list_beyond_colors(list),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The color one paint item contributes, faded by its fill with its effects carried out over that (see [`filled_color_after_effects`]), then faded by its opacity.
|
||||||
|
pub(crate) fn faded_paint_color(item: ItemRef<'_, Color>, for_mask: bool) -> Option<Color> {
|
||||||
|
let color = *item.element()?;
|
||||||
|
let (fill, opacity) = item.paint_fill_and_opacity(for_mask);
|
||||||
|
|
||||||
|
let filled = match item.attribute::<Effects>(ATTR_EFFECTS) {
|
||||||
|
Some(effects) => filled_color_after_effects(color, effects, fill),
|
||||||
|
None => color.with_alpha(color.a() * fill),
|
||||||
|
};
|
||||||
|
Some(filled.with_alpha(filled.a() * opacity))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ramp one gradient paint item contributes, faded by its fill with its effects carried out along it (see [`filled_gradient_after_effects`]), the settings to read it with,
|
||||||
|
/// and the opacity left to fade it by, which takes the fill too where there was nothing to carry out along the ramp.
|
||||||
|
pub(crate) fn painted_gradient(item: ItemRef<'_, Gradient>, for_mask: bool) -> Option<(Cow<'_, Gradient>, GradientSettings, f32)> {
|
||||||
let gradient = item.element()?;
|
let gradient = item.element()?;
|
||||||
let settings = gradient_settings_from_item(item);
|
let settings = gradient_settings_from_item(item);
|
||||||
|
let (fill, opacity) = item.paint_fill_and_opacity(for_mask);
|
||||||
|
|
||||||
let adjusted = item.attribute::<Effects>(ATTR_EFFECTS).and_then(|effects| gradient_after_effects(gradient, settings, effects));
|
let adjusted = item
|
||||||
|
.attribute::<Effects>(ATTR_EFFECTS)
|
||||||
|
.and_then(|effects| filled_gradient_after_effects(gradient, settings, effects, fill));
|
||||||
Some(match adjusted {
|
Some(match adjusted {
|
||||||
Some((gradient, settings)) => (Cow::Owned(gradient), settings),
|
Some((gradient, settings)) => (Cow::Owned(gradient), settings, opacity),
|
||||||
None => (Cow::Borrowed(gradient), settings),
|
None => (Cow::Borrowed(gradient), settings, opacity * fill),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2917,6 +2960,8 @@ pub struct RenderParams {
|
|||||||
pub canvas_image_scale: f64,
|
pub canvas_image_scale: f64,
|
||||||
/// The nearest ancestor's appearance, cascading to items that lack their own.
|
/// The nearest ancestor's appearance, cascading to items that lack their own.
|
||||||
pub inherited_appearance: Option<Appearance>,
|
pub inherited_appearance: Option<Appearance>,
|
||||||
|
/// The frame in the document of the shape a paint fills, within which endless content painting it is seen and has its effects carried out.
|
||||||
|
pub paint_frame: Option<DAffine2>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RenderParams {
|
impl RenderParams {
|
||||||
@@ -3128,6 +3173,24 @@ fn svg_only_approximates(paint: &Graphic) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a solid or gradient paint rendering as content (see [`paint_draws_by_its_colors`]) takes maps or images from the GPU for its effects, which can't reach the pattern it paints through.
|
||||||
|
/// Found by rendering it as content in the document, placed by `content_transform` in the current user space.
|
||||||
|
fn svg_paint_needs_the_gpu(paint: &Graphic, render: &SvgRender, content_transform: DAffine2, render_params: &RenderParams) -> bool {
|
||||||
|
if !paint_has_effects_beyond_its_colors(paint) || !render.images_replace_markup(render_params) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut content = SvgRender::new();
|
||||||
|
content.transform = render.transform * content_transform;
|
||||||
|
content.ancestors_reach = render.ancestors_reach;
|
||||||
|
let paint_render_params = RenderParams {
|
||||||
|
inherited_appearance: None,
|
||||||
|
..render_params.clone()
|
||||||
|
};
|
||||||
|
paint.render_svg(&mut content, &paint_render_params);
|
||||||
|
!content.effect_maps.is_empty() || !content.deferred_images.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
/// Maps a gradient's `transform` into the frame handed to the renderer: most shapes keep the full matrix (so a
|
/// Maps a gradient's `transform` into the frame handed to the renderer: most shapes keep the full matrix (so a
|
||||||
/// non-uniform transform makes an ellipse), while linear is reduced to the equivalent non-sheared gradient line (the
|
/// non-uniform transform makes an ellipse), while linear is reduced to the equivalent non-sheared gradient line (the
|
||||||
/// axis projected onto the band normal) so the iso-color bands keep following a sheared transform, which Vello can
|
/// axis projected onto the band normal) so the iso-color bands keep following a sheared transform, which Vello can
|
||||||
@@ -3575,9 +3638,9 @@ fn apollonian_geometry(parameters: &GradientApollonian) -> vello_gpu::PencilGeom
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// How Vello draws one gradient paint item, in the space `multiplied_transform` places it in.
|
/// How Vello draws one gradient paint item, in the space `multiplied_transform` places it in.
|
||||||
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
|
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_fill_and_opacity`] explains.
|
||||||
fn create_gradient_paint(gradient_item: ItemRef<'_, Gradient>, multiplied_transform: &DAffine2, for_mask: bool) -> Option<VelloGradientPaint> {
|
fn create_gradient_paint(gradient_item: ItemRef<'_, Gradient>, multiplied_transform: &DAffine2, for_mask: bool) -> Option<VelloGradientPaint> {
|
||||||
let (stops, settings) = painted_gradient(gradient_item)?;
|
let (stops, settings, paint_opacity) = painted_gradient(gradient_item, for_mask)?;
|
||||||
|
|
||||||
let shape = gradient_shape(gradient_item);
|
let shape = gradient_shape(gradient_item);
|
||||||
let gradient_transform: DAffine2 = gradient_item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
let gradient_transform: DAffine2 = gradient_item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
@@ -3585,7 +3648,6 @@ fn create_gradient_paint(gradient_item: ItemRef<'_, Gradient>, multiplied_transf
|
|||||||
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
|
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
|
||||||
with_two_stops_at_least(shape, &mut samples);
|
with_two_stops_at_least(shape, &mut samples);
|
||||||
|
|
||||||
let paint_opacity = gradient_item.paint_opacity(for_mask);
|
|
||||||
if paint_opacity < 1. {
|
if paint_opacity < 1. {
|
||||||
// A stopless ramp gets its black stop downstream, too late to be faded, so it needs one here instead
|
// A stopless ramp gets its black stop downstream, too late to be faded, so it needs one here instead
|
||||||
if samples.is_empty() {
|
if samples.is_empty() {
|
||||||
@@ -3864,7 +3926,11 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st
|
|||||||
if next_clips && mask_state.is_none() {
|
if next_clips && mask_state.is_none() {
|
||||||
let uuid = generate_uuid();
|
let uuid = generate_uuid();
|
||||||
let (base, nested) = clipping_base(element, transform, item.attribute::<Effects>(ATTR_EFFECTS));
|
let (base, nested) = clipping_base(element, transform, item.attribute::<Effects>(ATTR_EFFECTS));
|
||||||
let mask_type = if base.can_reduce_to_clip_path() { MaskType::Clip } else { MaskType::Mask };
|
let mask_type = if base.can_reduce_to_clip_path(render_params.inherited_appearance.as_ref()) {
|
||||||
|
MaskType::Clip
|
||||||
|
} else {
|
||||||
|
MaskType::Mask
|
||||||
|
};
|
||||||
|
|
||||||
// A base nested to take the item's effects carries the item's transform itself
|
// A base nested to take the item's effects carries the item's transform itself
|
||||||
let base_transform = if nested { DAffine2::IDENTITY } else { transform };
|
let base_transform = if nested { DAffine2::IDENTITY } else { transform };
|
||||||
@@ -4781,6 +4847,22 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, opacity:
|
|||||||
let override_paint_order = can_draw_aligned_stroke && can_use_paint_order;
|
let override_paint_order = can_draw_aligned_stroke && can_use_paint_order;
|
||||||
let use_face_fill = item.fills_faces();
|
let use_face_fill = item.fills_faces();
|
||||||
|
|
||||||
|
// Fills drawn as paths of their own composite with the stroke's path as one shape, through a group taking its opacity and blend mode
|
||||||
|
if (needs_separate_alignment_fill || use_face_fill) && (opacity < 1. || blend_mode != BlendMode::default()) {
|
||||||
|
let group_attributes = |attributes: &mut SvgRenderAttrs| {
|
||||||
|
if opacity < 1. {
|
||||||
|
attributes.push("opacity", opacity.to_string());
|
||||||
|
}
|
||||||
|
if blend_mode != BlendMode::default() {
|
||||||
|
attributes.push("style", blend_mode.render());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
render.parent_tag("g", group_attributes, |render| {
|
||||||
|
render_vector_shape_svg(item, vector, 1., BlendMode::default(), folded, render, render_params)
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if needs_separate_alignment_fill && !wants_stroke_below {
|
if needs_separate_alignment_fill && !wants_stroke_below {
|
||||||
emit_svg_fill_path(
|
emit_svg_fill_path(
|
||||||
render,
|
render,
|
||||||
@@ -4889,7 +4971,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, opacity:
|
|||||||
let paint_bounds = match paint {
|
let paint_bounds = match paint {
|
||||||
Graphic::Gradient(item) if gradient_draws_masked(ItemRef::Item(item)) => stroke_bounds_matrix,
|
Graphic::Gradient(item) if gradient_draws_masked(ItemRef::Item(item)) => stroke_bounds_matrix,
|
||||||
Graphic::GradientList(list) if list.len() == 1 && gradient_draws_masked(ItemRef::ListItem(list, 0)) => stroke_bounds_matrix,
|
Graphic::GradientList(list) if list.len() == 1 && gradient_draws_masked(ItemRef::ListItem(list, 0)) => stroke_bounds_matrix,
|
||||||
Graphic::Color(_) | Graphic::Gradient(_) | Graphic::ColorList(_) | Graphic::GradientList(_) => bounds_matrix,
|
Graphic::Color(_) | Graphic::Gradient(_) | Graphic::ColorList(_) | Graphic::GradientList(_) if paint_draws_by_its_colors(paint) => bounds_matrix,
|
||||||
_ => stroke_bounds_matrix,
|
_ => stroke_bounds_matrix,
|
||||||
};
|
};
|
||||||
paint.render(
|
paint.render(
|
||||||
@@ -4970,7 +5052,11 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask
|
|||||||
|
|
||||||
if next_clips && clip_mask_state.is_none() {
|
if next_clips && clip_mask_state.is_none() {
|
||||||
let masker = Graphic::VectorList(vector_clipping_base(vector, item));
|
let masker = Graphic::VectorList(vector_clipping_base(vector, item));
|
||||||
let mask_type = if masker.can_reduce_to_clip_path() { MaskType::Clip } else { MaskType::Mask };
|
let mask_type = if masker.can_reduce_to_clip_path(render_params.inherited_appearance.as_ref()) {
|
||||||
|
MaskType::Clip
|
||||||
|
} else {
|
||||||
|
MaskType::Mask
|
||||||
|
};
|
||||||
let uuid = generate_uuid();
|
let uuid = generate_uuid();
|
||||||
|
|
||||||
let mut masker_svg = SvgRender::new();
|
let mut masker_svg = SvgRender::new();
|
||||||
@@ -5012,12 +5098,14 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask
|
|||||||
None => compositing,
|
None => compositing,
|
||||||
};
|
};
|
||||||
|
|
||||||
// A fill or drawn stroke SVG only approximates, like a gradient of Apollonian circles, takes the GPU's image of the item
|
// A fill or drawn stroke SVG only approximates, like a gradient of Apollonian circles or a paint with effects needing the GPU, takes the GPU's image of the item
|
||||||
|
let item_transform = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
|
let approximates = |paint: &Graphic| svg_only_approximates(paint) || svg_paint_needs_the_gpu(paint, render, item_transform, render_params);
|
||||||
let svg_approximates_paint = render_params.render_mode != RenderMode::Outline
|
let svg_approximates_paint = render_params.render_mode != RenderMode::Outline
|
||||||
&& appearance().is_some_and(|appearance| {
|
&& appearance().is_some_and(|appearance| {
|
||||||
let FillAndStroke { fill_paint, stroke_paint, stroke, .. } = appearance.fill_and_stroke();
|
let FillAndStroke { fill_paint, stroke_paint, stroke, .. } = appearance.fill_and_stroke();
|
||||||
let strokes = stroke.is_some_and(|stroke| stroke.weight() > 0.);
|
let strokes = stroke.is_some_and(|stroke| stroke.weight() > 0.);
|
||||||
fill_paint.is_some_and(svg_only_approximates) || (strokes && stroke_paint.is_some_and(svg_only_approximates))
|
fill_paint.is_some_and(approximates) || (strokes && stroke_paint.is_some_and(approximates))
|
||||||
});
|
});
|
||||||
let compositing = ItemCompositing {
|
let compositing = ItemCompositing {
|
||||||
svg_approximates_paint,
|
svg_approximates_paint,
|
||||||
@@ -5257,6 +5345,13 @@ fn render_vector_item_to_vello(
|
|||||||
|
|
||||||
let use_layer = can_draw_aligned_stroke;
|
let use_layer = can_draw_aligned_stroke;
|
||||||
|
|
||||||
|
// A paint is seen within the shape it fills, or the stroke's outline for the stroke
|
||||||
|
let painting_within = |bounds: [DVec2; 2]| RenderParams {
|
||||||
|
paint_frame: Some(frame_of_bounds(bounds, multiplied_transform)),
|
||||||
|
..paint_render_params.clone()
|
||||||
|
};
|
||||||
|
let stroke_bounds = || element.stroke_inclusive_bounding_box_with_transform(element_paths, DAffine2::IDENTITY, stroke).unwrap_or(layer_bounds);
|
||||||
|
|
||||||
let do_fill_path = |scene: &mut VelloSceneBuilder, path: &kurbo::BezPath, fill_rule: peniko::Fill| {
|
let do_fill_path = |scene: &mut VelloSceneBuilder, path: &kurbo::BezPath, fill_rule: peniko::Fill| {
|
||||||
let Some(paint) = fill_paint else { return };
|
let Some(paint) = fill_paint else { return };
|
||||||
|
|
||||||
@@ -5282,15 +5377,18 @@ fn render_vector_item_to_vello(
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let by_colors = paint_draws_by_its_colors(paint);
|
||||||
match paint {
|
match paint {
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => (),
|
Graphic::None(_) | Graphic::NoneList(_) => (),
|
||||||
Graphic::Color(item) => solid_fill(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
|
Graphic::Color(item) if by_colors => solid_fill(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
|
||||||
Graphic::ColorList(list) => solid_fill(scene, composite_paint_colors(list, render_params.for_mask)),
|
Graphic::ColorList(list) if by_colors => solid_fill(scene, composite_paint_colors(list, render_params.for_mask)),
|
||||||
Graphic::Gradient(item) => gradient_fill(scene, ItemRef::Item(item)),
|
Graphic::Gradient(item) if by_colors => gradient_fill(scene, ItemRef::Item(item)),
|
||||||
// Stacked gradients cannot be composited into one brush, so they fall through to the clipped texture path
|
Graphic::GradientList(list) if by_colors => gradient_fill(scene, ItemRef::ListItem(list, 0)),
|
||||||
Graphic::GradientList(list) if list.len() <= 1 => gradient_fill(scene, ItemRef::ListItem(list, 0)),
|
|
||||||
// Any other graphic content paints as a texture clipped to the path
|
// Any other graphic content paints as a texture clipped to the path
|
||||||
Graphic::GradientList(_)
|
Graphic::Color(_)
|
||||||
|
| Graphic::ColorList(_)
|
||||||
|
| Graphic::Gradient(_)
|
||||||
|
| Graphic::GradientList(_)
|
||||||
| Graphic::Graphic(_)
|
| Graphic::Graphic(_)
|
||||||
| Graphic::Vector(_)
|
| Graphic::Vector(_)
|
||||||
| Graphic::RasterCPU(_)
|
| Graphic::RasterCPU(_)
|
||||||
@@ -5304,8 +5402,9 @@ fn render_vector_item_to_vello(
|
|||||||
| Graphic::GraphicList(_)
|
| Graphic::GraphicList(_)
|
||||||
| Graphic::TextList(_)
|
| Graphic::TextList(_)
|
||||||
| Graphic::StrokeList(_) => {
|
| Graphic::StrokeList(_) => {
|
||||||
scene.push_clip_layer(fill_rule, kurbo::Affine::new(element_transform.to_cols_array()), path);
|
// The paint composites within its own layer, as in its SVG pattern, so its blend modes act on nothing beneath the shape
|
||||||
paint.render_to_vello(scene, multiplied_transform, paint_render_params);
|
scene.push_layer(fill_rule, peniko::Mix::Normal, 1., kurbo::Affine::new(element_transform.to_cols_array()), path);
|
||||||
|
paint.render_to_vello(scene, multiplied_transform, &painting_within(layer_bounds));
|
||||||
scene.pop_layer();
|
scene.pop_layer();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -5376,15 +5475,18 @@ fn render_vector_item_to_vello(
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let by_colors = paint_draws_by_its_colors(paint);
|
||||||
match paint {
|
match paint {
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => (),
|
Graphic::None(_) | Graphic::NoneList(_) => (),
|
||||||
Graphic::Color(item) => solid_stroke(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
|
Graphic::Color(item) if by_colors => solid_stroke(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
|
||||||
Graphic::ColorList(list) => solid_stroke(scene, composite_paint_colors(list, render_params.for_mask)),
|
Graphic::ColorList(list) if by_colors => solid_stroke(scene, composite_paint_colors(list, render_params.for_mask)),
|
||||||
Graphic::Gradient(item) => gradient_stroke(scene, ItemRef::Item(item)),
|
Graphic::Gradient(item) if by_colors => gradient_stroke(scene, ItemRef::Item(item)),
|
||||||
// Stacked gradients cannot be composited into one brush, so they fall through to the clipped texture path
|
Graphic::GradientList(list) if by_colors => gradient_stroke(scene, ItemRef::ListItem(list, 0)),
|
||||||
Graphic::GradientList(list) if list.len() <= 1 => gradient_stroke(scene, ItemRef::ListItem(list, 0)),
|
|
||||||
// Any other graphic content paints as a texture clipped to the stroked region
|
// Any other graphic content paints as a texture clipped to the stroked region
|
||||||
Graphic::GradientList(_)
|
Graphic::Color(_)
|
||||||
|
| Graphic::ColorList(_)
|
||||||
|
| Graphic::Gradient(_)
|
||||||
|
| Graphic::GradientList(_)
|
||||||
| Graphic::Graphic(_)
|
| Graphic::Graphic(_)
|
||||||
| Graphic::Vector(_)
|
| Graphic::Vector(_)
|
||||||
| Graphic::RasterCPU(_)
|
| Graphic::RasterCPU(_)
|
||||||
@@ -5400,8 +5502,9 @@ fn render_vector_item_to_vello(
|
|||||||
| Graphic::StrokeList(_) => {
|
| Graphic::StrokeList(_) => {
|
||||||
let stroked = placed.stroke_outline(&stroke, 0.01);
|
let stroked = placed.stroke_outline(&stroke, 0.01);
|
||||||
|
|
||||||
scene.push_clip_layer(peniko::Fill::NonZero, element_affine, &*stroked);
|
// The paint composites within its own layer, as for the fill
|
||||||
paint.render_to_vello(scene, multiplied_transform, paint_render_params);
|
scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., element_affine, &*stroked);
|
||||||
|
paint.render_to_vello(scene, multiplied_transform, &painting_within(stroke_bounds()));
|
||||||
scene.pop_layer();
|
scene.pop_layer();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -5921,6 +6024,12 @@ pub(crate) fn render_raster_cpu_image_svg(image: &Raster<CPU>, transform: DAffin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The adjustments at the start of the image's effects that its render carries out on its own pixels, ahead of the rest.
|
||||||
|
pub fn leading_raster_adjustments(item: &Item<Raster<CPU>>) -> Vec<Adjustment> {
|
||||||
|
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
|
ItemRef::Item(item).compositing(&RenderParams::default(), transform).leading_adjustments()
|
||||||
|
}
|
||||||
|
|
||||||
/// Draws one item of CPU raster content into the Vello scene.
|
/// Draws one item of CPU raster content into the Vello scene.
|
||||||
fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster<CPU>>, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster<CPU>>, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
||||||
let Some(image) = item.element() else { return };
|
let Some(image) = item.element() else { return };
|
||||||
@@ -6325,10 +6434,10 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende
|
|||||||
render_edgeless_color_svg(item, render, &compositing, color, render_params);
|
render_edgeless_color_svg(item, render, &compositing, color, render_params);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether endless content carries out its `effects` over the area in view rather than on its paint: for filters and warps, which change even a flat color,
|
/// Whether endless content carries out its `effects` over the area in view rather than on its paint: for those reading the pixels around each one (like filters, warps, blurs, and Pixelate),
|
||||||
/// and for Blend Ifs spanning effect runs, which the paint's layers can't carry from one run to the next.
|
/// which change a ramp and some even a flat color, and for Blend Ifs spanning effect runs, which the paint's layers can't carry from one run to the next.
|
||||||
fn carried_out_in_view(effects: &Effects) -> bool {
|
fn carried_out_in_view(effects: &Effects) -> bool {
|
||||||
graphic_types::filters::has_filters(effects) || warps_change_endless_content(effects) || blend_ifs_span_runs(effects)
|
effects.operations().any(|operation| operation.reads_pixels_around() && !operation.changes_nothing()) || blend_ifs_span_runs(effects)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether any of the effects is a warp that changes something, which it does within its frame even to endless content.
|
/// Whether any of the effects is a warp that changes something, which it does within its frame even to endless content.
|
||||||
@@ -6550,7 +6659,15 @@ fn draw_endless_item_with_effects(
|
|||||||
if layer {
|
if layer {
|
||||||
scene.push_viewport_layer(peniko::BlendMode::new(blend_mode.to_peniko(), peniko::Compose::SrcOver), compositing.opacity);
|
scene.push_viewport_layer(peniko::BlendMode::new(blend_mode.to_peniko(), peniko::Compose::SrcOver), compositing.opacity);
|
||||||
}
|
}
|
||||||
compositing.draw_with_effects(scene, parent_transform, render_params, || RenderBoundingBox::Infinite, || None, 0., draw);
|
|
||||||
|
// Effects relative to the content's extent, like Pixelate, take the region it's seen in, being the shape it paints or else the view
|
||||||
|
let view = scene.view().inverse().transform_rect_bbox(kurbo::Rect::new(0., 0., scene.width() as f64, scene.height() as f64));
|
||||||
|
let frame = (render_params.paint_frame).unwrap_or_else(|| frame_of_bounds([DVec2::new(view.x0, view.y0), DVec2::new(view.x1, view.y1)], DAffine2::IDENTITY));
|
||||||
|
let bounds = match render_params.paint_frame {
|
||||||
|
Some(frame) => RenderBoundingBox::Rectangle((frame * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()),
|
||||||
|
None => RenderBoundingBox::Infinite,
|
||||||
|
};
|
||||||
|
compositing.draw_with_effects(scene, parent_transform, render_params, || bounds, || Some(frame), 0., draw);
|
||||||
if layer {
|
if layer {
|
||||||
scene.pop_layer();
|
scene.pop_layer();
|
||||||
}
|
}
|
||||||
@@ -6622,26 +6739,33 @@ fn gradient_control_interior_is_clickable(gradient_form: GradientForm) -> bool {
|
|||||||
gradient_form == GradientForm::Radial
|
gradient_form == GradientForm::Radial
|
||||||
}
|
}
|
||||||
|
|
||||||
/// For thumbnails the gradient fills a finite rect at the footprint's document space bounds, with a 1-unit margin to cover the `as u32` truncation of `Footprint::resolution`.
|
/// For thumbnails the gradient fills a finite rect around the footprint's document area in the user space, with a 1-unit margin for the `as u32` truncation of `Footprint::resolution`.
|
||||||
/// The viewBox crops the overshoot. Canvas rendering keeps the polyline path since Chrome rejects rects larger than ~20 million.
|
/// The viewBox crops the overshoot. Canvas rendering keeps the polyline path since Chrome rejects rects larger than ~20 million.
|
||||||
fn gradient_thumbnail_rect(render_params: &RenderParams) -> Option<(DVec2, DVec2)> {
|
fn gradient_thumbnail_rect(render: &SvgRender, render_params: &RenderParams) -> Option<(DVec2, DVec2)> {
|
||||||
if render_params.thumbnail {
|
if !render_params.thumbnail {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
let truncated_size = render_params.footprint.resolution.as_dvec2();
|
let truncated_size = render_params.footprint.resolution.as_dvec2();
|
||||||
let margin = DVec2::ONE;
|
let margin = DVec2::ONE;
|
||||||
Some((render_params.footprint.transform.translation - margin / 2., truncated_size + margin))
|
let (min, size) = (render_params.footprint.transform.translation - margin / 2., truncated_size + margin);
|
||||||
} else {
|
if !render.transform.matrix2.determinant().is_normal() {
|
||||||
None
|
return Some((min, size));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Content drawn in a space of its own, like a paint's pattern, takes the area mapped into that space
|
||||||
|
let [min, max] = (render.transform.inverse() * Quad::from_box([min, min + size])).bounding_box();
|
||||||
|
Some((min, max - min))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Emits one item of gradient content as SVG.
|
/// Emits one item of gradient content as SVG.
|
||||||
fn render_gradient_item_svg(item: ItemRef<'_, Gradient>, render: &mut SvgRender, render_params: &RenderParams) {
|
fn render_gradient_item_svg(item: ItemRef<'_, Gradient>, render: &mut SvgRender, render_params: &RenderParams) {
|
||||||
render_gradient_item_svg_with_thumbnail_rect(item, gradient_thumbnail_rect(render_params), render, render_params);
|
render_gradient_item_svg_with_thumbnail_rect(item, gradient_thumbnail_rect(render, render_params), render, render_params);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Render for List<Gradient> {
|
impl Render for List<Gradient> {
|
||||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||||
let thumbnail_rect = gradient_thumbnail_rect(render_params);
|
let thumbnail_rect = gradient_thumbnail_rect(render, render_params);
|
||||||
|
|
||||||
render_list_items_svg(self, render, render_params, |index, render| {
|
render_list_items_svg(self, render, render_params, |index, render| {
|
||||||
render_gradient_item_svg_with_thumbnail_rect(ItemRef::ListItem(self, index), thumbnail_rect, render, render_params)
|
render_gradient_item_svg_with_thumbnail_rect(ItemRef::ListItem(self, index), thumbnail_rect, render, render_params)
|
||||||
@@ -12115,7 +12239,7 @@ mod tests {
|
|||||||
// A gradient's dark start is hidden and its light end shown
|
// A gradient's dark start is hidden and its light end shown
|
||||||
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]));
|
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]));
|
||||||
stamp_effect(&mut gradient, blend_if());
|
stamp_effect(&mut gradient, blend_if());
|
||||||
let (ramp, settings) = painted_gradient(ItemRef::Item(&gradient)).expect("the Blend If fades the ramp");
|
let (ramp, settings, _) = painted_gradient(ItemRef::Item(&gradient), false).expect("the Blend If fades the ramp");
|
||||||
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
|
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
|
||||||
assert!(ramp.evaluate(0., settings).a() < 1e-6, "the start is hidden");
|
assert!(ramp.evaluate(0., settings).a() < 1e-6, "the start is hidden");
|
||||||
assert!(close(ramp.evaluate(1., settings), Color::WHITE), "the end shows");
|
assert!(close(ramp.evaluate(1., settings), Color::WHITE), "the end shows");
|
||||||
@@ -12141,12 +12265,363 @@ mod tests {
|
|||||||
|
|
||||||
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]));
|
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]));
|
||||||
stamp_effect(&mut gradient, invert());
|
stamp_effect(&mut gradient, invert());
|
||||||
let (ramp, settings) = painted_gradient(ItemRef::Item(&gradient)).unwrap();
|
let (ramp, settings, _) = painted_gradient(ItemRef::Item(&gradient), false).unwrap();
|
||||||
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
|
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
|
||||||
assert!(close(ramp.evaluate(0., settings), Color::WHITE), "the start turns white");
|
assert!(close(ramp.evaluate(0., settings), Color::WHITE), "the start turns white");
|
||||||
assert!(close(ramp.evaluate(1., settings), Color::BLACK), "the end turns black");
|
assert!(close(ramp.evaluate(1., settings), Color::BLACK), "the end turns black");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paints_fade_by_their_fill_before_their_adjustments_and_by_their_opacity_after() {
|
||||||
|
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||||
|
|
||||||
|
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
|
||||||
|
let make_opaque = || Effect::new(&EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. }));
|
||||||
|
let half_filled = |opacity: f64| Item::new_from_element(Color::RED).with_attribute(ATTR_OPACITY_FILL, 0.5).with_attribute(ATTR_OPACITY, opacity);
|
||||||
|
|
||||||
|
// Making a half-filled red opaque restores what the fill faded, though not what the opacity fades after it
|
||||||
|
let mut red = half_filled(1.);
|
||||||
|
stamp_effect(&mut red, make_opaque());
|
||||||
|
assert!(close(faded_paint_color(ItemRef::Item(&red), false).unwrap(), Color::RED));
|
||||||
|
let mut faded_red = half_filled(0.5);
|
||||||
|
stamp_effect(&mut faded_red, make_opaque());
|
||||||
|
assert!(close(faded_paint_color(ItemRef::Item(&faded_red), false).unwrap(), Color::RED.with_alpha(0.5)));
|
||||||
|
|
||||||
|
// Without effects, both fade it, though a masker drops the fill
|
||||||
|
assert!(close(faded_paint_color(ItemRef::Item(&half_filled(0.5)), false).unwrap(), Color::RED.with_alpha(0.25)));
|
||||||
|
assert!(close(faded_paint_color(ItemRef::Item(&half_filled(0.5)), true).unwrap(), Color::RED.with_alpha(0.5)));
|
||||||
|
|
||||||
|
// A gradient's ramp takes the fill where its effects are carried out along it, leaving only the opacity to fade it by, and otherwise leaves both
|
||||||
|
let half_filled_ramp = || Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||||
|
let mut opaque_ramp = half_filled_ramp();
|
||||||
|
stamp_effect(&mut opaque_ramp, make_opaque());
|
||||||
|
let (ramp, settings, opacity) = painted_gradient(ItemRef::Item(&opaque_ramp), false).unwrap();
|
||||||
|
assert!(ramp.evaluate(0.5, settings).a() > 1. - 1e-6 && opacity == 1., "{opacity}");
|
||||||
|
let plain_ramp = half_filled_ramp();
|
||||||
|
let (ramp, settings, opacity) = painted_gradient(ItemRef::Item(&plain_ramp), false).unwrap();
|
||||||
|
assert!(ramp.evaluate(0.5, settings).a() > 1. - 1e-6 && opacity == 0.5, "{opacity}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A square 100 across covered by a `paint`.
|
||||||
|
fn square_covered_by(coverage: Coverage, paint: Graphic) -> List<Vector> {
|
||||||
|
use kurbo::Shape;
|
||||||
|
|
||||||
|
let mut square = Vector::item_from_bezpath(&kurbo::Rect::new(0., 0., 100., 100.).to_path(0.1));
|
||||||
|
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
|
||||||
|
List::new_from_item(square)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A paint of `element` with the effect `operations` stamped on it.
|
||||||
|
fn effected_paint<T>(element: T, operations: impl IntoIterator<Item = graphic_types::EffectOperation>) -> Item<T> {
|
||||||
|
Item::new_from_element(element).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn speckle(amount: f64) -> graphic_types::EffectOperation {
|
||||||
|
graphic_types::EffectOperation::Speckle {
|
||||||
|
amount,
|
||||||
|
distribution: graphic_types::NoiseDistribution::Uniform,
|
||||||
|
monochromatic: false,
|
||||||
|
seed: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paints_draw_by_their_colors_only_where_every_effect_changes_each_color_alone() {
|
||||||
|
use graphic_types::EffectOperation;
|
||||||
|
|
||||||
|
let invert = EffectOperation::Adjustment(Adjustment::Invert);
|
||||||
|
let mut darks_hidden = BlendIfRanges::default();
|
||||||
|
darks_hidden.content.gray.falloff_start = 50.;
|
||||||
|
darks_hidden.content.gray.range_start = 50.;
|
||||||
|
let mut underlying_darks_hidden = BlendIfRanges::default();
|
||||||
|
underlying_darks_hidden.underlying.gray.falloff_start = 50.;
|
||||||
|
underlying_darks_hidden.underlying.gray.range_start = 50.;
|
||||||
|
let twirl = EffectOperation::Twirl {
|
||||||
|
angle: 90.,
|
||||||
|
transform: DAffine2::from_scale(DVec2::splat(100.)),
|
||||||
|
};
|
||||||
|
let pixelate = EffectOperation::Pixelate { cell_size: 10., offset: DVec2::ZERO };
|
||||||
|
|
||||||
|
// Adjustments, Blend Ifs reading the paint's own colors, and effects changing nothing keep to the fast path
|
||||||
|
for operations in [vec![], vec![invert.clone()], vec![EffectOperation::BlendIf(Box::new(darks_hidden)), invert.clone()], vec![speckle(0.)]] {
|
||||||
|
assert!(paint_draws_by_its_colors(&Graphic::Color(effected_paint(Color::BLACK, operations.clone()))), "{operations:?}");
|
||||||
|
assert!(paint_draws_by_its_colors(&Graphic::Gradient(effected_paint(Gradient::default(), operations))));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Effects reading neighbors, positions, or what lies beneath don't, nor do lists holding a paint with one
|
||||||
|
for operation in [speckle(50.), twirl, pixelate, EffectOperation::BlendIf(Box::new(underlying_darks_hidden))] {
|
||||||
|
assert!(!paint_draws_by_its_colors(&Graphic::Color(effected_paint(Color::BLACK, [operation.clone()]))), "{operation:?}");
|
||||||
|
assert!(!paint_draws_by_its_colors(&Graphic::Gradient(effected_paint(Gradient::default(), [operation.clone()]))));
|
||||||
|
|
||||||
|
let colors: List<Color> = [Item::new_from_element(Color::WHITE), effected_paint(Color::BLACK, [operation])].into_iter().collect();
|
||||||
|
assert!(!paint_draws_by_its_colors(&Graphic::ColorList(colors)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// So an inverted fill stays a plain color in SVG, without a pattern
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
square_covered_by(Coverage::new_fill(), Graphic::Color(effected_paint(Color::BLACK, [invert]))).render_svg(&mut render, &RenderParams::default());
|
||||||
|
let svg = render.svg.to_svg_string();
|
||||||
|
assert!(svg.contains(r##"fill="#ffffff""##) && !render.svg_defs.contains("<pattern"), "{svg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn svg_paints_with_effects_beyond_their_colors_render_as_content_clipped_to_the_shape() {
|
||||||
|
use glam::UVec2;
|
||||||
|
use graphic_types::EffectOperation;
|
||||||
|
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
|
||||||
|
|
||||||
|
let in_view = RenderParams {
|
||||||
|
view: Some(Footprint {
|
||||||
|
resolution: UVec2::new(160, 160),
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let stroke = |align: StrokeAlign| Coverage::new_stroke(&Stroke { align, ..Stroke::new(10.) });
|
||||||
|
let coverages = || [Coverage::new_fill(), stroke(StrokeAlign::Center), stroke(StrokeAlign::Inside), stroke(StrokeAlign::Outside)];
|
||||||
|
|
||||||
|
// A grained color or a twirled gradient, which SVG's filters can't draw in a pattern, takes the GPU's image of the vector
|
||||||
|
let twirl = EffectOperation::Twirl {
|
||||||
|
angle: 180.,
|
||||||
|
transform: DAffine2::from_scale_angle_translation(DVec2::splat(100.), 0., DVec2::splat(50.)),
|
||||||
|
};
|
||||||
|
let gradient = || Gradient::from(vec![Color::BLACK, Color::WHITE]);
|
||||||
|
for paint in [Graphic::Color(effected_paint(Color::RED, [speckle(50.)])), Graphic::Gradient(effected_paint(gradient(), [twirl]))] {
|
||||||
|
for coverage in coverages() {
|
||||||
|
let images = deferred_images_of(Graphic::VectorList(square_covered_by(coverage, paint.clone())), &in_view);
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
&images[..],
|
||||||
|
[DeferredImage {
|
||||||
|
content: DeferredContent::Item(Graphic::Vector(_)),
|
||||||
|
..
|
||||||
|
}]
|
||||||
|
),
|
||||||
|
"{} images",
|
||||||
|
images.len()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A masked gradient, which SVG draws, paints natively through a pattern holding the mask
|
||||||
|
let mut left_half = Vector::item_from_bezpath(&kurbo::Shape::to_path(&kurbo::Rect::new(0., 0., 50., 100.), 0.1));
|
||||||
|
left_half.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE))));
|
||||||
|
let mask = EffectOperation::Mask {
|
||||||
|
mask: Graphic::VectorList(List::new_from_item(left_half)),
|
||||||
|
mode: graphic_types::MaskMode::Luminance,
|
||||||
|
density: 100.,
|
||||||
|
feather: 0.,
|
||||||
|
invert: false,
|
||||||
|
};
|
||||||
|
for coverage in coverages() {
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
square_covered_by(coverage, Graphic::Gradient(effected_paint(gradient(), [mask.clone()]))).render_svg(&mut render, &in_view);
|
||||||
|
let (svg, defs) = (render.svg.to_svg_string(), render.svg_defs);
|
||||||
|
assert!(render.deferred_images.is_empty() && render.effect_maps.is_empty(), "{svg}");
|
||||||
|
assert!(svg.contains(r##"="url(#pattern-"##) && defs.contains("<pattern") && defs.contains("<mask"), "{svg}\n{defs}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Where no image can replace markup, the grained color paints through a pattern spanning the stroke as well as the fill
|
||||||
|
let thumbnail = RenderParams { thumbnail: true, ..in_view };
|
||||||
|
let pattern_width = |coverage: Coverage| {
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
square_covered_by(coverage, Graphic::Color(effected_paint(Color::RED, [speckle(50.)]))).render_svg(&mut render, &thumbnail);
|
||||||
|
assert!(render.deferred_images.is_empty(), "{}", render.svg.to_svg_string());
|
||||||
|
|
||||||
|
let defs = render.svg_defs;
|
||||||
|
let pattern = &defs[defs.find("<pattern").expect("the paint draws through a pattern")..];
|
||||||
|
let width = pattern.split(r#"width=""#).nth(1).and_then(|rest| rest.split('"').next()).expect("the pattern has a width");
|
||||||
|
width.parse::<f64>().unwrap()
|
||||||
|
};
|
||||||
|
assert_eq!(pattern_width(Coverage::new_fill()), 100.);
|
||||||
|
for (align, stroked_width) in [(StrokeAlign::Center, 110.), (StrokeAlign::Inside, 100.), (StrokeAlign::Outside, 120.)] {
|
||||||
|
let width = pattern_width(stroke(align));
|
||||||
|
assert!(width >= stroked_width, "{align:?}: {width}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn svg_endless_gradients_and_their_paints_blur_natively_and_pixelate_through_the_gpu() {
|
||||||
|
use glam::UVec2;
|
||||||
|
use graphic_types::EffectOperation;
|
||||||
|
|
||||||
|
let in_view = RenderParams {
|
||||||
|
view: Some(Footprint {
|
||||||
|
resolution: UVec2::new(160, 160),
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Graphic::default(),
|
||||||
|
radius: 4.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
let pixelate = EffectOperation::Pixelate { cell_size: 10., offset: DVec2::ZERO };
|
||||||
|
let gradient = |operation: &EffectOperation| Graphic::Gradient(effected_paint(Gradient::from(vec![Color::BLACK, Color::WHITE]), [operation.clone()]));
|
||||||
|
let render_of = |graphic: Graphic| {
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
List::new_from_element(graphic).render_svg(&mut render, &in_view);
|
||||||
|
render
|
||||||
|
};
|
||||||
|
|
||||||
|
// A gradient layer and a square it fills blur by SVG's own filter
|
||||||
|
for graphic in [gradient(&blur), Graphic::VectorList(square_covered_by(Coverage::new_fill(), gradient(&blur)))] {
|
||||||
|
let render = render_of(graphic);
|
||||||
|
assert!(render.deferred_images.is_empty() && render.svg_defs.contains("feGaussianBlur"), "{}", render.svg_defs);
|
||||||
|
}
|
||||||
|
|
||||||
|
// SVG can't pixelate, so each takes the GPU's image of it
|
||||||
|
for graphic in [gradient(&pixelate), Graphic::VectorList(square_covered_by(Coverage::new_fill(), gradient(&pixelate)))] {
|
||||||
|
let images = render_of(graphic).deferred_images;
|
||||||
|
assert_eq!(images.len(), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn svg_thumbnails_fill_the_patterns_of_moved_shapes_with_their_gradient_paints() {
|
||||||
|
use core_types::transform::RenderQuality;
|
||||||
|
|
||||||
|
// A square moved 500 across, filled by a blurred gradient through a pattern in the square's own space
|
||||||
|
let blur = graphic_types::EffectOperation::Blur {
|
||||||
|
radius_mask: Graphic::default(),
|
||||||
|
radius: 4.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
let mut square = square_covered_by(Coverage::new_fill(), Graphic::Gradient(effected_paint(Gradient::from(vec![Color::BLACK, Color::WHITE]), [blur])));
|
||||||
|
square.set_attribute(ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(500., 0.)));
|
||||||
|
|
||||||
|
let thumbnail = RenderParams {
|
||||||
|
footprint: Footprint::from_bounds([DVec2::new(500., 0.), DVec2::new(600., 100.)], RenderQuality::Full),
|
||||||
|
thumbnail: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
square.render_svg(&mut render, &thumbnail);
|
||||||
|
let defs = render.svg_defs;
|
||||||
|
|
||||||
|
// The gradient's rectangle covers the pattern's tile, from 0 to 100 in the square's space
|
||||||
|
let pattern = &defs[defs.find("<pattern").expect("the paint draws through a pattern")..];
|
||||||
|
let rect = &pattern[pattern.find("<rect").expect("the gradient fills a rectangle")..];
|
||||||
|
let attribute = |name: &str| -> f64 { rect.split(&format!(r#" {name}=""#)).nth(1).and_then(|rest| rest.split('"').next()).unwrap().parse().unwrap() };
|
||||||
|
let (x, width) = (attribute("x"), attribute("width"));
|
||||||
|
assert!(x <= 0. && x + width >= 100., "{rect}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn svg_shortcuts_for_opaque_or_transparent_paints_look_past_effects_that_might_change_alpha() {
|
||||||
|
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
|
||||||
|
use graphic_types::{CoverPlacement, EffectOperation};
|
||||||
|
|
||||||
|
let svg_of = |list: List<Vector>| {
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
list.render_svg(&mut render, &RenderParams::default());
|
||||||
|
(render.svg.to_svg_string(), render.svg_defs)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Black faded away by a Blend If hiding the darks
|
||||||
|
let mut darks_hidden = BlendIfRanges::default();
|
||||||
|
darks_hidden.content.gray.falloff_start = 50.;
|
||||||
|
darks_hidden.content.gray.range_start = 50.;
|
||||||
|
let faded_black = || Graphic::Color(effected_paint(Color::BLACK, [EffectOperation::BlendIf(Box::new(darks_hidden))]));
|
||||||
|
|
||||||
|
// A clipping base filled with it masks what clips to it by its alpha, rather than clipping to its outline as if it were opaque
|
||||||
|
for (base_paint, clips) in [(Graphic::Color(Item::new_from_element(Color::BLACK)), true), (faded_black(), false)] {
|
||||||
|
let mut list = square_covered_by(Coverage::new_fill(), base_paint);
|
||||||
|
let clipped = square_covered_by(Coverage::new_fill(), Graphic::Color(Item::new_from_element(Color::RED)));
|
||||||
|
list.push(clipped.into_iter().next().unwrap().with_attribute(ATTR_CLIPPING_MASK, true));
|
||||||
|
|
||||||
|
let (svg, defs) = svg_of(list);
|
||||||
|
assert_eq!(defs.contains("<clipPath"), clips, "{svg}\n{defs}");
|
||||||
|
assert_eq!(defs.contains("<mask"), !clips, "{svg}\n{defs}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// An outside stroke beneath it isn't hidden within the shape by drawing the fill over it, which would leave its inner half showing through
|
||||||
|
for (fill_paint, paint_order) in [(Graphic::Color(Item::new_from_element(Color::BLACK)), true), (faded_black(), false)] {
|
||||||
|
let mut list = square_covered_by(Coverage::new_fill(), fill_paint);
|
||||||
|
let red = Graphic::Color(Item::new_from_element(Color::RED));
|
||||||
|
let outside = Stroke {
|
||||||
|
align: StrokeAlign::Outside,
|
||||||
|
..Stroke::new(10.)
|
||||||
|
};
|
||||||
|
let mut appearance = list.attribute::<Appearance>(ATTR_APPEARANCE, 0).unwrap().clone();
|
||||||
|
appearance.replace_or_insert(Coverage::new_stroke(&outside), red, DAffine2::IDENTITY, CoverPlacement::Above);
|
||||||
|
list.set_attribute(ATTR_APPEARANCE, 0, appearance);
|
||||||
|
|
||||||
|
let (svg, defs) = svg_of(list);
|
||||||
|
assert_eq!(svg.contains("paint-order"), paint_order, "{svg}");
|
||||||
|
assert_eq!(defs.contains("alignment-"), !paint_order, "{svg}\n{defs}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A transparent stroke made opaque is drawn
|
||||||
|
let transparent_red = Color::from_rgbaf32_unchecked(1., 0., 0., 0.);
|
||||||
|
let made_opaque = Graphic::Color(effected_paint(transparent_red, [EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. })]));
|
||||||
|
let (svg, _) = svg_of(square_covered_by(Coverage::new_stroke(&Stroke::new(4.)), made_opaque));
|
||||||
|
assert!(svg.contains(r##"stroke="#ff0000""##), "{svg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn svg_fills_drawn_apart_from_an_aligned_stroke_share_the_shapes_opacity_and_blend_mode() {
|
||||||
|
use graphic_types::CoverPlacement;
|
||||||
|
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
|
||||||
|
|
||||||
|
// A translucent fill can't hide an outside stroke's inner half, so it's drawn as a path of its own
|
||||||
|
let mut list = square_covered_by(Coverage::new_fill(), Graphic::Color(Item::new_from_element(Color::RED.with_alpha(0.5))));
|
||||||
|
let outside = Stroke {
|
||||||
|
align: StrokeAlign::Outside,
|
||||||
|
..Stroke::new(10.)
|
||||||
|
};
|
||||||
|
let mut appearance = list.attribute::<Appearance>(ATTR_APPEARANCE, 0).unwrap().clone();
|
||||||
|
appearance.replace_or_insert(
|
||||||
|
Coverage::new_stroke(&outside),
|
||||||
|
Graphic::Color(Item::new_from_element(Color::BLUE)),
|
||||||
|
DAffine2::IDENTITY,
|
||||||
|
CoverPlacement::Above,
|
||||||
|
);
|
||||||
|
list.set_attribute(ATTR_APPEARANCE, 0, appearance);
|
||||||
|
list.set_attribute(ATTR_OPACITY, 0, 0.5);
|
||||||
|
list.set_attribute(ATTR_BLEND_MODE, 0, BlendMode::Multiply);
|
||||||
|
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
list.render_svg(&mut render, &RenderParams::default());
|
||||||
|
let svg = render.svg.to_svg_string();
|
||||||
|
|
||||||
|
// Both paths lie in one group taking the opacity and blend mode, which neither takes again
|
||||||
|
let group = &svg[svg.find("<g").expect("the paths are grouped")..];
|
||||||
|
assert!(group.matches("<path").count() == 2, "{svg}");
|
||||||
|
assert!(svg.matches(r#" opacity="0.5""#).count() == 1 && group.starts_with(r#"<g opacity="0.5""#), "{svg}");
|
||||||
|
assert!(svg.matches("multiply").count() == 1, "{svg}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn svg_clipping_bases_filled_by_an_inherited_paint_clip_by_its_alpha() {
|
||||||
|
use graphic_types::EffectOperation;
|
||||||
|
|
||||||
|
// Black faded away by a Blend If hiding the darks, or plain opaque black
|
||||||
|
let mut darks_hidden = BlendIfRanges::default();
|
||||||
|
darks_hidden.content.gray.falloff_start = 50.;
|
||||||
|
darks_hidden.content.gray.range_start = 50.;
|
||||||
|
let faded_black = Graphic::Color(effected_paint(Color::BLACK, [EffectOperation::BlendIf(Box::new(darks_hidden))]));
|
||||||
|
let opaque_black = Graphic::Color(Item::new_from_element(Color::BLACK));
|
||||||
|
|
||||||
|
// A group's fill cascades to a square without its own, which a red square clips to
|
||||||
|
for (inherited_fill, clips) in [(opaque_black, true), (faded_black, false)] {
|
||||||
|
let mut squares = square_covered_by(Coverage::new_fill(), Graphic::default());
|
||||||
|
squares.set_attribute(ATTR_APPEARANCE, 0, Appearance::default());
|
||||||
|
let clipped = square_covered_by(Coverage::new_fill(), Graphic::Color(Item::new_from_element(Color::RED)));
|
||||||
|
squares.push(clipped.into_iter().next().unwrap().with_attribute(ATTR_CLIPPING_MASK, true));
|
||||||
|
let group = Item::new_from_element(Graphic::VectorList(squares)).with_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), inherited_fill));
|
||||||
|
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
List::new_from_item(group).render_svg(&mut render, &RenderParams::default());
|
||||||
|
let (svg, defs) = (render.svg.to_svg_string(), render.svg_defs);
|
||||||
|
assert_eq!(defs.contains("<clipPath"), clips, "{svg}\n{defs}");
|
||||||
|
assert_eq!(defs.contains("<mask"), !clips, "{svg}\n{defs}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn svg_endless_colors_carry_out_filters_over_the_area_in_view_in_nested_groups() {
|
fn svg_endless_colors_carry_out_filters_over_the_area_in_view_in_nested_groups() {
|
||||||
use glam::UVec2;
|
use glam::UVec2;
|
||||||
|
|||||||
@@ -98,6 +98,8 @@ impl SvgFilterPrimitives {
|
|||||||
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
|
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
|
||||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
EffectOperation::MinimumMaximum { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
||||||
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
|
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
|
||||||
|
// No SVG primitive ranks values, and the GPU's median runs on the content's own grid besides
|
||||||
|
EffectOperation::Median { .. } => self.map_showing(capture, image),
|
||||||
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
|
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
|
||||||
EffectOperation::Speckle { amount, distribution, .. } => self.speckle(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
EffectOperation::Speckle { amount, distribution, .. } => self.speckle(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
||||||
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
|
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
|
||||||
|
|||||||
@@ -584,9 +584,12 @@ impl<'a> VelloSceneBuilder<'a> {
|
|||||||
square && !operation.changes_nothing()
|
square && !operation.changes_nothing()
|
||||||
});
|
});
|
||||||
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
|
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
|
||||||
let (frame_to_device, lengths_to_frame) = match follows_viewport {
|
// Effects that don't commute with resampling, like a median, work on the content's own grid of a texel to each unit of the effect space, then resample to the view
|
||||||
true => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
let content_grid_resolution = effects.content_grid_resolution();
|
||||||
false => {
|
let (frame_to_device, lengths_to_frame) = match (content_grid_resolution, follows_viewport) {
|
||||||
|
(Some(_), _) => (effect_to_device, DMat2::IDENTITY),
|
||||||
|
(None, true) => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
||||||
|
(None, false) => {
|
||||||
let density = largest_stretch(effect_to_device.matrix2);
|
let density = largest_stretch(effect_to_device.matrix2);
|
||||||
(effect_to_device * DAffine2::from_scale(DVec2::splat(1. / density)), DMat2::from_diagonal(DVec2::splat(density)))
|
(effect_to_device * DAffine2::from_scale(DVec2::splat(1. / density)), DMat2::from_diagonal(DVec2::splat(density)))
|
||||||
}
|
}
|
||||||
@@ -647,7 +650,15 @@ impl<'a> VelloSceneBuilder<'a> {
|
|||||||
|
|
||||||
// A region too large for one texture, or for its memory, renders at a lower resolution, which the blurs and shadows that make it so large hide.
|
// A region too large for one texture, or for its memory, renders at a lower resolution, which the blurs and shadows that make it so large hide.
|
||||||
// Its size rounds up to a size class so a group that moves between renders keeps reusing the same textures.
|
// Its size rounds up to a size class so a group that moves between renders keeps reusing the same textures.
|
||||||
let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt()).min(1.);
|
let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt());
|
||||||
|
let resolution = resolution.min(content_grid_resolution.unwrap_or(1.)).min(1.);
|
||||||
|
|
||||||
|
// A coarsened content grid keeps its texels on one lattice of the effect space, so they don't slide across the content as the view pans
|
||||||
|
if content_grid_resolution.is_some() && resolution < 1. {
|
||||||
|
let snap = |coordinate: f64| (coordinate * resolution).floor() / resolution;
|
||||||
|
region = Rect::new(snap(region.x0), snap(region.y0), region.x1, region.y1);
|
||||||
|
}
|
||||||
|
|
||||||
let size_along = |length: f64| ((length * resolution).ceil() as u32).next_multiple_of(EFFECTS_SIZE_CLASS).min(max_size);
|
let size_along = |length: f64| ((length * resolution).ceil() as u32).next_multiple_of(EFFECTS_SIZE_CLASS).min(max_size);
|
||||||
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
||||||
let origin = region.origin().to_vec2();
|
let origin = region.origin().to_vec2();
|
||||||
|
|||||||
@@ -211,7 +211,7 @@ fn a_clip_path_becomes_a_hidden_clipper_beneath_the_content_it_clips() -> Result
|
|||||||
let content = converted(r#"<clipPath id="clip"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)"><rect width="8" height="8"/></g>"#)?;
|
let content = converted(r#"<clipPath id="clip"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)"><rect width="8" height="8"/></g>"#)?;
|
||||||
|
|
||||||
let clipped = group(&content, 0);
|
let clipped = group(&content, 0);
|
||||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
|
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
|
||||||
assert_eq!(clipped.and_then(|clipped| clipped.attribute::<f64>(ATTR_OPACITY_FILL, 0)), Some(&0.));
|
assert_eq!(clipped.and_then(|clipped| clipped.attribute::<f64>(ATTR_OPACITY_FILL, 0)), Some(&0.));
|
||||||
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -314,7 +314,7 @@ fn a_mask_region_that_cuts_its_content_clips_the_masked_content() -> Result<(),
|
|||||||
let within_region = group(&content, 0).and_then(|masked| masked.element(1));
|
let within_region = group(&content, 0).and_then(|masked| masked.element(1));
|
||||||
assert!(within_region.is_some_and(Graphic::had_clip_enabled));
|
assert!(within_region.is_some_and(Graphic::had_clip_enabled));
|
||||||
let clipped = within_region.and_then(Graphic::as_graphic_list);
|
let clipped = within_region.and_then(Graphic::as_graphic_list);
|
||||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
|
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
|
||||||
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ mod buffer;
|
|||||||
mod context;
|
mod context;
|
||||||
mod deferred_svg_images;
|
mod deferred_svg_images;
|
||||||
mod pipeline;
|
mod pipeline;
|
||||||
|
mod raster_readback;
|
||||||
mod texture_cache;
|
mod texture_cache;
|
||||||
pub mod texture_conversion;
|
pub mod texture_conversion;
|
||||||
mod vello_adjustments;
|
mod vello_adjustments;
|
||||||
@@ -75,6 +76,19 @@ impl WgpuExecutor {
|
|||||||
/// Renders the document scene `draw` draws, with its content placed by `view`, into a new texture of `size` with straight alpha.
|
/// Renders the document scene `draw` draws, with its content placed by `view`, into a new texture of `size` with straight alpha.
|
||||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
||||||
pub fn render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
pub fn render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
||||||
|
Ok(self.render_vello_and_failure(size, view, draw)?.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`Self::render_vello`], but failing rather than leaving transparent a part Vello GPU fails to render, for a render read back as data.
|
||||||
|
pub fn try_render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
||||||
|
match self.render_vello_and_failure(size, view, draw)? {
|
||||||
|
(_, Some(failure)) => anyhow::bail!("Vello GPU failed to render: {failure}"),
|
||||||
|
(texture, None) => Ok(texture),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The texture [`Self::render_vello`] renders, with the first failure that left part of it transparent.
|
||||||
|
fn render_vello_and_failure(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<(Texture, Option<String>)> {
|
||||||
let limit = self.context().device.limits().max_texture_dimension_2d;
|
let limit = self.context().device.limits().max_texture_dimension_2d;
|
||||||
if size.x > limit || size.y > limit {
|
if size.x > limit || size.y > limit {
|
||||||
anyhow::bail!("Render size {size} exceeds the GPU's texture size limit of {limit}");
|
anyhow::bail!("Render size {size} exceeds the GPU's texture size limit of {limit}");
|
||||||
@@ -84,11 +98,12 @@ impl WgpuExecutor {
|
|||||||
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
|
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
|
||||||
|
|
||||||
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
|
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
self.inner
|
let failure = self
|
||||||
|
.inner
|
||||||
.vello_renderer
|
.vello_renderer
|
||||||
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
|
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
|
||||||
|
|
||||||
Ok(texture)
|
Ok((texture, failure))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Renders a scene drawn beforehand, on a canvas the caller owns, into a new texture of the scene's size with straight alpha.
|
/// Renders a scene drawn beforehand, on a canvas the caller owns, into a new texture of the scene's size with straight alpha.
|
||||||
|
|||||||
@@ -0,0 +1,648 @@
|
|||||||
|
use crate::WgpuExecutor;
|
||||||
|
use crate::texture_conversion::download_row_bytes;
|
||||||
|
use core_types::blending::BlendMode;
|
||||||
|
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||||||
|
use core_types::transform::Footprint;
|
||||||
|
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||||
|
use glam::{DAffine2, DVec2, UVec2};
|
||||||
|
use graphic_types::Graphic;
|
||||||
|
use graphic_types::effects::{EffectOperation, Effects};
|
||||||
|
use raster_kernels::adjustments::preserves_alpha;
|
||||||
|
use raster_kernels::raster_effects::adjusted_raster;
|
||||||
|
use raster_types::{CPU, Image, Pixels, Raster};
|
||||||
|
use rendering::{Render, RenderOutputType, RenderParams, leading_raster_adjustments};
|
||||||
|
|
||||||
|
/// The most pixels an image may grow to with the margin its effects paint into, beyond which the margin is cut short.
|
||||||
|
const MAX_PIXELS_WITH_MARGIN: f64 = (1 << 24) as f64;
|
||||||
|
|
||||||
|
/// The GPU's limits that a readback's renders and downloads stay within.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
struct ReadbackLimits {
|
||||||
|
/// The most pixels across or down a texture may have, which an image larger than it is downscaled to when uploaded whole.
|
||||||
|
texture_size: u32,
|
||||||
|
/// The most bytes a download buffer may hold.
|
||||||
|
buffer_size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReadbackLimits {
|
||||||
|
fn of(executor: &WgpuExecutor) -> Self {
|
||||||
|
let limits = executor.context().device.limits();
|
||||||
|
Self {
|
||||||
|
texture_size: limits.max_texture_dimension_2d,
|
||||||
|
buffer_size: limits.max_buffer_size,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The largest tile, at most `max` pixels across and down, that a texture and its download buffer can hold, or `None` if not even one pixel fits.
|
||||||
|
fn tile_size(&self, max: UVec2) -> Option<UVec2> {
|
||||||
|
// Each row's bytes are padded to 256, which 64 pixels fill
|
||||||
|
let widest_row = (self.buffer_size / wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as u64 * 64).min(u32::MAX as u64) as u32;
|
||||||
|
let width = max.x.min(self.texture_size).min(widest_row);
|
||||||
|
if width == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let height = max.y.min(self.texture_size).min((self.buffer_size / download_row_bytes(width) as u64).min(u32::MAX as u64) as u32);
|
||||||
|
(height > 0).then_some(UVec2::new(width, height))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WgpuExecutor {
|
||||||
|
/// The image's pixels as it's drawn, with its effects and fill carried out at its own pixel grid, grown by whole pixels to hold what they paint past its edges.
|
||||||
|
/// The opacity and blend mode stay for whatever draws the result.
|
||||||
|
pub async fn read_back(&self, item: Item<Raster<CPU>>) -> anyhow::Result<Item<Pixels>> {
|
||||||
|
self.read_back_within(item, ReadbackLimits::of(self)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`Self::read_back`], within the GPU `limits`.
|
||||||
|
async fn read_back_within(&self, item: Item<Raster<CPU>>, limits: ReadbackLimits) -> anyhow::Result<Item<Pixels>> {
|
||||||
|
let effects: Effects = item.attribute_cloned_or_default(ATTR_EFFECTS);
|
||||||
|
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
|
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.);
|
||||||
|
let size = UVec2::new(item.element().width, item.element().height);
|
||||||
|
|
||||||
|
// Nothing to carry out, or nothing to carry it out on
|
||||||
|
if (effects.change_nothing() && fill >= 1.) || size.cmpeq(UVec2::ZERO).any() || !transform.matrix2.determinant().is_normal() || !transform.is_finite() {
|
||||||
|
let raster = item.element().clone();
|
||||||
|
return Ok(carried_out(item, raster));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(adjusted) = adjusted_without_render(&item, &effects, fill) {
|
||||||
|
return Ok(carried_out(item, adjusted));
|
||||||
|
}
|
||||||
|
|
||||||
|
let reach = effects_reach(&effects, size.as_dvec2());
|
||||||
|
if !reach.is_finite() {
|
||||||
|
anyhow::bail!("The effects on a {} by {} image reach too far to render", size.x, size.y);
|
||||||
|
}
|
||||||
|
let margin = capped_margin(reach, size.as_dvec2());
|
||||||
|
let raster = self.render_at_pixel_grid(&item, &effects, transform, margin, reach, limits).await?;
|
||||||
|
|
||||||
|
let unit_margin = margin / size.as_dvec2();
|
||||||
|
let mut item = carried_out(item, raster);
|
||||||
|
item.set_attribute(
|
||||||
|
ATTR_TRANSFORM,
|
||||||
|
transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin),
|
||||||
|
);
|
||||||
|
Ok(item)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders the raster `item` placed by `transform` with its `effects`, one pixel of the render per pixel of its image, grown by `margin` pixels along each axis.
|
||||||
|
/// A render larger than the GPU's `limits` allow is drawn in tiles. When the whole image is too large to upload, each is drawn from a crop holding the pixels the effects `reach` past it.
|
||||||
|
async fn render_at_pixel_grid(&self, item: &Item<Raster<CPU>>, effects: &Effects, transform: DAffine2, margin: DVec2, reach: DVec2, limits: ReadbackLimits) -> anyhow::Result<Raster<CPU>> {
|
||||||
|
let image = item.element();
|
||||||
|
let size = UVec2::new(image.width, image.height);
|
||||||
|
let grown_size = size + 2 * margin.as_uvec2();
|
||||||
|
let document_to_pixels = DAffine2::from_translation(margin) * DAffine2::from_scale(size.as_dvec2()) * transform.inverse();
|
||||||
|
|
||||||
|
// The content on its own, without the opacity and blend mode that act on its effects' result as a whole
|
||||||
|
let mut content = item.clone();
|
||||||
|
content.remove_attribute::<f64>(ATTR_OPACITY);
|
||||||
|
content.remove_attribute::<BlendMode>(ATTR_BLEND_MODE);
|
||||||
|
|
||||||
|
// Each tile draws a crop of an image too large to upload whole, holding the pixels its effects read, unless they depend on the whole image's extent
|
||||||
|
let too_large_to_upload = size.cmpgt(UVec2::splat(limits.texture_size)).any();
|
||||||
|
let crops = too_large_to_upload && !effects.any_takes_frame() && !effects.reach_depends_on_size();
|
||||||
|
if too_large_to_upload && !crops {
|
||||||
|
log::warn!(
|
||||||
|
"A {} by {} image is read back at a lower resolution, since it's too large for the GPU and its effects depend on its whole extent",
|
||||||
|
size.x,
|
||||||
|
size.y
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// A crop holds what the effects reach on both sides of its tile, which has to leave a texture room for at least a pixel, checked before the reach becomes an integer
|
||||||
|
let max_tile_size = match crops {
|
||||||
|
true => {
|
||||||
|
let room = DVec2::splat(limits.texture_size as f64) - 2. * reach;
|
||||||
|
if !room.cmpge(DVec2::ONE).all() {
|
||||||
|
anyhow::bail!("The effects on a {} by {} image reach too far past each pixel to render it in tiles the GPU can hold", size.x, size.y);
|
||||||
|
}
|
||||||
|
room.floor().as_uvec2()
|
||||||
|
}
|
||||||
|
false => grown_size,
|
||||||
|
};
|
||||||
|
let (margin, reach) = (margin.as_uvec2(), reach.as_uvec2());
|
||||||
|
let Some(tile_size) = limits.tile_size(max_tile_size) else {
|
||||||
|
anyhow::bail!("The GPU's textures and buffers can't hold a tile of a {} by {} image's render with its effects", size.x, size.y);
|
||||||
|
};
|
||||||
|
|
||||||
|
// The raster's render carries out leading adjustments changing alpha on its image's own pixels, which a crop's group can't, so they're carried out first
|
||||||
|
if crops {
|
||||||
|
let leading_adjustments = leading_raster_adjustments(&content);
|
||||||
|
if leading_adjustments.iter().any(|adjustment| !preserves_alpha(adjustment)) {
|
||||||
|
let adjusted = adjusted_raster(content.element(), &leading_adjustments);
|
||||||
|
let (_, attributes) = content.into_parts();
|
||||||
|
content = Item::from_parts(adjusted, attributes);
|
||||||
|
content.set_attribute(ATTR_EFFECTS, effects.after(leading_adjustments.len()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let whole = List::new_from_item(content.clone());
|
||||||
|
if !crops && grown_size.cmple(tile_size).all() {
|
||||||
|
return self.render_tile(&whole, document_to_pixels, grown_size).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut pixels = Image::try_new(grown_size.x, grown_size.y, Color::TRANSPARENT)?;
|
||||||
|
for tile_y in (0..grown_size.y).step_by(tile_size.y as usize) {
|
||||||
|
for tile_x in (0..grown_size.x).step_by(tile_size.x as usize) {
|
||||||
|
let origin = UVec2::new(tile_x, tile_y);
|
||||||
|
let size_in_tile = (grown_size - origin).min(tile_size);
|
||||||
|
let tile_to_pixels = DAffine2::from_translation(-origin.as_dvec2()) * document_to_pixels;
|
||||||
|
|
||||||
|
let tile = match crops {
|
||||||
|
// The tile spans the image's pixels from `origin - margin`, and its effects read up to their reach past it
|
||||||
|
true => {
|
||||||
|
let start = origin.saturating_sub(margin + reach);
|
||||||
|
let end = (origin + size_in_tile + reach).saturating_sub(margin).min(size);
|
||||||
|
self.render_tile(&cropped(&content, start, end), tile_to_pixels, size_in_tile).await?
|
||||||
|
}
|
||||||
|
false => self.render_tile(&whole, tile_to_pixels, size_in_tile).await?,
|
||||||
|
};
|
||||||
|
|
||||||
|
for row in 0..size_in_tile.y as usize {
|
||||||
|
let start = (origin.y as usize + row) * grown_size.x as usize + origin.x as usize;
|
||||||
|
let tile_row = &tile.data[row * size_in_tile.x as usize..(row + 1) * size_in_tile.x as usize];
|
||||||
|
pixels.data[start..start + size_in_tile.x as usize].copy_from_slice(tile_row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Raster::new_cpu(pixels))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders the `content` into an image of `size` pixels, which `document_to_pixels` places the document in, and reads it back.
|
||||||
|
async fn render_tile(&self, content: &(impl Render + Sync), document_to_pixels: DAffine2, size: UVec2) -> anyhow::Result<Raster<CPU>> {
|
||||||
|
let render_params = RenderParams {
|
||||||
|
render_output_type: RenderOutputType::Vello,
|
||||||
|
footprint: Footprint {
|
||||||
|
transform: document_to_pixels,
|
||||||
|
resolution: size,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
for_export: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let texture = self.try_render_vello(size, document_to_pixels, &mut |scene| content.render_to_vello(scene, DAffine2::IDENTITY, &render_params))?;
|
||||||
|
|
||||||
|
self.try_download(Raster::new_gpu(texture)).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `item` with its image replaced by the `raster` its effects and fill are carried out in, without the attributes holding them.
|
||||||
|
fn carried_out(item: Item<Raster<CPU>>, raster: Raster<CPU>) -> Item<Pixels> {
|
||||||
|
let (_, attributes) = item.into_parts();
|
||||||
|
let mut item = Item::from_parts(Pixels::new(raster), attributes);
|
||||||
|
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||||
|
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
|
||||||
|
item
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The image with its `effects` and `fill` carried out on the CPU if the effects are all adjustments its render carries out on its own pixels, or `None` if any needs a render.
|
||||||
|
/// The CPU keeps the adjustments' full precision, including values past 0 to 1 and colors beneath zero alpha, which an 8-bit download would lose.
|
||||||
|
fn adjusted_without_render(item: &Item<Raster<CPU>>, effects: &Effects, fill: f64) -> Option<Raster<CPU>> {
|
||||||
|
let adjustments = leading_raster_adjustments(item);
|
||||||
|
if adjustments.len() < effects.operations().count() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Under a partial fill, the leading adjustments all keep alpha, so fading after them matches fading before
|
||||||
|
let mut adjusted = adjusted_raster(item.element(), &adjustments);
|
||||||
|
if fill < 1. {
|
||||||
|
adjusted.data_mut().data.iter_mut().for_each(|color| *color = color.with_alpha(color.a() * fill as f32));
|
||||||
|
}
|
||||||
|
Some(adjusted)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The raster `content` drawn from only its image's pixels from `start` up to `end`, at their own resolution where they lie in the whole image.
|
||||||
|
/// The crop sits within a group taking the content's placement and effects, so the effects measure and place what they draw as for the whole image.
|
||||||
|
fn cropped(content: &Item<Raster<CPU>>, start: UVec2, end: UVec2) -> List<Graphic> {
|
||||||
|
let image = content.element();
|
||||||
|
let (size, crop_size) = (UVec2::new(image.width, image.height), end.saturating_sub(start));
|
||||||
|
if crop_size.cmpeq(UVec2::ZERO).any() {
|
||||||
|
return List::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let data = (start.y..end.y)
|
||||||
|
.flat_map(|y| {
|
||||||
|
let row = (y * size.x) as usize;
|
||||||
|
image.data[row + start.x as usize..row + end.x as usize].iter().copied()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let crop = Image {
|
||||||
|
width: crop_size.x,
|
||||||
|
height: crop_size.y,
|
||||||
|
data,
|
||||||
|
};
|
||||||
|
let placement = DAffine2::from_translation(start.as_dvec2() / size.as_dvec2()) * DAffine2::from_scale(crop_size.as_dvec2() / size.as_dvec2());
|
||||||
|
let crop = Item::new_from_element(Raster::new_cpu(crop)).with_attribute(ATTR_TRANSFORM, placement);
|
||||||
|
|
||||||
|
let (_, attributes) = content.clone().into_parts();
|
||||||
|
List::new_from_item(Item::from_parts(Graphic::RasterCPU(Box::new(crop)), attributes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How far, in whole pixels along each axis of an image of `size` pixels, its `effects` paint and read past each pixel and its edges.
|
||||||
|
fn effects_reach(effects: &Effects, size: DVec2) -> DVec2 {
|
||||||
|
// The content's unit square spans the image's pixels
|
||||||
|
let content_to_pixels = DAffine2::from_scale(size);
|
||||||
|
let reach = (effects.reach_around(content_to_pixels, [DVec2::ZERO, size], 0.) + effects.read_beyond_painted(content_to_pixels)).ceil();
|
||||||
|
|
||||||
|
// A feather fades the content toward its edges, finding them against the pixels past them
|
||||||
|
match effects.operations().any(|operation| matches!(operation, EffectOperation::Feather { distance } if distance > 0.)) {
|
||||||
|
true => reach.max(DVec2::ONE),
|
||||||
|
false => reach,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The margin an image of `size` pixels grows by to hold its effects' `reach`, cut short evenly past [`MAX_PIXELS_WITH_MARGIN`].
|
||||||
|
fn capped_margin(reach: DVec2, size: DVec2) -> DVec2 {
|
||||||
|
if (size + 2. * reach).element_product() <= MAX_PIXELS_WITH_MARGIN {
|
||||||
|
return reach;
|
||||||
|
}
|
||||||
|
|
||||||
|
let margin = (reach * margin_fraction_that_fits(size, reach)).floor();
|
||||||
|
if margin.max_element() < reach.max_element() {
|
||||||
|
log::warn!(
|
||||||
|
"The effects on a {} by {} image end at a hard edge {} pixels past it, short of the {} they reach, since the image can't grow past {MAX_PIXELS_WITH_MARGIN} pixels",
|
||||||
|
size.x,
|
||||||
|
size.y,
|
||||||
|
margin.max_element(),
|
||||||
|
reach.max_element()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
margin
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fraction of `margin` that grows an image of `size` to [`MAX_PIXELS_WITH_MARGIN`], or 0 if the image alone already reaches it.
|
||||||
|
fn margin_fraction_that_fits(size: DVec2, margin: DVec2) -> f64 {
|
||||||
|
// The positive root of (width + 2 × fraction × margin width) × (height + 2 × fraction × margin height) = the limit
|
||||||
|
let quadratic = 4. * margin.x * margin.y;
|
||||||
|
let linear = 2. * (size.x * margin.y + size.y * margin.x);
|
||||||
|
let constant = size.element_product() - MAX_PIXELS_WITH_MARGIN;
|
||||||
|
if constant >= 0. || linear <= 0. {
|
||||||
|
return 0.;
|
||||||
|
}
|
||||||
|
|
||||||
|
let fraction = match quadratic > 0. {
|
||||||
|
true => (-linear + (linear * linear - 4. * quadratic * constant).sqrt()) / (2. * quadratic),
|
||||||
|
false => -constant / linear,
|
||||||
|
};
|
||||||
|
fraction.clamp(0., 1.)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use core_types::color::SRGBA8;
|
||||||
|
use core_types::list::ATTR_APPEARANCE;
|
||||||
|
use futures::executor::block_on;
|
||||||
|
use graphic_types::vector_types::vector::style::StrokeAlign;
|
||||||
|
use graphic_types::{Appearance, Coverage, Effect, Graphic, MaskMode, Vector, stamp_effect};
|
||||||
|
use vello_gpu::kurbo::{Rect, Shape};
|
||||||
|
|
||||||
|
/// The executor these tests share, or `None` without a GPU.
|
||||||
|
fn executor() -> Option<&'static WgpuExecutor> {
|
||||||
|
static EXECUTOR: std::sync::OnceLock<Option<WgpuExecutor>> = std::sync::OnceLock::new();
|
||||||
|
EXECUTOR.get_or_init(|| block_on(crate::WgpuContext::for_tests()).and_then(WgpuExecutor::with_context)).as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The size in the document of the pixels of an image scaled unevenly, 1 unit wide and 4 tall.
|
||||||
|
const TALL_PIXEL: DVec2 = DVec2::new(1., 4.);
|
||||||
|
|
||||||
|
/// An image of 20 by 20 pixels, each `pixel_size` in the document, colored by `color` at each pixel's column and row, with its corner at (100, 50).
|
||||||
|
fn image_of_pixels(pixel_size: DVec2, color: impl Fn(u32, u32) -> Color, effects: &[EffectOperation]) -> Item<Raster<CPU>> {
|
||||||
|
let data = (0..20 * 20).map(|index| color(index % 20, index / 20)).collect();
|
||||||
|
let transform = DAffine2::from_translation(DVec2::new(100., 50.)) * DAffine2::from_scale(20. * pixel_size);
|
||||||
|
|
||||||
|
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: 20, height: 20, data })).with_attribute(ATTR_TRANSFORM, transform);
|
||||||
|
for effect in effects {
|
||||||
|
stamp_effect(&mut item, Effect::new(effect));
|
||||||
|
}
|
||||||
|
item
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The read-back image's color at a `point` in the document, transparent past its edges.
|
||||||
|
fn color_at(image: &Item<Pixels>, point: DVec2) -> Color {
|
||||||
|
let raster = image.element();
|
||||||
|
let transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
|
let pixel = (transform.inverse().transform_point2(point) * DVec2::new(raster.width as f64, raster.height as f64)).floor();
|
||||||
|
|
||||||
|
let inside = pixel.cmpge(DVec2::ZERO).all() && pixel.x < raster.width as f64 && pixel.y < raster.height as f64;
|
||||||
|
if !inside {
|
||||||
|
return Color::TRANSPARENT;
|
||||||
|
}
|
||||||
|
raster.data[pixel.y as usize * raster.width as usize + pixel.x as usize]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_black(color: Color) -> bool {
|
||||||
|
color.a() > 0.98 && color.r().max(color.g()).max(color.b()) < 0.02
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_white(color: Color) -> bool {
|
||||||
|
color.a() > 0.98 && color.r().min(color.g()).min(color.b()) > 0.98
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_clear(color: Color) -> bool {
|
||||||
|
color.a() < 0.02
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_image_without_effects_comes_back_as_it_is() {
|
||||||
|
let Some(executor) = executor() else { return };
|
||||||
|
|
||||||
|
let image = image_of_pixels(TALL_PIXEL, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 0.25), &[]);
|
||||||
|
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(**read_back.element(), *image.element().data());
|
||||||
|
assert_eq!(
|
||||||
|
read_back.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM),
|
||||||
|
image.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fill fades the pixels read back the same whether no effects or an empty list of them is stamped, and goes with the effects while the other attributes stay.
|
||||||
|
#[test]
|
||||||
|
fn a_fill_fades_the_pixels_with_or_without_effects() {
|
||||||
|
let Some(executor) = executor() else { return };
|
||||||
|
|
||||||
|
let mut without_effects = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &[]);
|
||||||
|
without_effects.set_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||||
|
without_effects.set_attribute(ATTR_OPACITY, 0.25);
|
||||||
|
without_effects.set_attribute(ATTR_BLEND_MODE, BlendMode::Multiply);
|
||||||
|
without_effects.set_attribute("unrelated", 7.);
|
||||||
|
let mut with_no_effects = without_effects.clone();
|
||||||
|
with_no_effects.set_attribute(ATTR_EFFECTS, Effects::default());
|
||||||
|
|
||||||
|
for image in [without_effects, with_no_effects] {
|
||||||
|
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
||||||
|
|
||||||
|
let faded: Vec<_> = image.element().data.iter().map(|color| color.with_alpha(0.5)).collect();
|
||||||
|
assert_eq!(read_back.element().data, faded);
|
||||||
|
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||||
|
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
||||||
|
|
||||||
|
assert_eq!(read_back.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 0.25);
|
||||||
|
assert_eq!(read_back.attribute_cloned_or_default::<BlendMode>(ATTR_BLEND_MODE), BlendMode::Multiply);
|
||||||
|
assert_eq!(read_back.attribute_cloned_or::<f64>("unrelated", 0.), 7.);
|
||||||
|
assert_eq!(
|
||||||
|
read_back.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM),
|
||||||
|
image.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Levels adjustment bending each color channel its own way, and alpha by `alpha_midtones`.
|
||||||
|
fn uneven_levels(alpha_midtones: f64) -> graphic_types::Adjustment {
|
||||||
|
use graphic_types::adjustment::{LevelsRecord, LevelsSettings};
|
||||||
|
|
||||||
|
let record = |midtones, output_maximums| LevelsRecord {
|
||||||
|
shadows: 0.,
|
||||||
|
midtones,
|
||||||
|
highlights: 100.,
|
||||||
|
output_minimums: 0.,
|
||||||
|
output_maximums,
|
||||||
|
};
|
||||||
|
graphic_types::Adjustment::Levels(Box::new(LevelsSettings {
|
||||||
|
composite: record(1.4, 100.),
|
||||||
|
red: record(0.7, 90.),
|
||||||
|
green: record(1., 100.),
|
||||||
|
blue: record(1.2, 100.),
|
||||||
|
alpha: record(alpha_midtones, 100.),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn adjustments_carried_out_on_the_cpu_match_their_render() {
|
||||||
|
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||||
|
|
||||||
|
// Opaque, so the render's straight alpha keeps every color
|
||||||
|
let operations = [uneven_levels(1.), graphic_types::Adjustment::Invert].map(EffectOperation::Adjustment);
|
||||||
|
let image = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &operations);
|
||||||
|
let (effects, transform) = (image.attribute::<Effects>(ATTR_EFFECTS).unwrap().clone(), image.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||||
|
|
||||||
|
let on_the_cpu = adjusted_without_render(&image, &effects, 1.).expect("adjustments alone need no render");
|
||||||
|
let rendered = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, DVec2::ZERO, limits)).unwrap();
|
||||||
|
|
||||||
|
// The render carries out leading adjustments on the image's own pixels too, then draws them into an 8-bit texture
|
||||||
|
assert_alike(&on_the_cpu, &rendered, ADJUSTMENT_TOLERANCE);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn adjustments_alone_are_carried_out_on_the_cpu() {
|
||||||
|
use graphic_types::Adjustment;
|
||||||
|
|
||||||
|
let Some(executor) = executor() else { return };
|
||||||
|
|
||||||
|
let adjustments = [uneven_levels(2.2), Adjustment::Invert];
|
||||||
|
let operations: Vec<_> = adjustments.iter().cloned().map(EffectOperation::Adjustment).collect();
|
||||||
|
|
||||||
|
// A Levels stack bending alpha, with fine steps 8 bits can't hold
|
||||||
|
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 1000., y as f32 / 20., 0.5, (x + y) as f32 / 40.);
|
||||||
|
let image = image_of_pixels(DVec2::ONE, color, &operations);
|
||||||
|
let expected = adjusted_raster(image.element(), &adjustments);
|
||||||
|
let read_back = block_on(executor.read_back(image)).unwrap();
|
||||||
|
assert_eq!(**read_back.element(), *expected.data());
|
||||||
|
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||||
|
|
||||||
|
// Inverting keeps alpha, so a partial fill fades the inverted colors, which stay beneath zero alpha
|
||||||
|
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 20., 0.25, 1., if y < 10 { 0. } else { 0.8 });
|
||||||
|
let mut image = image_of_pixels(DVec2::ONE, color, &[EffectOperation::Adjustment(Adjustment::Invert)]);
|
||||||
|
image.set_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||||
|
let inverted = adjusted_raster(image.element(), &[Adjustment::Invert]);
|
||||||
|
let read_back = block_on(executor.read_back(image)).unwrap();
|
||||||
|
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
||||||
|
for (index, (color, inverted)) in read_back.element().data.iter().zip(&inverted.data().data).enumerate() {
|
||||||
|
assert_eq!(*color, inverted.with_alpha(inverted.a() * 0.5), "pixel {index}");
|
||||||
|
assert!(color.r() + color.g() + color.b() > 0., "pixel {index} lost its color");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Effects past adjustments need a render
|
||||||
|
let outlined = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[outline(2.)]);
|
||||||
|
let effects = outlined.attribute::<Effects>(ATTR_EFFECTS).unwrap();
|
||||||
|
assert!(adjusted_without_render(&outlined, effects, 1.).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_margin_holds_what_a_median_reads_past_the_image() {
|
||||||
|
// A median reads its whole radius and the pixel past it, across the image's pixels of one unit each
|
||||||
|
let image = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[EffectOperation::Median { radius: 2.5 }]);
|
||||||
|
let effects = image.attribute::<Effects>(ATTR_EFFECTS).unwrap();
|
||||||
|
assert_eq!(effects_reach(effects, DVec2::splat(20.)), DVec2::splat(3.));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effects_measure_lengths_in_the_document_across_unevenly_scaled_pixels() {
|
||||||
|
let Some(executor) = executor() else { return };
|
||||||
|
|
||||||
|
// An outline 8 units wide spans 8 of the image's pixels across, but only 2 of them down
|
||||||
|
let outline = EffectOperation::Outline {
|
||||||
|
paint: Color::BLACK.into(),
|
||||||
|
blend_mode: BlendMode::Normal,
|
||||||
|
weight: 8.,
|
||||||
|
align: StrokeAlign::Outside,
|
||||||
|
contour_gradient: false,
|
||||||
|
};
|
||||||
|
let read_back = block_on(executor.read_back(image_of_pixels(TALL_PIXEL, |_, _| Color::WHITE, &[outline]))).unwrap();
|
||||||
|
|
||||||
|
// The content spans from (100, 50) to (120, 130)
|
||||||
|
assert!(is_white(color_at(&read_back, DVec2::new(110., 90.))), "the content");
|
||||||
|
assert!(is_black(color_at(&read_back, DVec2::new(94.5, 90.))), "within the outline, 5.5 units left of the content");
|
||||||
|
assert!(is_clear(color_at(&read_back, DVec2::new(89.5, 90.))), "past the outline, 10.5 units left of the content");
|
||||||
|
assert!(is_black(color_at(&read_back, DVec2::new(110., 44.))), "within the outline, 6 units above the content");
|
||||||
|
assert!(is_clear(color_at(&read_back, DVec2::new(110., 40.))), "past the outline, 10 units above the content");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vector_masks_shape_the_pixels_read_back() {
|
||||||
|
let Some(executor) = executor() else { return };
|
||||||
|
|
||||||
|
// A mask lies in the content's own space, where the left half of its unit square covers the image's left half
|
||||||
|
let mut left_half = Vector::item_from_bezpath(&Rect::new(0., 0., 0.5, 1.).to_path(0.1));
|
||||||
|
left_half.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE))));
|
||||||
|
let mask = EffectOperation::Mask {
|
||||||
|
mask: Graphic::Vector(Box::new(left_half)),
|
||||||
|
mode: MaskMode::Alpha,
|
||||||
|
density: 100.,
|
||||||
|
feather: 0.,
|
||||||
|
invert: false,
|
||||||
|
};
|
||||||
|
let read_back = block_on(executor.read_back(image_of_pixels(TALL_PIXEL, |_, _| Color::WHITE, &[mask]))).unwrap();
|
||||||
|
|
||||||
|
assert!(is_white(color_at(&read_back, DVec2::new(105.5, 90.))), "the left half, which the mask shows");
|
||||||
|
assert!(is_clear(color_at(&read_back, DVec2::new(114.5, 90.))), "the right half, which the mask hides");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An outline of `weight` outside the content, in black.
|
||||||
|
fn outline(weight: f64) -> EffectOperation {
|
||||||
|
EffectOperation::Outline {
|
||||||
|
paint: Color::BLACK.into(),
|
||||||
|
blend_mode: BlendMode::Normal,
|
||||||
|
weight,
|
||||||
|
align: StrokeAlign::Outside,
|
||||||
|
contour_gradient: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The limits of the shared GPU, and its executor, or `None` without a GPU.
|
||||||
|
fn executor_and_limits() -> Option<(&'static WgpuExecutor, ReadbackLimits)> {
|
||||||
|
let executor = executor()?;
|
||||||
|
Some((executor, ReadbackLimits::of(executor)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many 8-bit levels the CPU's adjustments and the render of them may part by, which is the render's rounding to its 8-bit texture.
|
||||||
|
const ADJUSTMENT_TOLERANCE: u8 = 1;
|
||||||
|
|
||||||
|
/// Asserts that two images have the same size and 8-bit pixels within `tolerance` levels of each other.
|
||||||
|
fn assert_alike(actual: &Image<Color>, expected: &Image<Color>, tolerance: u8) {
|
||||||
|
assert_eq!((actual.width, actual.height), (expected.width, expected.height));
|
||||||
|
for (index, (actual, expected)) in actual.data.iter().zip(&expected.data).enumerate() {
|
||||||
|
let (SRGBA8 { red, green, blue, alpha }, wanted) = (SRGBA8::from(*actual), SRGBA8::from(*expected));
|
||||||
|
let differences = [red.abs_diff(wanted.red), green.abs_diff(wanted.green), blue.abs_diff(wanted.blue), alpha.abs_diff(wanted.alpha)];
|
||||||
|
assert!(
|
||||||
|
differences.iter().all(|&difference| difference <= tolerance),
|
||||||
|
"pixel {index} is {actual:?} but {expected:?} in the other"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tiles_small_enough_for_the_download_buffer_match_one_render() {
|
||||||
|
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||||
|
|
||||||
|
// Square pixels of the document's size keep the effects' working pixels on the render's, so neither render resamples them.
|
||||||
|
// A 2048 byte buffer holds 8 rows of up to 64 pixels, each padded to 256 bytes, so this render is drawn in tiles 8 pixels tall.
|
||||||
|
let image = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &[outline(2.)]);
|
||||||
|
let small_buffer = ReadbackLimits { buffer_size: 2048, ..limits };
|
||||||
|
assert_eq!(small_buffer.tile_size(UVec2::splat(100)), Some(UVec2::new(100, 2048 / 512)));
|
||||||
|
|
||||||
|
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
||||||
|
let tiled = block_on(executor.read_back_within(image, small_buffer)).unwrap();
|
||||||
|
assert_alike(tiled.element(), whole.element(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_image_too_large_to_upload_whole_keeps_its_own_pixels_in_crops() {
|
||||||
|
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||||
|
|
||||||
|
// Alternating black and white columns, inverted and outlined, which a downscaled upload would average to gray
|
||||||
|
let columns = |x: u32, _| if x.is_multiple_of(2) { Color::BLACK } else { Color::WHITE };
|
||||||
|
let image = image_of_pixels(DVec2::ONE, columns, &[EffectOperation::Adjustment(graphic_types::Adjustment::Invert), outline(2.)]);
|
||||||
|
let small_textures = ReadbackLimits { texture_size: 16, ..limits };
|
||||||
|
|
||||||
|
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
||||||
|
let cropped = block_on(executor.read_back_within(image, small_textures)).unwrap();
|
||||||
|
assert_alike(cropped.element(), whole.element(), 1);
|
||||||
|
|
||||||
|
for x in 0..20 {
|
||||||
|
let color = color_at(&cropped, DVec2::new(100.5 + x as f64, 60.5));
|
||||||
|
let inverted = if x % 2 == 0 { is_white(color) } else { is_black(color) };
|
||||||
|
assert!(inverted, "column {x} is {color:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn limits_too_small_for_any_tile_fail_without_panicking() {
|
||||||
|
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||||
|
|
||||||
|
let image = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[outline(2.)]);
|
||||||
|
let tiny_buffer = ReadbackLimits { buffer_size: 100, ..limits };
|
||||||
|
assert!(block_on(executor.read_back_within(image, tiny_buffer)).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_reach_too_far_for_any_crop_fails_without_overflowing() {
|
||||||
|
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||||
|
|
||||||
|
// A box blur reaching past 2^31 pixels, on an image too wide for the texture limit, at one document unit per pixel
|
||||||
|
let blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Graphic::default(),
|
||||||
|
radius: 2_147_483_647.,
|
||||||
|
box_blur: true,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(16_384, 64, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(16_384., 64.)));
|
||||||
|
stamp_effect(&mut image, Effect::new(&blur));
|
||||||
|
let small_textures = ReadbackLimits { texture_size: 8192, ..limits };
|
||||||
|
|
||||||
|
assert!(block_on(executor.read_back_within(image, small_textures)).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn crops_carry_out_leading_adjustments_on_transparent_pixels_as_the_whole_image_does() {
|
||||||
|
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||||
|
|
||||||
|
// Make Opaque raises the alpha of fully transparent pixels, which only the image's own pixels can carry, and the outline needs a render
|
||||||
|
let make_opaque = EffectOperation::Adjustment(graphic_types::Adjustment::MakeOpaque { strength: 100. });
|
||||||
|
let image = image_of_pixels(DVec2::ONE, |_, _| Color::from_rgbaf32_unchecked(1., 0., 0., 0.), &[make_opaque, outline(2.)]);
|
||||||
|
let small_textures = ReadbackLimits { texture_size: 16, ..limits };
|
||||||
|
|
||||||
|
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
||||||
|
let cropped = block_on(executor.read_back_within(image, small_textures)).unwrap();
|
||||||
|
assert_alike(cropped.element(), whole.element(), 1);
|
||||||
|
let pixels = (0..20).flat_map(|y| (0..20).map(move |x| DVec2::new(100.5 + x as f64, 50.5 + y as f64)));
|
||||||
|
assert!(pixels.map(|point| color_at(&cropped, point)).all(|color| color.a() > 0.99), "the transparent pixels became opaque");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn crops_hold_the_pixels_effects_reach_past_a_margin_cut_short() {
|
||||||
|
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||||
|
|
||||||
|
// A margin cut to nothing, as for an image too large to grow, still leaves the blur its neighbors across the tiles.
|
||||||
|
// The tiles are wide enough next to the blur's reach that its effects group keeps their full resolution.
|
||||||
|
let blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Graphic::default(),
|
||||||
|
radius: 1.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(64, 64, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.)));
|
||||||
|
stamp_effect(&mut image, Effect::new(&blur));
|
||||||
|
let (effects, transform) = (image.attribute::<Effects>(ATTR_EFFECTS).unwrap().clone(), image.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||||
|
let reach = effects_reach(&effects, DVec2::splat(64.));
|
||||||
|
assert!(reach.min_element() > 0.);
|
||||||
|
let small_textures = ReadbackLimits { texture_size: 60, ..limits };
|
||||||
|
|
||||||
|
let whole = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, reach, limits)).unwrap();
|
||||||
|
let cropped = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, reach, small_textures)).unwrap();
|
||||||
|
assert_alike(&cropped, &whole, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,23 +22,35 @@ struct RasterGpuToRasterCpuConverter {
|
|||||||
padded_bytes_per_row: u32,
|
padded_bytes_per_row: u32,
|
||||||
_source: raster_types::Texture,
|
_source: raster_types::Texture,
|
||||||
}
|
}
|
||||||
|
/// The bytes in each row of a download buffer for an image `width` pixels wide, padded to the alignment copies need.
|
||||||
|
pub(crate) fn download_row_bytes(width: u32) -> u32 {
|
||||||
|
let bytes_per_pixel = 4; // RGBA8
|
||||||
|
(width * bytes_per_pixel).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The buffer a texture of `width` by `height` pixels downloads into.
|
||||||
|
fn download_buffer(executor: &WgpuExecutor, width: u32, height: u32) -> Buffer {
|
||||||
|
executor.create_buffer(&wgpu::BufferDescriptor {
|
||||||
|
label: Some("texture_download_buffer"),
|
||||||
|
size: download_row_bytes(width) as u64 * height as u64,
|
||||||
|
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||||
|
mapped_at_creation: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
impl RasterGpuToRasterCpuConverter {
|
impl RasterGpuToRasterCpuConverter {
|
||||||
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
|
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
|
||||||
|
let buffer = download_buffer(executor, data_gpu.data().width(), data_gpu.data().height());
|
||||||
|
Self::with_buffer(encoder, data_gpu, buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copies the texture into the `buffer` made for its size, once the `encoder` is submitted.
|
||||||
|
fn with_buffer(encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>, buffer: Buffer) -> Self {
|
||||||
let texture = data_gpu.data();
|
let texture = data_gpu.data();
|
||||||
let width = texture.width();
|
let width = texture.width();
|
||||||
let height = texture.height();
|
let height = texture.height();
|
||||||
let bytes_per_pixel = 4; // RGBA8
|
let unpadded_bytes_per_row = width * 4;
|
||||||
let unpadded_bytes_per_row = width * bytes_per_pixel;
|
let padded_bytes_per_row = download_row_bytes(width);
|
||||||
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
|
||||||
let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
|
|
||||||
let buffer_size = padded_bytes_per_row as u64 * height as u64;
|
|
||||||
|
|
||||||
let buffer = executor.create_buffer(&wgpu::BufferDescriptor {
|
|
||||||
label: Some("texture_download_buffer"),
|
|
||||||
size: buffer_size,
|
|
||||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
|
||||||
mapped_at_creation: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
encoder.copy_texture_to_buffer(
|
encoder.copy_texture_to_buffer(
|
||||||
wgpu::TexelCopyTextureInfo {
|
wgpu::TexelCopyTextureInfo {
|
||||||
@@ -73,7 +85,7 @@ impl RasterGpuToRasterCpuConverter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn convert(self, device: &wgpu::Device) -> Result<Raster<CPU>, wgpu::BufferAsyncError> {
|
async fn convert(self, device: &wgpu::Device) -> anyhow::Result<Raster<CPU>> {
|
||||||
let buffer_slice = self.buffer.slice(..);
|
let buffer_slice = self.buffer.slice(..);
|
||||||
let (sender, receiver) = futures::channel::oneshot::channel();
|
let (sender, receiver) = futures::channel::oneshot::channel();
|
||||||
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
||||||
@@ -104,9 +116,12 @@ impl RasterGpuToRasterCpuConverter {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
map_result.expect("Failed to receive map result")?;
|
let Ok(map_result) = map_result else {
|
||||||
|
anyhow::bail!("The download of a {} by {} image was canceled before the GPU mapped its buffer", self.width, self.height);
|
||||||
|
};
|
||||||
|
map_result?;
|
||||||
|
|
||||||
let view = buffer_slice.get_mapped_range().expect("Failed to get mapped range");
|
let view = buffer_slice.get_mapped_range()?;
|
||||||
|
|
||||||
let row_stride = self.padded_bytes_per_row as usize;
|
let row_stride = self.padded_bytes_per_row as usize;
|
||||||
let row_bytes = self.unpadded_bytes_per_row as usize;
|
let row_bytes = self.unpadded_bytes_per_row as usize;
|
||||||
@@ -230,3 +245,33 @@ impl ConvertAsync<Raster<CPU>, WgpuExecutor> for Raster<GPU> {
|
|||||||
converter.convert(device).await.expect("Failed to download texture data")
|
converter.convert(device).await.expect("Failed to download texture data")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl WgpuExecutor {
|
||||||
|
/// Downloads the GPU raster's pixels, failing rather than panicking when the GPU can't make or map the buffer they're copied into.
|
||||||
|
pub async fn try_download(&self, raster: Raster<GPU>) -> anyhow::Result<Raster<CPU>> {
|
||||||
|
let device = &self.context().device;
|
||||||
|
let (width, height) = (raster.data().width(), raster.data().height());
|
||||||
|
let buffer_size = download_row_bytes(width) as u64 * height as u64;
|
||||||
|
let limit = device.limits().max_buffer_size;
|
||||||
|
if buffer_size > limit {
|
||||||
|
anyhow::bail!("Downloading a {width} by {height} image takes a {buffer_size} byte buffer, past the GPU's limit of {limit} bytes");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Popped in the reverse order they're pushed, before awaiting either, since the scopes can't be held across an await
|
||||||
|
let out_of_memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||||
|
let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||||
|
let buffer = download_buffer(self, width, height);
|
||||||
|
let (validation, out_of_memory) = (validation.pop(), out_of_memory.pop());
|
||||||
|
if let Some(error) = validation.await.or(out_of_memory.await) {
|
||||||
|
anyhow::bail!("The GPU couldn't make the buffer to download a {width} by {height} image: {error}");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||||
|
label: Some("fallible_texture_download_encoder"),
|
||||||
|
});
|
||||||
|
let converter = RasterGpuToRasterCpuConverter::with_buffer(&mut encoder, raster, buffer);
|
||||||
|
self.context().queue.submit([encoder.finish()]);
|
||||||
|
|
||||||
|
converter.convert(device).await
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -109,6 +109,7 @@ fn step_function(kind: StepKind) -> (&'static str, Option<[Encoding; 2]>) {
|
|||||||
StepKind::ColorLookup => ("color_lookup", Some([Gamma, Gamma])),
|
StepKind::ColorLookup => ("color_lookup", Some([Gamma, Gamma])),
|
||||||
StepKind::ColorOverlay => ("color_overlay", Some([Gamma, Gamma])),
|
StepKind::ColorOverlay => ("color_overlay", Some([Gamma, Gamma])),
|
||||||
StepKind::Solarize => ("solarize", Some([Gamma, Gamma])),
|
StepKind::Solarize => ("solarize", Some([Gamma, Gamma])),
|
||||||
|
StepKind::AlphaToGray => ("alpha_to_gray", Some([Gamma, Gamma])),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -365,6 +365,11 @@ fn solarize(color: vec4<f32>, at: u32) -> vec4<f32> {
|
|||||||
return vec4<f32>(min(color.rgb, 1. - color.rgb), color.a);
|
return vec4<f32>(min(color.rgb, 1. - color.rgb), color.a);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The alpha as a gray of the same gamma-encoded level, keeping the alpha
|
||||||
|
fn alpha_to_gray(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||||
|
return vec4<f32>(vec3<f32>(color.a), color.a);
|
||||||
|
}
|
||||||
|
|
||||||
// Matches `apply_levels` with the gamma of 1 that every caller here passes, so its power is left out
|
// Matches `apply_levels` with the gamma of 1 that every caller here passes, so its power is left out
|
||||||
fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, output_minimum: f32, output_maximum: f32) -> f32 {
|
fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, output_minimum: f32, output_maximum: f32) -> f32 {
|
||||||
let highlights_minus_shadows = clamp(input_highlights - input_shadows, F32_EPSILON, 1.);
|
let highlights_minus_shadows = clamp(input_highlights - input_shadows, F32_EPSILON, 1.);
|
||||||
|
|||||||
@@ -853,6 +853,18 @@ impl EffectPasses {
|
|||||||
capture_plane(recorder, plane, map, true)
|
capture_plane(recorder, plane, map, true)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// The fill's plane takes a median of its own, which an SVG takes as its map where the fill forks the content
|
||||||
|
EffectOperation::Median { radius } => {
|
||||||
|
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||||
|
let median_full = recorder.median(full.as_ref().unwrap_or(content), radius, lengths_to_pixels, frame.as_ref());
|
||||||
|
capture_plane(&mut recorder, 0, &median_full, true);
|
||||||
|
if let Some(filled) = filled.as_mut() {
|
||||||
|
let median_filled = recorder.median(filled, radius, lengths_to_pixels, frame.as_ref());
|
||||||
|
capture_plane(&mut recorder, 1, &median_filled, true);
|
||||||
|
recorder.replace(filled, median_filled);
|
||||||
|
}
|
||||||
|
recorder.replace_or_fill(&mut full, median_full);
|
||||||
|
}
|
||||||
EffectOperation::MotionBlur { angle, distance, gamma } => {
|
EffectOperation::MotionBlur { angle, distance, gamma } => {
|
||||||
// Anchored at the effect space's origin, which is the content's, so the shear moves with it
|
// Anchored at the effect space's origin, which is the content's, so the shear moves with it
|
||||||
let Some(shear) = MotionBlurShear::new(angle, distance, lengths_to_pixels, effect_to_pixels.translation) else {
|
let Some(shear) = MotionBlurShear::new(angle, distance, lengths_to_pixels, effect_to_pixels.translation) else {
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
//! The GPU passes of the filter effects, matching the CPU's `filter_kernels`.
|
//! The GPU passes of the filter effects, matching the CPU's `filter_kernels`.
|
||||||
|
|
||||||
use super::{PARAMETER_TAPS, Parameters, PassRecorder, SUMS_FORMAT, WORKING_FORMAT};
|
use super::{PARAMETER_TAPS, Parameters, PassRecorder, SUMS_FORMAT, WORKING_FORMAT};
|
||||||
use glam::{DAffine2, DMat2, DVec2};
|
use glam::{DAffine2, DMat2, DVec2, UVec2};
|
||||||
use graphic_types::effects::spans_along_axes;
|
use graphic_types::effects::{MAX_MEDIAN_GRID_RADIUS, spans_along_axes};
|
||||||
use graphic_types::filters::{
|
use graphic_types::filters::{
|
||||||
Convolution, FieldSampling, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, neighborhood_radii, noise_extent, sharpens_coverage, unsharp,
|
Convolution, FieldSampling, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, neighborhood_radii, noise_extent, sharpens_coverage, unsharp,
|
||||||
};
|
};
|
||||||
|
use graphic_types::resampling::EffectFrame;
|
||||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||||
use raster_kernels::effect_kernels::BlurKernel;
|
use raster_kernels::effect_kernels::BlurKernel;
|
||||||
use raster_kernels::filter_kernels::pixel_fill_shifts;
|
use raster_kernels::filter_kernels::pixel_fill_shifts;
|
||||||
@@ -13,6 +14,11 @@ use raster_kernels::filter_kernels::pixel_fill_shifts;
|
|||||||
/// The most texels a neighborhood's first pass reads each way, beyond which each further pass at most doubles its reach by reading two texels.
|
/// The most texels a neighborhood's first pass reads each way, beyond which each further pass at most doubles its reach by reading two texels.
|
||||||
const MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS: u32 = 8;
|
const MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS: u32 = 8;
|
||||||
|
|
||||||
|
/// How many bits a median ranks the values of half floats by: their 32-bit float bit patterns without the low 13 bits a half float leaves empty, which order as the values do.
|
||||||
|
const MEDIAN_KEY_BITS: u32 = 18;
|
||||||
|
/// How many bits of each median's key a median pass decides, by three thresholds for each channel.
|
||||||
|
const MEDIAN_BITS_PER_PASS: u32 = 2;
|
||||||
|
|
||||||
/// The `convolution`'s shifts mapped onto texels by `lengths_to_pixels`, with their weights divided by its divisor.
|
/// The `convolution`'s shifts mapped onto texels by `lengths_to_pixels`, with their weights divided by its divisor.
|
||||||
fn convolution_taps(convolution: &Convolution, lengths_to_pixels: DMat2) -> Vec<[f32; 4]> {
|
fn convolution_taps(convolution: &Convolution, lengths_to_pixels: DMat2) -> Vec<[f32; 4]> {
|
||||||
let tap = |&(shift, weight): &(DVec2, f64)| {
|
let tap = |&(shift, weight): &(DVec2, f64)| {
|
||||||
@@ -455,6 +461,48 @@ impl PassRecorder<'_> {
|
|||||||
}
|
}
|
||||||
widened
|
widened
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The image with each texel's alpha the median of those in the square of `radius` whole document pixels around it, and each straight color the median among those with coverage,
|
||||||
|
/// a texel inside the content's `frame` reading only those inside it. Exact, deciding two more bits of the medians' keys (see [`MEDIAN_KEY_BITS`]) a pass.
|
||||||
|
/// O(width × height × radius²), with the radius in texels at most [`MAX_MEDIAN_GRID_RADIUS`], past which the content's grid coarsens instead.
|
||||||
|
pub(super) fn median(&mut self, image: &wgpu::Texture, radius: f64, lengths_to_pixels: DMat2, frame: Option<&EffectFrame>) -> wgpu::Texture {
|
||||||
|
let radii = (spans_along_axes(lengths_to_pixels) * radius.max(0.).floor()).round().min(DVec2::splat(MAX_MEDIAN_GRID_RADIUS));
|
||||||
|
let radii = radii.as_uvec2().min(self.size);
|
||||||
|
if radii == UVec2::ZERO {
|
||||||
|
return self.scale(image, 1.);
|
||||||
|
}
|
||||||
|
|
||||||
|
let prepared = self.run("median_prepare", WORKING_FORMAT, self.size, image, None, None, Parameters::default());
|
||||||
|
|
||||||
|
// The frame's unit square, which a texel center within the frame lies in, placed on the texels
|
||||||
|
let (pixels_to_frame, clips) = match frame {
|
||||||
|
Some(frame) => (frame.to_pixels.inverse(), 1.),
|
||||||
|
None => (DAffine2::IDENTITY, 0.),
|
||||||
|
};
|
||||||
|
let [x_axis, y_axis] = [pixels_to_frame.matrix2.x_axis, pixels_to_frame.matrix2.y_axis].map(|axis| axis.as_vec2());
|
||||||
|
|
||||||
|
// Each pass decides more bits of every channel's median, carried between passes as whole numbers in 32-bit floats
|
||||||
|
let passes = MEDIAN_KEY_BITS / MEDIAN_BITS_PER_PASS;
|
||||||
|
let mut decided: Option<wgpu::Texture> = None;
|
||||||
|
for pass in 0..passes {
|
||||||
|
let last = pass + 1 == passes;
|
||||||
|
let lowest_bit = MEDIAN_KEY_BITS - MEDIAN_BITS_PER_PASS * (pass + 1);
|
||||||
|
let flag = |on: bool| if on { 1. } else { 0. };
|
||||||
|
let parameters = Parameters {
|
||||||
|
step: radii.as_vec2().to_array(),
|
||||||
|
offset: pixels_to_frame.translation.as_vec2().to_array(),
|
||||||
|
color: [x_axis.x, x_axis.y, y_axis.x, y_axis.y],
|
||||||
|
values: [lowest_bit as f32, flag(decided.is_some()), flag(last), clips],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let format = if last { WORKING_FORMAT } else { SUMS_FORMAT };
|
||||||
|
let next = self.run("median_bisect", format, self.size, &prepared, None, decided.as_ref(), parameters);
|
||||||
|
self.replace_or_fill(&mut decided, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.textures.release(prepared);
|
||||||
|
decided.unwrap_or_else(|| self.scale(image, 1.))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The radii a window of extremes widens through from `from` texels each way to `to`, each at most double the one before it, or from none, at most [`MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS`].
|
/// The radii a window of extremes widens through from `from` texels each way to `to`, each at most double the one before it, or from none, at most [`MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS`].
|
||||||
|
|||||||
@@ -492,3 +492,92 @@ fn dissolve(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
|||||||
let shown = select(0., field.x, color.a * 255. > field.y + 0.5);
|
let shown = select(0., field.x, color.a * 255. > field.y + 0.5);
|
||||||
return vec4<f32>(color.rgb / color.a * shown, shown);
|
return vec4<f32>(color.rgb / color.a * shown, shown);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The straight colors and alpha a median ranks, as half floats kept within their finite range at or above 0, where their bit patterns order as their values do, or nothing without coverage
|
||||||
|
@fragment
|
||||||
|
fn median_prepare(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
|
let color = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||||
|
if !(color.a > 0.) {
|
||||||
|
return vec4<f32>(0.);
|
||||||
|
}
|
||||||
|
let straight = color.rgb / color.a;
|
||||||
|
return vec4<f32>(min(select(vec3<f32>(0.), straight, straight > vec3<f32>(0.)), vec3<f32>(65504.)), min(color.a, 1.));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The 32-bit float bit patterns of the four half float values at or above 0, without the low 13 bits a half float leaves empty, which order as the values do
|
||||||
|
fn median_keys(values: vec4<f32>) -> vec4<u32> {
|
||||||
|
return bitcast<vec4<u32>>(values) >> vec4<u32>(13u);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Whether a texel's center lies within the content's frame, whose unit square the linear part `color` (by columns) and `offset` place texels in
|
||||||
|
fn median_in_frame(texel: vec2<i32>) -> bool {
|
||||||
|
let unit = mat2x2<f32>(parameters.color.xy, parameters.color.zw) * (vec2<f32>(texel) + 0.5) + parameters.offset;
|
||||||
|
return all(unit >= vec2<f32>(0.)) && all(unit < vec2<f32>(1.));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Two more bits (from bit `values.x` up) of each channel's median as `median_keys` (of `source`): the alpha's among the window's texels, and each straight color's among those with coverage,
|
||||||
|
// in the window reaching `step` texels across and down, taking the upper median of an even count. A pass after the first (`values.y` 1) goes on from the bits decided before it (`content`),
|
||||||
|
// and the last (`values.z` 1) writes the medians as a premultiplied color. With `values.w` 1, a texel within the content's frame reads only the texels within it.
|
||||||
|
@fragment
|
||||||
|
fn median_bisect(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
|
let pixel = vec2<i32>(position.xy);
|
||||||
|
let last = vec2<i32>(textureDimensions(source)) - 1;
|
||||||
|
let radii = vec2<i32>(parameters.step);
|
||||||
|
let width = 1u << u32(parameters.values.x);
|
||||||
|
|
||||||
|
var decided = vec4<u32>(0u);
|
||||||
|
if parameters.values.y > 0.5 {
|
||||||
|
decided = vec4<u32>(textureLoad(content, pixel, 0));
|
||||||
|
}
|
||||||
|
let first_threshold = decided + width;
|
||||||
|
let second_threshold = decided + 2u * width;
|
||||||
|
let third_threshold = decided + 3u * width;
|
||||||
|
|
||||||
|
// Only a window crossing the frame's edge has its texels tested, since the frame is convex
|
||||||
|
var clips = parameters.values.w > 0.5 && median_in_frame(pixel);
|
||||||
|
if clips {
|
||||||
|
let corners_within = median_in_frame(pixel - radii) && median_in_frame(pixel + radii) && median_in_frame(pixel + vec2<i32>(radii.x, -radii.y)) && median_in_frame(pixel + vec2<i32>(-radii.x, radii.y));
|
||||||
|
clips = !corners_within;
|
||||||
|
}
|
||||||
|
|
||||||
|
var below_first = vec4<u32>(0u);
|
||||||
|
var below_second = vec4<u32>(0u);
|
||||||
|
var below_third = vec4<u32>(0u);
|
||||||
|
var counted = 0u;
|
||||||
|
var visible = 0u;
|
||||||
|
for (var y = -radii.y; y <= radii.y; y++) {
|
||||||
|
for (var x = -radii.x; x <= radii.x; x++) {
|
||||||
|
let texel = pixel + vec2<i32>(x, y);
|
||||||
|
if clips && !median_in_frame(texel) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
counted += 1u;
|
||||||
|
|
||||||
|
// Past the texture's edges lies nothing, and a texel without coverage has no colors to rank
|
||||||
|
let within = all(texel >= vec2<i32>(0)) && all(texel <= last);
|
||||||
|
let keys = median_keys(select(vec4<f32>(0.), textureLoad(source, clamp(texel, vec2<i32>(0), last), 0), within));
|
||||||
|
// Counts convert from booleans, since WebGL's GLSL can't select between integers
|
||||||
|
let shown = u32(keys.a > 0u);
|
||||||
|
visible += shown;
|
||||||
|
let hidden = (1u - shown) * 0xffffffffu;
|
||||||
|
let ranked = keys | vec4<u32>(hidden, hidden, hidden, 0u);
|
||||||
|
|
||||||
|
below_first += vec4<u32>(ranked < first_threshold);
|
||||||
|
below_second += vec4<u32>(ranked < second_threshold);
|
||||||
|
below_third += vec4<u32>(ranked < third_threshold);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The median lies past each threshold that fewer keys than its rank lie below
|
||||||
|
let rank = vec4<u32>(vec3<u32>(visible / 2u + 1u), counted / 2u + 1u);
|
||||||
|
decided += (vec4<u32>(below_first < rank) + vec4<u32>(below_second < rank) + vec4<u32>(below_third < rank)) * width;
|
||||||
|
if parameters.values.z < 0.5 {
|
||||||
|
return vec4<f32>(decided);
|
||||||
|
}
|
||||||
|
|
||||||
|
let medians = bitcast<vec4<f32>>(decided << vec4<u32>(13u));
|
||||||
|
if visible == 0u || !(medians.a > 0.) {
|
||||||
|
return vec4<f32>(0.);
|
||||||
|
}
|
||||||
|
return vec4<f32>(medians.rgb * medians.a, medians.a);
|
||||||
|
}
|
||||||
@@ -73,6 +73,8 @@ struct RenderContext<'a> {
|
|||||||
canvas: &'a mut VelloCanvas,
|
canvas: &'a mut VelloCanvas,
|
||||||
device: &'a wgpu::Device,
|
device: &'a wgpu::Device,
|
||||||
queue: &'a Queue,
|
queue: &'a Queue,
|
||||||
|
/// The first failure that left part of the render transparent.
|
||||||
|
failure: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VelloRenderer {
|
impl VelloRenderer {
|
||||||
@@ -120,7 +122,7 @@ impl VelloRenderer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target` (an `Rgba8Unorm` texture of `size` with straight alpha).
|
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target` (an `Rgba8Unorm` texture of `size` with straight alpha).
|
||||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into. Gives the first failure that left a part transparent.
|
||||||
#[expect(clippy::too_many_arguments)]
|
#[expect(clippy::too_many_arguments)]
|
||||||
pub(crate) fn render(
|
pub(crate) fn render(
|
||||||
&self,
|
&self,
|
||||||
@@ -131,7 +133,7 @@ impl VelloRenderer {
|
|||||||
view: Affine,
|
view: Affine,
|
||||||
size: UVec2,
|
size: UVec2,
|
||||||
target: &wgpu::Texture,
|
target: &wgpu::Texture,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<Option<String>> {
|
||||||
if u16::try_from(size.x).is_err() || u16::try_from(size.y).is_err() {
|
if u16::try_from(size.x).is_err() || u16::try_from(size.y).is_err() {
|
||||||
anyhow::bail!("Render size {size} exceeds Vello GPU's limit");
|
anyhow::bail!("Render size {size} exceeds Vello GPU's limit");
|
||||||
}
|
}
|
||||||
@@ -142,12 +144,14 @@ impl VelloRenderer {
|
|||||||
canvas,
|
canvas,
|
||||||
device,
|
device,
|
||||||
queue,
|
queue,
|
||||||
|
failure: None,
|
||||||
};
|
};
|
||||||
context.render_area(draw, view, size, target, TargetAlpha::Straight);
|
context.render_area(draw, view, size, target, TargetAlpha::Straight);
|
||||||
|
let failure = context.failure;
|
||||||
canvas.images.free_unused();
|
canvas.images.free_unused();
|
||||||
canvas.effect_textures.finish_render();
|
canvas.effect_textures.finish_render();
|
||||||
|
|
||||||
Ok(())
|
Ok(failure)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Renders a `scene` drawn beforehand on `canvas` into `target` (an `Rgba8Unorm` texture of the scene's size with straight alpha).
|
/// Renders a `scene` drawn beforehand on `canvas` into `target` (an `Rgba8Unorm` texture of the scene's size with straight alpha).
|
||||||
@@ -160,6 +164,7 @@ impl VelloRenderer {
|
|||||||
canvas,
|
canvas,
|
||||||
device,
|
device,
|
||||||
queue,
|
queue,
|
||||||
|
failure: None,
|
||||||
};
|
};
|
||||||
let (scene, images) = scene.finish();
|
let (scene, images) = scene.finish();
|
||||||
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) {
|
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) {
|
||||||
@@ -192,6 +197,7 @@ impl RenderContext<'_> {
|
|||||||
if !too_much_to_hold || split_depth > MAX_SPLIT_DEPTH || size.max_element() <= 1 {
|
if !too_much_to_hold || split_depth > MAX_SPLIT_DEPTH || size.max_element() <= 1 {
|
||||||
// A failed render leaves its area transparent rather than taking down the editor
|
// A failed render leaves its area transparent rather than taking down the editor
|
||||||
log::error!("Vello GPU failed to render: {error}");
|
log::error!("Vello GPU failed to render: {error}");
|
||||||
|
self.failure.get_or_insert_with(|| error.to_string());
|
||||||
clear(device, queue, target);
|
clear(device, queue, target);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -230,6 +236,7 @@ impl RenderContext<'_> {
|
|||||||
};
|
};
|
||||||
if halves.iter().all(|(.., rendered)| stalled(rendered)) {
|
if halves.iter().all(|(.., rendered)| stalled(rendered)) {
|
||||||
log::error!("Vello GPU failed to render: {error}");
|
log::error!("Vello GPU failed to render: {error}");
|
||||||
|
self.failure.get_or_insert_with(|| error.to_string());
|
||||||
clear(device, queue, target);
|
clear(device, queue, target);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -491,6 +498,7 @@ impl EffectsRenderer for RenderContext<'_> {
|
|||||||
Ok(()) => Some(backdrop),
|
Ok(()) => Some(backdrop),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
log::error!("Vello GPU failed to render what lies beneath content reading it: {error}");
|
log::error!("Vello GPU failed to render what lies beneath content reading it: {error}");
|
||||||
|
self.failure.get_or_insert_with(|| error.to_string());
|
||||||
self.canvas.effect_textures.release(backdrop);
|
self.canvas.effect_textures.release(backdrop);
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1715,6 +1715,250 @@ fn endless_layers_clip_to_the_shape_beneath_them() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Black on the left half of a render 140 across and white on the right, with nothing between, its effects measured in its own space spanning the render.
|
||||||
|
fn hard_edged_gradient() -> core_types::list::Item<graphic_types::vector_types::gradient::Gradient> {
|
||||||
|
use core_types::list::{ATTR_GRADIENT_INTERPOLATION, Item};
|
||||||
|
use core_types::{ATTR_TRANSFORM, Color};
|
||||||
|
use graphic_types::vector_types::gradient::{Gradient, GradientInterpolation};
|
||||||
|
|
||||||
|
Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE, Color::WHITE]))
|
||||||
|
.with_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Stepped)
|
||||||
|
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::splat(140.)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pixelate with cells 10 across in a gradient's space spanning a render 140 across.
|
||||||
|
fn pixelated_by_tens() -> graphic_types::EffectOperation {
|
||||||
|
graphic_types::EffectOperation::Pixelate {
|
||||||
|
cell_size: 10. / 140.,
|
||||||
|
offset: glam::DVec2::ZERO,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Gaussian blur of radius 4 in a gradient's space spanning a render 140 across.
|
||||||
|
fn blurred_by_four() -> graphic_types::EffectOperation {
|
||||||
|
graphic_types::EffectOperation::Blur {
|
||||||
|
radius_mask: graphic_types::Graphic::default(),
|
||||||
|
radius: 4. / 140.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn endless_gradients_pixelate_and_blur_over_the_view() {
|
||||||
|
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_INTERPOLATION};
|
||||||
|
use core_types::{ATTR_TRANSFORM, Color};
|
||||||
|
use graphic_types::vector_types::gradient::{Gradient, GradientInterpolation};
|
||||||
|
use graphic_types::{Effects, Graphic};
|
||||||
|
use rendering::{Render, RenderParams};
|
||||||
|
|
||||||
|
let size = UVec2::new(140, 140);
|
||||||
|
let draw = |graphic: &Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
|
||||||
|
|
||||||
|
// A smooth black-to-white ramp across the render bands into cells 10 across, each one color
|
||||||
|
let ramp = core_types::list::Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
|
||||||
|
.with_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Linear)
|
||||||
|
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::splat(140.)))
|
||||||
|
.with_attribute(ATTR_EFFECTS, Effects::from_operations([pixelated_by_tens()]));
|
||||||
|
let Some(pixelated) = draw(&Graphic::Gradient(ramp)) else { return };
|
||||||
|
for cell in 1..13 {
|
||||||
|
let first = pixel(&pixelated, size, cell * 10 + 1, 70);
|
||||||
|
assert!((cell * 10 + 2..cell * 10 + 9).all(|x| pixel(&pixelated, size, x, 70) == first), "cell {cell} is one color");
|
||||||
|
assert_ne!(first, pixel(&pixelated, size, cell * 10 + 11, 70), "cell {cell} differs from the next");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The hard edge halfway across softens, from gray just beside it to black and white farther away
|
||||||
|
let blurred = draw(&Graphic::Gradient(hard_edged_gradient().with_attribute(ATTR_EFFECTS, Effects::from_operations([blurred_by_four()])))).unwrap();
|
||||||
|
let gray = |x: u32| pixel(&blurred, size, x, 70)[0];
|
||||||
|
assert!(gray(66) > 10 && gray(66) < 128 && gray(73) > 128 && gray(73) < 245, "{} and {}", gray(66), gray(73));
|
||||||
|
assert!(gray(50) < 3 && gray(90) > 252, "{} and {}", gray(50), gray(90));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paints_with_effects_beyond_their_colors_show_them_within_the_shape() {
|
||||||
|
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||||
|
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||||||
|
use glam::DVec2;
|
||||||
|
use graphic_types::vector_types::gradient::Gradient;
|
||||||
|
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
|
||||||
|
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, MaskMode, NoiseDistribution, Vector};
|
||||||
|
use rendering::{Render, RenderParams};
|
||||||
|
use vello_gpu::kurbo::Shape;
|
||||||
|
|
||||||
|
let size = UVec2::new(140, 140);
|
||||||
|
let draw = |graphic: &Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
|
||||||
|
let square_covered_by = |coverage: Coverage, paint: Graphic| {
|
||||||
|
let mut square = Vector::item_from_bezpath(&Rect::new(20., 20., 120., 120.).to_path(0.1));
|
||||||
|
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
|
||||||
|
Graphic::VectorList(List::new_from_item(square))
|
||||||
|
};
|
||||||
|
let close = |a: [u8; 4], b: [u8; 4]| a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 2);
|
||||||
|
|
||||||
|
// A color and a gradient across the render, grained, twirled, and masked to its left half, with the gradient's effects measured in its own space that spans the render
|
||||||
|
let color = || Item::new_from_element(GraphicColor::from_gamma_srgb_channels(0.8, 0.2, 0.4, 1.));
|
||||||
|
let gradient = || Item::new_from_element(Gradient::from(vec![GraphicColor::BLACK, GraphicColor::WHITE])).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(140.)));
|
||||||
|
let speckle = EffectOperation::Speckle {
|
||||||
|
amount: 50.,
|
||||||
|
distribution: NoiseDistribution::Uniform,
|
||||||
|
monochromatic: false,
|
||||||
|
seed: 0,
|
||||||
|
};
|
||||||
|
let twirl = EffectOperation::Twirl {
|
||||||
|
angle: 180.,
|
||||||
|
transform: DAffine2::from_scale_angle_translation(DVec2::splat(100. / 140.), 0., DVec2::splat(0.5)),
|
||||||
|
};
|
||||||
|
let mut left_half = Vector::item_from_bezpath(&Rect::new(0., 0., 0.5, 1.).to_path(0.001));
|
||||||
|
left_half.set_attribute(
|
||||||
|
ATTR_APPEARANCE,
|
||||||
|
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))),
|
||||||
|
);
|
||||||
|
let mask = EffectOperation::Mask {
|
||||||
|
mask: Graphic::VectorList(List::new_from_item(left_half)),
|
||||||
|
mode: MaskMode::Luminance,
|
||||||
|
density: 100.,
|
||||||
|
feather: 0.,
|
||||||
|
invert: false,
|
||||||
|
};
|
||||||
|
let effected = |operation: &EffectOperation| Effects::from_operations([operation.clone()]);
|
||||||
|
let paints = [
|
||||||
|
("speckled color", Graphic::Color(color().with_attribute(ATTR_EFFECTS, effected(&speckle))), Graphic::Color(color())),
|
||||||
|
(
|
||||||
|
"speckled gradient",
|
||||||
|
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&speckle))),
|
||||||
|
Graphic::Gradient(gradient()),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"twirled gradient",
|
||||||
|
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&twirl))),
|
||||||
|
Graphic::Gradient(gradient()),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"masked gradient",
|
||||||
|
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&mask))),
|
||||||
|
Graphic::Gradient(gradient()),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"pixelated gradient",
|
||||||
|
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&pixelated_by_tens()))),
|
||||||
|
Graphic::Gradient(gradient()),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"blurred hard-edged gradient",
|
||||||
|
Graphic::Gradient(hard_edged_gradient().with_attribute(ATTR_EFFECTS, effected(&blurred_by_four()))),
|
||||||
|
Graphic::Gradient(hard_edged_gradient()),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (name, paint, plain) in paints {
|
||||||
|
// The paint drawn as a layer filling everything, which the shape's paint matches where it covers it
|
||||||
|
let Some(layer) = draw(&paint) else { return };
|
||||||
|
|
||||||
|
// A fill shows the effect within the square and nothing past it
|
||||||
|
let filled = draw(&square_covered_by(Coverage::new_fill(), paint.clone())).unwrap();
|
||||||
|
let plain_filled = draw(&square_covered_by(Coverage::new_fill(), plain.clone())).unwrap();
|
||||||
|
for (x, y) in (22..118).flat_map(|x| (22..118).map(move |y| (x, y))) {
|
||||||
|
assert!(close(pixel(&filled, size, x, y), pixel(&layer, size, x, y)), "{name}: the fill matches the layer at ({x}, {y})");
|
||||||
|
}
|
||||||
|
for (x, y) in [(10, 70), (130, 70), (70, 10), (70, 130)] {
|
||||||
|
assert_eq!(pixel(&filled, size, x, y)[3], 0, "{name}: nothing is filled at ({x}, {y}), past the square");
|
||||||
|
}
|
||||||
|
let changed = (0..filled.len()).filter(|&index| !close(filled[index], plain_filled[index])).count();
|
||||||
|
assert!(changed > 500, "{name}: the effect changes the fill at {changed} pixels");
|
||||||
|
|
||||||
|
// A stroke shows it within its band, wherever its alignment places it along the square's left edge
|
||||||
|
for (align, band) in [(StrokeAlign::Center, 16..24), (StrokeAlign::Inside, 21..29), (StrokeAlign::Outside, 11..19)] {
|
||||||
|
let stroked = draw(&square_covered_by(Coverage::new_stroke(&Stroke { align, ..Stroke::new(10.) }), paint.clone())).unwrap();
|
||||||
|
for (x, y) in band.clone().flat_map(|x| (40..100).map(move |y| (x, y))) {
|
||||||
|
assert!(
|
||||||
|
close(pixel(&stroked, size, x, y), pixel(&layer, size, x, y)),
|
||||||
|
"{name}, {align:?}: the stroke matches the layer at ({x}, {y})"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for x in [band.start - 4, band.end + 3] {
|
||||||
|
assert_eq!(pixel(&stroked, size, x, 70)[3], 0, "{name}, {align:?}: nothing is stroked at ({x}, 70), past the band");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_half_filled_paint_made_opaque_looks_the_same_whether_drawn_by_its_color_or_as_content() {
|
||||||
|
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||||
|
use core_types::{ATTR_OPACITY_FILL, Color as GraphicColor};
|
||||||
|
use graphic_types::adjustment::Adjustment;
|
||||||
|
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector};
|
||||||
|
use rendering::{Render, RenderParams};
|
||||||
|
use vello_gpu::kurbo::Shape;
|
||||||
|
|
||||||
|
let size = UVec2::new(140, 140);
|
||||||
|
let filled_square = |operations: Vec<EffectOperation>| {
|
||||||
|
let paint = Item::new_from_element(GraphicColor::RED)
|
||||||
|
.with_attribute(ATTR_OPACITY_FILL, 0.5)
|
||||||
|
.with_attribute(ATTR_EFFECTS, Effects::from_operations(operations));
|
||||||
|
let mut square = Vector::item_from_bezpath(&Rect::new(20., 20., 120., 120.).to_path(0.1));
|
||||||
|
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::Color(paint)));
|
||||||
|
Graphic::VectorList(List::new_from_item(square))
|
||||||
|
};
|
||||||
|
|
||||||
|
// The fill fades the red before Make Opaque restores it, alike when a blur of the flat color draws it as content
|
||||||
|
let make_opaque = EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
|
||||||
|
let blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Graphic::default(),
|
||||||
|
radius: 4.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
for operations in [vec![make_opaque.clone()], vec![make_opaque, blur]] {
|
||||||
|
let count = operations.len();
|
||||||
|
let Some(pixels) = render(size, |scene| filled_square(operations.clone()).render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for (x, y) in [(70, 70), (25, 70), (115, 115)] {
|
||||||
|
assert_eq!(pixel(&pixels, size, x, y), [255, 0, 0, 255], "{count} effects at ({x}, {y})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_paints_own_blend_mode_composites_within_the_paint_rather_than_onto_what_lies_beneath_the_shape() {
|
||||||
|
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||||
|
use core_types::{ATTR_BLEND_MODE, Color as GraphicColor};
|
||||||
|
use graphic_types::vector_types::vector::style::Stroke;
|
||||||
|
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector};
|
||||||
|
use rendering::{Render, RenderParams};
|
||||||
|
use vello_gpu::kurbo::Shape;
|
||||||
|
|
||||||
|
let size = UVec2::new(140, 140);
|
||||||
|
let shape = |rect: Rect, coverage: Coverage, paint: Graphic| {
|
||||||
|
let mut vector = Vector::item_from_bezpath(&rect.to_path(0.1));
|
||||||
|
vector.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
|
||||||
|
Graphic::VectorList(List::new_from_item(vector))
|
||||||
|
};
|
||||||
|
let background = shape(Rect::new(0., 0., 140., 140.), Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::RED)));
|
||||||
|
|
||||||
|
// Green multiplied with nothing beneath it in its paint stays green, whatever lies beneath the shape, as in SVG's pattern, though a blur of it draws it as content
|
||||||
|
let blur = EffectOperation::Blur {
|
||||||
|
radius_mask: Graphic::default(),
|
||||||
|
radius: 4.,
|
||||||
|
box_blur: false,
|
||||||
|
gamma: false,
|
||||||
|
};
|
||||||
|
let green = Item::new_from_element(GraphicColor::GREEN)
|
||||||
|
.with_attribute(ATTR_BLEND_MODE, BlendMode::Multiply)
|
||||||
|
.with_attribute(ATTR_EFFECTS, Effects::from_operations([blur]));
|
||||||
|
for (coverage, inside) in [(Coverage::new_fill(), (70, 70)), (Coverage::new_stroke(&Stroke::new(10.)), (20, 70))] {
|
||||||
|
let square = shape(Rect::new(20., 20., 120., 120.), coverage, Graphic::Color(green.clone()));
|
||||||
|
let Some(pixels) = render(size, |scene| {
|
||||||
|
background.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
||||||
|
square.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
||||||
|
}) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let (x, y) = inside;
|
||||||
|
assert_eq!(pixel(&pixels, size, x, y), [0, 255, 0, 255], "green at ({x}, {y})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn feathers_fade_the_content_to_nothing_at_its_edges() {
|
fn feathers_fade_the_content_to_nothing_at_its_edges() {
|
||||||
use graphic_types::EffectOperation;
|
use graphic_types::EffectOperation;
|
||||||
@@ -4627,6 +4871,191 @@ fn gpu_neighborhood_extremes_match_the_cpu_kernels() {
|
|||||||
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The exact result of a Median of `radius` whole texels on premultiplied `texels` (`width` across) with nothing past their edges: the upper median of each window's alphas,
|
||||||
|
/// and of each straight color among the texels with coverage, which the passes hold as half floats. O(texels × radius² log radius).
|
||||||
|
fn median_reference(texels: &[[f32; 4]], width: usize, radius: isize) -> Vec<[f32; 4]> {
|
||||||
|
use half::f16;
|
||||||
|
|
||||||
|
let height = (texels.len() / width) as isize;
|
||||||
|
let straight: Vec<[f32; 4]> = (texels.iter())
|
||||||
|
.map(|&[red, green, blue, alpha]| match alpha > 0. {
|
||||||
|
true => [red / alpha, green / alpha, blue / alpha, alpha].map(|value| f16::from_f32(value).to_f32()),
|
||||||
|
false => [0.; 4],
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let upper_median = |mut values: Vec<f32>| {
|
||||||
|
values.sort_by(f32::total_cmp);
|
||||||
|
values[values.len() / 2]
|
||||||
|
};
|
||||||
|
|
||||||
|
(0..texels.len())
|
||||||
|
.map(|index| {
|
||||||
|
let (x, y) = ((index % width) as isize, (index / width) as isize);
|
||||||
|
let mut alphas = Vec::new();
|
||||||
|
let mut colors: [Vec<f32>; 3] = Default::default();
|
||||||
|
for (shift_x, shift_y) in (-radius..=radius).flat_map(|shift_y| (-radius..=radius).map(move |shift_x| (shift_x, shift_y))) {
|
||||||
|
let (read_x, read_y) = (x + shift_x, y + shift_y);
|
||||||
|
let within = (0..width as isize).contains(&read_x) && (0..height).contains(&read_y);
|
||||||
|
let texel = if within { straight[(read_y * width as isize + read_x) as usize] } else { [0.; 4] };
|
||||||
|
alphas.push(texel[3]);
|
||||||
|
if texel[3] > 0. {
|
||||||
|
colors.iter_mut().zip(texel).for_each(|(channel, value)| channel.push(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let alpha = upper_median(alphas);
|
||||||
|
if alpha <= 0. || colors[0].is_empty() {
|
||||||
|
return [0.; 4];
|
||||||
|
}
|
||||||
|
let [red, green, blue] = colors.map(upper_median);
|
||||||
|
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gpu_medians_match_the_exact_reference() {
|
||||||
|
use graphic_types::{EffectOperation, Effects};
|
||||||
|
use half::f16;
|
||||||
|
|
||||||
|
// Random colors, opaque but for a fully transparent band and a translucent one, so some windows rank colors among fewer texels than alphas
|
||||||
|
let (width, height) = (37, 23);
|
||||||
|
let texels: Vec<[f16; 4]> = (0..width * height)
|
||||||
|
.map(|index| {
|
||||||
|
let (x, y) = (index % width, index / width);
|
||||||
|
let alpha = match (x, y) {
|
||||||
|
(10..14, _) => 0.,
|
||||||
|
(_, 5..8) => 0.4,
|
||||||
|
_ => 1.,
|
||||||
|
};
|
||||||
|
let random = |seed: u32| ((index as u32).wrapping_mul(2_654_435_761).wrapping_add(seed.wrapping_mul(40_503)) >> 24) as f32 / 255.;
|
||||||
|
[random(1) * alpha, random(2) * alpha, random(3) * alpha, alpha].map(f16::from_f32)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let unrounded: Vec<[f32; 4]> = texels.iter().map(|texel| texel.map(f16::to_f32)).collect();
|
||||||
|
|
||||||
|
let mut strays = Vec::new();
|
||||||
|
for radius in [1, 2, 3, 6] {
|
||||||
|
let effects = Effects::from_operations([EffectOperation::Median { radius: radius as f64 + 0.5 }]);
|
||||||
|
let Some(gpu) = gpu_effect_texels(&effects, &texels, width, &[]) else { return };
|
||||||
|
let reference = median_reference(&unrounded, width, radius);
|
||||||
|
|
||||||
|
// In 8-bit levels, within the rounding of half floats
|
||||||
|
let levels = (gpu.iter().zip(&reference))
|
||||||
|
.flat_map(|(gpu, reference)| (0..4).map(|channel| (gpu[channel] - reference[channel]).abs() * 255.))
|
||||||
|
.fold(0_f32, f32::max);
|
||||||
|
if levels > 0.5 {
|
||||||
|
strays.push(format!("a median of radius {radius} strays from the exact one by {levels} levels"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn medians_work_on_an_images_own_pixels_at_any_zoom() {
|
||||||
|
use core_types::ATTR_TRANSFORM;
|
||||||
|
use core_types::list::{Item, List};
|
||||||
|
use glam::DVec2;
|
||||||
|
use graphic_types::raster_types::{Image, Raster};
|
||||||
|
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||||
|
use rendering::{Render, RenderParams};
|
||||||
|
|
||||||
|
// A square of 2×2 white pixels on black, which a median of radius 1 removes, since it fills under half of each 3×3 window
|
||||||
|
let mut image = Image::new(6, 6, core_types::Color::BLACK);
|
||||||
|
for (x, y) in [(2, 2), (3, 2), (2, 3), (3, 3)] {
|
||||||
|
image.data[y * 6 + x] = core_types::Color::WHITE;
|
||||||
|
}
|
||||||
|
let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(6.)));
|
||||||
|
stamp_effect(&mut item, Effect::new(&EffectOperation::Median { radius: 1. }));
|
||||||
|
let list = List::new_from_item(item);
|
||||||
|
|
||||||
|
// Zoomed in, a median of the view's pixels would keep the square, which then fills most of each window
|
||||||
|
for zoom in [1., 4.] {
|
||||||
|
let size = UVec2::splat((6. * zoom) as u32);
|
||||||
|
let view = DAffine2::from_scale(DVec2::splat(zoom));
|
||||||
|
let Some(pixels) = render_in_view(size, view, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let center = (3. * zoom) as u32;
|
||||||
|
assert_eq!(pixel(&pixels, size, center, center), [0, 0, 0, 255], "at a zoom of {zoom}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn medians_read_within_an_images_rectangle() {
|
||||||
|
use core_types::ATTR_TRANSFORM;
|
||||||
|
use core_types::list::{Item, List};
|
||||||
|
use glam::DVec2;
|
||||||
|
use graphic_types::raster_types::{Image, Raster};
|
||||||
|
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||||
|
use rendering::{Render, RenderParams};
|
||||||
|
|
||||||
|
// An opaque white image a pixel in from the render's corner
|
||||||
|
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(8.), 0., DVec2::ONE);
|
||||||
|
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(8, 8, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, placement);
|
||||||
|
stamp_effect(&mut item, Effect::new(&EffectOperation::Median { radius: 2. }));
|
||||||
|
let list = List::new_from_item(item);
|
||||||
|
|
||||||
|
let size = UVec2::splat(10);
|
||||||
|
let Some(pixels) = render(size, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Its corners keep their pixels, read as if the image were all there is, and nothing spreads past it
|
||||||
|
assert_eq!(pixel(&pixels, size, 1, 1), [255; 4]);
|
||||||
|
assert_eq!(pixel(&pixels, size, 8, 8), [255; 4]);
|
||||||
|
assert_eq!(pixel(&pixels, size, 0, 0)[3], 0);
|
||||||
|
assert_eq!(pixel(&pixels, size, 9, 4)[3], 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_median_baked_for_pixel_readers_matches_its_gpu_render() {
|
||||||
|
use core_types::ATTR_TRANSFORM;
|
||||||
|
use core_types::list::{Item, List};
|
||||||
|
use glam::DVec2;
|
||||||
|
use graphic_types::raster_types::{CPU, Image, Raster};
|
||||||
|
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||||
|
use rendering::{Render, RenderParams};
|
||||||
|
|
||||||
|
// Random colors with a fully transparent band, a pixel in from the render's corner, on the content's own grid and on one coarsened past its largest radius
|
||||||
|
let (width, height) = (40, 30);
|
||||||
|
let data = (0..width * height)
|
||||||
|
.map(|index| {
|
||||||
|
let random = |seed: u32| ((index as u32).wrapping_mul(2_654_435_761).wrapping_add(seed.wrapping_mul(40_503)) >> 24) as f32 / 255.;
|
||||||
|
let alpha = if (12..16).contains(&(index % width)) { 0. } else { 1. };
|
||||||
|
core_types::Color::from_gamma_srgb_channels(random(1), random(2), random(3), alpha)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let placement = DAffine2::from_scale_angle_translation(DVec2::new(width as f64, height as f64), 0., DVec2::ONE);
|
||||||
|
let image = Item::new_from_element(Raster::new_cpu(Image {
|
||||||
|
width: width as u32,
|
||||||
|
height: height as u32,
|
||||||
|
data,
|
||||||
|
}))
|
||||||
|
.with_attribute(ATTR_TRANSFORM, placement);
|
||||||
|
|
||||||
|
let size = UVec2::new(width as u32 + 2, height as u32 + 2);
|
||||||
|
let draw = |item: Item<Raster<CPU>>| {
|
||||||
|
let list = List::new_from_item(item);
|
||||||
|
render(size, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||||||
|
};
|
||||||
|
for radius in [2., 20.] {
|
||||||
|
let mut item = image.clone();
|
||||||
|
stamp_effect(&mut item, Effect::new(&EffectOperation::Median { radius }));
|
||||||
|
|
||||||
|
// A reader bakes the effect into the image's pixels, which must draw as the GPU draws the effect
|
||||||
|
let baked = raster_kernels::evaluate_raster_effects(item.clone());
|
||||||
|
let (Some(gpu), Some(baked)) = (draw(item), draw(baked)) else { return };
|
||||||
|
// Compared premultiplied, since the straight colors of nearly transparent pixels read back in steps as coarse as their alpha, within the rounding of half floats and 8 bits
|
||||||
|
let premultiplied = |[red, green, blue, alpha]: [u8; 4]| [red, green, blue].map(|channel| channel as f32 * alpha as f32 / 255.).into_iter().chain([alpha as f32]);
|
||||||
|
let stray = (gpu.iter().zip(&baked))
|
||||||
|
.flat_map(|(gpu, baked)| premultiplied(*gpu).zip(premultiplied(*baked)).map(|(gpu, baked)| (gpu - baked).abs()))
|
||||||
|
.fold(0_f32, f32::max);
|
||||||
|
assert!(stray <= 3., "a median of radius {radius} baked strays from its GPU render by {stray} levels");
|
||||||
|
assert_ne!(baked, draw(image.clone()).unwrap_or_default(), "the median changes the pixels");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Colors across the RGB cube, among them black, white, grays, and saturated and near-black colors, each opaque, with some also translucent or fully transparent.
|
/// Colors across the RGB cube, among them black, white, grays, and saturated and near-black colors, each opaque, with some also translucent or fully transparent.
|
||||||
fn adjustment_test_colors() -> Vec<core_types::Color> {
|
fn adjustment_test_colors() -> Vec<core_types::Color> {
|
||||||
const LEVELS: [f32; 12] = [0., 1. / 255., 4. / 255., 0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95, 254. / 255., 1.];
|
const LEVELS: [f32; 12] = [0., 1. / 255., 4. / 255., 0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95, 254. / 255., 1.];
|
||||||
@@ -5035,9 +5464,20 @@ fn gpu_color_adjustments_match_the_cpu_kernels() {
|
|||||||
("Photo Filter", photo_filter(warming, 25., true)),
|
("Photo Filter", photo_filter(warming, 25., true)),
|
||||||
("Photo Filter at full density", photo_filter(cooling, 100., false)),
|
("Photo Filter at full density", photo_filter(cooling, 100., false)),
|
||||||
("Photo Filter at full density preserving luminosity", photo_filter(cooling, 100., true)),
|
("Photo Filter at full density preserving luminosity", photo_filter(cooling, 100., true)),
|
||||||
|
("Alpha to Gray", Adjustment::AlphaToGray),
|
||||||
];
|
];
|
||||||
let mut runs: Vec<(String, Vec<Adjustment>)> = runs.into_iter().map(|(name, adjustment)| (name.to_string(), vec![adjustment])).collect();
|
let mut runs: Vec<(String, Vec<Adjustment>)> = runs.into_iter().map(|(name, adjustment)| (name.to_string(), vec![adjustment])).collect();
|
||||||
|
|
||||||
|
// The opaque grays of one channel each that 'Into Channels' outputs
|
||||||
|
let opaque = Adjustment::MakeOpaque { strength: 100. };
|
||||||
|
let green_gray = Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||||
|
monochrome: true,
|
||||||
|
monochrome_mix: row(0., 100., 0., 0.),
|
||||||
|
..Default::default()
|
||||||
|
}));
|
||||||
|
runs.push(("Green as an opaque gray".to_string(), vec![green_gray, opaque.clone()]));
|
||||||
|
runs.push(("Alpha as an opaque gray".to_string(), vec![Adjustment::AlphaToGray, opaque]));
|
||||||
|
|
||||||
// Every blend mode, overlaying an opaque color and a translucent one, each with a luma apart from every test color's, which Darker Color and Lighter Color compare, and off Hard Mix's steep ramp over them
|
// Every blend mode, overlaying an opaque color and a translucent one, each with a luma apart from every test color's, which Darker Color and Lighter Color compare, and off Hard Mix's steep ramp over them
|
||||||
for blend_mode in BlendMode::list().into_iter().flatten().chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha]) {
|
for blend_mode in BlendMode::list().into_iter().flatten().chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha]) {
|
||||||
for (color, opacity) in [
|
for (color, opacity) in [
|
||||||
|
|||||||
@@ -3,13 +3,13 @@ use core_types::blending::BlendMode;
|
|||||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||||
use core_types::list::{Item, List};
|
use core_types::list::{Item, List};
|
||||||
use core_types::transfer_curve::TransferCurve;
|
use core_types::transfer_curve::TransferCurve;
|
||||||
use core_types::{ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color, Ctx};
|
use core_types::{ATTR_TRANSFORM, Color, Ctx};
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||||
use graphic_types::{
|
use graphic_types::{
|
||||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectOperation, Generator, GlowSource, GlowTechnique, Graphic, Vector, linked_to_content, paint_with_envelope_effects, stamp_effect,
|
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectOperation, Generator, GlowSource, GlowTechnique, Graphic, Vector, linked_to_content, paint_with_envelope_effects, stamp_effect,
|
||||||
};
|
};
|
||||||
use raster_kernels::{evaluate_color_effects, evaluate_gradient_effects};
|
use raster_kernels::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
|
||||||
use vector_types::Gradient;
|
use vector_types::Gradient;
|
||||||
use vector_types::vector::style::{StrokeAlign, initial_gradient_transform_for_bounding_box};
|
use vector_types::vector::style::{StrokeAlign, initial_gradient_transform_for_bounding_box};
|
||||||
|
|
||||||
@@ -99,7 +99,7 @@ fn drop_shadow<T>(
|
|||||||
stamp_effect(
|
stamp_effect(
|
||||||
&mut content,
|
&mut content,
|
||||||
Effect::new(&EffectOperation::DropShadow {
|
Effect::new(&EffectOperation::DropShadow {
|
||||||
color: evaluate_color_effects(color).into_element(),
|
color: evaluate_color_parameter(color).into_element(),
|
||||||
blend_mode: *blend_mode.element(),
|
blend_mode: *blend_mode.element(),
|
||||||
angle: *angle.element(),
|
angle: *angle.element(),
|
||||||
distance: *distance.element(),
|
distance: *distance.element(),
|
||||||
@@ -155,7 +155,7 @@ fn inner_shadow<T>(
|
|||||||
stamp_effect(
|
stamp_effect(
|
||||||
&mut content,
|
&mut content,
|
||||||
Effect::new(&EffectOperation::InnerShadow {
|
Effect::new(&EffectOperation::InnerShadow {
|
||||||
color: evaluate_color_effects(color).into_element(),
|
color: evaluate_color_parameter(color).into_element(),
|
||||||
blend_mode: *blend_mode.element(),
|
blend_mode: *blend_mode.element(),
|
||||||
angle: *angle.element(),
|
angle: *angle.element(),
|
||||||
distance: *distance.element(),
|
distance: *distance.element(),
|
||||||
@@ -468,7 +468,7 @@ fn satin<T>(
|
|||||||
stamp_effect(
|
stamp_effect(
|
||||||
&mut content,
|
&mut content,
|
||||||
Effect::new(&EffectOperation::Satin {
|
Effect::new(&EffectOperation::Satin {
|
||||||
color: evaluate_color_effects(color).into_element(),
|
color: evaluate_color_parameter(color).into_element(),
|
||||||
blend_mode: *blend_mode.element(),
|
blend_mode: *blend_mode.element(),
|
||||||
angle: *angle.element(),
|
angle: *angle.element(),
|
||||||
distance: *distance.element(),
|
distance: *distance.element(),
|
||||||
@@ -620,9 +620,9 @@ fn bevel_and_emboss<T: PaintFitBounds>(
|
|||||||
soften: *soften.element(),
|
soften: *soften.element(),
|
||||||
angle: *angle.element(),
|
angle: *angle.element(),
|
||||||
altitude: *altitude.element(),
|
altitude: *altitude.element(),
|
||||||
highlight_color: evaluate_color_effects(highlight_color).into_element(),
|
highlight_color: evaluate_color_parameter(highlight_color).into_element(),
|
||||||
highlight_blend_mode: *highlight_blend_mode.element(),
|
highlight_blend_mode: *highlight_blend_mode.element(),
|
||||||
shadow_color: evaluate_color_effects(shadow_color).into_element(),
|
shadow_color: evaluate_color_parameter(shadow_color).into_element(),
|
||||||
shadow_blend_mode: *shadow_blend_mode.element(),
|
shadow_blend_mode: *shadow_blend_mode.element(),
|
||||||
texture,
|
texture,
|
||||||
texture_depth: *texture_depth.element(),
|
texture_depth: *texture_depth.element(),
|
||||||
@@ -661,11 +661,7 @@ fn paint_overlay<T: PaintFitBounds>(
|
|||||||
let paint = match paint_with_envelope_effects(paint) {
|
let paint = match paint_with_envelope_effects(paint) {
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => return content,
|
Graphic::None(_) | Graphic::NoneList(_) => return content,
|
||||||
// A solid paint becomes a bare color, so its own opacity fades the color's alpha
|
// A solid paint becomes a bare color, so its own opacity fades the color's alpha
|
||||||
Graphic::Color(color) => {
|
Graphic::Color(color) => Graphic::from(evaluate_color_parameter(color).into_element()),
|
||||||
let opacity = color.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) * color.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.);
|
|
||||||
let color = evaluate_color_effects(color).into_element();
|
|
||||||
Graphic::from(color.with_alpha(color.a() * opacity as f32))
|
|
||||||
}
|
|
||||||
paint => paint_with_placement(&content, paint, _has_transform, _transform),
|
paint => paint_with_placement(&content, paint, _has_transform, _transform),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -775,6 +771,33 @@ mod test {
|
|||||||
assert!(color.r() > 0.05 && color.r() < 0.95, "half the black paint leaves {color:?}");
|
assert!(color.r() > 0.05 && color.r() < 0.95, "half the black paint leaves {color:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn drop_shadow_fades_its_color_by_the_colors_own_opacity() {
|
||||||
|
use core_types::ATTR_OPACITY;
|
||||||
|
use core_types::transfer_curve::TransferCurve;
|
||||||
|
use graphic_types::EffectOperation;
|
||||||
|
|
||||||
|
let number = |value: f64| Item::new_from_element(value);
|
||||||
|
let shadowed = super::drop_shadow(
|
||||||
|
(),
|
||||||
|
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::WHITE))),
|
||||||
|
Item::new_from_element(Color::BLACK).with_attribute(ATTR_OPACITY, 0.5_f64),
|
||||||
|
BlendMode::Normal.into(),
|
||||||
|
number(120.),
|
||||||
|
number(5.),
|
||||||
|
number(0.),
|
||||||
|
number(5.),
|
||||||
|
Item::new_from_element(TransferCurve::default()),
|
||||||
|
true.into(),
|
||||||
|
);
|
||||||
|
|
||||||
|
let operation = shadowed.attribute::<Effects>(ATTR_EFFECTS).and_then(|effects| effects.operations().next());
|
||||||
|
let Some(EffectOperation::DropShadow { color, .. }) = operation else {
|
||||||
|
panic!("expected a drop shadow, got {operation:?}")
|
||||||
|
};
|
||||||
|
assert_eq!(color, Color::BLACK.with_alpha(0.5));
|
||||||
|
}
|
||||||
|
|
||||||
type PaintEffectNode<T> = fn(Item<T>, Graphic, bool, DAffine2) -> Item<T>;
|
type PaintEffectNode<T> = fn(Item<T>, Graphic, bool, DAffine2) -> Item<T>;
|
||||||
|
|
||||||
fn paint_effect_nodes<T: super::PaintFitBounds>() -> [(&'static str, PaintEffectNode<T>); 3] {
|
fn paint_effect_nodes<T: super::PaintFitBounds>() -> [(&'static str, PaintEffectNode<T>); 3] {
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ fn create_artboard<T: IntoGraphicList>(
|
|||||||
let normalized_location = location.min(location + dimensions);
|
let normalized_location = location.min(location + dimensions);
|
||||||
let normalized_dimensions = dimensions.abs().max(DVec2::ONE);
|
let normalized_dimensions = dimensions.abs().max(DVec2::ONE);
|
||||||
|
|
||||||
let background = raster_kernels::evaluate_color_effects(background).into_element();
|
let background = raster_kernels::evaluate_color_parameter(background).into_element();
|
||||||
|
|
||||||
// Name is not stored here, it's resolved live from the parent layer's display name
|
// Name is not stored here, it's resolved live from the parent layer's display name
|
||||||
Ok(Item::new_from_element(Artboard::new(content))
|
Ok(Item::new_from_element(Artboard::new(content))
|
||||||
|
|||||||
@@ -1142,7 +1142,9 @@ fn flatten_gradient(_: impl Ctx, content: List<Graphic>) -> List<Gradient> {
|
|||||||
/// Constructs a gradient from a `Color[]`, where each color becomes a gradient stop. A `position` attribute on the colors places their stops along the ramp and a `midpoint` attribute skews each transition, while colors carrying neither are distributed evenly across the 0 to 1 range.
|
/// Constructs a gradient from a `Color[]`, where each color becomes a gradient stop. A `position` attribute on the colors places their stops along the ramp and a `midpoint` attribute skews each transition, while colors carrying neither are distributed evenly across the 0 to 1 range.
|
||||||
#[node_macro::node(category("Gradient"), icon("NodeColorsToGradient"), name("Colors to Gradient"))]
|
#[node_macro::node(category("Gradient"), icon("NodeColorsToGradient"), name("Colors to Gradient"))]
|
||||||
fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Item<Gradient> {
|
fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Item<Gradient> {
|
||||||
Item::new_from_element(Gradient::from(colors.into_flattened_list::<Color>()))
|
// Each color's own effects and opacity go into it before it becomes a stop
|
||||||
|
let colors: List<Color> = colors.into_flattened_list::<Color>().into_iter().map(value_effects::evaluate_color_parameter).collect();
|
||||||
|
Item::new_from_element(Gradient::from(colors))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unwraps a gradient into a `Color[]` of its stops, keeping any `position` and `midpoint` attributes that place them along the ramp. Attributes belonging to the gradient as a whole (like spread and interpolation), rather than its individual color stops, are not preserved.
|
/// Unwraps a gradient into a `Color[]` of its stops, keeping any `position` and `midpoint` attributes that place them along the ramp. Attributes belonging to the gradient as a whole (like spread and interpolation), rather than its individual color stops, are not preserved.
|
||||||
@@ -1423,4 +1425,18 @@ mod test {
|
|||||||
expected.set_positions(&[0.25, 0.75]);
|
expected.set_positions(&[0.25, 0.75]);
|
||||||
assert_eq!(colors_to_gradient((), embed_colors(colors)).element(), &expected, "each stop should keep its place");
|
assert_eq!(colors_to_gradient((), embed_colors(colors)).element(), &expected, "each stop should keep its place");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn colors_to_gradient_carries_out_each_colors_effects_and_opacity() {
|
||||||
|
use core_types::ATTR_OPACITY;
|
||||||
|
use graphic_types::{Adjustment, EffectOperation};
|
||||||
|
|
||||||
|
let inverted = Item::new_from_element(Color::BLACK).with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::Adjustment(Adjustment::Invert)]));
|
||||||
|
let half_opacity = Item::new_from_element(Color::RED).with_attribute(ATTR_OPACITY, 0.5_f64);
|
||||||
|
let colors: List<Color> = [inverted, half_opacity].into_iter().collect();
|
||||||
|
|
||||||
|
let gradient = colors_to_gradient((), embed_colors(colors));
|
||||||
|
let expected = Gradient::from(vec![Color::WHITE, Color::RED.with_alpha(0.5)]);
|
||||||
|
assert_eq!(gradient.element(), &expected, "the inverted black should become a white stop, and the half-opaque red a half-alpha one");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -45,7 +45,6 @@ wgpu-executor = { workspace = true }
|
|||||||
core-types = { workspace = true }
|
core-types = { workspace = true }
|
||||||
vector-types = { workspace = true }
|
vector-types = { workspace = true }
|
||||||
graphic-types = { workspace = true }
|
graphic-types = { workspace = true }
|
||||||
raster-kernels = { workspace = true }
|
|
||||||
svg-convert = { workspace = true }
|
svg-convert = { workspace = true }
|
||||||
blending-nodes = { workspace = true }
|
blending-nodes = { workspace = true }
|
||||||
text-nodes = { workspace = true }
|
text-nodes = { workspace = true }
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
pub mod any;
|
pub mod any;
|
||||||
pub mod platform_application_io;
|
pub mod platform_application_io;
|
||||||
pub mod poll_debug;
|
pub mod poll_debug;
|
||||||
|
pub mod read_back;
|
||||||
pub mod render_background;
|
pub mod render_background;
|
||||||
pub mod render_cache;
|
pub mod render_cache;
|
||||||
pub mod render_node;
|
pub mod render_node;
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ pub use graph_craft::document::value::RenderOutputType;
|
|||||||
#[cfg(target_family = "wasm")]
|
#[cfg(target_family = "wasm")]
|
||||||
pub use graphene_canvas_utils as canvas_utils;
|
pub use graphene_canvas_utils as canvas_utils;
|
||||||
use graphic_types::Graphic;
|
use graphic_types::Graphic;
|
||||||
use graphic_types::raster_types::{CPU, Raster};
|
use graphic_types::raster_types::{CPU, Pixels, Raster};
|
||||||
use graphic_types::raster_types::{Image, ImageError};
|
use graphic_types::raster_types::{Image, ImageError};
|
||||||
use rendering::{Render, RenderParams};
|
use rendering::{Render, RenderParams};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -172,8 +172,8 @@ fn string_to_bytes(_: impl Ctx, string: Item<String>) -> Item<Resource> {
|
|||||||
|
|
||||||
/// Converts extracted raw RGBA pixel data from an input image. Each pixel becomes 4 sequential bytes. Useful for transmission over HTTP or writing to files.
|
/// Converts extracted raw RGBA pixel data from an input image. Each pixel becomes 4 sequential bytes. Useful for transmission over HTTP or writing to files.
|
||||||
#[node_macro::node(category("Data: I/O"), icon("NodeImageToBytes"), name("Image to Bytes"))]
|
#[node_macro::node(category("Data: I/O"), icon("NodeImageToBytes"), name("Image to Bytes"))]
|
||||||
fn image_to_bytes(_: impl Ctx, image: Item<Raster<CPU>>) -> Item<Resource> {
|
fn image_to_bytes(_: impl Ctx, image: Item<Pixels>) -> Item<Resource> {
|
||||||
let bytes: Vec<u8> = raster_kernels::evaluate_raster_effects(image)
|
let bytes: Vec<u8> = image
|
||||||
.element()
|
.element()
|
||||||
.data
|
.data
|
||||||
.iter()
|
.iter()
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
use core_types::list::{Item, List};
|
||||||
|
use core_types::{Ctx, NodeError, ProtoNodeIdentifier};
|
||||||
|
use graphic_types::raster_types::{CPU, Pixels, Raster};
|
||||||
|
|
||||||
|
/// The input adapter the compiler places ahead of each node input taking `Pixels`, with `read_back` and `read_back_list` as its rows.
|
||||||
|
pub const INPUT_ADAPTER: ProtoNodeIdentifier = ProtoNodeIdentifier::new("input_adapter<Pixels>");
|
||||||
|
|
||||||
|
/// Reads back the pixels of an image as the GPU draws it with its effects and fill, for a node input taking `Pixels`. It stays pending until the download lands, so the reader doesn't run on stand-in pixels.
|
||||||
|
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||||
|
async fn read_back(
|
||||||
|
_: impl Ctx,
|
||||||
|
image: Item<Raster<CPU>>,
|
||||||
|
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item<wgpu_executor::WgpuExecutor>,
|
||||||
|
) -> Result<Item<Pixels>, NodeError> {
|
||||||
|
executor.element().read_back(image).await.map_err(NodeError::new)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `List` counterpart of `read_back`, reading back each image in turn.
|
||||||
|
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||||
|
async fn read_back_list(
|
||||||
|
_: impl Ctx,
|
||||||
|
images: List<Raster<CPU>>,
|
||||||
|
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item<wgpu_executor::WgpuExecutor>,
|
||||||
|
) -> Result<List<Pixels>, NodeError> {
|
||||||
|
let executor = executor.element();
|
||||||
|
|
||||||
|
let mut read_back = List::new();
|
||||||
|
for image in images.into_iter() {
|
||||||
|
read_back.push(executor.read_back(image).await.map_err(NodeError::new)?);
|
||||||
|
}
|
||||||
|
Ok(read_back)
|
||||||
|
}
|
||||||
@@ -53,5 +53,10 @@ tsify = { workspace = true, optional = true }
|
|||||||
wasm-bindgen = { workspace = true, optional = true }
|
wasm-bindgen = { workspace = true, optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
# Local dependencies
|
||||||
|
rendering = { workspace = true }
|
||||||
|
wgpu-executor = { workspace = true }
|
||||||
|
|
||||||
|
# Workspace dependencies
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
futures = { workspace = true }
|
futures = { workspace = true }
|
||||||
@@ -14,8 +14,8 @@ use graphic_types::adjustment::{
|
|||||||
pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute};
|
pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute};
|
||||||
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
||||||
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||||
use raster_kernels::{evaluate_color_effects, evaluate_gradient_effects};
|
use raster_kernels::{evaluate_color_parameter, evaluate_gradient_effects};
|
||||||
use raster_types::{CPU, GPU, Image, Raster};
|
use raster_types::{CPU, GPU, Raster};
|
||||||
use vector_types::Gradient;
|
use vector_types::Gradient;
|
||||||
|
|
||||||
/// Stamps the adjustment onto the item's effects, to be carried out wherever its content is rendered or read.
|
/// Stamps the adjustment onto the item's effects, to be carried out wherever its content is rendered or read.
|
||||||
@@ -50,42 +50,6 @@ fn gamma_correction<T>(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The red, green, blue, and alpha channels of an image, split into separate node outputs.
|
|
||||||
#[derive(Debug, Clone, dyn_any::DynAny, node_macro::Destructure)]
|
|
||||||
pub struct ImageChannels {
|
|
||||||
/// The red channel of the image, as a grayscale image.
|
|
||||||
pub red: Item<Raster<CPU>>,
|
|
||||||
/// The green channel of the image, as a grayscale image.
|
|
||||||
pub green: Item<Raster<CPU>>,
|
|
||||||
/// The blue channel of the image, as a grayscale image.
|
|
||||||
pub blue: Item<Raster<CPU>>,
|
|
||||||
/// The alpha channel of the image, as a grayscale image.
|
|
||||||
pub alpha: Item<Raster<CPU>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Separates an image into its red, green, blue, and alpha channels, each provided as a grayscale image.
|
|
||||||
#[node_macro::node(category("Raster"), icon("NodeImageToChannels"), name("Image to Channels"))]
|
|
||||||
fn image_to_channels(_: impl Ctx, image: Item<Raster<CPU>>) -> ImageChannels {
|
|
||||||
let (image, attributes) = raster_kernels::evaluate_raster_effects(image).into_parts();
|
|
||||||
let (width, height) = (image.width, image.height);
|
|
||||||
|
|
||||||
// O(4 × pixels), since all four channels are written even when only some outputs are connected
|
|
||||||
let mut channels: [Vec<Color>; 4] = core::array::from_fn(|_| Vec::with_capacity(image.data.len()));
|
|
||||||
for color in &image.data {
|
|
||||||
for (channel, value) in channels.iter_mut().zip([color.r(), color.g(), color.b(), color.a()]) {
|
|
||||||
channel.push(Color::from_rgbaf32_unchecked(value, value, value, 1.));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Each channel image keeps the source image's attributes, such as its transform
|
|
||||||
let [red, green, blue, alpha] = channels.map(|data| {
|
|
||||||
let channel_image = Image { width, height, data };
|
|
||||||
Item::from_parts(Raster::new_cpu(channel_image), attributes.clone())
|
|
||||||
});
|
|
||||||
|
|
||||||
ImageChannels { red, green, blue, alpha }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"), version(2))]
|
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"), version(2))]
|
||||||
fn make_opaque<T>(
|
fn make_opaque<T>(
|
||||||
_: impl Ctx,
|
_: impl Ctx,
|
||||||
@@ -414,7 +378,7 @@ fn black_and_white<T>(
|
|||||||
) -> Item<T> {
|
) -> Item<T> {
|
||||||
let settings = BlackAndWhiteSettings {
|
let settings = BlackAndWhiteSettings {
|
||||||
use_tint: use_tint.into_element(),
|
use_tint: use_tint.into_element(),
|
||||||
tint: evaluate_color_effects(tint).into_element(),
|
tint: evaluate_color_parameter(tint).into_element(),
|
||||||
reds: reds.into_element(),
|
reds: reds.into_element(),
|
||||||
yellows: yellows.into_element(),
|
yellows: yellows.into_element(),
|
||||||
greens: greens.into_element(),
|
greens: greens.into_element(),
|
||||||
@@ -1417,7 +1381,7 @@ fn photo_filter<T>(
|
|||||||
adjust(
|
adjust(
|
||||||
image,
|
image,
|
||||||
Adjustment::PhotoFilter {
|
Adjustment::PhotoFilter {
|
||||||
color: evaluate_color_effects(color).into_element(),
|
color: evaluate_color_parameter(color).into_element(),
|
||||||
density: density.into_element(),
|
density: density.into_element(),
|
||||||
preserve_luminosity: preserve_luminosity.into_element(),
|
preserve_luminosity: preserve_luminosity.into_element(),
|
||||||
},
|
},
|
||||||
@@ -1460,6 +1424,8 @@ mod _graphene_hash_impls {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use raster_kernels::evaluate_color_effects;
|
||||||
|
use raster_types::Image;
|
||||||
|
|
||||||
/// Matched to within one 8-bit level.
|
/// Matched to within one 8-bit level.
|
||||||
fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
|
fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
|
||||||
|
|||||||
@@ -18,8 +18,8 @@ fn mix_colors(
|
|||||||
#[default(100.)]
|
#[default(100.)]
|
||||||
opacity: Item<f64>,
|
opacity: Item<f64>,
|
||||||
) -> Item<Color> {
|
) -> Item<Color> {
|
||||||
let mut under = raster_kernels::evaluate_color_effects(under);
|
let mut under = raster_kernels::evaluate_color_parameter(under);
|
||||||
let over = raster_kernels::evaluate_color_effects(over);
|
let over = raster_kernels::evaluate_color_parameter(over);
|
||||||
let blend_mode = blend_mode.into_element();
|
let blend_mode = blend_mode.into_element();
|
||||||
let opacity = (opacity.into_element() / 100.) as f32;
|
let opacity = (opacity.into_element() / 100.) as f32;
|
||||||
|
|
||||||
@@ -41,4 +41,20 @@ mod test {
|
|||||||
|
|
||||||
assert_eq!(mixed, Color::from_rgbaf32_unchecked(0.25, 0., 0.75, 1.));
|
assert_eq!(mixed, Color::from_rgbaf32_unchecked(0.25, 0., 0.75, 1.));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mix_colors_fades_each_color_by_its_opacity() {
|
||||||
|
use core_types::ATTR_OPACITY;
|
||||||
|
use core_types::list::Item;
|
||||||
|
|
||||||
|
let half_opacity = |color: Color| Item::new_from_element(color).with_attribute(ATTR_OPACITY, 0.5_f64);
|
||||||
|
let mix = |under: Item<Color>, over: Item<Color>| super::mix_colors((), under, over, BlendMode::Normal.into(), 100_f64.into());
|
||||||
|
|
||||||
|
assert_eq!(*mix(Color::TRANSPARENT.into(), half_opacity(Color::RED)).element(), Color::RED.with_alpha(0.5));
|
||||||
|
|
||||||
|
// The under color's opacity goes into its alpha, so the result carries none to fade it twice
|
||||||
|
let mixed = mix(half_opacity(Color::BLUE), Color::TRANSPARENT.into());
|
||||||
|
assert_eq!(*mixed.element(), Color::BLUE.with_alpha(0.5));
|
||||||
|
assert_eq!(mixed.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 1.);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
use core_types::blending::BlendMode;
|
||||||
|
use core_types::context::Ctx;
|
||||||
|
use core_types::list::{ATTR_EFFECTS, Item, ItemAttributeValues, List};
|
||||||
|
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL};
|
||||||
|
use glam::DAffine2;
|
||||||
|
use graphic_types::adjustment::{Adjustment, ChannelMixerRow, ChannelMixerSettings};
|
||||||
|
use graphic_types::{Effect, EffectOperation, Effects, Graphic, MaskMode, linked_to_content, stamp_effect_on};
|
||||||
|
|
||||||
|
/// The red, green, blue, and alpha channels of a graphic, split into separate node outputs.
|
||||||
|
#[derive(Debug, Clone, dyn_any::DynAny, node_macro::Destructure)]
|
||||||
|
pub struct Channels {
|
||||||
|
/// The red channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||||
|
pub red: Item<Graphic>,
|
||||||
|
/// The green channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||||
|
pub green: Item<Graphic>,
|
||||||
|
/// The blue channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||||
|
pub blue: Item<Graphic>,
|
||||||
|
/// The alpha channel of the graphic as an opaque grayscale graphic, from black where the graphic is transparent to white where it's opaque.
|
||||||
|
pub alpha: Item<Graphic>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Separates the input graphic into its red, green, blue, and alpha channels, each as a grayscale graphic.
|
||||||
|
///
|
||||||
|
/// The color channels keep the graphic's transparency, while the alpha channel is opaque, so it masks by its luminance as the alpha did.
|
||||||
|
#[node_macro::node(category("Raster"), icon("NodeImageToChannels"), version(2))]
|
||||||
|
fn into_channels(_: impl Ctx, content: Item<Graphic>) -> Channels {
|
||||||
|
// Each output is the content with adjustments graying it by one channel, carried out wherever it's rendered or read
|
||||||
|
let channel = |grays: &[Adjustment]| {
|
||||||
|
let mut channel = content.clone();
|
||||||
|
with_effects_holder(&mut channel, |attributes| grays.iter().for_each(|gray| stamp_adjustment(attributes, gray.clone())));
|
||||||
|
channel
|
||||||
|
};
|
||||||
|
|
||||||
|
Channels {
|
||||||
|
red: channel(&[channel_gray([100., 0., 0.])]),
|
||||||
|
green: channel(&[channel_gray([0., 100., 0.])]),
|
||||||
|
blue: channel(&[channel_gray([0., 0., 100.])]),
|
||||||
|
alpha: channel(&[Adjustment::AlphaToGray, Adjustment::MakeOpaque { strength: 100. }]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Combines graphics into the red, green, blue, and alpha channels of one graphic. Each color channel comes from the same channel of its input, and the alpha from the alpha input's red channel, so grayscale graphics like those from 'Into Channels' recombine exactly.
|
||||||
|
///
|
||||||
|
/// The inputs line up where they lie in the document, and the result covers them all, transparent where none lies. Unconnected color channels are black, and an unconnected alpha leaves the result opaque.
|
||||||
|
#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), version(2))]
|
||||||
|
fn from_channels(
|
||||||
|
_: impl Ctx,
|
||||||
|
_primary: (),
|
||||||
|
/// The graphic whose red channel becomes the red channel.
|
||||||
|
#[expose]
|
||||||
|
red: Item<Graphic>,
|
||||||
|
/// The graphic whose green channel becomes the green channel.
|
||||||
|
#[expose]
|
||||||
|
green: Item<Graphic>,
|
||||||
|
/// The graphic whose blue channel becomes the blue channel.
|
||||||
|
#[expose]
|
||||||
|
blue: Item<Graphic>,
|
||||||
|
/// The graphic whose red channel becomes the alpha, from transparent where it's black to opaque where it's white. Past its edges, the result is transparent.
|
||||||
|
#[expose]
|
||||||
|
alpha: Item<Graphic>,
|
||||||
|
) -> Item<Graphic> {
|
||||||
|
// An unconnected channel arrives as a graphic drawing nothing, which counts as absent
|
||||||
|
let present = |channel: Item<Graphic>| (!channel.element().draws_nothing()).then_some(channel);
|
||||||
|
let [red, green, blue, alpha] = [red, green, blue, alpha].map(present);
|
||||||
|
|
||||||
|
// Each input made opaque, keeping only its own color channel, or none for the alpha, which also masks the group by a gray of its red channel
|
||||||
|
let opaque = |channel: Item<Graphic>, keep: Adjustment| {
|
||||||
|
let mut channel = without_compositing(channel);
|
||||||
|
with_effects_holder(&mut channel, |attributes| {
|
||||||
|
stamp_adjustment(attributes, Adjustment::MakeOpaque { strength: 100. });
|
||||||
|
stamp_adjustment(attributes, keep);
|
||||||
|
});
|
||||||
|
channel
|
||||||
|
};
|
||||||
|
let mask = alpha.clone().map(|alpha| opaque(alpha, channel_gray([100., 0., 0.])));
|
||||||
|
let kept = [Some(0), Some(1), Some(2), None].map(kept_channel);
|
||||||
|
let channels = [red, green, blue, alpha].into_iter().zip(kept).filter_map(|(channel, keep)| Some(opaque(channel?, keep)));
|
||||||
|
|
||||||
|
// Each channel adds onto those before it, holding none of their channels, so the group covers every input
|
||||||
|
let mut group = List::default();
|
||||||
|
for (index, mut channel) in channels.enumerate() {
|
||||||
|
if index > 0 {
|
||||||
|
channel.set_attribute(ATTR_BLEND_MODE, BlendMode::LinearDodge);
|
||||||
|
}
|
||||||
|
group.push(channel);
|
||||||
|
}
|
||||||
|
if group.is_empty() {
|
||||||
|
return Item::default();
|
||||||
|
}
|
||||||
|
let mut result = Item::new_from_element(Graphic::GraphicList(group));
|
||||||
|
|
||||||
|
// The alpha's gray shows the group by its luminance, which for a gray is its level, or else the group is made opaque.
|
||||||
|
// Either effect also renders the group apart from what lies beneath, so its channels add only onto each other.
|
||||||
|
let effect = match mask {
|
||||||
|
Some(mask) => EffectOperation::Mask {
|
||||||
|
mask: linked_to_content(Graphic::Graphic(Box::new(mask)), DAffine2::IDENTITY),
|
||||||
|
mode: MaskMode::Luminance,
|
||||||
|
density: 100.,
|
||||||
|
feather: 0.,
|
||||||
|
invert: false,
|
||||||
|
},
|
||||||
|
None => EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. }),
|
||||||
|
};
|
||||||
|
stamp_effect_on(result.attributes_mut(), Effect::new(&effect));
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The graphic without the opacity, fill, blend mode, and clipping a channel takes no part in, on its envelope and the one item it may hold.
|
||||||
|
fn without_compositing(mut graphic: Item<Graphic>) -> Item<Graphic> {
|
||||||
|
let strip = |attributes: &mut ItemAttributeValues| {
|
||||||
|
attributes.remove::<f64>(ATTR_OPACITY);
|
||||||
|
attributes.remove::<f64>(ATTR_OPACITY_FILL);
|
||||||
|
attributes.remove::<BlendMode>(ATTR_BLEND_MODE);
|
||||||
|
attributes.remove::<bool>(ATTR_CLIPPING_MASK);
|
||||||
|
};
|
||||||
|
strip(graphic.attributes_mut());
|
||||||
|
if let Some(attributes) = lone_item_attributes(graphic.element_mut()) {
|
||||||
|
strip(attributes);
|
||||||
|
}
|
||||||
|
graphic
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Channel Mixer keeping only the red, green, or blue channel by its `index`, or none for black.
|
||||||
|
fn kept_channel(index: Option<usize>) -> Adjustment {
|
||||||
|
let row = |row_index: usize| {
|
||||||
|
let weight = |channel: usize| if index == Some(row_index) && channel == row_index { 100. } else { 0. };
|
||||||
|
ChannelMixerRow {
|
||||||
|
red: weight(0),
|
||||||
|
green: weight(1),
|
||||||
|
blue: weight(2),
|
||||||
|
constant: 0.,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||||
|
monochrome: false,
|
||||||
|
monochrome_mix: ChannelMixerRow {
|
||||||
|
red: 40.,
|
||||||
|
green: 40.,
|
||||||
|
blue: 20.,
|
||||||
|
constant: 0.,
|
||||||
|
},
|
||||||
|
red: row(0),
|
||||||
|
green: row(1),
|
||||||
|
blue: row(2),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gives `edit` the attributes of the item a graphic's effects go on.
|
||||||
|
/// That's the one item the graphic holds, which keeps the handling of its own kind (an image's adjustments reach even its fully transparent pixels) and stays an image for 'Flatten Raster' to take out,
|
||||||
|
/// unless the graphic's own effects or fill, which act before effects appended to the graphic, would then act after them.
|
||||||
|
fn with_effects_holder<R>(graphic: &mut Item<Graphic>, edit: impl FnOnce(&mut ItemAttributeValues) -> R) -> R {
|
||||||
|
let envelope_has_effects = graphic.attribute::<Effects>(ATTR_EFFECTS).is_some_and(|effects| !effects.is_empty());
|
||||||
|
let envelope_acts_first = envelope_has_effects || graphic.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) != 1.;
|
||||||
|
|
||||||
|
if !envelope_acts_first && let Some(attributes) = lone_item_attributes(graphic.element_mut()) {
|
||||||
|
return edit(attributes);
|
||||||
|
}
|
||||||
|
edit(graphic.attributes_mut())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The attributes of the one item a graphic holds, or `None` if it holds a list.
|
||||||
|
fn lone_item_attributes(graphic: &mut Graphic) -> Option<&mut ItemAttributeValues> {
|
||||||
|
Some(match graphic {
|
||||||
|
Graphic::Graphic(item) => item.attributes_mut(),
|
||||||
|
Graphic::Vector(item) => item.attributes_mut(),
|
||||||
|
Graphic::RasterCPU(item) => item.attributes_mut(),
|
||||||
|
Graphic::RasterGPU(item) => item.attributes_mut(),
|
||||||
|
Graphic::Color(item) => item.attributes_mut(),
|
||||||
|
Graphic::Gradient(item) => item.attributes_mut(),
|
||||||
|
Graphic::Generator(item) => item.attributes_mut(),
|
||||||
|
Graphic::Text(item) => item.attributes_mut(),
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stamps the adjustment onto the effects in these attributes.
|
||||||
|
fn stamp_adjustment(attributes: &mut ItemAttributeValues, adjustment: Adjustment) {
|
||||||
|
stamp_effect_on(attributes, Effect::new(&EffectOperation::Adjustment(adjustment)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A monochrome Channel Mixer graying each color by its red, green, and blue channels weighted by the `weights` in percent.
|
||||||
|
fn channel_gray(weights: [f64; 3]) -> Adjustment {
|
||||||
|
let row = |[red, green, blue]: [f64; 3]| ChannelMixerRow { red, green, blue, constant: 0. };
|
||||||
|
|
||||||
|
// The rows a monochrome mixer ignores keep the node's defaults, so they stamp nothing
|
||||||
|
Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||||
|
monochrome: true,
|
||||||
|
monochrome_mix: row(weights),
|
||||||
|
red: row([100., 0., 0.]),
|
||||||
|
green: row([0., 100., 0.]),
|
||||||
|
blue: row([0., 0., 100.]),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use core_types::ATTR_TRANSFORM;
|
||||||
|
use core_types::color::Color;
|
||||||
|
use glam::{DVec2, UVec2};
|
||||||
|
use raster_types::{CPU, Image, Raster};
|
||||||
|
|
||||||
|
/// An image of `pixels` in one row, one pixel per document unit, embedded in a graphic as a wire of images embeds it.
|
||||||
|
fn image(pixels: &[Color]) -> Item<Graphic> {
|
||||||
|
let image = Image {
|
||||||
|
width: pixels.len() as u32,
|
||||||
|
height: 1,
|
||||||
|
data: pixels.to_vec(),
|
||||||
|
};
|
||||||
|
let raster = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(pixels.len() as f64, 1.)));
|
||||||
|
Item::new_from_element(Graphic::from(raster))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The image a graphic holds alone.
|
||||||
|
fn lone_image(graphic: &Item<Graphic>) -> &Item<Raster<CPU>> {
|
||||||
|
let Graphic::RasterCPU(raster) = graphic.element() else { panic!("expected a lone image") };
|
||||||
|
raster
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The graphic's rendered pixels as straight-alpha RGBA8, one pixel per document unit from its origin across a `size` view, or `None` without a GPU.
|
||||||
|
fn rendered(graphic: &Item<Graphic>, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||||||
|
use rendering::{Render, RenderParams};
|
||||||
|
|
||||||
|
let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?;
|
||||||
|
let list = core_types::list::List::new_from_item(graphic.clone());
|
||||||
|
let draw = &mut |scene: &mut rendering::vello_scene_builder::VelloSceneBuilder| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
||||||
|
let texture = executor.render_vello(size, DAffine2::IDENTITY, draw).expect("the graphic should render");
|
||||||
|
let pixels = executor.read_texture_pixels(&texture).expect("the render should read back");
|
||||||
|
Some(pixels.as_chunks::<4>().0.to_vec())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn into_channels_grays_each_color_keeping_its_alpha_and_makes_the_alpha_opaque() {
|
||||||
|
use raster_kernels::adjustments::adjust_color;
|
||||||
|
|
||||||
|
// A translucent pixel and a fully transparent one, whose hidden color its channels still gray
|
||||||
|
let pixels = [Color::from_rgbaf32_unchecked(0.75, 0.1, 0.3, 0.6), Color::from_rgbaf32_unchecked(0.25, 0.5, 1., 0.)];
|
||||||
|
let Channels { red, green, blue, alpha } = into_channels((), image(&pixels));
|
||||||
|
|
||||||
|
// Each output is the image itself, still an image, with adjustments graying each pixel to one channel's gamma-encoded level, or the alpha's
|
||||||
|
for (channel, output) in [red, green, blue, alpha].into_iter().enumerate() {
|
||||||
|
assert_eq!(output.attributes().iter_any().count(), 0, "the envelope stays empty");
|
||||||
|
let raster = lone_image(&output);
|
||||||
|
assert_eq!(raster.element().data, pixels, "the pixels are left alone");
|
||||||
|
let effects = raster.attribute::<Effects>(ATTR_EFFECTS).cloned().unwrap_or_default();
|
||||||
|
|
||||||
|
for pixel in pixels {
|
||||||
|
let gray = effects.operations().fold(pixel, |color, operation| match operation {
|
||||||
|
EffectOperation::Adjustment(adjustment) => adjust_color(&adjustment, color),
|
||||||
|
operation => panic!("{operation:?} isn't an adjustment"),
|
||||||
|
});
|
||||||
|
|
||||||
|
// The colors keep the pixel's alpha, and the alpha is opaque
|
||||||
|
let (level, kept_alpha) = match channel {
|
||||||
|
3 => (pixel.a(), 1.),
|
||||||
|
_ => (pixel.to_gamma_srgb_channels()[channel], pixel.a()),
|
||||||
|
};
|
||||||
|
let [r, g, b, a] = gray.to_gamma_srgb_channels();
|
||||||
|
assert!(
|
||||||
|
[r, g, b].iter().all(|gray| (gray - level).abs() < 1e-5) && (a - kept_alpha).abs() < 1e-6,
|
||||||
|
"channel {channel} of {pixel:?} grays to {gray:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn into_channels_color_outputs_keep_the_sources_transparency() {
|
||||||
|
// Half transparent white, then fully transparent red, then opaque white
|
||||||
|
let Channels { red, .. } = into_channels((), image(&[Color::WHITE.with_alpha(0.5), Color::from_rgbaf32_unchecked(1., 0., 0., 0.), Color::WHITE]));
|
||||||
|
|
||||||
|
let Some(pixels) = rendered(&red, UVec2::new(3, 1)) else { return };
|
||||||
|
assert!(pixels[0][..3] == [255; 3] && pixels[0][3].abs_diff(128) <= 1, "{:?}", pixels[0]);
|
||||||
|
assert_eq!(pixels[1][3], 0, "the transparent pixel stays transparent");
|
||||||
|
assert_eq!(pixels[2], [255; 4]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn into_channels_adjusts_a_graphic_by_its_envelope_where_its_fill_acts_first() {
|
||||||
|
use graphic_types::EffectKind::{AlphaToGray, MakeOpaque};
|
||||||
|
|
||||||
|
let kinds = |effects: Option<&Effects>| effects.map_or(Vec::new(), |effects| effects.effects().map(|effect| effect.kind()).collect::<Vec<_>>());
|
||||||
|
|
||||||
|
// A placement alone leaves the image within to take the effects, so a placement left at its default acts as no placement
|
||||||
|
let placed = image(&[Color::WHITE]).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(3., 0.)));
|
||||||
|
let Channels { alpha, .. } = into_channels((), placed);
|
||||||
|
assert_eq!(kinds(lone_image(&alpha).attribute(ATTR_EFFECTS)), [AlphaToGray, MakeOpaque]);
|
||||||
|
|
||||||
|
// The envelope's fill fades the image before the effects appended to the graphic, so they go on the envelope
|
||||||
|
let faded = image(&[Color::WHITE]).with_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||||
|
let Channels { alpha, .. } = into_channels((), faded);
|
||||||
|
assert_eq!(kinds(alpha.attribute(ATTR_EFFECTS)), [AlphaToGray, MakeOpaque]);
|
||||||
|
assert!(lone_image(&alpha).attribute::<Effects>(ATTR_EFFECTS).is_none(), "the image within is left alone");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn into_channels_renders_an_images_alpha_opaque_across_its_rectangle() {
|
||||||
|
// A half transparent pixel, which shows middle gray, then a fully transparent one, which shows black rather than nothing
|
||||||
|
let Channels { alpha, .. } = into_channels((), image(&[Color::WHITE.with_alpha(0.5), Color::TRANSPARENT]));
|
||||||
|
|
||||||
|
let Some(pixels) = rendered(&alpha, UVec2::new(3, 1)) else { return };
|
||||||
|
assert!(pixels[0][..3].iter().all(|level| level.abs_diff(128) <= 1) && pixels[0][3] == 255, "{:?}", pixels[0]);
|
||||||
|
assert_eq!(pixels[1], [0, 0, 0, 255]);
|
||||||
|
assert_eq!(pixels[2][3], 0, "past the image");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A square image of `size` pixels filled with one straight color, placed at `x` with one pixel per document unit, embedded in a graphic as a wire of images embeds it.
|
||||||
|
fn filled(size: u32, color: Color, x: f64) -> Item<Graphic> {
|
||||||
|
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(size as f64), 0., DVec2::new(x, 0.));
|
||||||
|
Item::new_from_element(Graphic::from(
|
||||||
|
Item::new_from_element(Raster::new_cpu(Image::new(size, size, color))).with_attribute(ATTR_TRANSFORM, placement),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn from_channels_groups_each_input_keeping_only_its_own_channel() {
|
||||||
|
use core_types::ATTR_OPACITY;
|
||||||
|
use graphic_types::EffectKind::{ChannelMixer, MakeOpaque, Mask};
|
||||||
|
|
||||||
|
let gray = |value: f32| filled(2, Color::from_rgbaf32_unchecked(value, value, value, 1.), 0.);
|
||||||
|
let kinds = |effects: Option<&Effects>| effects.map_or(Vec::new(), |effects| effects.effects().map(|effect| effect.kind()).collect::<Vec<_>>());
|
||||||
|
let members = |graphic: &Item<Graphic>| match graphic.element() {
|
||||||
|
Graphic::GraphicList(group) => group.clone(),
|
||||||
|
element => panic!("expected a group, found {element:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Each input in turn, made opaque with only its own channel, its opacity left out, and those after the first added on, all masked by the alpha
|
||||||
|
let mut red = gray(0.25);
|
||||||
|
red.set_attribute(ATTR_OPACITY, 0.5);
|
||||||
|
let result = from_channels((), (), red, gray(0.5), gray(0.75), gray(1.));
|
||||||
|
let group = members(&result);
|
||||||
|
assert_eq!(group.len(), 4);
|
||||||
|
for (index, member) in (0..group.len()).filter_map(|index| group.clone_item(index)).enumerate() {
|
||||||
|
let blend_mode = member.attribute_cloned_or_default::<BlendMode>(ATTR_BLEND_MODE);
|
||||||
|
assert_eq!(blend_mode, if index == 0 { BlendMode::Normal } else { BlendMode::LinearDodge });
|
||||||
|
assert_eq!(member.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 1.);
|
||||||
|
let Graphic::RasterCPU(raster) = member.element() else { panic!("expected an image") };
|
||||||
|
assert_eq!(kinds(raster.attribute(ATTR_EFFECTS)), [MakeOpaque, ChannelMixer]);
|
||||||
|
}
|
||||||
|
assert_eq!(kinds(result.attribute(ATTR_EFFECTS)), [Mask]);
|
||||||
|
|
||||||
|
// Without the alpha, the group is made opaque, and the alpha alone gives black it masks
|
||||||
|
let opaque = from_channels((), (), gray(0.25), Item::default(), Item::default(), Item::default());
|
||||||
|
assert_eq!((members(&opaque).len(), kinds(opaque.attribute(ATTR_EFFECTS))), (1, vec![MakeOpaque]));
|
||||||
|
let alpha = from_channels((), (), Item::default(), Item::default(), Item::default(), gray(0.5));
|
||||||
|
assert_eq!((members(&alpha).len(), kinds(alpha.attribute(ATTR_EFFECTS))), (1, vec![Mask]));
|
||||||
|
assert!(from_channels((), (), Item::default(), Item::default(), Item::default(), Item::default()).element().draws_nothing());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn into_channels_and_back_from_channels_reproduces_the_image_with_its_partial_alpha() {
|
||||||
|
// Colors across each channel, with every third pixel half transparent
|
||||||
|
let data = (0..64)
|
||||||
|
.map(|index| {
|
||||||
|
let (x, y) = ((index % 8) as f32, (index / 8) as f32);
|
||||||
|
let alpha = if index % 3 == 0 { 0.5 } else { 1. };
|
||||||
|
Color::from_gamma_srgb_channels(x / 7., y / 7., (x + y) / 14., alpha)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let raster = Item::new_from_element(Raster::new_cpu(Image { width: 8, height: 8, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.)));
|
||||||
|
let image = Item::new_from_element(Graphic::from(raster));
|
||||||
|
|
||||||
|
let Channels { red, green, blue, alpha } = into_channels((), image.clone());
|
||||||
|
let recombined = from_channels((), (), red, green, blue, alpha);
|
||||||
|
|
||||||
|
let size = UVec2::splat(8);
|
||||||
|
let (Some(original), Some(recombined)) = (rendered(&image, size), rendered(&recombined, size)) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for (index, (original, recombined)) in original.iter().zip(&recombined).enumerate() {
|
||||||
|
let stray = original.iter().zip(recombined).map(|(original, recombined)| original.abs_diff(*recombined)).max().unwrap_or_default();
|
||||||
|
assert!(stray <= 2, "pixel {index} renders as {recombined:?} rather than {original:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn from_channels_lines_up_its_inputs_where_they_lie_in_the_document() {
|
||||||
|
// Red and green overlap by half, and a half gray alpha starts a pixel in from the red
|
||||||
|
let half_gray = Color::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.);
|
||||||
|
let result = from_channels((), (), filled(4, Color::WHITE, 0.), filled(4, Color::WHITE, 2.), Item::default(), filled(4, half_gray, 1.));
|
||||||
|
|
||||||
|
let size = UVec2::new(8, 4);
|
||||||
|
let Some(pixels) = rendered(&result, size) else { return };
|
||||||
|
let at = |x: u32| pixels[(size.x + x) as usize];
|
||||||
|
let half_shown = |[red, green, blue, alpha]: [u8; 4], expected: [u8; 3]| [red, green, blue] == expected && alpha.abs_diff(128) <= 1;
|
||||||
|
assert_eq!(at(0)[3], 0, "outside the alpha");
|
||||||
|
assert!(half_shown(at(1), [255, 0, 0]), "red alone, half shown: {:?}", at(1));
|
||||||
|
assert!(half_shown(at(3), [255, 255, 0]), "red and green: {:?}", at(3));
|
||||||
|
assert_eq!(at(5)[3], 0, "outside the alpha");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Red over the left four of a 12 by 4 render and green over the right four, past the red's rectangle, without an alpha.
|
||||||
|
fn red_and_green_apart() -> Item<Graphic> {
|
||||||
|
from_channels((), (), filled(4, Color::WHITE, 0.), filled(4, Color::WHITE, 8.), Item::default(), Item::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn from_channels_covers_a_green_input_shifted_past_the_red() {
|
||||||
|
// Over a gray beneath, which the channels don't add onto
|
||||||
|
let beneath = filled(12, Color::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.), 0.);
|
||||||
|
let group: List<Graphic> = [beneath, red_and_green_apart()].into_iter().collect();
|
||||||
|
|
||||||
|
let size = UVec2::new(12, 4);
|
||||||
|
let Some(pixels) = rendered(&Item::new_from_element(Graphic::GraphicList(group)), size) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
assert_eq!(pixels[(size.x + 1) as usize], [255, 0, 0, 255]);
|
||||||
|
assert_eq!(pixels[(size.x + 10) as usize], [0, 255, 0, 255]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn from_channels_leaves_what_no_input_covers_transparent() {
|
||||||
|
let size = UVec2::new(12, 4);
|
||||||
|
let Some(pixels) = rendered(&red_and_green_apart(), size) else { return };
|
||||||
|
assert_eq!(pixels[(size.x + 1) as usize], [255, 0, 0, 255]);
|
||||||
|
assert_eq!(pixels[(size.x + 6) as usize][3], 0, "between the inputs");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,15 +2,14 @@ use core_types::context::Ctx;
|
|||||||
use core_types::list::Item;
|
use core_types::list::Item;
|
||||||
use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage};
|
use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage};
|
||||||
use ndarray::{Array2, ArrayBase, Dim, OwnedRepr};
|
use ndarray::{Array2, ArrayBase, Dim, OwnedRepr};
|
||||||
use raster_kernels::evaluate_raster_effects;
|
|
||||||
use raster_types::Image;
|
use raster_types::Image;
|
||||||
use raster_types::{CPU, Raster};
|
use raster_types::{CPU, Pixels, Raster};
|
||||||
use std::cmp::{max, min};
|
use std::cmp::{max, min};
|
||||||
|
|
||||||
#[node_macro::node(category("Raster: Filter"), icon("NodeDehaze"), memoize)]
|
#[node_macro::node(category("Raster: Filter"), icon("NodeDehaze"), memoize)]
|
||||||
fn dehaze(
|
fn dehaze(
|
||||||
_: impl Ctx,
|
_: impl Ctx,
|
||||||
image_frame: Item<Raster<CPU>>,
|
image_frame: Item<Pixels>,
|
||||||
#[unit("%")]
|
#[unit("%")]
|
||||||
#[range]
|
#[range]
|
||||||
#[hard(0..100)]
|
#[hard(0..100)]
|
||||||
@@ -18,7 +17,8 @@ fn dehaze(
|
|||||||
) -> Item<Raster<CPU>> {
|
) -> Item<Raster<CPU>> {
|
||||||
let strength = *strength.element();
|
let strength = *strength.element();
|
||||||
|
|
||||||
let (image, attributes) = evaluate_raster_effects(image_frame).into_parts();
|
let (pixels, attributes) = image_frame.into_parts();
|
||||||
|
let image = pixels.into_raster();
|
||||||
let (width, height) = (image.width, image.height);
|
let (width, height) = (image.width, image.height);
|
||||||
|
|
||||||
// Prepare the image data for processing
|
// Prepare the image data for processing
|
||||||
|
|||||||
@@ -1,95 +1,27 @@
|
|||||||
use core_types::color::Color;
|
use core_types::color::Color;
|
||||||
use core_types::context::Ctx;
|
use core_types::context::Ctx;
|
||||||
use core_types::list::Item;
|
use core_types::list::Item;
|
||||||
use raster_kernels::evaluate_raster_effects;
|
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||||
use raster_types::Bitmap;
|
use raster_types::{CPU, GPU, Raster};
|
||||||
use raster_types::Image;
|
use vector_types::Gradient;
|
||||||
use raster_types::parallel_rows::fill_rows;
|
|
||||||
use raster_types::{CPU, Raster};
|
|
||||||
|
|
||||||
/// Applies a median filter to reduce noise while preserving edges.
|
/// Applies a median filter to reduce noise while preserving edges, giving each pixel the middle value of each channel among the pixels in a square around it.
|
||||||
#[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"), memoize)]
|
///
|
||||||
fn median_filter(
|
/// It works on an image's own pixels, or the document's pixels for other graphics, so it looks the same at any zoom.
|
||||||
|
#[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"), version(2))]
|
||||||
|
fn median_filter<T>(
|
||||||
_: impl Ctx,
|
_: impl Ctx,
|
||||||
/// The image to be filtered.
|
/// The content to be filtered.
|
||||||
image_frame: Item<Raster<CPU>>,
|
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||||
/// The radius of the filter kernel. Larger values remove more noise but may blur fine details.
|
content: Item<T>,
|
||||||
|
/// How far the square around each pixel reaches, in whole pixels. Larger values remove more noise but may blur fine details.
|
||||||
#[unit(" px")]
|
#[unit(" px")]
|
||||||
#[range]
|
#[range]
|
||||||
#[hard(0..)]
|
#[hard(0..)]
|
||||||
#[soft(..50)]
|
#[soft(..50)]
|
||||||
radius: Item<f64>,
|
radius: Item<f64>,
|
||||||
) -> Item<Raster<CPU>> {
|
) -> Item<T> {
|
||||||
let radius = *radius.element();
|
let mut content = content;
|
||||||
|
stamp_effect(&mut content, Effect::new(&EffectOperation::Median { radius: *radius.element() }));
|
||||||
let (image, attributes) = evaluate_raster_effects(image_frame).into_parts();
|
content
|
||||||
|
|
||||||
// TODO: Scale the radius through the footprint so it acts as the document-space length its Pixels unit promises, with a
|
|
||||||
// window that varies continuously rather than snapping to whole source pixels
|
|
||||||
let filtered_image = if radius < 0.5 {
|
|
||||||
// Minimum filter radius
|
|
||||||
image
|
|
||||||
} else {
|
|
||||||
Raster::new_cpu(median_filter_algorithm(image.into_data(), radius as u32))
|
|
||||||
};
|
|
||||||
|
|
||||||
Item::from_parts(filtered_image, attributes)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn median_filter_algorithm(original_buffer: Image<Color>, radius: u32) -> Image<Color> {
|
|
||||||
let (width, height) = original_buffer.dimensions();
|
|
||||||
let mut output = Image::new(width, height, Color::TRANSPARENT);
|
|
||||||
|
|
||||||
let window_span = |extent: u32| (radius as usize).saturating_mul(2).saturating_add(1).min(extent as usize);
|
|
||||||
let window_capacity = window_span(width) * window_span(height);
|
|
||||||
|
|
||||||
fill_rows(&mut output.data, width as usize, |y, row| {
|
|
||||||
let y = y as u32;
|
|
||||||
|
|
||||||
// Allocated once for the row and reused for each of its pixels
|
|
||||||
let mut r_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
|
||||||
let mut g_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
|
||||||
let mut b_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
|
||||||
let mut a_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
|
||||||
|
|
||||||
for (x, output_pixel) in row.iter_mut().enumerate() {
|
|
||||||
let x = x as u32;
|
|
||||||
r_vals.clear();
|
|
||||||
g_vals.clear();
|
|
||||||
b_vals.clear();
|
|
||||||
a_vals.clear();
|
|
||||||
|
|
||||||
// Use saturating_add to avoid potential overflow in extreme cases
|
|
||||||
let y_max = y.saturating_add(radius).min(height - 1);
|
|
||||||
let x_max = x.saturating_add(radius).min(width - 1);
|
|
||||||
|
|
||||||
for ny in y.saturating_sub(radius)..=y_max {
|
|
||||||
for nx in x.saturating_sub(radius)..=x_max {
|
|
||||||
if let Some(px) = original_buffer.get_pixel(nx, ny) {
|
|
||||||
r_vals.push(px.r());
|
|
||||||
g_vals.push(px.g());
|
|
||||||
b_vals.push(px.b());
|
|
||||||
a_vals.push(px.a());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let r = median_quickselect(&mut r_vals);
|
|
||||||
let g = median_quickselect(&mut g_vals);
|
|
||||||
let b = median_quickselect(&mut b_vals);
|
|
||||||
let a = median_quickselect(&mut a_vals);
|
|
||||||
|
|
||||||
*output_pixel = Color::from_rgbaf32_unchecked(r, g, b, a);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
output
|
|
||||||
}
|
|
||||||
/// Finds the median of a slice using quickselect for O(n) average case performance.
|
|
||||||
/// This is more efficient than sorting the entire slice which would be O(n log n).
|
|
||||||
fn median_quickselect(values: &mut [f32]) -> f32 {
|
|
||||||
let mid: usize = values.len() / 2;
|
|
||||||
// nth_unstable is like quickselect: average O(n)
|
|
||||||
// Use total_cmp for safe NaN handling instead of partial_cmp().unwrap()
|
|
||||||
*values.select_nth_unstable_by(mid, |a, b| a.total_cmp(b)).1
|
|
||||||
}
|
}
|
||||||
@@ -2,8 +2,7 @@ use color::{ColorSpace, Oklab};
|
|||||||
use core_types::color::Color;
|
use core_types::color::Color;
|
||||||
use core_types::context::Ctx;
|
use core_types::context::Ctx;
|
||||||
use core_types::list::{Item, List};
|
use core_types::list::{Item, List};
|
||||||
use raster_kernels::evaluate_raster_effects;
|
use raster_types::Pixels;
|
||||||
use raster_types::{CPU, Raster};
|
|
||||||
use std::collections::BinaryHeap;
|
use std::collections::BinaryHeap;
|
||||||
use std::ops::{AddAssign, SubAssign};
|
use std::ops::{AddAssign, SubAssign};
|
||||||
|
|
||||||
@@ -19,14 +18,13 @@ const OKLAB_GAMUT_RANGES: [(f32, f32); 3] = [(0., 1.), (-0.24, 0.28), (-0.32, 0.
|
|||||||
fn image_color_palette(
|
fn image_color_palette(
|
||||||
_: impl Ctx,
|
_: impl Ctx,
|
||||||
/// The image to find colors in.
|
/// The image to find colors in.
|
||||||
image: Item<Raster<CPU>>,
|
image: Item<Pixels>,
|
||||||
/// How many colors to find. Raising it adds a color at the end and may adjust one existing color, leaving the rest as they were.
|
/// How many colors to find. Raising it adds a color at the end and may adjust one existing color, leaving the rest as they were.
|
||||||
#[default(4)]
|
#[default(4)]
|
||||||
#[hard(1..)]
|
#[hard(1..)]
|
||||||
count: Item<i64>,
|
count: Item<i64>,
|
||||||
) -> List<Color> {
|
) -> List<Color> {
|
||||||
let count = *count.element() as usize;
|
let count = *count.element() as usize;
|
||||||
let image = evaluate_raster_effects(image);
|
|
||||||
|
|
||||||
// O(n) binning of the image's n pixels into an OkLab histogram, weighted by alpha so transparent pixels are ignored
|
// O(n) binning of the image's n pixels into an OkLab histogram, weighted by alpha so transparent pixels are ignored
|
||||||
let mut cumulative = vec![Moments::default(); TABLE_SIDE.pow(3)];
|
let mut cumulative = vec![Moments::default(); TABLE_SIDE.pow(3)];
|
||||||
@@ -227,7 +225,7 @@ fn table_index(position: [usize; 3]) -> usize {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use super::*;
|
use super::*;
|
||||||
use raster_types::Image;
|
use raster_types::{Image, Raster};
|
||||||
|
|
||||||
fn palette(runs: &[(Color, usize)], count: i64) -> Vec<Color> {
|
fn palette(runs: &[(Color, usize)], count: i64) -> Vec<Color> {
|
||||||
let data = runs.iter().flat_map(|&(color, length)| std::iter::repeat_n(color, length)).collect::<Vec<_>>();
|
let data = runs.iter().flat_map(|&(color, length)| std::iter::repeat_n(color, length)).collect::<Vec<_>>();
|
||||||
@@ -237,7 +235,7 @@ mod test {
|
|||||||
data,
|
data,
|
||||||
});
|
});
|
||||||
|
|
||||||
let palette = image_color_palette((), Item::new_from_element(image), Item::new_from_element(count));
|
let palette = image_color_palette((), Item::new_from_element(Pixels::new(image)), Item::new_from_element(count));
|
||||||
palette.iter_element_values().copied().collect()
|
palette.iter_element_values().copied().collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
pub mod adjustments;
|
pub mod adjustments;
|
||||||
pub mod blending_nodes;
|
pub mod blending_nodes;
|
||||||
|
pub mod channels;
|
||||||
pub use raster_kernels::color_lookup_table;
|
pub use raster_kernels::color_lookup_table;
|
||||||
pub mod dehaze;
|
pub mod dehaze;
|
||||||
pub mod filter;
|
pub mod filter;
|
||||||
|
|||||||
@@ -1,17 +1,10 @@
|
|||||||
use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
||||||
use core_types::ATTR_TRANSFORM;
|
|
||||||
use core_types::color::Color;
|
|
||||||
use core_types::color::{AlphaMut, LinearChannel, Luminance, RGBMut};
|
|
||||||
use core_types::context::Ctx;
|
use core_types::context::Ctx;
|
||||||
use core_types::list::Item;
|
use core_types::list::Item;
|
||||||
use core_types::math::bbox::Bbox;
|
|
||||||
use core_types::transform::Transform;
|
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
use glam::{DAffine2, DVec2, UVec2};
|
use glam::DVec2;
|
||||||
use graphene_resource::Resource;
|
use graphene_resource::Resource;
|
||||||
use graphic_types::generator::{Generator, MandelbrotSettings, NoiseSettings};
|
use graphic_types::generator::{Generator, MandelbrotSettings, NoiseSettings};
|
||||||
use raster_kernels::evaluate_raster_effects;
|
|
||||||
use raster_types::{Bitmap, BitmapMut};
|
|
||||||
use raster_types::{CPU, Raster};
|
use raster_types::{CPU, Raster};
|
||||||
use raster_types::{Image, ImageError};
|
use raster_types::{Image, ImageError};
|
||||||
use std::fmt::Debug;
|
use std::fmt::Debug;
|
||||||
@@ -29,156 +22,6 @@ impl From<std::io::Error> for Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Two rasters that must line up pixel for pixel but differ in size.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
|
||||||
#[error("{first} and {second} must be the same size, but {first} is {}×{} pixels and {second} is {}×{}", .first_size.x, .first_size.y, .second_size.x, .second_size.y)]
|
|
||||||
pub struct SizeMismatchError {
|
|
||||||
pub first: &'static str,
|
|
||||||
pub first_size: UVec2,
|
|
||||||
pub second: &'static str,
|
|
||||||
pub second_size: UVec2,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), name("Channels to Image"), memoize)]
|
|
||||||
fn channels_to_image(
|
|
||||||
_: impl Ctx,
|
|
||||||
_primary: (),
|
|
||||||
#[expose] red: Item<Raster<CPU>>,
|
|
||||||
#[expose] green: Item<Raster<CPU>>,
|
|
||||||
#[expose] blue: Item<Raster<CPU>>,
|
|
||||||
#[expose] alpha: Item<Raster<CPU>>,
|
|
||||||
) -> Result<Item<Raster<CPU>>, SizeMismatchError> {
|
|
||||||
// An unconnected channel arrives as the default zero-sized raster, which counts as absent
|
|
||||||
let present = |channel: Item<Raster<CPU>>| (channel.element().width > 0 && channel.element().height > 0).then_some(channel);
|
|
||||||
let channels = [red, green, blue, alpha].map(present);
|
|
||||||
|
|
||||||
// All present channels must share the same dimensions
|
|
||||||
let dimensions = |channel: &Item<Raster<CPU>>| UVec2::new(channel.element().width, channel.element().height);
|
|
||||||
let mut present_channels = ["Red", "Green", "Blue", "Alpha"]
|
|
||||||
.into_iter()
|
|
||||||
.zip(&channels)
|
|
||||||
.filter_map(|(name, channel)| Some((name, channel.as_ref()?)));
|
|
||||||
let Some((first, first_channel)) = present_channels.next() else {
|
|
||||||
return Ok(Item::default());
|
|
||||||
};
|
|
||||||
let (first_size, transform) = (dimensions(first_channel), first_channel.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM));
|
|
||||||
if let Some((second, second_channel)) = present_channels.find(|(_, channel)| dimensions(channel) != first_size) {
|
|
||||||
return Err(SizeMismatchError {
|
|
||||||
first,
|
|
||||||
first_size,
|
|
||||||
second,
|
|
||||||
second_size: dimensions(second_channel),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let (width, height) = (first_size.x, first_size.y);
|
|
||||||
|
|
||||||
// A channel's effects grow it by the margin they cast past its edges, so every channel is placed within the widest margin
|
|
||||||
let channels = channels.map(|channel| channel.map(evaluate_raster_effects));
|
|
||||||
let margin = |channel: &Item<Raster<CPU>>| ((channel.element().width - width) / 2, (channel.element().height - height) / 2);
|
|
||||||
let (margin_x, margin_y) = channels
|
|
||||||
.iter()
|
|
||||||
.flatten()
|
|
||||||
.map(margin)
|
|
||||||
.fold((0, 0), |(x, y), (channel_x, channel_y)| (x.max(channel_x), y.max(channel_y)));
|
|
||||||
|
|
||||||
// Take this item's blending attributes from the first present channel, whose effects are carried out by now
|
|
||||||
let Some(mut attributes) = channels.iter().flatten().next().map(|channel| channel.attributes().clone()) else {
|
|
||||||
return Ok(Item::default());
|
|
||||||
};
|
|
||||||
let size = DVec2::new(width as f64, height as f64);
|
|
||||||
let unit_margin = DVec2::new(margin_x as f64, margin_y as f64) / size;
|
|
||||||
attributes.insert(
|
|
||||||
ATTR_TRANSFORM,
|
|
||||||
transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin),
|
|
||||||
);
|
|
||||||
|
|
||||||
// A channel's value at a pixel of the output, with nothing past its own edges, or `None` if the channel is absent
|
|
||||||
let value = |channel: &Option<Item<Raster<CPU>>>, x: u32, y: u32| {
|
|
||||||
channel.as_ref().map(|channel| {
|
|
||||||
let (channel_margin_x, channel_margin_y) = margin(channel);
|
|
||||||
let (x, y) = ((x + channel_margin_x).checked_sub(margin_x), (y + channel_margin_y).checked_sub(margin_y));
|
|
||||||
x.zip(y).and_then(|(x, y)| channel.element().get_pixel(x, y)).map_or(0., |pixel| pixel.l().cast_linear_channel())
|
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
// Set each output pixel's channels from the present inputs, defaulting absent color channels to 0 and absent alpha to 1
|
|
||||||
let [red, green, blue, alpha] = &channels;
|
|
||||||
let mut image = Image::new(width + 2 * margin_x, height + 2 * margin_y, Color::TRANSPARENT);
|
|
||||||
for y in 0..image.height() {
|
|
||||||
for x in 0..image.width() {
|
|
||||||
let image_pixel = image.get_pixel_mut(x, y).unwrap();
|
|
||||||
|
|
||||||
image_pixel.set_red(value(red, x, y).unwrap_or(0.));
|
|
||||||
image_pixel.set_green(value(green, x, y).unwrap_or(0.));
|
|
||||||
image_pixel.set_blue(value(blue, x, y).unwrap_or(0.));
|
|
||||||
image_pixel.set_alpha(value(alpha, x, y).unwrap_or(1.));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Item::from_parts(Raster::new_cpu(image), attributes))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[node_macro::node(category(""))]
|
|
||||||
fn extend_image_to_bounds(_: impl Ctx, image: Item<Raster<CPU>>, bounds: Item<DAffine2>) -> Result<Item<Raster<CPU>>, (Item<Raster<CPU>>, ImageError)> {
|
|
||||||
let image = evaluate_raster_effects(image);
|
|
||||||
let bounds = *bounds.element();
|
|
||||||
|
|
||||||
let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
|
||||||
let image_aabb = Bbox::unit().affine_transform(image_transform).to_axis_aligned_bbox();
|
|
||||||
let bounds_aabb = Bbox::unit().affine_transform(bounds.transform()).to_axis_aligned_bbox();
|
|
||||||
if image_aabb.contains(bounds_aabb.start) && image_aabb.contains(bounds_aabb.end) {
|
|
||||||
return Ok(image);
|
|
||||||
}
|
|
||||||
|
|
||||||
let (image_width, image_height) = (image.element().width, image.element().height);
|
|
||||||
if image_width == 0 || image_height == 0 {
|
|
||||||
return empty_image(bounds, Color::TRANSPARENT).map_err(|error| (image, error));
|
|
||||||
}
|
|
||||||
if image_transform.matrix2.determinant() == 0. {
|
|
||||||
return Ok(image);
|
|
||||||
}
|
|
||||||
|
|
||||||
let orig_image_scale = DVec2::new(image_width as f64, image_height as f64);
|
|
||||||
let layer_to_image_space = DAffine2::from_scale(orig_image_scale) * image_transform.inverse();
|
|
||||||
let bounds_in_image_space = Bbox::unit().affine_transform(layer_to_image_space * bounds).to_axis_aligned_bbox();
|
|
||||||
|
|
||||||
let new_start = bounds_in_image_space.start.floor().min(DVec2::ZERO);
|
|
||||||
let new_end = bounds_in_image_space.end.ceil().max(orig_image_scale);
|
|
||||||
let new_scale = new_end - new_start;
|
|
||||||
|
|
||||||
// Copy over original image into enlarged image.
|
|
||||||
let mut new_image = match Image::try_new(new_scale.x as u32, new_scale.y as u32, Color::TRANSPARENT) {
|
|
||||||
Ok(new_image) => new_image,
|
|
||||||
Err(error) => return Err((image, error)),
|
|
||||||
};
|
|
||||||
let (image, mut attributes) = image.into_parts();
|
|
||||||
let offset_in_new_image = (-new_start).as_uvec2();
|
|
||||||
for y in 0..image_height {
|
|
||||||
let old_start = y * image_width;
|
|
||||||
let new_start = (y + offset_in_new_image.y) * new_image.width + offset_in_new_image.x;
|
|
||||||
let old_row = &image.data[old_start as usize..(old_start + image_width) as usize];
|
|
||||||
let new_row = &mut new_image.data[new_start as usize..(new_start + image_width) as usize];
|
|
||||||
new_row.copy_from_slice(old_row);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Compute new transform.
|
|
||||||
// let layer_to_new_texture_space = (DAffine2::from_scale(1. / new_scale) * DAffine2::from_translation(new_start) * layer_to_image_space).inverse();
|
|
||||||
let new_texture_to_layer_space = image_transform * DAffine2::from_scale(1. / orig_image_scale) * DAffine2::from_translation(new_start) * DAffine2::from_scale(new_scale);
|
|
||||||
|
|
||||||
attributes.insert(ATTR_TRANSFORM, new_texture_to_layer_space);
|
|
||||||
Ok(Item::from_parts(Raster::new_cpu(new_image), attributes))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates an image filled with one color, sized in pixels by the transform's scale and placed by the transform.
|
|
||||||
fn empty_image(transform: DAffine2, color: Color) -> Result<Item<Raster<CPU>>, ImageError> {
|
|
||||||
let width = transform.transform_vector2(DVec2::new(1., 0.)).length() as u32;
|
|
||||||
let height = transform.transform_vector2(DVec2::new(0., 1.)).length() as u32;
|
|
||||||
|
|
||||||
let image = Image::try_new(width, height, color)?;
|
|
||||||
|
|
||||||
Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Displays an image from a file.
|
/// Displays an image from a file.
|
||||||
///
|
///
|
||||||
/// Reads PNG, JPG, GIF, WEBP, TIFF, BMP, TGA, ICO, HDR, and EXR files. Light brighter than white, as HDR and EXR files can hold, is clipped to white.
|
/// Reads PNG, JPG, GIF, WEBP, TIFF, BMP, TGA, ICO, HDR, and EXR files. Light brighter than white, as HDR and EXR files can hold, is clipped to white.
|
||||||
@@ -318,40 +161,3 @@ fn mandelbrot(
|
|||||||
settings.stamp(&mut generator);
|
settings.stamp(&mut generator);
|
||||||
generator
|
generator
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn channels_stay_aligned_when_effects_grow_only_one() {
|
|
||||||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
|
||||||
|
|
||||||
let gray = |value: f32| {
|
|
||||||
let image = Image::new(8, 8, Color::from_rgbaf32_unchecked(value, value, value, 1.));
|
|
||||||
Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.)))
|
|
||||||
};
|
|
||||||
|
|
||||||
// Only the red channel is blurred, which grows it by the blur's margin
|
|
||||||
let mut red = gray(1.);
|
|
||||||
stamp_effect(
|
|
||||||
&mut red,
|
|
||||||
Effect::new(&EffectOperation::Blur {
|
|
||||||
radius_mask: Graphic::default(),
|
|
||||||
radius: 1.,
|
|
||||||
box_blur: false,
|
|
||||||
gamma: false,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
let image = channels_to_image((), (), red, gray(0.5), gray(0.25), gray(1.)).unwrap();
|
|
||||||
|
|
||||||
// The other channels are placed within the same margin, and the whole image keeps its place in the document
|
|
||||||
let raster = image.element();
|
|
||||||
assert!(raster.width > 8 && raster.height > 8, "the image grows to hold the blur, rather than coming out empty");
|
|
||||||
let transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
|
||||||
let to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * transform.inverse();
|
|
||||||
let center = to_pixels.transform_point2(DVec2::splat(4.)).as_uvec2();
|
|
||||||
let pixel = raster.get_pixel(center.x, center.y).unwrap();
|
|
||||||
assert!((pixel.g() - 0.5).abs() < 1e-6 && (pixel.b() - 0.25).abs() < 1e-6, "the unblurred channels line up: {pixel:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -19,7 +19,6 @@ workspace = true
|
|||||||
core-types = { workspace = true }
|
core-types = { workspace = true }
|
||||||
vector-types = { workspace = true }
|
vector-types = { workspace = true }
|
||||||
raster-types = { workspace = true }
|
raster-types = { workspace = true }
|
||||||
raster-kernels = { workspace = true }
|
|
||||||
graphic-types = { workspace = true }
|
graphic-types = { workspace = true }
|
||||||
graphene-hash = { workspace = true }
|
graphene-hash = { workspace = true }
|
||||||
node-macro = { workspace = true }
|
node-macro = { workspace = true }
|
||||||
|
|||||||
@@ -9,8 +9,7 @@ use core_types::runtime::Runtime;
|
|||||||
use core_types::{ATTR_TRANSFORM, CacheHash, Ctx, Poll, RuntimeHandle, SourceId};
|
use core_types::{ATTR_TRANSFORM, CacheHash, Ctx, Poll, RuntimeHandle, SourceId};
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use graphic_types::Graphic;
|
use graphic_types::Graphic;
|
||||||
use raster_kernels::evaluate_raster_effects;
|
use raster_types::Pixels;
|
||||||
use raster_types::{CPU, Raster};
|
|
||||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@@ -42,7 +41,7 @@ const BROWSER_MAX_MEGABYTES: f64 = 1000.;
|
|||||||
fn vectorize(
|
fn vectorize(
|
||||||
_: impl Ctx,
|
_: impl Ctx,
|
||||||
/// The image to trace.
|
/// The image to trace.
|
||||||
image: Item<Raster<CPU>>,
|
image: Item<Pixels>,
|
||||||
/// How much detail to keep, as a multiple of the default level read from how busy the image is. Higher values spend more segments on smaller features.
|
/// How much detail to keep, as a multiple of the default level read from how busy the image is. Higher values spend more segments on smaller features.
|
||||||
#[default(1.)]
|
#[default(1.)]
|
||||||
#[hard(0.01..)]
|
#[hard(0.01..)]
|
||||||
@@ -107,7 +106,7 @@ fn vectorize(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Runs one slice of the trace held in `slot`, starting a new trace if `slot` holds none for these inputs.
|
/// Runs one slice of the trace held in `slot`, starting a new trace if `slot` holds none for these inputs.
|
||||||
fn trace_slice(image: &Item<Raster<CPU>>, detail: f64, tolerance: f64, stages: ollev::Stages, max_pixels: Option<usize>, slot: &TraceSlot, slice: Duration) -> Poll<List<Graphic>> {
|
fn trace_slice(image: &Item<Pixels>, detail: f64, tolerance: f64, stages: ollev::Stages, max_pixels: Option<usize>, slot: &TraceSlot, slice: Duration) -> Poll<List<Graphic>> {
|
||||||
if image.element().width == 0 || image.element().height == 0 {
|
if image.element().width == 0 || image.element().height == 0 {
|
||||||
slot.clear();
|
slot.clear();
|
||||||
return Poll::Final(List::new());
|
return Poll::Final(List::new());
|
||||||
@@ -118,9 +117,7 @@ fn trace_slice(image: &Item<Raster<CPU>>, detail: f64, tolerance: f64, stages: o
|
|||||||
(detail.to_bits(), tolerance.to_bits(), max_pixels).hash(&mut hasher);
|
(detail.to_bits(), tolerance.to_bits(), max_pixels).hash(&mut hasher);
|
||||||
[stages.translucency, stages.strokes, stages.primitives, stages.effects, stages.instancing, stages.path_gradients].hash(&mut hasher);
|
[stages.translucency, stages.strokes, stages.primitives, stages.effects, stages.instancing, stages.path_gradients].hash(&mut hasher);
|
||||||
|
|
||||||
// The image's effects are carried out once for the whole trace, rather than on each slice
|
|
||||||
let start = || {
|
let start = || {
|
||||||
let image = evaluate_raster_effects(image.clone());
|
|
||||||
let raster = image.element();
|
let raster = image.element();
|
||||||
let (width, height) = (raster.width as usize, raster.height as usize);
|
let (width, height) = (raster.width as usize, raster.height as usize);
|
||||||
let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
@@ -154,23 +151,23 @@ mod test {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use core_types::runtime::{AsyncRuntime, Spawn, Task};
|
use core_types::runtime::{AsyncRuntime, Spawn, Task};
|
||||||
use raster_types::Image;
|
use raster_types::{Image, Raster};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::task::{Context, Waker};
|
use std::task::{Context, Waker};
|
||||||
|
|
||||||
/// An image of `width` by `height` pixels colored by `color` at each pixel's column and row.
|
/// An image of `width` by `height` pixels colored by `color` at each pixel's column and row.
|
||||||
fn raster(width: u32, height: u32, color: impl Fn(u32, u32) -> Color) -> Item<Raster<CPU>> {
|
fn raster(width: u32, height: u32, color: impl Fn(u32, u32) -> Color) -> Item<Pixels> {
|
||||||
let data = (0..width * height).map(|index| color(index % width, index / width)).collect();
|
let data = (0..width * height).map(|index| color(index % width, index / width)).collect();
|
||||||
Item::new_from_element(Raster::new_cpu(Image { width, height, data }))
|
Item::new_from_element(Pixels::new(Raster::new_cpu(Image { width, height, data })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One slice of `image` traced at default settings by the node holding `slot`.
|
/// One slice of `image` traced at default settings by the node holding `slot`.
|
||||||
fn slice(image: &Item<Raster<CPU>>, slot: &TraceSlot) -> Poll<List<Graphic>> {
|
fn slice(image: &Item<Pixels>, slot: &TraceSlot) -> Poll<List<Graphic>> {
|
||||||
trace_slice(image, 1., 1., ollev::Stages::ALL, None, slot, SLICE)
|
trace_slice(image, 1., 1., ollev::Stages::ALL, None, slot, SLICE)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The shapes traced from `image` at `detail` and `tolerance` by a node of its own, slice by slice.
|
/// The shapes traced from `image` at `detail` and `tolerance` by a node of its own, slice by slice.
|
||||||
fn trace(image: &Item<Raster<CPU>>, detail: f64, tolerance: f64) -> List<Graphic> {
|
fn trace(image: &Item<Pixels>, detail: f64, tolerance: f64) -> List<Graphic> {
|
||||||
let slot = TraceSlot::default();
|
let slot = TraceSlot::default();
|
||||||
loop {
|
loop {
|
||||||
match trace_slice(image, detail, tolerance, ollev::Stages::ALL, None, &slot, SLICE) {
|
match trace_slice(image, detail, tolerance, ollev::Stages::ALL, None, &slot, SLICE) {
|
||||||
@@ -184,7 +181,7 @@ mod test {
|
|||||||
const DARK: Color = Color::from_rgbaf32_unchecked(0.05, 0.1, 0.4, 1.);
|
const DARK: Color = Color::from_rgbaf32_unchecked(0.05, 0.1, 0.4, 1.);
|
||||||
|
|
||||||
/// A dark ring from `inner` to `inner + width` pixels out from the middle of a light square of `size` pixels.
|
/// A dark ring from `inner` to `inner + width` pixels out from the middle of a light square of `size` pixels.
|
||||||
fn ring(size: u32, inner: f64, width: f64) -> Item<Raster<CPU>> {
|
fn ring(size: u32, inner: f64, width: f64) -> Item<Pixels> {
|
||||||
let center = size as f64 / 2.;
|
let center = size as f64 / 2.;
|
||||||
raster(size, size, |x, y| {
|
raster(size, size, |x, y| {
|
||||||
let distance = DVec2::new(x as f64 + 0.5, y as f64 + 0.5).distance(DVec2::splat(center));
|
let distance = DVec2::new(x as f64 + 0.5, y as f64 + 0.5).distance(DVec2::splat(center));
|
||||||
@@ -228,7 +225,7 @@ mod test {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Shapes partly over one another: rings, a disc and a ramp, enough to keep a trace busy for many short slices.
|
/// Shapes partly over one another: rings, a disc and a ramp, enough to keep a trace busy for many short slices.
|
||||||
fn busy(size: u32) -> Item<Raster<CPU>> {
|
fn busy(size: u32) -> Item<Pixels> {
|
||||||
let center = DVec2::splat(size as f64 / 2.);
|
let center = DVec2::splat(size as f64 / 2.);
|
||||||
raster(size, size, |x, y| {
|
raster(size, size, |x, y| {
|
||||||
let point = DVec2::new(x as f64 + 0.5, y as f64 + 0.5);
|
let point = DVec2::new(x as f64 + 0.5, y as f64 + 0.5);
|
||||||
@@ -351,7 +348,7 @@ mod test {
|
|||||||
const SOURCE: SourceId = SourceId(7);
|
const SOURCE: SourceId = SourceId(7);
|
||||||
|
|
||||||
/// One evaluation of the node holding `slot` on `image`, with every stage on.
|
/// One evaluation of the node holding `slot` on `image`, with every stage on.
|
||||||
fn evaluate(slot: &TraceSlot, image: &Item<Raster<CPU>>, runtime: &AsyncRuntime) -> Poll<List<Graphic>> {
|
fn evaluate(slot: &TraceSlot, image: &Item<Pixels>, runtime: &AsyncRuntime) -> Poll<List<Graphic>> {
|
||||||
let one = || Item::new_from_element(1.);
|
let one = || Item::new_from_element(1.);
|
||||||
let on = || Item::new_from_element(true);
|
let on = || Item::new_from_element(true);
|
||||||
vectorize(
|
vectorize(
|
||||||
|
|||||||
@@ -31,3 +31,5 @@ futures = { workspace = true }
|
|||||||
glam = { workspace = true }
|
glam = { workspace = true }
|
||||||
node-macro = { workspace = true }
|
node-macro = { workspace = true }
|
||||||
document-loader = { workspace = true }
|
document-loader = { workspace = true }
|
||||||
|
graphic-types = { workspace = true }
|
||||||
|
wgpu-executor = { workspace = true }
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate log;
|
extern crate log;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod readback_tests;
|
||||||
mod value_types;
|
mod value_types;
|
||||||
|
|
||||||
use graph_craft::Type;
|
use graph_craft::Type;
|
||||||
@@ -195,7 +197,18 @@ impl Preprocessor {
|
|||||||
// We pre initialize the node registry here to avoid a deadlock
|
// We pre initialize the node registry here to avoid a deadlock
|
||||||
let into_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
|
let into_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
|
||||||
let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
|
let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
|
||||||
for (id, metadata) in core_types::registry::NODE_METADATA.lock().unwrap().iter() {
|
let node_metadata = core_types::registry::NODE_METADATA.lock().unwrap();
|
||||||
|
|
||||||
|
// The read-back adapter is async, so it takes the executor, runtime, and source ID after the wire
|
||||||
|
let read_back_environment: Vec<NodeInput> = match node_metadata.get(&read_back::read_back::IDENTIFIER) {
|
||||||
|
Some(metadata) => node_inputs(&metadata.fields, const { &NodeIOTypes::empty() }).into_iter().skip(1).collect(),
|
||||||
|
None => {
|
||||||
|
error!("The read-back adapter's node has no metadata, so it can't be given its executor, runtime, and source ID");
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (id, metadata) in node_metadata.iter() {
|
||||||
let id = id.clone();
|
let id = id.clone();
|
||||||
|
|
||||||
let NodeMetadata {
|
let NodeMetadata {
|
||||||
@@ -254,8 +267,14 @@ impl Preprocessor {
|
|||||||
generated_nodes += 1;
|
generated_nodes += 1;
|
||||||
let mut original_location = OriginalLocation::default();
|
let mut original_location = OriginalLocation::default();
|
||||||
original_location.auto_convert_index = Some(i);
|
original_location.auto_convert_index = Some(i);
|
||||||
|
|
||||||
|
let mut adapter_inputs = vec![NodeInput::import(generic!(X), i)];
|
||||||
|
if input_adapter_identifier == read_back::INPUT_ADAPTER {
|
||||||
|
adapter_inputs.extend(read_back_environment.iter().cloned());
|
||||||
|
}
|
||||||
|
|
||||||
let document_node = DocumentNode {
|
let document_node = DocumentNode {
|
||||||
inputs: vec![NodeInput::import(generic!(X), i)],
|
inputs: adapter_inputs,
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(input_adapter_identifier),
|
implementation: DocumentNodeImplementation::ProtoNode(input_adapter_identifier),
|
||||||
visible: true,
|
visible: true,
|
||||||
compile_metadata: forwarding,
|
compile_metadata: forwarding,
|
||||||
|
|||||||
@@ -0,0 +1,588 @@
|
|||||||
|
//! Node inputs taking `Pixels`, which the compiler reads back from the images wired into them.
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use core_types::blending::BlendMode;
|
||||||
|
use core_types::list::{Item, List};
|
||||||
|
use core_types::runtime::{AsyncRuntime, Spawn, Task};
|
||||||
|
use core_types::{ATTR_TRANSFORM, Color, Ctx, ExtractIndex, OwnedContextImpl, Poll};
|
||||||
|
use glam::{DAffine2, DVec2};
|
||||||
|
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||||
|
use graph_craft::graphene_compiler::Compiler;
|
||||||
|
use graphene_std::platform_application_io::Resource;
|
||||||
|
use graphene_std::raster::{CPU, Image, Pixels, Raster};
|
||||||
|
use graphene_std::vector::style::StrokeAlign;
|
||||||
|
use graphic_types::{Adjustment, Effect, EffectOperation, Graphic, stamp_effect};
|
||||||
|
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||||
|
use interpreted_executor::util::wrap_network_in_scope;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
/// A 2 by 2 black image, inverted by an effect if `inverted`, which reads back as white.
|
||||||
|
fn black_image(inverted: bool) -> Item<Raster<CPU>> {
|
||||||
|
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::BLACK))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(2.)));
|
||||||
|
if inverted {
|
||||||
|
stamp_effect(&mut image, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert)));
|
||||||
|
}
|
||||||
|
image
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A black image and one inverted to white by its effect, as a list, like the output of Rasterize.
|
||||||
|
#[node_macro::node(category(""))]
|
||||||
|
fn black_and_inverted_images(_: impl Ctx, _primary: ()) -> List<Raster<CPU>> {
|
||||||
|
[black_image(false), black_image(true)].into_iter().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A black image inverted to white by its effect.
|
||||||
|
#[node_macro::node(category(""))]
|
||||||
|
fn inverted_image(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
|
||||||
|
black_image(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A 4 by 4 image lighter for a higher index in its context, outlined so it reads back through a render. It lands a task after it's asked for, as a load in the browser does.
|
||||||
|
#[node_macro::node(category(""))]
|
||||||
|
async fn indexed_image(ctx: impl Ctx + ExtractIndex, _primary: ()) -> Item<Raster<CPU>> {
|
||||||
|
YieldOnce(false).await;
|
||||||
|
|
||||||
|
let index = ctx.try_index().and_then(|mut indices| indices.next()).unwrap_or_default();
|
||||||
|
let gray = index as f32 / 4.;
|
||||||
|
let color = Color::from_rgbaf32_unchecked(gray, gray, gray, 1.);
|
||||||
|
|
||||||
|
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(4, 4, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(4.)));
|
||||||
|
stamp_effect(&mut image, Effect::new(&outline()));
|
||||||
|
image
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A black outline a unit wide outside the content, which only a render carries out.
|
||||||
|
fn outline() -> EffectOperation {
|
||||||
|
EffectOperation::Outline {
|
||||||
|
paint: Graphic::from(Color::BLACK),
|
||||||
|
blend_mode: BlendMode::Normal,
|
||||||
|
weight: 1.,
|
||||||
|
align: StrokeAlign::Outside,
|
||||||
|
contour_gradient: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pixels read back from the image wired into it, as a reader for these tests.
|
||||||
|
#[node_macro::node(category(""))]
|
||||||
|
fn read_pixels(_: impl Ctx, pixels: Item<Pixels>) -> Item<Raster<CPU>> {
|
||||||
|
let (pixels, attributes) = pixels.into_parts();
|
||||||
|
Item::from_parts(pixels.into_raster(), attributes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The size of each image `recorded_pixels` was given, which only one test reads.
|
||||||
|
static RECORDED_SIZES: Mutex<Vec<(u32, u32)>> = Mutex::new(Vec::new());
|
||||||
|
|
||||||
|
/// The pixels read back from the image wired into it, as a reader recording the size of each image it's given.
|
||||||
|
#[node_macro::node(category(""))]
|
||||||
|
fn recorded_pixels(_: impl Ctx, pixels: Item<Pixels>) -> Item<Raster<CPU>> {
|
||||||
|
RECORDED_SIZES.lock().unwrap().push((pixels.element().width, pixels.element().height));
|
||||||
|
|
||||||
|
let (pixels, attributes) = pixels.into_parts();
|
||||||
|
Item::from_parts(pixels.into_raster(), attributes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The image it's given, passed on as another node of a second output.
|
||||||
|
#[node_macro::node(category(""))]
|
||||||
|
fn same_image(_: impl Ctx, image: Item<Raster<CPU>>) -> Item<Raster<CPU>> {
|
||||||
|
image
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pending when first polled, as a download in the browser is until a later task of its event loop.
|
||||||
|
struct YieldOnce(bool);
|
||||||
|
|
||||||
|
impl std::future::Future for YieldOnce {
|
||||||
|
type Output = ();
|
||||||
|
|
||||||
|
fn poll(mut self: std::pin::Pin<&mut Self>, context: &mut std::task::Context<'_>) -> std::task::Poll<()> {
|
||||||
|
if self.0 {
|
||||||
|
return std::task::Poll::Ready(());
|
||||||
|
}
|
||||||
|
|
||||||
|
self.0 = true;
|
||||||
|
context.waker().wake_by_ref();
|
||||||
|
std::task::Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Holds each spawned task until the test runs it, as the browser runs it after the evaluation that spawned it.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct QueuedSpawner(Mutex<Vec<Task>>);
|
||||||
|
|
||||||
|
impl Spawn for QueuedSpawner {
|
||||||
|
fn spawn(&self, task: Task) {
|
||||||
|
self.0.lock().unwrap().push(task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl QueuedSpawner {
|
||||||
|
/// Runs each queued task to its end, giving how many there were.
|
||||||
|
fn run_queued(&self) -> usize {
|
||||||
|
let tasks = std::mem::take(&mut *self.0.lock().unwrap());
|
||||||
|
let count = tasks.len();
|
||||||
|
tasks.into_iter().for_each(futures::executor::block_on);
|
||||||
|
count
|
||||||
|
}
|
||||||
|
|
||||||
|
fn queued(&self) -> usize {
|
||||||
|
self.0.lock().unwrap().len()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A network compiled with the editor API in scope, and the runtime its async nodes spawn their tasks on.
|
||||||
|
struct Compiled {
|
||||||
|
dynamic_executor: DynamicExecutor,
|
||||||
|
output: OutputHandle,
|
||||||
|
runtime: AsyncRuntime,
|
||||||
|
spawner: Arc<QueuedSpawner>,
|
||||||
|
editor_api: Arc<PlatformEditorApi>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Compiled {
|
||||||
|
/// The `network` preprocessed and compiled with a GPU in scope, or `None` without a GPU.
|
||||||
|
fn new(network: NodeNetwork) -> Option<Self> {
|
||||||
|
let gpu = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?;
|
||||||
|
let application_io = PlatformApplicationIo::new_with_executor(gpu);
|
||||||
|
Some(Self::with_application_io(network, application_io))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `network` preprocessed and compiled with the `application_io` in scope.
|
||||||
|
fn with_application_io(network: NodeNetwork, application_io: PlatformApplicationIo) -> Self {
|
||||||
|
let spawner = Arc::new(QueuedSpawner::default());
|
||||||
|
let mut compiled = Self {
|
||||||
|
dynamic_executor: DynamicExecutor::default(),
|
||||||
|
output: OutputHandle::default(),
|
||||||
|
runtime: AsyncRuntime::new(spawner.clone()),
|
||||||
|
spawner,
|
||||||
|
editor_api: Arc::new(PlatformEditorApi {
|
||||||
|
application_io: Some(Arc::new(application_io)),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
compiled.output = compiled.compile(network);
|
||||||
|
compiled
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The output of the `network`, compiled beside those before it and sharing the nodes they have in common.
|
||||||
|
fn compile(&mut self, network: NodeNetwork) -> OutputHandle {
|
||||||
|
let mut network = wrap_network_in_scope(network, self.editor_api.clone(), self.runtime.handle());
|
||||||
|
Preprocessor::new().preprocess(&mut network, &|_| None).expect("preprocessing should succeed");
|
||||||
|
let proto_network = Compiler {}.compile_single(network).expect("the network should compile").network;
|
||||||
|
let (output, _) = self.dynamic_executor.update(proto_network).expect("the network should type check and build");
|
||||||
|
self.runtime.update_sources(self.dynamic_executor.sources());
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One evaluation of the `output` with the `index` in its context if given, reading the generations the landed tasks bumped, as the editor's evaluations do.
|
||||||
|
fn evaluate_once(&self, output: &OutputHandle, index: Option<usize>) -> Poll<core_types::registry::Any> {
|
||||||
|
let mut context = OwnedContextImpl::empty().with_generations(self.runtime.snapshot());
|
||||||
|
if let Some(index) = index {
|
||||||
|
context = context.with_index(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.dynamic_executor.tree().evaluate(output.node(), &context.into_context()).expect("the output should evaluate")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The output evaluated until it's final, with the `index` in its context if given, running the tasks each evaluation spawns before the next.
|
||||||
|
/// Gives how many evaluations that took.
|
||||||
|
fn evaluate(&self, index: Option<usize>) -> (core_types::registry::Any, usize) {
|
||||||
|
for evaluations in 1..=1000 {
|
||||||
|
match self.evaluate_once(&self.output, index) {
|
||||||
|
Poll::Final(value) => return (value, evaluations),
|
||||||
|
Poll::Pending | Poll::Partial(_) => {
|
||||||
|
self.spawner.run_queued();
|
||||||
|
}
|
||||||
|
Poll::Error(error) => panic!("the output failed: {error}"),
|
||||||
|
Poll::Fallback(boxed) => panic!("the output failed: {}", boxed.1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("the output never became final")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||||
|
DocumentNode {
|
||||||
|
inputs,
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A network of the `node` fed by the `source` node, exporting the node's output `output_index`.
|
||||||
|
fn network(source: ProtoNodeIdentifier, node: DocumentNode, output_index: usize) -> NodeNetwork {
|
||||||
|
NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(1), output_index)],
|
||||||
|
nodes: [(NodeId(0), proto_node(source, vec![NodeInput::value(TaggedValue::None, false)])), (NodeId(1), node)]
|
||||||
|
.into_iter()
|
||||||
|
.collect(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node's inputs as a new one of it gets them.
|
||||||
|
fn default_inputs(identifier: &ProtoNodeIdentifier) -> Vec<NodeInput> {
|
||||||
|
let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
|
||||||
|
let metadata_registry = core_types::registry::NODE_METADATA.lock().unwrap();
|
||||||
|
let first_node_io = node_registry.get(identifier).and_then(|implementations| implementations.first()).map(|(_, node_io)| node_io);
|
||||||
|
let metadata = metadata_registry.get(identifier).expect("the node should have registered metadata");
|
||||||
|
|
||||||
|
node_inputs(&metadata.fields, first_node_io.unwrap_or(const { &NodeIOTypes::empty() }))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wire() -> NodeInput {
|
||||||
|
NodeInput::node(NodeId(0), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first pixel of each image, as the gamma-encoded red channel and alpha.
|
||||||
|
fn first_pixels(images: &List<Raster<CPU>>) -> Vec<(f32, f32)> {
|
||||||
|
images.iter_element_values().map(|image| (image.data[0].r(), image.data[0].a())).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_read_back_adapter_takes_the_inputs_of_an_async_node() {
|
||||||
|
let reader = proto_node(read_pixels::IDENTIFIER, vec![NodeInput::value(TaggedValue::None, false)]);
|
||||||
|
let mut network = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(0), 0)],
|
||||||
|
nodes: [(NodeId(0), reader)].into_iter().collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let runtime = AsyncRuntime::new(Arc::new(QueuedSpawner::default()));
|
||||||
|
network = wrap_network_in_scope(network, Arc::default(), runtime.handle());
|
||||||
|
Preprocessor::new().preprocess(&mut network, &|_| None).expect("preprocessing should succeed");
|
||||||
|
|
||||||
|
let adapters: Vec<_> = (network.definitions.values().flat_map(|definition| definition.nodes.values()))
|
||||||
|
.filter(|node| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::read_back::INPUT_ADAPTER))
|
||||||
|
.collect();
|
||||||
|
let [adapter] = adapters.as_slice() else {
|
||||||
|
panic!("the reader's input should have one read-back adapter, but has {}", adapters.len())
|
||||||
|
};
|
||||||
|
let environment = [
|
||||||
|
NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER),
|
||||||
|
NodeInput::scope("runtime"),
|
||||||
|
NodeInput::Reflection(DocumentNodeMetadata::SourceId),
|
||||||
|
];
|
||||||
|
assert_eq!(adapter.inputs[1..], environment, "the adapter takes the executor, runtime, and source ID after the wire");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_item_wire_reads_back_the_image_with_its_effects() {
|
||||||
|
let Some(compiled) = Compiled::new(network(inverted_image::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0)) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let (output, _) = compiled.evaluate(None);
|
||||||
|
let image = output.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image");
|
||||||
|
assert!(image.element().data.iter().all(|color| *color == Color::WHITE), "the black image reads back inverted to white");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_list_wire_reads_back_each_image() {
|
||||||
|
let Some(compiled) = Compiled::new(network(black_and_inverted_images::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0)) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let (output, _) = compiled.evaluate(None);
|
||||||
|
let images = output.downcast::<List<Raster<CPU>>>().expect("the reader should output a list of images");
|
||||||
|
assert_eq!(first_pixels(&images), [(0., 1.), (1., 1.)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unwired_input_reads_back_no_pixels() {
|
||||||
|
let inputs = default_inputs(&read_pixels::IDENTIFIER);
|
||||||
|
assert_eq!(
|
||||||
|
inputs[0].as_value(),
|
||||||
|
Some(&TaggedValue::TypeDefault(core_types::item!(Raster<CPU>))),
|
||||||
|
"an unwired input holds the empty image"
|
||||||
|
);
|
||||||
|
|
||||||
|
let reader = NodeNetwork {
|
||||||
|
exports: vec![NodeInput::node(NodeId(0), 0)],
|
||||||
|
nodes: [(NodeId(0), proto_node(read_pixels::IDENTIFIER, inputs))].into_iter().collect(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let Some(compiled) = Compiled::new(reader) else { return };
|
||||||
|
|
||||||
|
let (output, _) = compiled.evaluate(None);
|
||||||
|
let image = output.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image");
|
||||||
|
assert!(image.element().data.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluated under a series of contexts as a Repeat node does, the read-back adapter keeps a result for each, so evaluating them again neither waits nor reads back again.
|
||||||
|
#[test]
|
||||||
|
fn the_read_back_finishes_under_each_context_in_turn_and_keeps_its_result() {
|
||||||
|
let Some(compiled) = Compiled::new(network(indexed_image::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0)) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let read_back = |index: usize| {
|
||||||
|
let (output, evaluations) = compiled.evaluate(Some(index));
|
||||||
|
let image = output.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image");
|
||||||
|
let raster = image.element();
|
||||||
|
let middle = raster.data[(raster.height / 2 * raster.width + raster.width / 2) as usize];
|
||||||
|
(raster.buffer_id(), middle.r(), evaluations)
|
||||||
|
};
|
||||||
|
|
||||||
|
// The source's task lands one evaluation later, and the readback with it
|
||||||
|
let first: Vec<_> = (0..3).map(read_back).collect();
|
||||||
|
for (index, &(_, _, evaluations)) in first.iter().enumerate() {
|
||||||
|
assert_eq!(evaluations, 2, "index {index} should become final once its source lands");
|
||||||
|
}
|
||||||
|
assert!(first[0].1 < first[1].1 && first[1].1 < first[2].1, "each index reads back its own image: {first:?}");
|
||||||
|
|
||||||
|
// Each landing bumps the source's generation, which the readback's context holds, so this pass may read back again, but each is final at once
|
||||||
|
let settled: Vec<_> = (0..3).map(read_back).collect();
|
||||||
|
assert!(
|
||||||
|
settled.iter().all(|&(_, _, evaluations)| evaluations == 1),
|
||||||
|
"a landed source keeps each index final at once: {settled:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(compiled.spawner.run_queued(), 0, "nothing waits on a task");
|
||||||
|
|
||||||
|
// Once nothing lands, each context's read-back pixels are the ones kept for it, in any order
|
||||||
|
for index in [2, 0, 1] {
|
||||||
|
let (buffer_id, middle, evaluations) = read_back(index);
|
||||||
|
assert_eq!(evaluations, 1);
|
||||||
|
assert_eq!((buffer_id, middle), (settled[index].0, settled[index].1), "index {index} read back again");
|
||||||
|
}
|
||||||
|
assert_eq!(compiled.spawner.run_queued(), 0, "nothing waits on a task");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Readbacks waiting under three contexts at once, asked for by two outputs held together, all finish once what they wait on lands, sharing their pixels between the outputs.
|
||||||
|
/// A native download lands when it's asked for, so what's held pending is the image each readback waits on, as a download in the browser would be.
|
||||||
|
#[test]
|
||||||
|
fn readbacks_pending_under_several_contexts_for_two_outputs_finish_together() {
|
||||||
|
let Some(mut compiled) = Compiled::new(network(indexed_image::IDENTIFIER, proto_node(recorded_pixels::IDENTIFIER, vec![wire()]), 0)) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let first_output = compiled.output.clone();
|
||||||
|
|
||||||
|
// The second output passes the reader's pixels through one more node, sharing the reader and its readback with the first
|
||||||
|
let mut second_network = network(indexed_image::IDENTIFIER, proto_node(recorded_pixels::IDENTIFIER, vec![wire()]), 0);
|
||||||
|
second_network.nodes.insert(NodeId(2), proto_node(same_image::IDENTIFIER, vec![NodeInput::node(NodeId(1), 0)]));
|
||||||
|
second_network.exports = vec![NodeInput::node(NodeId(2), 0)];
|
||||||
|
let second_output = compiled.compile(second_network);
|
||||||
|
|
||||||
|
// Each context waits on its image's task, which stays queued, and asking again starts nothing new
|
||||||
|
let asked_for = [(&first_output, 0), (&second_output, 1), (&first_output, 2)];
|
||||||
|
for _ in 0..2 {
|
||||||
|
for (output, index) in asked_for {
|
||||||
|
assert!(matches!(compiled.evaluate_once(output, Some(index)), Poll::Pending), "index {index} should wait on its image");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(compiled.spawner.queued(), 3, "one task for each context");
|
||||||
|
assert!(RECORDED_SIZES.lock().unwrap().is_empty(), "the reader ran while its pixels were unfinished");
|
||||||
|
|
||||||
|
// Once the images land, both outputs get each context's read-back pixels at once, the same ones
|
||||||
|
assert_eq!(compiled.spawner.run_queued(), 3);
|
||||||
|
let buffer_ids = |output: &OutputHandle| -> Vec<u64> {
|
||||||
|
(0..3)
|
||||||
|
.map(|index| match compiled.evaluate_once(output, Some(index)) {
|
||||||
|
Poll::Final(value) => value.downcast::<Item<Raster<CPU>>>().expect("the reader should output an image").element().buffer_id(),
|
||||||
|
_ => panic!("index {index} should be final once its image landed"),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
let first = buffer_ids(&first_output);
|
||||||
|
assert_eq!(buffer_ids(&second_output), first, "both outputs share each context's pixels");
|
||||||
|
assert_eq!(buffer_ids(&first_output), first, "evaluating again reuses each context's pixels");
|
||||||
|
assert_eq!(compiled.spawner.queued(), 0, "nothing was read back again");
|
||||||
|
|
||||||
|
// The reader only ever ran on read-back pixels, grown past the 4 by 4 image by its outline
|
||||||
|
assert!(RECORDED_SIZES.lock().unwrap().iter().all(|&size| size == (8, 8)), "{:?}", RECORDED_SIZES.lock().unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Without a GPU, a reader's input is an error.
|
||||||
|
#[test]
|
||||||
|
fn a_reader_without_a_gpu_fails() {
|
||||||
|
let compiled = Compiled::with_application_io(
|
||||||
|
network(inverted_image::IDENTIFIER, proto_node(read_pixels::IDENTIFIER, vec![wire()]), 0),
|
||||||
|
PlatformApplicationIo::default(),
|
||||||
|
);
|
||||||
|
|
||||||
|
let Poll::Error(error) = compiled.evaluate_once(&compiled.output, None) else {
|
||||||
|
panic!("the reader should fail without a GPU")
|
||||||
|
};
|
||||||
|
assert!(error.error().is::<wgpu_executor::NoGpuError>(), "the reader failed with {error}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An image of 32 by 32 pixels with a dark disc and a red band on a light ground, enough for every reader to find shapes and colors in, inverted by an effect if `inverted`.
|
||||||
|
fn varied_image(inverted: bool) -> Item<Raster<CPU>> {
|
||||||
|
let data = (0..32 * 32)
|
||||||
|
.map(|index| {
|
||||||
|
let (x, y) = ((index % 32) as f64, (index / 32) as f64);
|
||||||
|
if DVec2::new(x - 12., y - 12.).length() < 8. {
|
||||||
|
Color::from_rgbaf32_unchecked(0.05, 0.1, 0.3, 1.)
|
||||||
|
} else if y >= 24. {
|
||||||
|
Color::from_rgbaf32_unchecked(0.8, 0.1, 0.1, 1.)
|
||||||
|
} else {
|
||||||
|
Color::from_rgbaf32_unchecked(0.9, 0.85, 0.7, 1.)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut image = Item::new_from_element(Raster::new_cpu(Image { width: 32, height: 32, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(32.)));
|
||||||
|
if inverted {
|
||||||
|
stamp_effect(&mut image, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert)));
|
||||||
|
}
|
||||||
|
image
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The varied image as it is.
|
||||||
|
#[node_macro::node(category(""))]
|
||||||
|
fn plain_varied_image(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
|
||||||
|
varied_image(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The varied image inverted by its effect.
|
||||||
|
#[node_macro::node(category(""))]
|
||||||
|
fn inverted_varied_image(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
|
||||||
|
varied_image(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether two outputs of a reader are equal, as tagged values where they convert or else as one of the types the readers output.
|
||||||
|
/// `None` for outputs of a type this can't compare.
|
||||||
|
fn outputs_equal(a: &core_types::registry::Any, b: &core_types::registry::Any) -> Option<bool> {
|
||||||
|
if let (Ok(a), Ok(b)) = (TaggedValue::try_from_std_any_ref(&**a), TaggedValue::try_from_std_any_ref(&**b)) {
|
||||||
|
return Some(a == b);
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! compare_as {
|
||||||
|
($($ty:ty),*) => {$(
|
||||||
|
if let (Some(a), Some(b)) = (a.downcast_ref::<$ty>(), b.downcast_ref::<$ty>()) {
|
||||||
|
return Some(a == b);
|
||||||
|
}
|
||||||
|
)*};
|
||||||
|
}
|
||||||
|
compare_as!(Item<Raster<CPU>>, List<Raster<CPU>>, List<Color>, List<Graphic>);
|
||||||
|
|
||||||
|
// Resources compare by their bytes
|
||||||
|
if let (Some(a), Some(b)) = (a.downcast_ref::<Item<Resource>>(), b.downcast_ref::<Item<Resource>>()) {
|
||||||
|
return Some(a.element().as_ref() == b.element().as_ref());
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every node input taking `Pixels`, by its node's identifier and its index, besides this module's own readers.
|
||||||
|
fn pixel_reading_inputs() -> Vec<(ProtoNodeIdentifier, usize)> {
|
||||||
|
let node_registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
|
||||||
|
let metadata_registry = core_types::registry::NODE_METADATA.lock().unwrap();
|
||||||
|
let takes_pixels = |ty: &Type| matches!(ty.clone().normalize_rank().nested_type(), Type::Item(element) | Type::List(element) if **element == concrete!(Pixels));
|
||||||
|
|
||||||
|
let mut inputs: Vec<_> = (node_registry.iter())
|
||||||
|
.filter(|(identifier, _)| metadata_registry.contains_key(*identifier) && ![read_pixels::IDENTIFIER, recorded_pixels::IDENTIFIER].contains(*identifier))
|
||||||
|
.flat_map(|(identifier, implementations)| {
|
||||||
|
let indices: HashSet<usize> = (implementations.iter())
|
||||||
|
.flat_map(|(_, node_io)| node_io.inputs.iter().enumerate().filter(|(_, ty)| takes_pixels(ty)).map(|(index, _)| index))
|
||||||
|
.collect();
|
||||||
|
indices.into_iter().map(|index| (identifier.clone(), index))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
inputs.sort_by(|a, b| (a.0.as_str(), a.1).cmp(&(b.0.as_str(), b.1)));
|
||||||
|
inputs
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every node input taking `Pixels` reads the pixels as drawn, so an image under an effect gives a different output than the image alone.
|
||||||
|
/// A node gaining such an input has to be added to the list below on purpose.
|
||||||
|
#[test]
|
||||||
|
fn every_pixel_reading_input_reads_the_image_with_its_effects() {
|
||||||
|
let inputs = pixel_reading_inputs();
|
||||||
|
let identifiers: Vec<&str> = inputs.iter().map(|(identifier, _)| identifier.as_str()).collect();
|
||||||
|
let mut readers = [
|
||||||
|
graphene_std::platform_application_io::image_to_bytes::IDENTIFIER,
|
||||||
|
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
|
||||||
|
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
|
||||||
|
graphene_std::vectorize_nodes::vectorize::IDENTIFIER,
|
||||||
|
];
|
||||||
|
readers.sort_by(|a, b| a.as_str().cmp(b.as_str()));
|
||||||
|
assert_eq!(identifiers, readers.iter().map(ProtoNodeIdentifier::as_str).collect::<Vec<_>>(), "the nodes reading pixels");
|
||||||
|
|
||||||
|
for (identifier, index) in inputs {
|
||||||
|
let mut node_inputs = default_inputs(&identifier);
|
||||||
|
node_inputs[index] = wire();
|
||||||
|
let output = |source: ProtoNodeIdentifier| {
|
||||||
|
let compiled = Compiled::new(network(source, proto_node(identifier.clone(), node_inputs.clone()), 0))?;
|
||||||
|
Some(compiled.evaluate(None).0)
|
||||||
|
};
|
||||||
|
let (Some(plain), Some(inverted)) = (output(plain_varied_image::IDENTIFIER), output(inverted_varied_image::IDENTIFIER)) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let equal = outputs_equal(&plain, &inverted).unwrap_or_else(|| panic!("{} gives an output this test can't compare", identifier.as_str()));
|
||||||
|
assert!(!equal, "{} gives the same output for an image whether or not it's inverted by an effect", identifier.as_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A 96 by 96 image of gray noise, outlined so it reads back through a render, which Vectorize traces over several evaluations.
|
||||||
|
#[node_macro::node(category(""))]
|
||||||
|
fn outlined_noise(_: impl Ctx, _primary: ()) -> Item<Raster<CPU>> {
|
||||||
|
// Pseudo-random grays from an xorshift sequence, so the trace finds many small regions
|
||||||
|
let mut state = 0x2545_f491_u32;
|
||||||
|
let data = (0..96 * 96)
|
||||||
|
.map(|_| {
|
||||||
|
state ^= state << 13;
|
||||||
|
state ^= state >> 17;
|
||||||
|
state ^= state << 5;
|
||||||
|
let gray = (state % 256) as f32 / 255.;
|
||||||
|
Color::from_rgbaf32_unchecked(gray, gray, gray, 1.)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let mut image = Item::new_from_element(Raster::new_cpu(Image { width: 96, height: 96, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(96.)));
|
||||||
|
stamp_effect(&mut image, Effect::new(&outline()));
|
||||||
|
image
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each slice of a trace bumps the generation of Vectorize's source, which mustn't read the image back again and so restart the trace.
|
||||||
|
#[test]
|
||||||
|
fn a_trace_of_read_back_pixels_runs_to_its_end() {
|
||||||
|
let mut inputs = default_inputs(&graphene_std::vectorize_nodes::vectorize::IDENTIFIER);
|
||||||
|
inputs[0] = wire();
|
||||||
|
let Some(compiled) = Compiled::new(network(outlined_noise::IDENTIFIER, proto_node(graphene_std::vectorize_nodes::vectorize::IDENTIFIER, inputs), 0)) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let (output, evaluations) = compiled.evaluate(None);
|
||||||
|
let traced = output.downcast::<List<Graphic>>().expect("Vectorize should output graphics");
|
||||||
|
assert!(evaluations > 1, "the trace should take several slices");
|
||||||
|
assert!(!traced.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node `identifier` with these `inputs`, its input fed a list of a black image and one inverted to white by an effect, giving its output.
|
||||||
|
fn evaluate_on_two_images<T: 'static>(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> Option<T> {
|
||||||
|
let compiled = Compiled::new(network(black_and_inverted_images::IDENTIFIER, proto_node(identifier.clone(), inputs), 0))?;
|
||||||
|
let (output, _) = compiled.evaluate(None);
|
||||||
|
Some(*output.downcast::<T>().unwrap_or_else(|_| panic!("{} should output a list of each image's result", identifier.as_str())))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dehaze_reads_back_each_image_of_a_list() {
|
||||||
|
let inputs = vec![wire(), NodeInput::value(TaggedValue::Number(0.), false)];
|
||||||
|
let Some(images) = evaluate_on_two_images::<List<Raster<CPU>>>(graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER, inputs) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let sizes: Vec<_> = images.iter_element_values().map(|image| (image.width, image.height)).collect();
|
||||||
|
assert_eq!(sizes, [(2, 2), (2, 2)]);
|
||||||
|
|
||||||
|
// Without any strength, the haze removal keeps each image's own read-back colors
|
||||||
|
let colors: Vec<_> = images
|
||||||
|
.iter_element_values()
|
||||||
|
.flat_map(|image| image.data.iter().map(|color| (color.r().round(), color.a().round())))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(colors, [[(0., 1.); 4], [(1., 1.); 4]].concat(), "the black image stays black and the inverted one white");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn image_color_palette_finds_each_image_of_a_list_its_own_colors() {
|
||||||
|
let inputs = vec![wire(), NodeInput::value(TaggedValue::Integer(1), false)];
|
||||||
|
let Some(colors) = evaluate_on_two_images::<List<Color>>(graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER, inputs) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let colors: Vec<_> = colors.iter_element_values().map(|color| (color.r().round(), color.a())).collect();
|
||||||
|
assert_eq!(colors, [(0., 1.), (1., 1.)], "one color for each image, in order");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn image_to_bytes_reads_back_each_image_of_a_list() {
|
||||||
|
let Some(resources) = evaluate_on_two_images::<List<Resource>>(graphene_std::platform_application_io::image_to_bytes::IDENTIFIER, vec![wire()]) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let bytes: Vec<Vec<u8>> = resources.iter_element_values().map(|resource| resource.as_ref().to_vec()).collect();
|
||||||
|
assert_eq!(bytes, [[0, 0, 0, 255].repeat(4), [255, 255, 255, 255].repeat(4)]);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user