mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1404b36081 | ||
|
|
06467de601 | ||
|
|
430b2030ed | ||
|
|
284ca6d509 | ||
|
|
056bec13e5 |
No files matched your search
Generated
+3
-3
@@ -6491,7 +6491,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -6506,7 +6506,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -6520,7 +6520,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
|
||||
+3
-3
@@ -281,6 +281,6 @@ debug = true
|
||||
[patch.crates-io]
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
@@ -11,6 +11,7 @@ use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::format_f64;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
@@ -377,6 +378,7 @@ macro_rules! inspectable_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
@@ -433,6 +435,7 @@ macro_rules! inspectable_types {
|
||||
Item<Raster<GPU>>,
|
||||
Item<Color>,
|
||||
Item<Gradient>,
|
||||
Item<Generator>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<i64>,
|
||||
@@ -880,6 +883,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.identifier(),
|
||||
Self::Color(item) => item.identifier(),
|
||||
Self::Gradient(item) => item.identifier(),
|
||||
Self::Generator(item) => item.identifier(),
|
||||
Self::Text(item) => item.identifier(),
|
||||
Self::NoneList(list) => list.identifier(),
|
||||
Self::GraphicList(list) => list.identifier(),
|
||||
@@ -888,6 +892,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.identifier(),
|
||||
Self::ColorList(list) => list.identifier(),
|
||||
Self::GradientList(list) => list.identifier(),
|
||||
Self::GeneratorList(list) => list.identifier(),
|
||||
Self::TextList(list) => list.identifier(),
|
||||
Self::StrokeList(list) => list.identifier(),
|
||||
}
|
||||
@@ -905,6 +910,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Color(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Gradient(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Generator(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Text(item) => item.layout_with_breadcrumb(data),
|
||||
Self::NoneList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
|
||||
@@ -913,6 +919,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::ColorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GradientList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GeneratorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::TextList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
|
||||
}
|
||||
@@ -1245,6 +1252,7 @@ impl_table_item_layout_for_choice_enum!(
|
||||
BevelDirection,
|
||||
BevelStyle,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
@@ -1392,9 +1400,11 @@ macro_rules! known_item_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
Gradient,
|
||||
Generator,
|
||||
Color,
|
||||
NodeId,
|
||||
DAffine2,
|
||||
|
||||
@@ -759,20 +759,26 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
|
||||
/// from the default (`Linear`).
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||
let [start, end] = match gradient_form {
|
||||
GradientForm::Linear => LINEAR_DIALS,
|
||||
GradientForm::Radial => RADIAL_DIALS,
|
||||
};
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
}
|
||||
|
||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||
|
||||
@@ -611,10 +611,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::scope(raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string()),
|
||||
],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
@@ -837,6 +834,7 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
||||
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
||||
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
||||
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
|
||||
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
|
||||
@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
@@ -3000,6 +3001,79 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
|
||||
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
||||
}
|
||||
|
||||
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::math_nodes::gradient_curvature::*;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
|
||||
let curvatures = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
|
||||
Some(&TaggedValue::Number(value)) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
|
||||
// Each form's button sets both curvatures to the form's own, and stands out while they're exactly those
|
||||
let mut form = vec![
|
||||
TextLabel::new("Form")
|
||||
.tooltip_label("Form")
|
||||
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
|
||||
.widget_instance(),
|
||||
];
|
||||
add_blank_assist(&mut form);
|
||||
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
for (label, [start, end], tooltip) in [
|
||||
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
|
||||
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
|
||||
] {
|
||||
form.push(
|
||||
TextButton::new(label)
|
||||
.tooltip_description(tooltip)
|
||||
.emphasized(curvatures == Some([start, end]))
|
||||
.disabled(curvatures.is_none())
|
||||
.on_update(move |_: &TextButton| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: StartCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(start).into(),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: EndCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(end).into(),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
// The same sliders the curvatures would get without this panel
|
||||
let options = ParameterOptions {
|
||||
soft_min: Some(-1.),
|
||||
soft_max: Some(1.),
|
||||
slider: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
|
||||
|
||||
let mut layout = vec![LayoutGroup::row(form)];
|
||||
layout.extend(curvature(StartCurvatureInput::INDEX));
|
||||
layout.extend(curvature(EndCurvatureInput::INDEX));
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
|
||||
@@ -34,6 +34,8 @@ impl FrontendGraphDataType {
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
// A generator draws pixels like an image, at whatever resolution is needed
|
||||
"Generator" => Self::Raster,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
|
||||
+16
@@ -737,6 +737,22 @@ mod tests {
|
||||
assert!(!type_feeds_input(&item!(f64), &item!(Graphic), paint_conversions), "a number has no conversion into a graphic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cpu_raster_feeds_an_input_that_only_takes_gpu_rasters() {
|
||||
use graphene_std::raster_nodes::dehaze::dehaze::ImageFrameInput;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
|
||||
let dehaze_image = input_conversions(&ImageFrameInput::NODE_IDENTIFIER).get(ImageFrameInput::INDEX).copied().flatten();
|
||||
|
||||
assert!(
|
||||
type_feeds_input(&item!(Raster<CPU>), &item!(Raster<GPU>), dehaze_image),
|
||||
"a CPU raster should upload through the input adapter"
|
||||
);
|
||||
assert!(type_feeds_input(&list!(Raster<CPU>), &list!(Raster<GPU>), dehaze_image), "a list of CPU rasters should too");
|
||||
assert!(type_feeds_input(&item!(Raster<GPU>), &item!(Raster<GPU>), dehaze_image), "a GPU raster should pass through");
|
||||
assert!(!type_feeds_input(&item!(Raster<GPU>), &item!(Raster<CPU>), None), "nothing downloads a GPU raster implicitly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_promote_onto_list_inputs() {
|
||||
let paint_conversions = input_conversions(&PaintInput::NODE_IDENTIFIER).get(PaintInput::INDEX).copied().flatten();
|
||||
|
||||
@@ -16,12 +16,11 @@ use graphene_std::ParameterRef;
|
||||
use graphene_std::ProtoNodeIdentifier;
|
||||
use graphene_std::extract_xy::XY;
|
||||
use graphene_std::raster::RedGreenBlueAlpha;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -300,10 +299,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
aliases: &["math_nodes::GradientTypeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
aliases: &["math_nodes::SpreadMethodNode"],
|
||||
@@ -534,8 +529,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ChannelMixerNode",
|
||||
],
|
||||
},
|
||||
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::ColorOverlayNode",
|
||||
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
|
||||
@@ -543,6 +539,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::adjustments::ColorOverlayNode",
|
||||
"raster_nodes::generate_curves::ColorOverlayNode",
|
||||
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
"raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -1273,6 +1270,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), under.clone(), &network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), over.clone(), &network_path);
|
||||
}
|
||||
|
||||
if *new == graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1635,6 +1636,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take the presets of the form it set
|
||||
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
|
||||
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
|
||||
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path) in &gradient_form_nodes {
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
reset_default_display_name(document, node_id, network_path, "Gradient Form");
|
||||
|
||||
if let Some(input) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
|
||||
}
|
||||
|
||||
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::GradientForm(GradientForm::Radial)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
|
||||
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
|
||||
_ => {
|
||||
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
|
||||
graphene_std::renderer::dial_gradient::LINEAR_DIALS
|
||||
}
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
|
||||
}
|
||||
|
||||
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
|
||||
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
|
||||
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
||||
@@ -1813,6 +1857,56 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew images cut off at a square, 100 units for a clipped Noise Pattern and 1 for Mandelbrot, where their
|
||||
// patterns now fill the plane. An old Noise Pattern has a Clip toggle, after the primary input or first from before that input existed,
|
||||
// and an old Mandelbrot lacks the primary input. Each takes the current inputs, with a square filled by its pattern where it was cut off.
|
||||
const NOISE_SETTINGS: usize = 14;
|
||||
let old_pattern_nodes = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let reference = document.network_interface.reference(node_id, &path)?;
|
||||
let clipped = |clip_index: usize| !matches!(node.inputs.get(clip_index).and_then(|input| input.as_value()), Some(TaggedValue::Bool(false)));
|
||||
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER);
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
|
||||
let starts_with_clip = matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::Bool(_)));
|
||||
let clip_index = match node.inputs.len() {
|
||||
// Also with the pipeline input these nodes took when they rendered on the GPU themselves
|
||||
17 if node.inputs.last() == Some(&pipeline) => 1,
|
||||
16 => 1,
|
||||
15 if starts_with_clip => 0,
|
||||
_ => return None,
|
||||
};
|
||||
return Some((*node_id, path, reference, Some(clip_index), clipped(clip_index).then_some(100.)));
|
||||
}
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) && (node.inputs.is_empty() || node.inputs == [pipeline]) {
|
||||
return Some((*node_id, path, reference, None, Some(1.)));
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for (node_id, network_path, reference, clip_index, clipped_size) in &old_pattern_nodes {
|
||||
let Some(definition) = resolve_document_node_type(reference) else { continue };
|
||||
let mut node_template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
|
||||
if let Some(clip_index) = clip_index {
|
||||
for (offset, input) in old_inputs.iter().skip(clip_index + 1).take(NOISE_SETTINGS).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(size) = clipped_size {
|
||||
fill_square_with_pattern(document, node_id, network_path, *size);
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
|
||||
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
|
||||
@@ -1859,35 +1953,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::Integer(integer), exposed), &network_path);
|
||||
}
|
||||
|
||||
let cpu_raster_type_defaults: Vec<(NodeId, Vec<NodeId>, usize, Type, bool)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.flat_map(|(node_id, node, path)| {
|
||||
node.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, input)| {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
let TaggedValue::TypeDefault(stored_type) = &**tagged_value else { return None };
|
||||
let gpu_type = if *stored_type == item!(Raster<CPU>) {
|
||||
item!(Raster<GPU>)
|
||||
} else if *stored_type == list!(Raster<CPU>) {
|
||||
list!(Raster<GPU>)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
Some((*node_id, path.clone(), index, gpu_type, *exposed))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path, index, gpu_type, exposed) in cpu_raster_type_defaults {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::type_default(gpu_type, exposed), &network_path);
|
||||
}
|
||||
|
||||
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
|
||||
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
|
||||
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
|
||||
@@ -1895,6 +1960,76 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.require_whole_document_stage();
|
||||
}
|
||||
|
||||
/// Splices a rectangle filled with the pattern node's output onto the wires leaving it, covering the square from the origin of the pattern's space out to `size`.
|
||||
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
|
||||
fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_id: &NodeId, network_path: &[NodeId], size: f64) -> Option<()> {
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
|
||||
|
||||
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
|
||||
let rectangle_template = template(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)?;
|
||||
let fill_template = template(graphene_std::vector_nodes::fill::IDENTIFIER)?;
|
||||
let transform_template = template(graphene_std::transform_nodes::transform::IDENTIFIER)?;
|
||||
|
||||
let [rectangle_id, fill_id, paint_transform_id, placement_transform_id] = [(); 4].map(|_| NodeId::new());
|
||||
document.network_interface.insert_node(rectangle_id, rectangle_template, network_path);
|
||||
document.network_interface.insert_node(fill_id, fill_template, network_path);
|
||||
document.network_interface.insert_node(paint_transform_id, transform_template.clone(), network_path);
|
||||
document.network_interface.insert_node(placement_transform_id, transform_template, network_path);
|
||||
|
||||
let set_value = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, value: TaggedValue| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(value, false), network_path);
|
||||
};
|
||||
let wire = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, source: NodeId| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::node(source, 0), network_path);
|
||||
};
|
||||
|
||||
// The rectangle's width and height, and the half-square translations of the paint and the filled rectangle
|
||||
set_value(document, rectangle_id, 1, TaggedValue::Number(size));
|
||||
set_value(document, rectangle_id, 2, TaggedValue::Number(size));
|
||||
set_value(document, paint_transform_id, 1, TaggedValue::DVec2(DVec2::splat(-size / 2.)));
|
||||
set_value(document, placement_transform_id, 1, TaggedValue::DVec2(DVec2::splat(size / 2.)));
|
||||
|
||||
wire(document, paint_transform_id, 0, *pattern_node_id);
|
||||
wire(document, fill_id, 0, rectangle_id);
|
||||
wire(document, fill_id, 1, paint_transform_id);
|
||||
wire(document, placement_transform_id, 0, fill_id);
|
||||
for consumer in &downstream_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(placement_transform_id, 0), network_path);
|
||||
}
|
||||
|
||||
// A pattern in a layer chain gives way to the filled rectangle there, moving below to paint it, and otherwise the new nodes sit beside it
|
||||
if was_in_chain {
|
||||
document.network_interface.force_set_upstream_to_chain(&placement_transform_id, network_path);
|
||||
|
||||
if let Some(fill_position) = document.network_interface.position(&fill_id, network_path) {
|
||||
document.network_interface.set_absolute_position(&paint_transform_id, fill_position + IVec2::new(-7, 3), network_path);
|
||||
document.network_interface.set_absolute_position(pattern_node_id, fill_position + IVec2::new(-14, 3), network_path);
|
||||
}
|
||||
} else if let Some(position) = document.network_interface.position(pattern_node_id, network_path) {
|
||||
let offsets = [
|
||||
(paint_transform_id, IVec2::new(7, 0)),
|
||||
(rectangle_id, IVec2::new(7, -3)),
|
||||
(fill_id, IVec2::new(14, 0)),
|
||||
(placement_transform_id, IVec2::new(21, 0)),
|
||||
];
|
||||
for (node_id, offset) in offsets {
|
||||
document.network_interface.shift_absolute_node_position(&node_id, position + offset, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -2425,7 +2560,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
|
||||
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
|
||||
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
|
||||
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
|
||||
];
|
||||
for (parameter, fallback) in conversions {
|
||||
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
|
||||
@@ -2746,20 +2880,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
|
||||
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), NodeInput::value(TaggedValue::None, false), network_path);
|
||||
for (i, input) in old_inputs.iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i + 1), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The Threshold node's luminance calculation input was retired
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -3565,18 +3685,14 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
photo_filter::IDENTIFIER,
|
||||
color_lookup::IDENTIFIER,
|
||||
image_to_channels::IDENTIFIER,
|
||||
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER,
|
||||
graphene_std::raster_nodes::filter::median_filter::IDENTIFIER,
|
||||
graphene_std::raster_nodes::effects::blur::IDENTIFIER,
|
||||
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
|
||||
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::image::IDENTIFIER,
|
||||
graphene_std::platform_application_io::bytes_to_image::IDENTIFIER,
|
||||
graphene_std::platform_application_io::image_to_bytes::IDENTIFIER,
|
||||
graphene_std::platform_application_io::rasterize::IDENTIFIER,
|
||||
]
|
||||
@@ -4672,7 +4788,7 @@ mod tests {
|
||||
migrate(&mut document);
|
||||
|
||||
let image_node = &document.network_interface.document_network().nodes[&image_id];
|
||||
assert_eq!(image_node.inputs.len(), 3, "the image node should gain its placeholder primary input and pipeline scope input");
|
||||
assert_eq!(image_node.inputs.len(), 2, "the image node should gain its placeholder primary input");
|
||||
let migrated = &image_node.inputs[1];
|
||||
match legacy_input.as_value() {
|
||||
None => assert_eq!(migrated.as_node(), Some(upstream_id), "the wire should sit at input 1"),
|
||||
@@ -4708,24 +4824,51 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_raster_type_defaults_become_gpu_defaults() {
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let mut blur_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::effects::blur::IDENTIFIER))
|
||||
.expect("the definition should exist")
|
||||
.default_node_template();
|
||||
blur_template.inputs[0] = NodeInput::type_default(item!(Raster<CPU>), true);
|
||||
document.network_interface.insert_node(node_id, blur_template, &[]);
|
||||
fn gradient_form_nodes_become_gradient_curvature_presets() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
migrate(&mut document);
|
||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
||||
for (identifier, form, dials) in [
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
|
||||
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
|
||||
] {
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let placeholder = || NodeInput::value(TaggedValue::None, false);
|
||||
document.network_interface.insert_node(
|
||||
source_id,
|
||||
NodeTemplate {
|
||||
inputs: vec![placeholder()],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.insert_node(
|
||||
form_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![placeholder(); 2],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), false), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let migrated = &document.network_interface.document_network().nodes[&node_id].inputs[0];
|
||||
assert_eq!(
|
||||
migrated.as_value(),
|
||||
Some(&TaggedValue::TypeDefault(item!(Raster<GPU>))),
|
||||
"the CPU raster default should become the GPU raster default"
|
||||
);
|
||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
||||
let node = &document.network_interface.document_network().nodes[&form_id];
|
||||
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
|
||||
|
||||
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(
|
||||
[curvature(1), curvature(2)],
|
||||
dials.map(|dial| Some(TaggedValue::Number(dial))),
|
||||
"{form:?} should become its curvature presets"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -5277,4 +5420,81 @@ mod tests {
|
||||
assert_eq!(interface.display_name(&node_id, &[]), "Image", "node {node_id}");
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew a square of their patterns, which now fill the plane, so the square becomes a rectangle filled with the pattern
|
||||
#[tokio::test]
|
||||
async fn clipped_patterns_become_rectangles_filled_with_them() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let noise = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER)).await;
|
||||
let mandelbrot = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER)).await;
|
||||
let noise_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
let mandelbrot_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
|
||||
let document = editor.active_document_mut();
|
||||
for (reader, pattern) in [(noise_reader, noise), (mandelbrot_reader, mandelbrot)] {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(pattern, 0), &[]);
|
||||
}
|
||||
|
||||
// Save them as an older editor did, the Noise Pattern with its Clip toggle on and the Mandelbrot without a primary input
|
||||
let mut noise_inputs = document.network_interface.document_node(&noise, &[]).unwrap().inputs.clone();
|
||||
noise_inputs.insert(1, NodeInput::value(TaggedValue::Bool(true), false));
|
||||
noise_inputs[2] = NodeInput::value(TaggedValue::Integer(7), false);
|
||||
for (node_id, inputs) in [(noise, noise_inputs), (mandelbrot, Vec::new())] {
|
||||
let mut legacy = NodeTemplate { inputs, ..Default::default() };
|
||||
legacy.normalize_input_metadata();
|
||||
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
|
||||
}
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
let input = |node_id: NodeId, index: usize| interface.document_node(&node_id, &[]).and_then(|node| node.inputs.get(index)).cloned();
|
||||
let upstream = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_node());
|
||||
let value = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_value().cloned());
|
||||
|
||||
// Each reader now reads a rectangle of the square's size, moved onto the square, filled with the pattern moved back by the same amount
|
||||
for (reader, pattern, size) in [(noise_reader, noise, 100.), (mandelbrot_reader, mandelbrot, 1.)] {
|
||||
let placement = upstream(reader, 0).expect("the reader should read the placement transform");
|
||||
assert_eq!(value(placement, 1), Some(TaggedValue::DVec2(DVec2::splat(size / 2.))));
|
||||
|
||||
let fill = upstream(placement, 0).expect("the placement should move the filled rectangle");
|
||||
let rectangle = upstream(fill, 0).expect("the fill should paint a rectangle");
|
||||
assert_eq!((value(rectangle, 1), value(rectangle, 2)), (Some(TaggedValue::Number(size)), Some(TaggedValue::Number(size))));
|
||||
|
||||
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
|
||||
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
|
||||
assert_eq!(upstream(paint, 0), Some(pattern));
|
||||
}
|
||||
|
||||
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
|
||||
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
|
||||
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
|
||||
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
|
||||
}
|
||||
|
||||
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
||||
#[tokio::test]
|
||||
async fn marbled_mandelbrot_renders_after_migration() {
|
||||
use crate::messages::portfolio::ingest::utility_types::IngestAction;
|
||||
use crate::messages::prelude::IngestMessage;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
let content = std::fs::read_to_string("../demo-artwork/marbled-mandelbrot.graphite").unwrap();
|
||||
editor.editor.handle_message(IngestMessage::Ingest {
|
||||
data: content.into_bytes(),
|
||||
action: IngestAction::Open,
|
||||
mime_type: String::new(),
|
||||
path: Some("marbled-mandelbrot.graphite".into()),
|
||||
});
|
||||
if let Err(error) = editor.eval_graph_until_finished().await {
|
||||
panic!("The migrated demo failed to render: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -342,7 +342,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
|
||||
// A generator discards its primary input, so the chain ends at whichever one is reached
|
||||
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
|
||||
let setters = [
|
||||
graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
||||
|
||||
@@ -413,7 +413,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
||||
|
||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
|
||||
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
||||
let mut gradient_form: Option<GradientForm> = None;
|
||||
@@ -430,11 +430,14 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
|
||||
if reference == transform_reference {
|
||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||
} else if reference == gradient_form_reference
|
||||
&& gradient_form.is_none()
|
||||
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||
{
|
||||
gradient_form = Some(*value);
|
||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
||||
// Curvatures other than the radial form's are drawn with the linear form's controls
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::Number(value)) => value,
|
||||
_ => 0.,
|
||||
};
|
||||
let is_radial = [curvature(1), curvature(2)] == graphene_std::renderer::dial_gradient::RADIAL_DIALS;
|
||||
gradient_form = Some(if is_radial { GradientForm::Radial } else { GradientForm::Linear });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3366,7 +3369,7 @@ mod test_gradient {
|
||||
.await;
|
||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
||||
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
editor
|
||||
@@ -3375,7 +3378,7 @@ mod test_gradient {
|
||||
})
|
||||
.await;
|
||||
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let form_node_id = {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
network_interface
|
||||
@@ -3384,10 +3387,10 @@ mod test_gradient {
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
||||
.expect("Gradient Form node should have been inserted")
|
||||
.expect("Gradient Curvature node should have been inserted")
|
||||
};
|
||||
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
|
||||
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
||||
|
||||
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
||||
|
||||
@@ -1238,3 +1238,82 @@ mod test {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod raster_input_adapter_tests {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId};
|
||||
use graphene_std::Effects;
|
||||
use graphene_std::list::{ATTR_EFFECTS, Item};
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
use graphene_std::raster_nodes::adjustments::invert;
|
||||
use graphene_std::raster_nodes::dehaze::dehaze;
|
||||
use graphene_std::raster_nodes::filter::median_filter;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::transform::Footprint;
|
||||
|
||||
/// A document whose image feeds `nodes` in turn, ending in the export, with each node's ID.
|
||||
async fn image_through(editor: &mut EditorTestUtils, color: Color, nodes: &[ProtoNodeIdentifier]) -> Vec<NodeId> {
|
||||
editor.new_document().await;
|
||||
editor.create_raster_image(Image::new(4, 4, color), None).await;
|
||||
let image = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
||||
.map(|(id, _)| *id)
|
||||
.expect("the pasted image should be an Image node");
|
||||
|
||||
let mut ids = Vec::new();
|
||||
let mut previous = OutputConnector::node(image, 0);
|
||||
for (index, identifier) in nodes.iter().enumerate() {
|
||||
let id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(identifier.clone()), (index as i32 + 1) * 10, 0).await;
|
||||
let input = InputConnector::node_at_index(id, 0);
|
||||
editor.active_document_mut().network_interface.create_wire(&previous, &input, &[]);
|
||||
previous = OutputConnector::node(id, 0);
|
||||
ids.push(id);
|
||||
}
|
||||
editor.active_document_mut().network_interface.create_wire(&previous, &InputConnector::Export(0), &[]);
|
||||
ids
|
||||
}
|
||||
|
||||
async fn read(editor: &EditorTestUtils, raster: Raster<GPU>) -> Raster<CPU> {
|
||||
let executor = editor.gpu_executor();
|
||||
raster.convert(Footprint::DEFAULT, executor).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_images_stamped_effects_are_carried_out_before_the_gpu_only_node_it_feeds() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
image_through(&mut editor, Color::WHITE, &[invert::IDENTIFIER, median_filter::IDENTIFIER, invert::IDENTIFIER]).await;
|
||||
|
||||
let instrumented = editor.eval_graph_until_finished().await.expect("the CPU raster should reach Median through its input adapter");
|
||||
let reached_median: Item<Raster<CPU>> = instrumented
|
||||
.grab_all_input::<median_filter::ImageFrameInput, Item<Raster<CPU>>>(&editor.runtime)
|
||||
.next()
|
||||
.expect("the image should arrive at Median as a CPU raster");
|
||||
assert!(reached_median.attribute::<Effects>(ATTR_EFFECTS).is_some(), "the first Invert should only stamp the image");
|
||||
|
||||
// Median at its default radius passes its input through, so its output shows what the adapter gave it
|
||||
let output = instrumented
|
||||
.grab_all_input::<invert::InputInput, Item<Raster<GPU>>>(&editor.runtime)
|
||||
.next()
|
||||
.expect("Median should output a GPU raster");
|
||||
assert!(output.attribute::<Effects>(ATTR_EFFECTS).is_none(), "no stamp should be left to apply after Median");
|
||||
let raster = read(&editor, output.into_element()).await;
|
||||
assert!(raster.data[0].r() < 0.01, "the white image should be black by the time Median reads it, not {:?}", raster.data[0]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_image_feeding_dehaze_compiles_and_renders_without_a_migration() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
image_through(&mut editor, Color::from_rgbaf32_unchecked(0.5, 0.6, 0.7, 1.), &[dehaze::IDENTIFIER]).await;
|
||||
|
||||
// A compile error or a failed render fails this
|
||||
editor.eval_graph_uninstrumented().await.expect("the image should reach Dehaze through its input adapter");
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,11 @@ impl EditorTestUtils {
|
||||
editor
|
||||
}
|
||||
|
||||
/// The GPU executor the graph runs on.
|
||||
pub fn gpu_executor(&self) -> <PlatformApplicationIo as ApplicationIo>::Executor {
|
||||
gpu_application_io().gpu_executor().cloned().expect("tests render on the GPU")
|
||||
}
|
||||
|
||||
pub fn dispatch(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
|
||||
let mut responses = self.editor.handle_message(message);
|
||||
while self.woken.swap(false, Ordering::Relaxed) {
|
||||
@@ -108,6 +113,33 @@ impl EditorTestUtils {
|
||||
Ok(instrumented)
|
||||
}
|
||||
|
||||
/// Compiles and runs the graph without the monitors of [`Instrumented`], which can't wrap the runtime handle that asynchronous nodes take.
|
||||
pub async fn eval_graph_uninstrumented(&mut self) -> Result<(), String> {
|
||||
let portfolio = &mut self.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).unwrap();
|
||||
|
||||
if let Err(e) = executor.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, Default::default()) {
|
||||
return Err(format!("submit_node_graph_evaluation failed\n\n{e}"));
|
||||
}
|
||||
self.finish_evaluation().await
|
||||
}
|
||||
|
||||
/// Waits for the submitted evaluation and processes its results, failing if the graph didn't render.
|
||||
async fn finish_evaluation(&mut self) -> Result<(), String> {
|
||||
self.runtime.run().await;
|
||||
|
||||
let frontend_messages = self.dispatch(Message::Wake);
|
||||
if frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
|
||||
return Err("Graph should render".to_string());
|
||||
}
|
||||
for message in frontend_messages {
|
||||
message.check_node_graph_error();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
|
||||
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
|
||||
const MAX_ITERATIONS: usize = 16;
|
||||
|
||||
@@ -540,9 +540,10 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||
> .text-label:only-child {
|
||||
// A label with no expose button before it lines up with the parameter names that follow one
|
||||
> .text-label:first-child {
|
||||
margin-left: calc(20px + 8px + 8px);
|
||||
--wire-indent: 20px;
|
||||
}
|
||||
|
||||
> .separator.horizontal.unrelated {
|
||||
|
||||
@@ -8,6 +8,7 @@ use graphene_animation::AnimationCurve;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::Stroke;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{AttributeValueDyn, Bundle, Item, List, ListDyn, NodeIdPath};
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -46,6 +47,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Generator>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Artboard>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Graphic>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Vector>]),
|
||||
@@ -56,6 +58,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Generator>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
@@ -104,6 +107,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
@@ -124,6 +128,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
@@ -370,6 +375,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Graphic,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
String,
|
||||
f64,
|
||||
DVec2,
|
||||
@@ -383,8 +389,28 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// The nested-generic `Box<VectorModification>` registers directly rather than through the shared callback, since the
|
||||
// extra macro layer mangles the `stringify!` whitespace in its adapter identifier; its cache chain is likewise direct below
|
||||
node_types.extend(rank_adapter_nodes!(Box<VectorModification>));
|
||||
// A GPU raster's input adapter also takes the pipeline to upload a CPU raster wire with, so its rows don't come from `rank_adapter_nodes`
|
||||
#[cfg(feature = "gpu")]
|
||||
node_types.extend(rank_adapter_nodes!(Raster<GPU>));
|
||||
{
|
||||
use graphene_std::raster_nodes::effects::{PassRasterNode, UploadItemNode, UploadListNode};
|
||||
use wgpu_executor::WgpuPipelineCache;
|
||||
|
||||
macro_rules! gpu_raster_input_adapter {
|
||||
($path:ty, $from:ty) => {
|
||||
async_node!(
|
||||
identifier: ProtoNodeIdentifier::new("input_adapter<Raster<GPU>>"),
|
||||
$path,
|
||||
input: Context,
|
||||
fn_params: [Context => $from, Context => Item<WgpuPipelineCache>]
|
||||
)
|
||||
};
|
||||
}
|
||||
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, Item<Raster<GPU>>));
|
||||
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, List<Raster<GPU>>));
|
||||
node_types.push(gpu_raster_input_adapter!(UploadItemNode<_, _>, Item<Raster<CPU>>));
|
||||
node_types.push(gpu_raster_input_adapter!(UploadListNode<_, _>, List<Raster<CPU>>));
|
||||
node_types.push(item_to_list_node!(element: Raster<GPU>));
|
||||
}
|
||||
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
||||
macro_rules! list_dyn_rows {
|
||||
($($element:ty),* $(,)?) => {{
|
||||
@@ -402,6 +428,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
f64,
|
||||
i64,
|
||||
bool,
|
||||
@@ -442,6 +469,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
String,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
Artboard,
|
||||
));
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -495,6 +523,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// This is what lets a paint list zip element-wise against the content it paints.
|
||||
node_types.extend(embed_adapter_row!(from_element: Color, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Gradient, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Generator, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: String, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Vector, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Raster<CPU>, element: Graphic));
|
||||
@@ -552,6 +581,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(List<String>),
|
||||
attribute_value_node!(List<Color>),
|
||||
attribute_value_node!(List<Gradient>),
|
||||
attribute_value_node!(List<Generator>),
|
||||
attribute_value_node!(List<Vector>),
|
||||
attribute_value_node!(List<Raster<CPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -579,6 +609,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
transform_list_node!(element: Raster<GPU>),
|
||||
transform_list_node!(element: Color),
|
||||
transform_list_node!(element: Gradient),
|
||||
transform_list_node!(element: Generator),
|
||||
];
|
||||
node_types.extend(transform_list_rows);
|
||||
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
|
||||
|
||||
@@ -33,9 +33,9 @@ pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD,
|
||||
ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
|
||||
ATTR_TYPE,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
|
||||
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
|
||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use num_traits;
|
||||
|
||||
@@ -61,6 +61,11 @@ pub const ATTR_CLIP: &str = "clip";
|
||||
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
||||
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||
/// Gradient's `f64` curvature dial for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
|
||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, the form decides it.
|
||||
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
|
||||
/// Gradient's `f64` curvature dial for the contour through its end, like `gradient_start_curvature` with the ends swapped.
|
||||
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
|
||||
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::effects::{EffectKind, ParameterVisitor};
|
||||
use crate::Graphic;
|
||||
use crate::effects::EffectKind;
|
||||
use crate::parameters::ParameterVisitor;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
@@ -120,7 +122,7 @@ impl Adjustment {
|
||||
Self::ColorBalance(_) => EffectKind::ColorBalance,
|
||||
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::ColorOverlay,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,7 +272,12 @@ impl Adjustment {
|
||||
}
|
||||
Self::ColorLookup { lut_file } => visitor.parameter("lut_file", lut_file, Resource::default()),
|
||||
Self::ColorOverlay { color, blend_mode, opacity } => {
|
||||
visitor.parameter("color", color, Color::BLACK);
|
||||
// Rides the row as the paint of the Paint Overlay node, which stamps it
|
||||
let mut paint = Graphic::from(*color);
|
||||
visitor.parameter("paint", &mut paint, Graphic::from(Color::BLACK));
|
||||
if let Graphic::Color(paint) = paint {
|
||||
*color = *paint.element();
|
||||
}
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
|
||||
@@ -2,13 +2,17 @@
|
||||
//! Each row is an [`EffectKind`] whose parameters ride its item as attributes, read as their defaults when absent.
|
||||
//! Each renderer decodes the rows into [`EffectOperation`]s and carries them out its own way, at the resolution of each render.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DMat2, DVec2, DVec3};
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
use std::fmt::Debug;
|
||||
use vector_types::vector::style::StrokeAlign;
|
||||
|
||||
@@ -32,6 +36,8 @@ pub enum EffectKind {
|
||||
Outline,
|
||||
/// Lights the content as if raised from the surface or pressed into it, with highlights and shadows along its edges.
|
||||
BevelAndEmboss,
|
||||
/// Paints over the content within its silhouette, mixing with its colors by a blend mode. A solid color paint is the color overlay adjustment.
|
||||
PaintOverlay,
|
||||
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
@@ -52,7 +58,6 @@ pub enum EffectKind {
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
ColorOverlay,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
@@ -66,6 +71,7 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::Satin => "Satin",
|
||||
Self::Outline => "Outline",
|
||||
Self::BevelAndEmboss => "Bevel & Emboss",
|
||||
Self::PaintOverlay => "Paint Overlay",
|
||||
Self::Desaturate => "Desaturate",
|
||||
Self::GammaCorrection => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
@@ -85,7 +91,6 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::ColorBalance => "Color Balance",
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
Self::ColorOverlay => "Color Overlay",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -145,6 +150,29 @@ pub fn bevel_light(angle: f64, altitude: f64, lengths_to_target: DMat2) -> DVec3
|
||||
(across * altitude.cos()).extend(altitude.sin())
|
||||
}
|
||||
|
||||
/// An overlay's paint with its unit square fitted to `content_bounds`, the content's extent in the space it's drawn in, if it's a gradient or image without its own placement.
|
||||
pub fn fitted_paint(paint: &Graphic, content_bounds: [DVec2; 2]) -> Option<Graphic> {
|
||||
let unplaced = match paint {
|
||||
Graphic::Gradient(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterCPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterGPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
_ => false,
|
||||
};
|
||||
if !unplaced {
|
||||
return None;
|
||||
}
|
||||
|
||||
let fit = DAffine2::from_translation(content_bounds[0]) * DAffine2::from_scale(content_bounds[1] - content_bounds[0]);
|
||||
let mut paint = paint.clone();
|
||||
match &mut paint {
|
||||
Graphic::Gradient(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterCPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterGPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
_ => {}
|
||||
}
|
||||
Some(paint)
|
||||
}
|
||||
|
||||
/// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item.
|
||||
/// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
@@ -166,8 +194,21 @@ impl Effect {
|
||||
/// Decodes the parameters into an [`EffectOperation`], falling back to the default for any absent attribute.
|
||||
pub fn operation(&self) -> EffectOperation {
|
||||
let mut operation = EffectOperation::placeholder(self.kind());
|
||||
operation.visit_parameters(&mut ReadParameters(&self.0));
|
||||
operation
|
||||
operation.visit_parameters(&mut ReadParameters(&|key| self.0.attributes().get_any(key)));
|
||||
|
||||
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
|
||||
match operation {
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: Graphic::Color(color),
|
||||
blend_mode,
|
||||
opacity,
|
||||
} => EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: *color.element(),
|
||||
blend_mode,
|
||||
opacity,
|
||||
}),
|
||||
operation => operation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,6 +336,14 @@ pub enum EffectOperation {
|
||||
highlight_color: Color,
|
||||
shadow_color: Color,
|
||||
},
|
||||
/// Paints over the content with a paint other than a solid color, since a solid one decodes into the color overlay adjustment instead.
|
||||
PaintOverlay {
|
||||
/// Placed in the space the content's item is, or fitted to the content's bounds if it's a gradient or image without its own placement.
|
||||
paint: Graphic,
|
||||
blend_mode: BlendMode,
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
Adjustment(Adjustment),
|
||||
}
|
||||
|
||||
@@ -314,6 +363,7 @@ impl EffectOperation {
|
||||
Self::Satin { .. } => EffectKind::Satin,
|
||||
Self::Outline { .. } => EffectKind::Outline,
|
||||
Self::BevelAndEmboss { .. } => EffectKind::BevelAndEmboss,
|
||||
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Adjustment(adjustment) => adjustment.kind(),
|
||||
}
|
||||
}
|
||||
@@ -330,7 +380,7 @@ impl EffectOperation {
|
||||
Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
|
||||
Self::Outline { weight, .. } => weight.max(0.),
|
||||
Self::BevelAndEmboss { size, soften, .. } => size.max(0.) + 3. * (soften.max(0.) + bevel_smoothing(*size)),
|
||||
Self::Adjustment(_) => 0.,
|
||||
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,6 +437,11 @@ impl EffectOperation {
|
||||
highlight_color: Color::TRANSPARENT,
|
||||
shadow_color: Color::TRANSPARENT,
|
||||
},
|
||||
EffectKind::PaintOverlay => Self::PaintOverlay {
|
||||
paint: Graphic::default(),
|
||||
blend_mode: BlendMode::default(),
|
||||
opacity: 0.,
|
||||
},
|
||||
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
|
||||
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
|
||||
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque),
|
||||
@@ -422,11 +477,6 @@ impl EffectOperation {
|
||||
preserve_luminosity: false,
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
EffectKind::ColorOverlay => Self::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::TRANSPARENT,
|
||||
blend_mode: Default::default(),
|
||||
opacity: 0.,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -487,43 +537,20 @@ impl EffectOperation {
|
||||
visitor.parameter("highlight_color", highlight_color, Color::from(SRGBA8::new(0xff, 0xff, 0xff, 0xbf)));
|
||||
visitor.parameter("shadow_color", shadow_color, Color::from(SRGBA8::new(0, 0, 0, 0xbf)));
|
||||
}
|
||||
Self::PaintOverlay { paint, blend_mode, opacity } => {
|
||||
visitor.parameter("paint", paint, Graphic::from(Color::BLACK));
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a value needs to ride an attribute.
|
||||
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
|
||||
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
|
||||
|
||||
/// Handles each parameter of an operation, given the attribute key it rides and its implicit default.
|
||||
pub(crate) trait ParameterVisitor {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
|
||||
}
|
||||
|
||||
/// Stamps each parameter that differs from its default onto a row.
|
||||
struct WriteParameters<'a>(&'a mut Item<EffectKind>);
|
||||
|
||||
impl ParameterVisitor for WriteParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
if *value != default {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads each parameter from a row, or its default where the row lacks it.
|
||||
struct ReadParameters<'a>(&'a Item<EffectKind>);
|
||||
|
||||
impl ParameterVisitor for ReadParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
*value = self.0.attribute::<T>(key).cloned().unwrap_or(default);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vector_types::{Gradient, GradientStop};
|
||||
|
||||
#[test]
|
||||
fn rows_round_trip_their_operations_eliding_defaults() {
|
||||
@@ -573,12 +600,43 @@ mod tests {
|
||||
highlight_color: Color::YELLOW,
|
||||
shadow_color: Color::BLUE,
|
||||
},
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: Graphic::from(Gradient::new([0., 1.].map(|position| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: Color::from_rgbaf32_unchecked(position as f32, 0., 1., 1.),
|
||||
}))),
|
||||
blend_mode: BlendMode::Multiply,
|
||||
opacity: 60.,
|
||||
},
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::GREEN,
|
||||
blend_mode: BlendMode::Screen,
|
||||
opacity: 100.,
|
||||
}),
|
||||
];
|
||||
|
||||
for operation in operations {
|
||||
assert_eq!(Effect::new(&operation).operation(), operation);
|
||||
}
|
||||
|
||||
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
|
||||
let solid = EffectOperation::PaintOverlay {
|
||||
paint: Graphic::from(Color::RED),
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
};
|
||||
let solid_row = Effect::new(&solid);
|
||||
assert_eq!(solid_row.kind(), EffectKind::PaintOverlay);
|
||||
assert_eq!(
|
||||
solid_row.operation(),
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
})
|
||||
);
|
||||
|
||||
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
|
||||
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
|
||||
}
|
||||
@@ -606,7 +664,7 @@ mod tests {
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
ColorOverlay,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
let operation = EffectOperation::default_for(kind);
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DAffine2;
|
||||
use std::any::Any;
|
||||
|
||||
/// Style of noise pattern.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -90,7 +96,7 @@ pub enum DomainWarpType {
|
||||
}
|
||||
|
||||
/// The settings of a noise pattern, whose lengths are measured in the document units of the space it's sampled in.
|
||||
#[derive(Debug, Clone, PartialEq, CacheHash)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, CacheHash)]
|
||||
pub struct NoiseSettings {
|
||||
pub seed: i64,
|
||||
pub scale: f64,
|
||||
@@ -115,3 +121,82 @@ pub enum GeneratorPattern {
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
/// A procedural pattern filling the whole plane, which renderers draw at whatever resolution they need across whatever part they see.
|
||||
/// The item's transform places the pattern's own space, and a noise pattern's settings ride the item as attributes named after the Noise Pattern node's parameters.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny)]
|
||||
pub enum Generator {
|
||||
#[default]
|
||||
Noise,
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Generator {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Noise => "Noise",
|
||||
Self::Mandelbrot => "Mandelbrot",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl BoundingBox for Generator {
|
||||
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
|
||||
match transform.matrix2.determinant() == 0. {
|
||||
true => RenderBoundingBox::None,
|
||||
false => RenderBoundingBox::Infinite,
|
||||
}
|
||||
}
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
self.bounding_box(transform, include_stroke)
|
||||
}
|
||||
}
|
||||
|
||||
impl NoiseSettings {
|
||||
/// Stamps every setting onto the generator's item, whatever its value, so which attributes the item carries doesn't depend on them.
|
||||
pub fn stamp(&self, item: &mut Item<Generator>) {
|
||||
self.clone().visit_parameters(&mut StampParameters(item));
|
||||
}
|
||||
|
||||
/// Visits each setting with the attribute it rides, named after the Noise Pattern node's parameter, and its default, which is the node's.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
visitor.parameter("seed", &mut self.seed, 0);
|
||||
visitor.parameter("scale", &mut self.scale, 10.);
|
||||
visitor.parameter("noise_type", &mut self.noise_type, NoiseType::default());
|
||||
visitor.parameter("domain_warp_type", &mut self.domain_warp_type, DomainWarpType::default());
|
||||
visitor.parameter("domain_warp_amplitude", &mut self.domain_warp_amplitude, 100.);
|
||||
visitor.parameter("fractal_type", &mut self.fractal_type, FractalType::default());
|
||||
visitor.parameter("fractal_octaves", &mut self.fractal_octaves, 3);
|
||||
visitor.parameter("fractal_lacunarity", &mut self.fractal_lacunarity, 2.);
|
||||
visitor.parameter("fractal_gain", &mut self.fractal_gain, 0.5);
|
||||
visitor.parameter("fractal_weighted_strength", &mut self.fractal_weighted_strength, 0.);
|
||||
visitor.parameter("fractal_ping_pong_strength", &mut self.fractal_ping_pong_strength, 2.);
|
||||
visitor.parameter("cellular_distance_function", &mut self.cellular_distance_function, CellularDistanceFunction::default());
|
||||
visitor.parameter("cellular_return_type", &mut self.cellular_return_type, CellularReturnType::default());
|
||||
visitor.parameter("cellular_jitter", &mut self.cellular_jitter, 1.);
|
||||
}
|
||||
}
|
||||
|
||||
impl GeneratorPattern {
|
||||
/// The pattern a generator draws, reading a noise pattern's settings with `attribute`, which looks one of the item's attributes up by key.
|
||||
/// Each setting the item lacks takes its default.
|
||||
pub fn decode<'a>(generator: Generator, attribute: &'a dyn Fn(&str) -> Option<&'a dyn Any>) -> Self {
|
||||
match generator {
|
||||
Generator::Noise => {
|
||||
let mut settings = NoiseSettings::default();
|
||||
settings.visit_parameters(&mut ReadParameters(attribute));
|
||||
Self::Noise(settings)
|
||||
}
|
||||
Generator::Mandelbrot => Self::Mandelbrot,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern a generator item draws.
|
||||
pub fn of_item(item: &Item<Generator>) -> Self {
|
||||
Self::decode(*item.element(), &|key| item.attributes().get_any(key))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::appearance::{Appearance, Cover, Coverage};
|
||||
use crate::generator::Generator;
|
||||
use brush_types::Stroke;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
@@ -26,6 +27,7 @@ pub enum Graphic {
|
||||
RasterGPU(Item<Raster<GPU>>),
|
||||
Color(Item<Color>),
|
||||
Gradient(Item<Gradient>),
|
||||
Generator(Item<Generator>),
|
||||
Text(Item<String>),
|
||||
NoneList(List<none::None>),
|
||||
GraphicList(List<Graphic>),
|
||||
@@ -34,6 +36,7 @@ pub enum Graphic {
|
||||
RasterGPUList(List<Raster<GPU>>),
|
||||
ColorList(List<Color>),
|
||||
GradientList(List<Gradient>),
|
||||
GeneratorList(List<Generator>),
|
||||
TextList(List<String>),
|
||||
StrokeList(List<Stroke>),
|
||||
}
|
||||
@@ -137,6 +140,23 @@ impl From<List<Gradient>> for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
// Generator
|
||||
impl From<Generator> for Graphic {
|
||||
fn from(generator: Generator) -> Self {
|
||||
Graphic::Generator(Item::new_from_element(generator))
|
||||
}
|
||||
}
|
||||
impl From<Item<Generator>> for Graphic {
|
||||
fn from(generator: Item<Generator>) -> Self {
|
||||
Graphic::Generator(generator)
|
||||
}
|
||||
}
|
||||
impl From<List<Generator>> for Graphic {
|
||||
fn from(generator: List<Generator>) -> Self {
|
||||
Graphic::GeneratorList(generator)
|
||||
}
|
||||
}
|
||||
|
||||
// Stroke
|
||||
impl From<Stroke> for Graphic {
|
||||
fn from(stroke: Stroke) -> Self {
|
||||
@@ -312,12 +332,14 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
|
||||
Graphic::RasterCPU(item) => bake_item_transform(item, transform),
|
||||
Graphic::RasterGPU(item) => bake_item_transform(item, transform),
|
||||
Graphic::Gradient(item) => bake_item_transform(item, transform),
|
||||
Graphic::Generator(item) => bake_item_transform(item, transform),
|
||||
Graphic::Text(item) => bake_item_transform(item, transform),
|
||||
Graphic::GraphicList(list) => bake_list_transform(list, transform),
|
||||
Graphic::VectorList(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterCPUList(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterGPUList(list) => bake_list_transform(list, transform),
|
||||
Graphic::GradientList(list) => bake_list_transform(list, transform),
|
||||
Graphic::GeneratorList(list) => bake_list_transform(list, transform),
|
||||
Graphic::TextList(list) => bake_list_transform(list, transform),
|
||||
Graphic::StrokeList(list) => bake_list_transform(list, transform),
|
||||
// A color has no spatial extent, so there is no placement for a transform to move
|
||||
@@ -390,6 +412,16 @@ impl TryFromGraphic for Gradient {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Generator {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
match graphic {
|
||||
Graphic::Generator(item) => Some(List::new_from_item(item)),
|
||||
Graphic::GeneratorList(list) => Some(list),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for String {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
match graphic {
|
||||
@@ -457,6 +489,12 @@ impl IntoGraphicList for List<Gradient> {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Generator> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
List::new_from_element(Graphic::GeneratorList(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Stroke> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
let layer_path: NodeIdPath = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
@@ -570,6 +608,7 @@ impl Graphic {
|
||||
Graphic::RasterGPU(item) => item_clipped(item),
|
||||
Graphic::Color(item) => item_clipped(item),
|
||||
Graphic::Gradient(item) => item_clipped(item),
|
||||
Graphic::Generator(item) => item_clipped(item),
|
||||
Graphic::Text(item) => item_clipped(item),
|
||||
Graphic::NoneList(list) => all_clipped(list),
|
||||
Graphic::VectorList(list) => all_clipped(list),
|
||||
@@ -578,6 +617,7 @@ impl Graphic {
|
||||
Graphic::RasterGPUList(list) => all_clipped(list),
|
||||
Graphic::ColorList(list) => all_clipped(list),
|
||||
Graphic::GradientList(list) => all_clipped(list),
|
||||
Graphic::GeneratorList(list) => all_clipped(list),
|
||||
Graphic::TextList(list) => all_clipped(list),
|
||||
Graphic::StrokeList(list) => all_clipped(list),
|
||||
}
|
||||
@@ -616,6 +656,7 @@ impl Graphic {
|
||||
}
|
||||
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
||||
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
||||
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
||||
Graphic::Color(item) => item_opacity_is_full(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()),
|
||||
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
|
||||
@@ -662,9 +703,11 @@ impl Graphic {
|
||||
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
||||
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
||||
Graphic::Generator(item) => item_opacity_is_zero(item),
|
||||
Graphic::Text(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterCPUList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::RasterGPUList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::GeneratorList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::TextList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::StrokeList(list) => every_item_has_zero_opacity(list),
|
||||
}
|
||||
@@ -680,11 +723,12 @@ impl Graphic {
|
||||
match self {
|
||||
// A leaf always holds exactly one element, so only the none-typed content is truly empty
|
||||
Graphic::None(_) | Graphic::NoneList(_) => true,
|
||||
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Text(_) => false,
|
||||
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) | Graphic::Text(_) => false,
|
||||
Graphic::GraphicList(list) => list.is_empty(),
|
||||
Graphic::VectorList(list) => list.is_empty(),
|
||||
Graphic::ColorList(list) => list.is_empty(),
|
||||
Graphic::GradientList(list) => list.is_empty(),
|
||||
Graphic::GeneratorList(list) => list.is_empty(),
|
||||
Graphic::RasterCPUList(list) => list.is_empty(),
|
||||
Graphic::RasterGPUList(list) => list.is_empty(),
|
||||
Graphic::TextList(list) => list.is_empty(),
|
||||
@@ -841,6 +885,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::RasterGPU(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Color(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Generator(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Text(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::VectorList(list) => vector_list_bounding_box(list, transform, include_stroke),
|
||||
Graphic::RasterCPUList(list) => list.bounding_box(transform, include_stroke),
|
||||
@@ -848,6 +893,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::GraphicList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::ColorList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::GradientList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::GeneratorList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::TextList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::StrokeList(list) => list.bounding_box(transform, include_stroke),
|
||||
}
|
||||
@@ -862,6 +908,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::RasterGPU(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Color(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Generator(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Text(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::VectorList(vector) => vector_list_bounding_box(vector, transform, include_stroke),
|
||||
Graphic::RasterCPUList(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
@@ -869,6 +916,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::GraphicList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::ColorList(color) => color.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::GradientList(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::GeneratorList(generator) => generator.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::TextList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::StrokeList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ pub mod artboard;
|
||||
pub mod effects;
|
||||
pub mod generator;
|
||||
pub mod graphic;
|
||||
pub(crate) mod parameters;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
pub use core_types;
|
||||
@@ -14,7 +15,8 @@ pub use vector_types;
|
||||
pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, stamp_effect};
|
||||
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
|
||||
pub use generator::Generator;
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
|
||||
pub mod migrations {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Parameters riding an item as attributes, each read as its default when absent, which one listing per operation both writes and reads.
|
||||
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use std::any::Any;
|
||||
use std::fmt::Debug;
|
||||
|
||||
/// What a value needs to ride an attribute.
|
||||
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
|
||||
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
|
||||
|
||||
/// Handles each parameter of an operation, given the attribute key it rides and its default.
|
||||
pub(crate) trait ParameterVisitor {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
|
||||
}
|
||||
|
||||
/// Stamps each parameter that differs from its default onto an item, for rows whose attributes are part of their value.
|
||||
pub(crate) struct WriteParameters<'a, T>(pub &'a mut Item<T>);
|
||||
|
||||
impl<T> ParameterVisitor for WriteParameters<'_, T> {
|
||||
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, default: U) {
|
||||
if *value != default {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stamps every parameter onto an item, for an item on a wire, whose attributes mustn't come and go with their values.
|
||||
pub(crate) struct StampParameters<'a, T>(pub &'a mut Item<T>);
|
||||
|
||||
impl<T> ParameterVisitor for StampParameters<'_, T> {
|
||||
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, _default: U) {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads each parameter from the attribute that the lookup finds by key, or its default where there's none.
|
||||
pub(crate) struct ReadParameters<'a>(pub &'a dyn Fn(&str) -> Option<&'a dyn Any>);
|
||||
|
||||
impl ParameterVisitor for ReadParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
*value = (self.0)(key).and_then(|value| value.downcast_ref::<T>()).cloned().unwrap_or(default);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use crate::{RasterKernel, Wgsl, gpu_params};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
|
||||
/// A color as the premultiplied, gamma-encoded channels the passes work with, carried in a [`Color`] to be passed to them.
|
||||
pub fn premultiplied_gamma_channels(color: Color) -> Color {
|
||||
@@ -244,3 +245,19 @@ impl RasterKernel for KeepEmpty {
|
||||
Wgsl::function(include_str!("wgsl/effect_keep_empty.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The image (input 0) with a straight-alpha linear-light paint (input 1) mixed over its colors by a blend mode, as much as the paint covers and `opacity` lets it, keeping the image's alpha.
|
||||
#[derive(Clone)]
|
||||
pub struct PaintOverlay {
|
||||
pub blend_mode: BlendMode,
|
||||
pub opacity: f32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for PaintOverlay {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(format!("{}\n{}", include_str!("wgsl/blending.wgsl"), include_str!("wgsl/effect_paint_overlay.wgsl")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// The blend modes work on straight linear colors, as they do for a solid color overlay
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let parameters = params();
|
||||
let image = input_0_load(coord);
|
||||
let paint = input_1_load(coord);
|
||||
if image.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
if paint.a <= 0. {
|
||||
return image;
|
||||
}
|
||||
|
||||
let backdrop = vec4<f32>(srgb_to_linear(image.rgb / image.a), 1.);
|
||||
let blended = apply_blend_mode(vec4<f32>(paint.rgb, 1.), backdrop, parameters.blend_mode);
|
||||
let mixed = mix(backdrop.rgb, blended.rgb, parameters.opacity * paint.a);
|
||||
|
||||
return vec4<f32>(linear_to_srgb(mixed) * image.a, image.a);
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
//! Gradients whose two ends are each a contour dialed between a line, a circle, and a point, with the contours between
|
||||
//! them filling in as the pencil of circles the two end contours span.
|
||||
//!
|
||||
//! Everything here is in gradient space, where the gradient line runs from the start point at the origin to the end point
|
||||
//! at (1, 0). Each end's contour passes through its endpoint with its center on the line, and is described by its dial
|
||||
//! `α ∈ [-1, 1]`: 0 is the line perpendicular to the gradient line, ±1 is the endpoint itself, and in between is a circle
|
||||
//! bowing toward (positive) or away from (negative) the other endpoint.
|
||||
//!
|
||||
//! The contours between are the members of the pencil the end contours span. Each member is spaced by where it crosses
|
||||
//! the gradient line, so a stop at 0.3 sits where the 0.3 contour crosses the line. This reproduces the linear and radial
|
||||
//! forms exactly, since their contours cross the line at a distance in proportion to their place along the ramp.
|
||||
|
||||
use glam::DVec2;
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
|
||||
pub use graphic_types::vector_types::gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
/// Stands in for a t of infinity, on the contours whose crossing with the gradient line is at infinity.
|
||||
const UNBOUNDED_T: f64 = 1e6;
|
||||
|
||||
/// A generalized circle `a(x² + y²) + bx + c = 0` with its center on the gradient line: a circle, a line where `a` is zero,
|
||||
/// or a point where it has zero radius.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct AxisCircle {
|
||||
pub a: f64,
|
||||
pub b: f64,
|
||||
pub c: f64,
|
||||
}
|
||||
|
||||
impl AxisCircle {
|
||||
/// The contour through the start point at the origin, dialed by `alpha` toward the end point.
|
||||
pub fn start(alpha: f64) -> Self {
|
||||
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
|
||||
Self { a: sin, b: -2. * cos, c: 0. }
|
||||
}
|
||||
|
||||
/// The contour through the end point at (1, 0), dialed by `alpha` toward the start point.
|
||||
pub fn end(alpha: f64) -> Self {
|
||||
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
|
||||
Self {
|
||||
a: sin,
|
||||
b: 2. * cos - 2. * sin,
|
||||
c: sin - 2. * cos,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value(&self, point: DVec2) -> f64 {
|
||||
self.a * point.length_squared() + self.b * point.x + self.c
|
||||
}
|
||||
|
||||
/// The points where it crosses the gradient line, in homogeneous form.
|
||||
fn crossings(&self) -> [Homogeneous; 2] {
|
||||
solve_quadratic(self.a, self.b, self.c)
|
||||
}
|
||||
|
||||
/// The member of the pencil `self·weight + other·other_weight`.
|
||||
fn combine(&self, weight: f64, other: &Self, other_weight: f64) -> Self {
|
||||
Self {
|
||||
a: self.a * weight + other.a * other_weight,
|
||||
b: self.b * weight + other.b * other_weight,
|
||||
c: self.c * weight + other.c * other_weight,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A point on the gradient line in homogeneous form, `numerator / denominator`, so the point at infinity is just a zero denominator.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
struct Homogeneous {
|
||||
numerator: f64,
|
||||
denominator: f64,
|
||||
}
|
||||
|
||||
impl Homogeneous {
|
||||
const INFINITY: Self = Self { numerator: 1., denominator: 0. };
|
||||
|
||||
fn value(&self) -> Option<f64> {
|
||||
(self.denominator != 0.).then(|| self.numerator / self.denominator)
|
||||
}
|
||||
|
||||
/// Scaled so the larger of its two parts has a magnitude of 1, keeping products of points in range.
|
||||
fn normalized(self) -> Self {
|
||||
let scale = self.numerator.abs().max(self.denominator.abs());
|
||||
if scale == 0. {
|
||||
return self;
|
||||
}
|
||||
Self {
|
||||
numerator: self.numerator / scale,
|
||||
denominator: self.denominator / scale,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The roots of `a y² + b y + c = 0`, in homogeneous form so a vanishing `a` puts a root at infinity rather than dividing by zero.
|
||||
fn solve_quadratic(a: f64, b: f64, c: f64) -> [Homogeneous; 2] {
|
||||
let discriminant = (b * b - 4. * a * c).max(0.);
|
||||
let sign = if b >= 0. { 1. } else { -1. };
|
||||
let q = -0.5 * (b + sign * discriminant.sqrt());
|
||||
|
||||
[Homogeneous { numerator: q, denominator: a }.normalized(), Homogeneous { numerator: c, denominator: q }.normalized()]
|
||||
}
|
||||
|
||||
/// How the crossing of a pixel's contour is told apart from the other place the same circle crosses the gradient line.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum CrossingSelection {
|
||||
/// The end contours cross, so every member passes through the two points where they cross, and the gradient line is split by
|
||||
/// the line through those points at `radical_x`. Each side of a member circle is its own contour, crossing the gradient line
|
||||
/// on the same side of `radical_x` as the pixel.
|
||||
SameSideAs { radical_x: f64 },
|
||||
/// The end contours don't cross, so the members nest around two limit points that split the gradient line into two arcs, and
|
||||
/// every member crosses each arc once. The crossing on the arc holding the gradient's band is the one where
|
||||
/// `quadratic[0] y² + quadratic[1] y + quadratic[2]` (with `y` in homogeneous form) is smallest.
|
||||
OnArc { quadratic: [f64; 3] },
|
||||
}
|
||||
|
||||
/// Where the arc holding the band passes through infinity, the crossings beyond infinity on its other side.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Wrap {
|
||||
/// A point on the gradient line between the two limit points, which separates the arc's two sides of infinity.
|
||||
pub reference_x: f64,
|
||||
/// Which side of `reference_x` the band is on, `1` or `-1`.
|
||||
pub band_side: f64,
|
||||
/// The t of the crossings on the far side of infinity.
|
||||
pub t: f64,
|
||||
}
|
||||
|
||||
/// Everything needed to find the t of any pixel in a dialed gradient.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PencilParameters {
|
||||
pub start: AxisCircle,
|
||||
pub end: AxisCircle,
|
||||
pub selection: CrossingSelection,
|
||||
pub wrap: Option<Wrap>,
|
||||
/// The t of a crossing at `y` is `y * t_scale + t_offset`.
|
||||
pub t_scale: f64,
|
||||
pub t_offset: f64,
|
||||
}
|
||||
|
||||
impl PencilParameters {
|
||||
/// The parameters of the gradient with these two dials, which must be finite and within -1 to 1.
|
||||
pub fn new(start_dial: f64, end_dial: f64) -> Self {
|
||||
let start = AxisCircle::start(start_dial);
|
||||
let end = AxisCircle::end(end_dial);
|
||||
|
||||
// The members of the pencil that are points have a zero discriminant, which as a quadratic form in the two members'
|
||||
// weights has these coefficients. Its determinant says whether the pencil has two such points (it's hyperbolic), none
|
||||
// (elliptic, where the end contours cross), or one (parabolic, where they touch).
|
||||
let point_quadratic_start = start.b * start.b - 4. * start.a * start.c;
|
||||
let point_quadratic_cross = start.b * end.b - 2. * (start.a * end.c + end.a * start.c);
|
||||
let point_quadratic_end = end.b * end.b - 4. * end.a * end.c;
|
||||
let determinant = point_quadratic_start * point_quadratic_end - point_quadratic_cross * point_quadratic_cross;
|
||||
let scale = point_quadratic_start.abs().max(point_quadratic_end.abs()).max(point_quadratic_cross.abs()).max(f64::MIN_POSITIVE);
|
||||
|
||||
if determinant > 1e-12 * scale * scale {
|
||||
// The line through the two points where the end contours cross is the member with no curvature
|
||||
let line = start.combine(end.a, &end, -start.a);
|
||||
let radical_x = -line.c / line.b;
|
||||
|
||||
return Self::with_band(start, end, CrossingSelection::SameSideAs { radical_x }, None, 0., 1.);
|
||||
}
|
||||
|
||||
// The limit points are where the point members sit, with a point member of no curvature being the point at infinity
|
||||
let limit_points = point_member_weights(point_quadratic_start, point_quadratic_cross, point_quadratic_end).map(|(start_weight, end_weight)| {
|
||||
let member = start.combine(start_weight, &end, end_weight);
|
||||
let magnitude = member.a.abs().max(member.b.abs()).max(member.c.abs());
|
||||
if member.a.abs() <= 1e-12 * magnitude {
|
||||
return Homogeneous::INFINITY;
|
||||
}
|
||||
|
||||
Homogeneous {
|
||||
numerator: -member.b,
|
||||
denominator: 2. * member.a,
|
||||
}
|
||||
.normalized()
|
||||
});
|
||||
|
||||
// Each crossing's place relative to the limit points, negative between them and positive beyond them
|
||||
let arc_quadratic = arc_quadratic(limit_points);
|
||||
let arc_of = |point: Homogeneous| evaluate_homogeneous_quadratic(arc_quadratic, point.normalized());
|
||||
|
||||
// Find each end contour's crossing on each arc, where a point contour (a limit point itself) lies on both
|
||||
let choose_on_arc = |crossings: [Homogeneous; 2], negative_arc: bool| {
|
||||
crossings
|
||||
.into_iter()
|
||||
.min_by(|a, b| {
|
||||
let (a, b) = (arc_of(*a), arc_of(*b));
|
||||
if negative_arc { a.total_cmp(&b) } else { b.total_cmp(&a) }
|
||||
})
|
||||
.unwrap_or(Homogeneous::INFINITY)
|
||||
};
|
||||
let candidates = [true, false].map(|negative_arc| {
|
||||
let band_start = choose_on_arc(start.crossings(), negative_arc);
|
||||
let band_end = choose_on_arc(end.crossings(), negative_arc);
|
||||
(negative_arc, band_start, band_end)
|
||||
});
|
||||
|
||||
// A band through infinity would give a contour within it an infinite t, so it's unusable. Among the rest, prefer the
|
||||
// band that keeps the endpoints at t of 0 and 1.
|
||||
let limit_values = limit_points.map(|point| point.value());
|
||||
let usable = |band_start: Homogeneous, band_end: Homogeneous| {
|
||||
let (Some(band_start), Some(band_end)) = (band_start.value(), band_end.value()) else {
|
||||
return false;
|
||||
};
|
||||
match limit_values {
|
||||
[Some(first), Some(second)] => {
|
||||
let (low, high) = (first.min(second), first.max(second));
|
||||
let beyond = |y: f64| {
|
||||
if y > high {
|
||||
1
|
||||
} else if y < low {
|
||||
-1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
// On the outer arc, crossings on opposite sides of the limit points lie across infinity from each other
|
||||
beyond(band_start) * beyond(band_end) >= 0
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let truthfulness = |band_start: Homogeneous, band_end: Homogeneous| {
|
||||
let is = |point: Homogeneous, target: f64| point.value().is_some_and(|value| (value - target).abs() < 1e-9);
|
||||
is(band_start, 0.) as u8 + is(band_end, 1.) as u8
|
||||
};
|
||||
let chosen = candidates
|
||||
.into_iter()
|
||||
.filter(|&(_, band_start, band_end)| usable(band_start, band_end))
|
||||
.max_by_key(|&(_, band_start, band_end)| truthfulness(band_start, band_end))
|
||||
.unwrap_or(candidates[1]);
|
||||
let (negative_arc, band_start, band_end) = chosen;
|
||||
|
||||
// Choosing the smallest value picks the crossing on the chosen arc
|
||||
let sign = if negative_arc { 1. } else { -1. };
|
||||
let selection = CrossingSelection::OnArc {
|
||||
quadratic: arc_quadratic.map(|coefficient| coefficient * sign),
|
||||
};
|
||||
|
||||
let band_start = band_start.value().unwrap_or(0.);
|
||||
let band_end = band_end.value().unwrap_or(1.);
|
||||
|
||||
// An outer arc between two finite limit points passes through infinity, beyond which its crossings belong past the band's far end
|
||||
let wrap = match (negative_arc, limit_values) {
|
||||
(false, [Some(first), Some(second)]) if (first - second).abs() > 0. => {
|
||||
let reference_x = (first + second) / 2.;
|
||||
let band_side = if band_start > reference_x { 1. } else { -1. };
|
||||
let t_direction = (band_end - band_start).signum();
|
||||
Some(Wrap {
|
||||
reference_x,
|
||||
band_side,
|
||||
t: band_side * t_direction * UNBOUNDED_T,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
Self::with_band(start, end, selection, wrap, band_start, band_end)
|
||||
}
|
||||
|
||||
fn with_band(start: AxisCircle, end: AxisCircle, selection: CrossingSelection, wrap: Option<Wrap>, band_start: f64, band_end: f64) -> Self {
|
||||
let width = band_end - band_start;
|
||||
let width = if width.abs() < 1e-12 { 1e-12_f64.copysign(width) } else { width };
|
||||
|
||||
Self {
|
||||
start,
|
||||
end,
|
||||
selection,
|
||||
wrap,
|
||||
t_scale: 1. / width,
|
||||
t_offset: -band_start / width,
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient's t at `point` in gradient space, by the same steps the renderer's shader takes.
|
||||
pub fn t(&self, point: DVec2) -> f64 {
|
||||
let start_value = self.start.value(point);
|
||||
let end_value = self.end.value(point);
|
||||
let scale = start_value.abs().max(end_value.abs());
|
||||
if scale == 0. {
|
||||
return 0.;
|
||||
}
|
||||
let (start_value, end_value) = (start_value / scale, end_value / scale);
|
||||
|
||||
// The pixel's contour is the member where the end contours' values keep this ratio, which crosses the gradient line at the
|
||||
// roots of this quadratic
|
||||
let a = end_value * self.start.a - start_value * self.end.a;
|
||||
let b = end_value * self.start.b - start_value * self.end.b;
|
||||
let c = end_value * self.start.c - start_value * self.end.c;
|
||||
let roots = solve_quadratic(a, b, c);
|
||||
|
||||
let crossing = match self.selection {
|
||||
CrossingSelection::SameSideAs { radical_x } => {
|
||||
// A pixel on the dividing line itself is on the line member, whose crossing is the finite root
|
||||
let side = |root: Homogeneous| (root.numerator - radical_x * root.denominator) * root.denominator * (point.x - radical_x);
|
||||
let (first, second) = (side(roots[0]), side(roots[1]));
|
||||
let first_wins = if first == second {
|
||||
roots[0].denominator.abs() >= roots[1].denominator.abs()
|
||||
} else {
|
||||
first > second
|
||||
};
|
||||
if first_wins { roots[0] } else { roots[1] }
|
||||
}
|
||||
CrossingSelection::OnArc { quadratic } => {
|
||||
if evaluate_homogeneous_quadratic(quadratic, roots[0]) <= evaluate_homogeneous_quadratic(quadratic, roots[1]) {
|
||||
roots[0]
|
||||
} else {
|
||||
roots[1]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(wrap) = self.wrap
|
||||
&& (crossing.numerator - wrap.reference_x * crossing.denominator) * crossing.denominator * wrap.band_side < 0.
|
||||
{
|
||||
return wrap.t;
|
||||
}
|
||||
|
||||
if crossing.denominator == 0. {
|
||||
let direction = crossing.numerator * self.t_scale;
|
||||
return if direction == 0. { 0. } else { direction.signum() * UNBOUNDED_T };
|
||||
}
|
||||
crossing.numerator / crossing.denominator * self.t_scale + self.t_offset
|
||||
}
|
||||
}
|
||||
|
||||
impl PencilParameters {
|
||||
/// The same parameters for Vello GPU's pencil gradient paint.
|
||||
pub fn to_vello(&self) -> vello_gpu::PencilGeometry {
|
||||
let circle = |circle: &AxisCircle| [circle.a as f32, circle.b as f32, circle.c as f32];
|
||||
|
||||
vello_gpu::PencilGeometry {
|
||||
start: circle(&self.start),
|
||||
end: circle(&self.end),
|
||||
selection: match self.selection {
|
||||
CrossingSelection::SameSideAs { radical_x } => vello_gpu::PencilSelection::SameSideAs { radical_x: radical_x as f32 },
|
||||
CrossingSelection::OnArc { quadratic } => vello_gpu::PencilSelection::OnArc {
|
||||
quadratic: quadratic.map(|coefficient| coefficient as f32),
|
||||
},
|
||||
},
|
||||
wrap: self.wrap.map(|wrap| vello_gpu::PencilWrap {
|
||||
reference_x: wrap.reference_x as f32,
|
||||
band_side: wrap.band_side as f32,
|
||||
t: wrap.t as f32,
|
||||
}),
|
||||
t_scale: self.t_scale as f32,
|
||||
t_offset: self.t_offset as f32,
|
||||
}
|
||||
}
|
||||
|
||||
/// The closest gradient SVG can express: a radial gradient from the start circle to the end circle when one nests inside
|
||||
/// the other, or else the linear gradient along the gradient line.
|
||||
pub fn svg_approximation(&self) -> SvgApproximation {
|
||||
let (Some(start), Some(end)) = (self.start.center_and_radius(), self.end.center_and_radius()) else {
|
||||
return SvgApproximation::Linear;
|
||||
};
|
||||
|
||||
let distance = (start.0 - end.0).abs();
|
||||
let nested = distance <= (start.1 - end.1).abs();
|
||||
if !nested {
|
||||
return SvgApproximation::Linear;
|
||||
}
|
||||
|
||||
SvgApproximation::Radial {
|
||||
start_center: start.0,
|
||||
start_radius: start.1,
|
||||
end_center: end.0,
|
||||
end_radius: end.1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient SVG can draw in place of a dialed one, in gradient space.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum SvgApproximation {
|
||||
Linear,
|
||||
/// From the start circle, as SVG's focal circle, out to the end circle, both centered on the gradient line.
|
||||
Radial {
|
||||
start_center: f64,
|
||||
start_radius: f64,
|
||||
end_center: f64,
|
||||
end_radius: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl AxisCircle {
|
||||
/// Where its center sits on the gradient line, and its radius, unless it's a line.
|
||||
fn center_and_radius(&self) -> Option<(f64, f64)> {
|
||||
if self.a.abs() < 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let center = -self.b / (2. * self.a);
|
||||
let radius = (center * center - self.c / self.a).max(0.).sqrt();
|
||||
Some((center, radius))
|
||||
}
|
||||
}
|
||||
|
||||
/// The weights of the two members that are points, the roots of the homogeneous quadratic form `start s² + 2·cross·s·e + end e²`.
|
||||
fn point_member_weights(start: f64, cross: f64, end: f64) -> [(f64, f64); 2] {
|
||||
let discriminant = (cross * cross - start * end).max(0.).sqrt();
|
||||
|
||||
if start.abs() < 1e-12 && end.abs() < 1e-12 {
|
||||
// Both end contours are points already
|
||||
[(1., 0.), (0., 1.)]
|
||||
} else if start.abs() >= end.abs() {
|
||||
[((-cross + discriminant) / start, 1.), ((-cross - discriminant) / start, 1.)]
|
||||
} else {
|
||||
[(1., (-cross + discriminant) / end), (1., (-cross - discriminant) / end)]
|
||||
}
|
||||
}
|
||||
|
||||
/// The quadratic in a homogeneous point that is negative between the two limit points and positive beyond them.
|
||||
fn arc_quadratic([first, second]: [Homogeneous; 2]) -> [f64; 3] {
|
||||
// (y·d₁ - n₁)(y·d₂ - n₂) with the denominators kept nonnegative, so its sign doesn't depend on how each point is scaled
|
||||
let orient = |point: Homogeneous| {
|
||||
if point.denominator < 0. {
|
||||
Homogeneous {
|
||||
numerator: -point.numerator,
|
||||
denominator: -point.denominator,
|
||||
}
|
||||
} else {
|
||||
point
|
||||
}
|
||||
};
|
||||
let (first, second) = (orient(first), orient(second));
|
||||
|
||||
[
|
||||
first.denominator * second.denominator,
|
||||
-(first.denominator * second.numerator + first.numerator * second.denominator),
|
||||
first.numerator * second.numerator,
|
||||
]
|
||||
}
|
||||
|
||||
fn evaluate_homogeneous_quadratic([a, b, c]: [f64; 3], point: Homogeneous) -> f64 {
|
||||
let Homogeneous { numerator, denominator } = point;
|
||||
a * numerator * numerator + b * numerator * denominator + c * denominator * denominator
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn assert_close(actual: f64, expected: f64, context: &str) {
|
||||
assert!((actual - expected).abs() < 1e-6, "{context}: expected {expected}, got {actual}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_dials_space_contours_by_radius() {
|
||||
let parameters = PencilParameters::new(RADIAL_DIALS[0], RADIAL_DIALS[1]);
|
||||
for radius in [0.1, 0.3, 0.75, 1., 1.5, 4.] {
|
||||
for angle in [0., 0.7, 2., 3.1, 4.5] {
|
||||
let point = DVec2::from_angle(angle) * radius;
|
||||
assert_close(parameters.t(point), radius, &format!("radius {radius} at angle {angle}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_dials_space_contours_by_distance_along_the_line() {
|
||||
let parameters = PencilParameters::new(LINEAR_DIALS[0], LINEAR_DIALS[1]);
|
||||
for point in [DVec2::new(0.25, 0.), DVec2::new(0.6, 3.), DVec2::new(-2., -7.), DVec2::new(5., 0.5)] {
|
||||
assert_close(parameters.t(point), point.x, &format!("point {point}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concentric_dials_space_contours_by_radius_between_the_ends() {
|
||||
// The donut: a hole of radius 1 centered 1 before the start, and an end circle of radius 2 around the same center
|
||||
let parameters = PencilParameters::new(-0.5, 0.5_f64.atan() / FRAC_PI_2);
|
||||
let center = DVec2::new(-1., 0.);
|
||||
for radius in [1., 1.25, 1.5, 2., 3.] {
|
||||
for angle in [0., 1., 2.5, 4.] {
|
||||
let point = center + DVec2::from_angle(angle) * radius;
|
||||
assert_close(parameters.t(point), radius - 1., &format!("radius {radius} at angle {angle}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_dials_space_contours_by_distance_ratio() {
|
||||
let parameters = PencilParameters::new(1., 1.);
|
||||
for point in [DVec2::new(0.5, 0.), DVec2::new(0.5, 2.), DVec2::new(0.2, 0.3), DVec2::new(3., -1.)] {
|
||||
// The contours are the circles of Apollonius, each crossing the line between the points at y / (1 - y) = ratio
|
||||
let ratio = point.length() / (point - DVec2::X).length();
|
||||
assert_close(parameters.t(point), ratio / (1. + ratio), &format!("point {point}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dials_near_a_preset_render_like_it() {
|
||||
let radial = PencilParameters::new(RADIAL_DIALS[0], RADIAL_DIALS[1]);
|
||||
let near_radial = PencilParameters::new(RADIAL_DIALS[0] - 1e-7, RADIAL_DIALS[1] + 1e-7);
|
||||
let linear = PencilParameters::new(LINEAR_DIALS[0], LINEAR_DIALS[1]);
|
||||
let near_linear = PencilParameters::new(LINEAR_DIALS[0] + 1e-7, LINEAR_DIALS[1] - 1e-7);
|
||||
|
||||
for point in [DVec2::new(0.3, 0.2), DVec2::new(-0.5, 0.4), DVec2::new(0.9, -0.1)] {
|
||||
assert!((radial.t(point) - near_radial.t(point)).abs() < 1e-4, "near radial at {point}");
|
||||
assert!((linear.t(point) - near_linear.t(point)).abs() < 1e-4, "near linear at {point}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focal_gradient_pads_everywhere_outside_its_end_circle() {
|
||||
// The start point sits inside the end circle, off its center
|
||||
let parameters = PencilParameters::new(1., 0.6);
|
||||
|
||||
assert_close(parameters.t(DVec2::X), 1., "end point");
|
||||
let inside = parameters.t(DVec2::new(0.5, 0.));
|
||||
assert!(inside > 0. && inside < 1., "inside: {inside}");
|
||||
for point in [DVec2::new(-5., 0.), DVec2::new(-0.5, 0.), DVec2::new(5., 0.), DVec2::new(0.3, 4.), DVec2::new(-40., 30.)] {
|
||||
let t = parameters.t(point);
|
||||
assert!(t > 1., "outside at {point}: {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_contours_fan_through_their_lens() {
|
||||
let parameters = PencilParameters::new(0.6, 0.6);
|
||||
assert!(matches!(parameters.selection, CrossingSelection::SameSideAs { .. }));
|
||||
|
||||
for x in [0., 0.1, 0.25, 0.5, 0.8, 1.] {
|
||||
assert_close(parameters.t(DVec2::new(x, 0.)), x, &format!("on the line at {x}"));
|
||||
}
|
||||
// Mirrored across the gradient line
|
||||
assert_close(parameters.t(DVec2::new(0.3, 0.2)), parameters.t(DVec2::new(0.3, -0.2)), "mirror");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_dial_pair_gives_a_number_everywhere() {
|
||||
for start_step in -10..=10 {
|
||||
for end_step in -10..=10 {
|
||||
let parameters = PencilParameters::new(start_step as f64 / 10., end_step as f64 / 10.);
|
||||
for x in -8..=8 {
|
||||
for y in -8..=8 {
|
||||
let point = DVec2::new(x as f64 * 0.37, y as f64 * 0.41);
|
||||
let t = parameters.t(point);
|
||||
assert!(!t.is_nan(), "dials ({start_step}, {end_step}) at {point}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod convert_usvg_path;
|
||||
pub mod dial_gradient;
|
||||
pub mod render_ext;
|
||||
mod renderer;
|
||||
pub mod to_peniko;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use crate::renderer::{
|
||||
ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_settings_from_item, spread_adjusted_samples, transform_is_invertible,
|
||||
GradientShape, ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_settings_from_item, spread_adjusted_samples,
|
||||
svg_gradient_definition, transform_is_invertible,
|
||||
};
|
||||
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::uuid::generate_uuid;
|
||||
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
|
||||
use core_types::{ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::vector_types::gradient::GradientForm;
|
||||
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use std::fmt::Write;
|
||||
use vector_types::Gradient;
|
||||
@@ -88,11 +88,11 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
|
||||
let item = item?;
|
||||
let stops = item.element()?;
|
||||
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
|
||||
let shape = GradientShape::of(item);
|
||||
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let settings = gradient_settings_from_item(item);
|
||||
|
||||
let mut samples = spread_adjusted_samples(stops, settings, gradient_form);
|
||||
let mut samples = spread_adjusted_samples(stops, settings, shape.reaches_before_start());
|
||||
|
||||
let paint_opacity = item.paint_opacity(for_mask);
|
||||
if paint_opacity < 1. {
|
||||
@@ -134,7 +134,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
|
||||
let document_transform = item_transform * local_gradient_transform;
|
||||
|
||||
let placement = gradient_placement(document_transform, gradient_form);
|
||||
let placement = gradient_placement(document_transform, shape);
|
||||
let gradient_transform = format_transform_matrix(element_transform_inverse * placement);
|
||||
let gradient_transform = if gradient_transform.is_empty() {
|
||||
String::new()
|
||||
@@ -149,23 +149,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
};
|
||||
|
||||
let gradient_id = generate_uuid();
|
||||
|
||||
match gradient_form {
|
||||
GradientForm::Linear => {
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<linearGradient id="{}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{gradient_spread}{gradient_transform}>{}</linearGradient>"#,
|
||||
gradient_id, stop
|
||||
);
|
||||
}
|
||||
GradientForm::Radial => {
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<radialGradient id="{}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"{gradient_spread}{gradient_transform}>{}</radialGradient>"#,
|
||||
gradient_id, stop
|
||||
);
|
||||
}
|
||||
}
|
||||
svg_defs.push_str(&svg_gradient_definition(shape, gradient_id, &format!("{gradient_spread}{gradient_transform}"), &stop));
|
||||
|
||||
Some(gradient_id)
|
||||
}
|
||||
@@ -285,10 +269,12 @@ impl RenderExt for Graphic {
|
||||
| Graphic::Vector(_)
|
||||
| Graphic::RasterCPU(_)
|
||||
| Graphic::RasterGPU(_)
|
||||
| Graphic::Generator(_)
|
||||
| Graphic::Text(_)
|
||||
| Graphic::VectorList(_)
|
||||
| Graphic::RasterCPUList(_)
|
||||
| Graphic::RasterGPUList(_)
|
||||
| Graphic::GeneratorList(_)
|
||||
| Graphic::GraphicList(_)
|
||||
| Graphic::GradientList(_)
|
||||
| Graphic::TextList(_)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,11 +1,13 @@
|
||||
use glam::{DMat2, UVec2};
|
||||
use glam::{DMat2, DVec2, UVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use graphic_types::raster_types::{CPU, Raster, Texture};
|
||||
use graphic_types::{Adjustment, Effects};
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use vello_gpu::peniko::{self, BlendMode, BrushRef, Fill};
|
||||
use vello_gpu::{Image, ImageSource, PaintType, TextureId, TextureRegion};
|
||||
use vello_gpu::peniko::{self, BlendMode, Brush, Fill};
|
||||
use vello_gpu::{Image, ImageSource, PaintType, PencilGradient, TextureId, TextureRegion};
|
||||
|
||||
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
|
||||
const SHAPE_TOLERANCE: f64 = 0.1;
|
||||
@@ -13,6 +15,16 @@ const SHAPE_TOLERANCE: f64 = 0.1;
|
||||
/// The texture size an effects group's area rounds up to a multiple of, so a group moving across renders keeps reusing the same pooled textures.
|
||||
const EFFECTS_SIZE_CLASS: u32 = 64;
|
||||
|
||||
/// The pixels across and down a generator's tile covers, besides the samples bordering it that let neighboring tiles overlap seamlessly.
|
||||
const GENERATOR_TILE_PIXELS: u32 = 256;
|
||||
|
||||
/// The samples bordering each side of a generator's tile, and how many of them its neighbor's drawing overlaps.
|
||||
const GENERATOR_TILE_BORDER: u32 = 2;
|
||||
const GENERATOR_TILE_OVERLAP: u32 = 1;
|
||||
|
||||
/// The most tiles one generator draws in a render, past which larger tiles render at a lower resolution, as for a view skewed far along one axis.
|
||||
const MAX_GENERATOR_TILES_PER_DRAW: f64 = 256.;
|
||||
|
||||
/// Builds a Vello GPU scene of a fixed size, recording the images it draws so the renderer can supply their textures at render time.
|
||||
pub struct VelloSceneBuilder<'a> {
|
||||
scene: vello_gpu::Scene,
|
||||
@@ -33,13 +45,65 @@ pub trait EffectsRenderer: Send {
|
||||
/// Whether the GPU can carry out effects, without which effects groups draw their content faded by their fill.
|
||||
fn renders_effects(&self) -> bool;
|
||||
|
||||
/// Renders the content `draw` draws, placed by `view`, into a texture of `size`, returning a straight-alpha texture of the same size with `effects` carried out on it.
|
||||
/// Renders the content `draw` draws, and each paint overlay's paint `draw_paint` draws by index, placed by `view` in textures of `size`, returning a straight-alpha texture of the same size with `effects` carried out on it.
|
||||
/// `lengths_to_pixels` maps the effects' lengths onto the texture's pixels, and `fill` fades the content but not the shadows and glows cast from it.
|
||||
fn render_effects(&mut self, size: UVec2, view: Affine, effects: &Effects, fill: f32, lengths_to_pixels: DMat2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Texture;
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_effects(
|
||||
&mut self,
|
||||
size: UVec2,
|
||||
view: Affine,
|
||||
effects: &Effects,
|
||||
fill: f32,
|
||||
lengths_to_pixels: DMat2,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) -> Texture;
|
||||
|
||||
/// A straight-alpha texture of the size of the CPU `raster`, with `adjustments` carried out on its pixels, kept for as long as they're drawn that way.
|
||||
/// `None` if they can't be carried out.
|
||||
fn adjust_raster(&mut self, raster: &Raster<CPU>, adjustments: &[Adjustment]) -> Option<Texture>;
|
||||
|
||||
/// Makes `tile` of `pattern` ready to be drawn as an image, rendering it unless it's been kept from an earlier render. `false` if it can't be rendered.
|
||||
fn prepare_generator_tile(&mut self, pattern: &GeneratorPattern, tile: GeneratorTile) -> bool;
|
||||
}
|
||||
|
||||
/// What a fill or stroke paints with.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SceneBrush {
|
||||
/// A solid color, gradient, or image.
|
||||
Peniko(Brush),
|
||||
/// A gradient whose contours are a pencil of circles, which only Vello GPU's fork can draw.
|
||||
PencilGradient(PencilGradient),
|
||||
}
|
||||
|
||||
impl From<Brush> for SceneBrush {
|
||||
fn from(brush: Brush) -> Self {
|
||||
Self::Peniko(brush)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Brush> for SceneBrush {
|
||||
fn from(brush: &Brush) -> Self {
|
||||
Self::Peniko(brush.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<peniko::Color> for SceneBrush {
|
||||
fn from(color: peniko::Color) -> Self {
|
||||
Self::Peniko(Brush::Solid(color))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&peniko::Gradient> for SceneBrush {
|
||||
fn from(gradient: &peniko::Gradient) -> Self {
|
||||
Self::Peniko(Brush::Gradient(gradient.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PencilGradient> for SceneBrush {
|
||||
fn from(gradient: PencilGradient) -> Self {
|
||||
Self::PencilGradient(gradient)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels behind an image the scene draws.
|
||||
@@ -51,6 +115,8 @@ pub enum SceneImage {
|
||||
Raster(Raster<CPU>),
|
||||
/// Straight-alpha pixels in a GPU texture, whose copy for sampling gets mipmaps if it's drawn `minified`.
|
||||
Texture { texture: Texture, minified: bool },
|
||||
/// One tile of a generator's pattern, which the renderer made and kept when it was drawn.
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
|
||||
@@ -58,6 +124,36 @@ enum ImageKey {
|
||||
Blob(u64),
|
||||
Raster(u64),
|
||||
Texture(Texture, bool),
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
/// One tile of a generator's pattern, from a grid in the pattern's space whose tiles span a power of two of units.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub struct GeneratorTile {
|
||||
/// Identifies the pattern by the hash of its settings.
|
||||
pub pattern: u64,
|
||||
/// The tiles span `2^-level` units, so a tile is about the same number of pixels in view at any zoom.
|
||||
pub level: i32,
|
||||
pub column: i64,
|
||||
pub row: i64,
|
||||
}
|
||||
|
||||
impl GeneratorTile {
|
||||
/// The samples across and down the tile and its border.
|
||||
pub const SAMPLES: u32 = GENERATOR_TILE_PIXELS + 2 * GENERATOR_TILE_BORDER;
|
||||
|
||||
/// The area of the pattern's space the tile and its border's samples cover, from its minimum to its maximum corner.
|
||||
pub fn area(&self) -> [DVec2; 2] {
|
||||
let (corner, texel) = self.corner_and_texel();
|
||||
[corner, corner + DVec2::splat(Self::SAMPLES as f64 * texel)]
|
||||
}
|
||||
|
||||
/// The corner of the tile's samples, including its border, in the pattern's space, and the span of one sample.
|
||||
fn corner_and_texel(&self) -> (DVec2, f64) {
|
||||
let span = 2_f64.powi(-self.level);
|
||||
let texel = span / GENERATOR_TILE_PIXELS as f64;
|
||||
(DVec2::new(self.column as f64, self.row as f64) * span - GENERATOR_TILE_BORDER as f64 * texel, texel)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -139,35 +235,32 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
}
|
||||
|
||||
/// Fills a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
||||
pub fn fill<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
pub fn fill(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
self.fill_path(fill_rule, transform, brush, brush_transform, &shape.to_path(SHAPE_TOLERANCE));
|
||||
}
|
||||
|
||||
/// Like [`Self::fill`] for a path, which it draws without copying.
|
||||
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
pub fn fill_path(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, path: &BezPath) {
|
||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
self.scene.fill_path(&finite_path(path));
|
||||
}
|
||||
|
||||
/// Strokes a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
||||
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
pub fn stroke(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_stroke(stroke.clone());
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
self.scene.stroke_path(&finite_path(&shape.to_path(SHAPE_TOLERANCE)));
|
||||
}
|
||||
|
||||
/// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content.
|
||||
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
pub fn fill_viewport(&mut self, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>) {
|
||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
||||
self.scene.set_transform(Affine::IDENTITY);
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(self.view * brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
self.scene.fill_rect(&Rect::new(0., 0., self.width() as f64, self.height() as f64));
|
||||
}
|
||||
@@ -241,9 +334,79 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self.effects_renderer.as_deref_mut().filter(|renderer| renderer.renders_effects())?.adjust_raster(raster, adjustments)
|
||||
}
|
||||
|
||||
/// Draws the content `draw` draws with `effects` carried out on it, given the area it covers in the space of the drawn content, or `None` if unbounded.
|
||||
/// `fill` fades the content but not the shadows and glows cast from it. Rendering a split scene calls `draw` again for each part.
|
||||
pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option<Rect>, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) {
|
||||
/// Draws a generator's pattern, whose own space `transform` places, across the part of the scene it covers as tiles the renderer makes the first time each is seen.
|
||||
/// The tiles span a power of two of the pattern's units, so a pan reuses them, as does a zoom until the scale nears the next power.
|
||||
pub fn draw_generator(&mut self, pattern: &GeneratorPattern, transform: Affine) {
|
||||
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let local_to_device = self.view * transform;
|
||||
let [a, b, c, d, _, _] = local_to_device.as_coeffs();
|
||||
let determinant = a * d - b * c;
|
||||
if !determinant.is_normal() {
|
||||
return;
|
||||
}
|
||||
|
||||
// The part of the pattern's space in view
|
||||
let viewport = Rect::new(0., 0., self.width() as f64, self.height() as f64);
|
||||
let visible = local_to_device.inverse().transform_rect_bbox(viewport);
|
||||
if visible.width() <= 0. || visible.height() <= 0. {
|
||||
return;
|
||||
}
|
||||
|
||||
// The tile size nearest to a tile's pixels in view, grown if the view would otherwise need too many
|
||||
let pixels_per_unit = determinant.abs().sqrt();
|
||||
let tile_span = |level: i32| 2_f64.powi(-level);
|
||||
let tile_range = |start: f64, end: f64, span: f64| (start / span).floor() as i64..(end / span).ceil() as i64;
|
||||
let tile_count = |level: i32| {
|
||||
let span = tile_span(level);
|
||||
(tile_range(visible.x0, visible.x1, span).count() * tile_range(visible.y0, visible.y1, span).count()) as f64
|
||||
};
|
||||
let mut level = (pixels_per_unit / GENERATOR_TILE_PIXELS as f64).log2().round() as i32;
|
||||
while tile_count(level) > MAX_GENERATOR_TILES_PER_DRAW {
|
||||
level -= 1;
|
||||
}
|
||||
let span = tile_span(level);
|
||||
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
pattern.cache_hash(&mut hasher);
|
||||
let pattern_hash = std::hash::Hasher::finish(&hasher);
|
||||
|
||||
let (border, overlap) = (GENERATOR_TILE_BORDER as f64, GENERATOR_TILE_OVERLAP as f64);
|
||||
for row in tile_range(visible.y0, visible.y1, span) {
|
||||
for column in tile_range(visible.x0, visible.x1, span) {
|
||||
let tile = GeneratorTile {
|
||||
pattern: pattern_hash,
|
||||
level,
|
||||
column,
|
||||
row,
|
||||
};
|
||||
if !self.effects_renderer.as_deref_mut().is_some_and(|renderer| renderer.prepare_generator_tile(pattern, tile)) {
|
||||
continue;
|
||||
}
|
||||
let id = *self.image_ids.entry(ImageKey::GeneratorTile(tile)).or_insert_with(|| {
|
||||
self.images.push(SceneImage::GeneratorTile(tile));
|
||||
TextureId(self.images.len() as u64 - 1)
|
||||
});
|
||||
|
||||
// Drawn across the tile and part of its border, overlapping its neighbors' identical samples so no seam shows between them
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
self.scene.set_transform(local_to_device * Affine::translate((corner.x, corner.y)) * Affine::scale(texel));
|
||||
self.scene.set_paint(PaintType::Image(Image {
|
||||
image: ImageSource::external_texture(id, TextureRegion::Full, true),
|
||||
sampler: peniko::ImageSampler::new(),
|
||||
}));
|
||||
self.scene.set_paint_transform(Affine::IDENTITY);
|
||||
let (start, end) = (border - overlap, border + GENERATOR_TILE_PIXELS as f64 + overlap);
|
||||
self.scene.fill_rect(&Rect::new(start, start, end, end));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the content `draw` draws with `effects` carried out on it, within `bounds` in the space of the drawn content (or everywhere for `None`), drawing again for each part of a split render.
|
||||
/// `draw_paint` draws each paint overlay's paint by its index among them, and `fill` fades the content but not the shadows and glows cast from it.
|
||||
pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option<Rect>, draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder)) {
|
||||
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) {
|
||||
self.push_viewport_layer(peniko::Mix::Normal, fill);
|
||||
draw(self);
|
||||
@@ -273,7 +436,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
let content_view = Affine::scale(resolution) * Affine::translate(-origin) * self.view;
|
||||
let Some(renderer) = self.effects_renderer.as_deref_mut() else { return };
|
||||
let result = renderer.render_effects(size, content_view, effects, fill, lengths_to_device * resolution, draw);
|
||||
let result = renderer.render_effects(size, content_view, effects, fill, lengths_to_device * resolution, draw_paint, draw);
|
||||
|
||||
// Draw the result where the content was
|
||||
self.images.push(SceneImage::Texture { texture: result, minified: false });
|
||||
@@ -294,22 +457,31 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self.scene.fill_rect(&Rect::new(0., 0., width as f64, height as f64));
|
||||
}
|
||||
|
||||
/// The Vello GPU paint for a brush, plus the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
|
||||
fn paint(&mut self, brush: BrushRef<'_>) -> Option<(PaintType, Affine)> {
|
||||
match brush {
|
||||
BrushRef::Solid(color) => Some((PaintType::Solid(color), Affine::IDENTITY)),
|
||||
BrushRef::Gradient(gradient) => Some((PaintType::Gradient(gradient.clone()), Affine::IDENTITY)),
|
||||
BrushRef::Image(image) => {
|
||||
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image.clone()))?;
|
||||
Some((
|
||||
PaintType::Image(Image {
|
||||
image: source,
|
||||
sampler: image.sampler,
|
||||
}),
|
||||
texture_to_image,
|
||||
))
|
||||
/// Paints with `brush`, returning the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
|
||||
fn set_paint(&mut self, brush: SceneBrush) -> Option<Affine> {
|
||||
let brush = match brush {
|
||||
SceneBrush::Peniko(brush) => brush,
|
||||
SceneBrush::PencilGradient(gradient) => {
|
||||
self.scene.set_pencil_gradient_paint(gradient);
|
||||
return Some(Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let (paint, paint_to_brush) = match brush {
|
||||
Brush::Solid(color) => (PaintType::Solid(color), Affine::IDENTITY),
|
||||
Brush::Gradient(gradient) => (PaintType::Gradient(gradient), Affine::IDENTITY),
|
||||
Brush::Image(image) => {
|
||||
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image))?;
|
||||
let paint = PaintType::Image(Image {
|
||||
image: source,
|
||||
sampler: image.sampler,
|
||||
});
|
||||
(paint, texture_to_image)
|
||||
}
|
||||
};
|
||||
self.scene.set_paint(paint);
|
||||
|
||||
Some(paint_to_brush)
|
||||
}
|
||||
|
||||
/// The external texture standing for an image, with the transform from its texture's pixels onto the image's own pixels and its texture's size.
|
||||
@@ -318,6 +490,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
SceneImage::Pixels(data) => (data.width, data.height),
|
||||
SceneImage::Raster(raster) => (raster.width, raster.height),
|
||||
SceneImage::Texture { texture, .. } => (texture.width(), texture.height()),
|
||||
SceneImage::GeneratorTile(_) => (GeneratorTile::SAMPLES, GeneratorTile::SAMPLES),
|
||||
};
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
@@ -327,6 +500,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
|
||||
SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::Texture { texture, minified } => ImageKey::Texture(texture.clone(), *minified),
|
||||
SceneImage::GeneratorTile(tile) => ImageKey::GeneratorTile(*tile),
|
||||
};
|
||||
let id = *self.image_ids.entry(key).or_insert_with(|| {
|
||||
self.images.push(image);
|
||||
|
||||
@@ -16,6 +16,26 @@ pub enum GradientForm {
|
||||
Radial,
|
||||
}
|
||||
|
||||
/// The curvature dials of the linear form: both ends are lines.
|
||||
pub const LINEAR_DIALS: [f64; 2] = [0., 0.];
|
||||
/// The curvature dials of the radial form: the start is a point at the center, and the end is the circle around it through the end point.
|
||||
pub const RADIAL_DIALS: [f64; 2] = [1., 0.5];
|
||||
|
||||
impl GradientForm {
|
||||
/// The curvature dials of the start and end contours that make this form.
|
||||
pub fn dials(self) -> [f64; 2] {
|
||||
match self {
|
||||
Self::Linear => LINEAR_DIALS,
|
||||
Self::Radial => RADIAL_DIALS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A curvature dial wrapped into the range ending at 1, since -1 and 1 are both the end's own point, or `preset` if it isn't finite.
|
||||
pub fn wrapped_dial(dial: f64, preset: f64) -> f64 {
|
||||
if dial.is_finite() { 1. - (1. - dial).rem_euclid(2.) } else { preset }
|
||||
}
|
||||
|
||||
/// A gradient's stops: a list of colors (linear, unassociated alpha) whose optional `position` and `midpoint`
|
||||
/// attributes place each stop along the 0 to 1 range. Stops lacking the `position` attribute distribute evenly,
|
||||
/// and stops lacking the `midpoint` attribute interpolate linearly (`0.5`).
|
||||
|
||||
@@ -5,15 +5,20 @@ use crate::WgpuPipelineCache;
|
||||
use crate::raster_kernel::{MAX_FRAME_SIDE, adjust_raster, blur_raster, run_raster_kernel};
|
||||
use crate::shader_runtime::raster_kernel_runtime::RasterKernelInput;
|
||||
use core_types::list::{ATTR_EFFECTS, Item};
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::ops::Convert;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color, NodeError};
|
||||
use glam::{DAffine2, DMat2, DVec2, UVec2};
|
||||
use graphic_types::effects::{bevel_light, bevel_smoothing, outline_extents};
|
||||
use graphic_types::{Adjustment, BevelDirection, EffectOperation, Effects, GlowSource};
|
||||
use graphic_types::effects::{bevel_light, bevel_smoothing, fitted_paint, outline_extents};
|
||||
use graphic_types::{Adjustment, BevelDirection, EffectOperation, Effects, GlowSource, Graphic};
|
||||
use raster_kernels::RasterKernel;
|
||||
use raster_kernels::adjustments::{leading_adjustments, preserves_alpha};
|
||||
use raster_kernels::blur::BlurSpace;
|
||||
use raster_kernels::effects::*;
|
||||
use raster_types::{GPU, Raster, Storage};
|
||||
use raster_types::{CPU, GPU, Raster, Storage};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
/// Blurs and spreads shorter than this, in pixels, leave no visible trace.
|
||||
pub const NEGLIGIBLE_LENGTH: f64 = 0.01;
|
||||
@@ -41,6 +46,16 @@ pub fn evaluate_raster_effects(item: Item<Raster<GPU>>, pipeline: &WgpuPipelineC
|
||||
Ok(item)
|
||||
}
|
||||
|
||||
/// The CPU raster uploaded with its effects carried out into its pixels, for the Eager node and the input adapter that feeds a CPU raster to a node taking only GPU rasters.
|
||||
pub fn upload_raster(image: Item<Raster<CPU>>, pipeline: &WgpuPipelineCache) -> Result<Item<Raster<GPU>>, NodeError> {
|
||||
let executor = pipeline.executor().cloned().ok_or_else(|| NodeError::new("A GPU is required to upload a raster"))?;
|
||||
|
||||
let (image, attributes) = image.into_parts();
|
||||
let uploaded: Raster<GPU> = image.convert(Footprint::DEFAULT, executor);
|
||||
|
||||
evaluate_raster_effects(Item::from_parts(uploaded, attributes), pipeline)
|
||||
}
|
||||
|
||||
/// The larger raster of the effects carried out on `raster`, an item's whose `transform` is kept, with the coverage placing that larger raster where the original's pixels were.
|
||||
/// `None` when there's nothing to carry out, or the raster is empty or its placement can't be inverted.
|
||||
fn evaluate(raster: &Raster<GPU>, transform: DAffine2, operations: &[EffectOperation], fill: f32, pipeline: &WgpuPipelineCache) -> Result<Option<Raster<GPU>>, NodeError> {
|
||||
@@ -78,9 +93,24 @@ fn evaluate(raster: &Raster<GPU>, transform: DAffine2, operations: &[EffectOpera
|
||||
margin = margin.min(((DVec2::splat(MAX_FRAME_SIDE as f64) - size.as_dvec2()) / 2.).max(DVec2::ZERO).floor());
|
||||
let grown_size = grown(margin).as_uvec2();
|
||||
|
||||
// A paint is placed in the space the raster's item is placed in, or fitted to the raster's extent there, and rendered over the grown raster's pixels
|
||||
let parent_to_pixels = DAffine2::from_translation(margin) * DAffine2::from_scale(size.as_dvec2()) * placement.inverse();
|
||||
let bounds = (placement * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box();
|
||||
let mut render_paint = |_: usize, paint: &Graphic| {
|
||||
let executor = pipeline.executor().ok_or_else(|| NodeError::new("A GPU is required to render a paint"))?;
|
||||
let fitted = fitted_paint(paint, bounds);
|
||||
let paint = fitted.as_ref().unwrap_or(paint);
|
||||
let render_params = RenderParams::default().for_pattern();
|
||||
let mut draw = |scene: &mut VelloSceneBuilder| paint.render_to_vello(scene, DAffine2::IDENTITY, &render_params);
|
||||
let texture = executor
|
||||
.render_vello_raster(grown_size, parent_to_pixels, &mut draw)
|
||||
.map_err(|error| NodeError::new(error.to_string()))?;
|
||||
Ok(Raster::<GPU>::new_gpu(texture))
|
||||
};
|
||||
|
||||
let mut pass = EffectsPass::new(raster, grown_size, DAffine2::from_translation(-margin), fill, lengths_to_pixels, pipeline)?;
|
||||
for operation in operations {
|
||||
pass.apply(operation)?;
|
||||
pass.apply(operation, &mut render_paint)?;
|
||||
}
|
||||
let result = pass.finish()?;
|
||||
|
||||
@@ -89,17 +119,18 @@ fn evaluate(raster: &Raster<GPU>, transform: DAffine2, operations: &[EffectOpera
|
||||
}
|
||||
|
||||
/// Carries out `operations` in order on `content`, a straight-alpha raster in the pixels `lengths_to_pixels` maps the effects' lengths onto, into a raster of its size.
|
||||
/// `fill` fades the content but not the shadows and glows cast from it.
|
||||
/// `fill` fades the content but not the shadows and glows cast from it, and `render_paint` renders each paint overlay's paint, by its index among them, over the same pixels.
|
||||
pub fn apply_effects(
|
||||
content: &Raster<GPU>,
|
||||
operations: impl IntoIterator<Item = EffectOperation>,
|
||||
fill: f32,
|
||||
lengths_to_pixels: DMat2,
|
||||
render_paint: &mut dyn FnMut(usize, &Graphic) -> Result<Raster<GPU>, NodeError>,
|
||||
pipeline: &WgpuPipelineCache,
|
||||
) -> Result<Raster<GPU>, NodeError> {
|
||||
let mut pass = EffectsPass::new(content, content.size(), DAffine2::IDENTITY, fill, lengths_to_pixels, pipeline)?;
|
||||
for operation in operations {
|
||||
pass.apply(&operation)?;
|
||||
pass.apply(&operation, render_paint)?;
|
||||
}
|
||||
Ok(pass.finish()?.with_coverage(content.coverage()))
|
||||
}
|
||||
@@ -115,6 +146,8 @@ pub struct EffectsPass<'a> {
|
||||
filled: Option<Raster<GPU>>,
|
||||
/// The shadows and glows stacked beneath the content.
|
||||
beneath: Option<Raster<GPU>>,
|
||||
/// How many paint overlays have been carried out.
|
||||
paint_overlays: usize,
|
||||
}
|
||||
|
||||
impl<'a> EffectsPass<'a> {
|
||||
@@ -131,11 +164,12 @@ impl<'a> EffectsPass<'a> {
|
||||
full,
|
||||
filled,
|
||||
beneath: None,
|
||||
paint_overlays: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Carries out the next effect.
|
||||
pub fn apply(&mut self, operation: &EffectOperation) -> Result<(), NodeError> {
|
||||
/// Carries out the next effect, with `render_paint` rendering a paint overlay's paint, by its index among them, into a straight-alpha raster over the images' pixels.
|
||||
pub fn apply(&mut self, operation: &EffectOperation, render_paint: &mut dyn FnMut(usize, &Graphic) -> Result<Raster<GPU>, NodeError>) -> Result<(), NodeError> {
|
||||
let lengths_to_pixels = self.lengths_to_pixels;
|
||||
let length_scale = lengths_to_pixels.determinant().abs().sqrt();
|
||||
|
||||
@@ -244,6 +278,19 @@ impl<'a> EffectsPass<'a> {
|
||||
self.shade_within(&coverage, color)?;
|
||||
}
|
||||
}
|
||||
EffectOperation::PaintOverlay { ref paint, blend_mode, opacity } => {
|
||||
let paint = render_paint(self.paint_overlays, paint)?;
|
||||
self.paint_overlays += 1;
|
||||
|
||||
let overlay = PaintOverlay {
|
||||
blend_mode,
|
||||
opacity: (opacity / 100.) as f32,
|
||||
};
|
||||
self.full = self.run(&overlay, &[&self.full, &paint])?;
|
||||
if let Some(filled) = &self.filled {
|
||||
self.filled = Some(self.run(&overlay, &[filled, &paint])?);
|
||||
}
|
||||
}
|
||||
EffectOperation::Adjustment(ref adjustment) => {
|
||||
self.full = self.adjust_image(&self.full, adjustment)?;
|
||||
if let Some(filled) = &self.filled {
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
use crate::WgpuPipelineCache;
|
||||
use crate::raster_effects::apply_effects;
|
||||
use crate::raster_kernel::adjust_raster;
|
||||
use crate::raster_kernel::{adjust_raster, render_generator};
|
||||
use core_types::NodeError;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::ops::Convert;
|
||||
use core_types::transform::Footprint;
|
||||
use glam::{DMat2, UVec2};
|
||||
use graphic_types::{Adjustment, Effects};
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use graphic_types::{Adjustment, Effects, Graphic};
|
||||
use raster_types::{CPU, GPU, Raster, Texture, WeakCPU};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use vello_gpu::kurbo::Affine;
|
||||
@@ -25,6 +26,9 @@ const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
|
||||
/// How many renders a GPU texture's premultiplied copy survives without being drawn before it is freed.
|
||||
const UNUSED_IMAGE_RENDER_LIMIT: u64 = 60;
|
||||
|
||||
/// The most tiles of generators kept between renders, past which the least recently drawn are freed.
|
||||
const MAX_CACHED_GENERATOR_TILES: usize = 256;
|
||||
|
||||
/// How many times a render with too much content for Vello GPU is halved, reaching areas 1/4096 the size of the original.
|
||||
const MAX_SPLIT_DEPTH: u32 = 12;
|
||||
|
||||
@@ -305,14 +309,31 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
self.kernels.executor().is_some()
|
||||
}
|
||||
|
||||
fn render_effects(&mut self, size: UVec2, view: Affine, effects: &Effects, fill: f32, lengths_to_pixels: DMat2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Texture {
|
||||
fn render_effects(
|
||||
&mut self,
|
||||
size: UVec2,
|
||||
view: Affine,
|
||||
effects: &Effects,
|
||||
fill: f32,
|
||||
lengths_to_pixels: DMat2,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) -> Texture {
|
||||
// Rendered into a raster of the content, which the effects are carried out on with the same kernels as a raster's own effects
|
||||
let executor = self.kernels.executor().expect("effects are only rendered with a GPU");
|
||||
let kernels = self.kernels;
|
||||
let executor = kernels.executor().expect("effects are only rendered with a GPU");
|
||||
let content = executor.request_texture_with_format(size, executor.raster_format());
|
||||
self.render_area(draw, view, size, &content);
|
||||
let content = Raster::<GPU>::new_gpu(content);
|
||||
|
||||
match apply_effects(&content, effects.operations(), fill, lengths_to_pixels, self.kernels) {
|
||||
// The paint overlays' paints, each rendered over the same pixels as the content
|
||||
let mut render_paint = |index: usize, _: &Graphic| {
|
||||
let paint = executor.request_texture_with_format(size, executor.raster_format());
|
||||
self.render_area(&mut |scene| draw_paint(index, scene), view, size, &paint);
|
||||
Ok(Raster::<GPU>::new_gpu(paint))
|
||||
};
|
||||
|
||||
match apply_effects(&content, effects.operations(), fill, lengths_to_pixels, &mut render_paint, kernels) {
|
||||
Ok(result) => result
|
||||
.texture()
|
||||
.cloned()
|
||||
@@ -334,6 +355,59 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_generator_tile(&mut self, pattern: &GeneratorPattern, tile: GeneratorTile) -> bool {
|
||||
let key = ImageKey::GeneratorTile(tile);
|
||||
let render_count = self.canvas.images.render_count;
|
||||
if let Some(image_texture) = self.canvas.images.textures.get_mut(&key) {
|
||||
image_texture.last_used = render_count;
|
||||
return true;
|
||||
}
|
||||
|
||||
let size = UVec2::splat(GeneratorTile::SAMPLES);
|
||||
let rendered = render_generator(pattern, tile.area(), size, self.kernels);
|
||||
let source = match rendered.as_ref().map(|raster| raster.texture()) {
|
||||
Ok(Some(source)) => source,
|
||||
Ok(None) => return false,
|
||||
Err(error) => {
|
||||
log::error!("Failed to render a generator's tile: {error}");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Unlike a raster's texture, which the texture cache may hand back with new contents, the tile's pixels stay as they are, so its copy for sampling is made once
|
||||
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("vello_gpu_generator_tile"),
|
||||
});
|
||||
let texture = premultiplied_image_texture(self.device, source, true);
|
||||
self.renderer.alpha_conversion.premultiply_with_mipmaps(self.device, &mut encoder, source, &texture);
|
||||
self.queue.lock().submit([encoder.finish()]);
|
||||
|
||||
self.canvas.images.textures.insert(
|
||||
key,
|
||||
ImageTexture {
|
||||
texture,
|
||||
last_used: render_count,
|
||||
raster: None,
|
||||
},
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// A texture to hold the premultiplied copy of `source` that Vello GPU samples, with mipmaps if it's drawn `minified`.
|
||||
fn premultiplied_image_texture(device: &wgpu::Device, source: &wgpu::Texture, minified: bool) -> wgpu::Texture {
|
||||
let level_count = if minified { source.width().max(source.height()).ilog2() + 1 } else { 1 };
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_premultiplied_image"),
|
||||
size: source.size(),
|
||||
mip_level_count: level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
|
||||
/// Leaves `target` transparent.
|
||||
@@ -343,12 +417,13 @@ fn clear(device: &wgpu::Device, queue: &Queue, target: &wgpu::Texture) {
|
||||
queue.submit([encoder.finish()]);
|
||||
}
|
||||
|
||||
/// Identifies the pixels behind an image texture: a blob of CPU pixels, or a GPU texture.
|
||||
/// Identifies the pixels behind an image texture: a blob of CPU pixels, a GPU texture, or a tile of a generator's pattern.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
enum ImageKey {
|
||||
Blob(u64),
|
||||
Raster(u64),
|
||||
Texture(wgpu::Texture, bool),
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
/// A premultiplied copy of an image's pixels that Vello GPU samples as an external texture.
|
||||
@@ -382,6 +457,7 @@ impl ImageTextures {
|
||||
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
|
||||
SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::Texture { texture, minified } => ImageKey::Texture((**texture).clone(), *minified),
|
||||
SceneImage::GeneratorTile(tile) => ImageKey::GeneratorTile(*tile),
|
||||
};
|
||||
|
||||
if !self.textures.contains_key(&key) {
|
||||
@@ -398,23 +474,13 @@ impl ImageTextures {
|
||||
let (pixels, width, height) = raster.to_flat_u8();
|
||||
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
SceneImage::Texture { texture, minified } => {
|
||||
let level_count = if *minified { texture.width().max(texture.height()).ilog2() + 1 } else { 1 };
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_premultiplied_image"),
|
||||
size: texture.size(),
|
||||
mip_level_count: level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
SceneImage::Texture { texture, minified } => premultiplied_image_texture(device, texture, *minified),
|
||||
// Kept since it was drawn, so there's nothing to supply if it couldn't be made
|
||||
SceneImage::GeneratorTile(_) => return None,
|
||||
};
|
||||
let raster = match image {
|
||||
SceneImage::Raster(raster) => Some(raster.downgrade()),
|
||||
SceneImage::Pixels(_) | SceneImage::Texture { .. } => None,
|
||||
SceneImage::Pixels(_) | SceneImage::Texture { .. } | SceneImage::GeneratorTile(_) => None,
|
||||
};
|
||||
self.textures.insert(key.clone(), ImageTexture { texture, last_used: 0, raster });
|
||||
}
|
||||
@@ -424,22 +490,7 @@ impl ImageTextures {
|
||||
let view = image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
if let SceneImage::Texture { texture: source, .. } = image {
|
||||
let level_view = |level: u32| {
|
||||
image_texture.texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
base_mip_level: level,
|
||||
mip_level_count: Some(1),
|
||||
..Default::default()
|
||||
})
|
||||
};
|
||||
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let loads_linear_light = source.format().is_srgb() || matches!(source.format(), crate::RASTER_FORMAT | crate::FALLBACK_RASTER_FORMAT);
|
||||
alpha_conversion.premultiply(device, encoder, &source_view, loads_linear_light, &level_view(0));
|
||||
|
||||
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
|
||||
for level in 1..image_texture.texture.mip_level_count() {
|
||||
alpha_conversion.halve(device, encoder, &level_view(level - 1), &level_view(level));
|
||||
}
|
||||
alpha_conversion.premultiply_with_mipmaps(device, encoder, source, &image_texture.texture);
|
||||
}
|
||||
|
||||
Some(view)
|
||||
@@ -453,9 +504,21 @@ impl ImageTextures {
|
||||
// CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return
|
||||
ImageKey::Blob(_) => unused_renders == 0,
|
||||
ImageKey::Raster(_) => unused_renders == 0 || (unused_renders < UNUSED_IMAGE_RENDER_LIMIT && image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive)),
|
||||
ImageKey::Texture(..) => unused_renders < UNUSED_IMAGE_RENDER_LIMIT,
|
||||
ImageKey::Texture(..) | ImageKey::GeneratorTile(_) => unused_renders < UNUSED_IMAGE_RENDER_LIMIT,
|
||||
}
|
||||
});
|
||||
|
||||
// Panning and zooming across a generator leaves tiles behind faster than they go unused for long, so the least recent beyond a limit are freed too
|
||||
let mut tile_ages: Vec<u64> = (self.textures.iter())
|
||||
.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_)))
|
||||
.map(|(_, image_texture)| image_texture.last_used)
|
||||
.collect();
|
||||
if tile_ages.len() > MAX_CACHED_GENERATOR_TILES {
|
||||
let excess = tile_ages.len() - MAX_CACHED_GENERATOR_TILES;
|
||||
let (_, &mut oldest_kept, _) = tile_ages.select_nth_unstable(excess);
|
||||
self.textures
|
||||
.retain(|key, image_texture| !matches!(key, ImageKey::GeneratorTile(_)) || image_texture.last_used >= oldest_kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -820,6 +883,26 @@ impl AlphaConversion {
|
||||
self.run(device, encoder, &self.premultiply_pipeline, parameters, source, target);
|
||||
}
|
||||
|
||||
/// Fills `target` and each of its mipmap levels with the premultiplied pixels of the straight-alpha `source`.
|
||||
fn premultiply_with_mipmaps(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: &wgpu::Texture, target: &wgpu::Texture) {
|
||||
let level_view = |level: u32| {
|
||||
target.create_view(&wgpu::TextureViewDescriptor {
|
||||
base_mip_level: level,
|
||||
mip_level_count: Some(1),
|
||||
..Default::default()
|
||||
})
|
||||
};
|
||||
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let loads_linear_light = source.format().is_srgb() || matches!(source.format(), crate::RASTER_FORMAT | crate::FALLBACK_RASTER_FORMAT);
|
||||
self.premultiply(device, encoder, &source_view, loads_linear_light, &level_view(0));
|
||||
|
||||
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
|
||||
for level in 1..target.mip_level_count() {
|
||||
self.halve(device, encoder, &level_view(level - 1), &level_view(level));
|
||||
}
|
||||
}
|
||||
|
||||
fn halve(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: &wgpu::TextureView, target: &wgpu::TextureView) {
|
||||
self.run(device, encoder, &self.halve_pipeline, &self.linear_source_parameters, source, target);
|
||||
}
|
||||
|
||||
@@ -274,13 +274,65 @@ fn degenerate_strokes_render() {
|
||||
let Some(_) = render(size, draw) else { return };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dial_gradients_match_their_cpu_evaluation() {
|
||||
use rendering::dial_gradient::PencilParameters;
|
||||
|
||||
let size = UVec2::new(200, 200);
|
||||
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100)
|
||||
let gradient_to_pixels = Affine::new([50., 0., 0., 50., 60., 100.]);
|
||||
|
||||
for dials in [(1., 0.6), (0.6, 0.6), (-0.5, 0.2952), (1., 1.), (0.5, 0.25), (0.3, -0.3)] {
|
||||
let parameters = PencilParameters::new(dials.0, dials.1);
|
||||
let ramp = peniko::Gradient::new_linear((0., 0.), (1., 0.)).with_stops([Color::from_rgb8(0, 0, 0), Color::from_rgb8(255, 255, 255)]);
|
||||
let gradient = vello_gpu::PencilGradient {
|
||||
ramp,
|
||||
geometry: parameters.to_vello(),
|
||||
};
|
||||
|
||||
let draw = |scene: &mut VelloSceneBuilder| scene.fill_viewport(gradient.clone(), Some(gradient_to_pixels));
|
||||
|
||||
let Some(pixels) = render(size, draw) else { return };
|
||||
|
||||
let mut worst = 0_i32;
|
||||
for y in (5..195).step_by(10) {
|
||||
for x in (5..195).step_by(10) {
|
||||
let point = gradient_to_pixels.inverse() * vello_gpu::kurbo::Point::new(x as f64 + 0.5, y as f64 + 0.5);
|
||||
let t = parameters.t(glam::DVec2::new(point.x, point.y)).clamp(0., 1.);
|
||||
let expected = (t * 255.).round() as i32;
|
||||
let actual = pixel(&pixels, size, x, y)[0] as i32;
|
||||
worst = worst.max((expected - actual).abs());
|
||||
}
|
||||
}
|
||||
assert!(worst <= 3, "dials {dials:?} differ from the CPU evaluation by up to {worst} levels");
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders an opaque white square from (`min`, `min`) to (`max`, `max`) through `effects` with `fill`.
|
||||
fn render_square_with_effects(effects: Vec<graphic_types::EffectOperation>, fill: f32, min: f64, max: f64, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||||
let square = Rect::new(min, min, max, max);
|
||||
let effects = graphic_types::Effects::from_operations(effects);
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let square = Rect::new(min, min, max, max);
|
||||
|
||||
// The paint overlays' paints, drawn as the renderer does for content placed in the scene's space
|
||||
let paints: Vec<graphic_types::Graphic> = (effects.iter())
|
||||
.filter_map(|operation| match operation {
|
||||
graphic_types::EffectOperation::PaintOverlay { paint, .. } => Some(paint),
|
||||
_ => None,
|
||||
})
|
||||
.map(|paint| graphic_types::fitted_paint(paint, [glam::DVec2::splat(min), glam::DVec2::splat(max)]).unwrap_or_else(|| paint.clone()))
|
||||
.collect();
|
||||
let mut draw_paint = |index: usize, scene: &mut VelloSceneBuilder| {
|
||||
if let Some(paint) = paints.get(index) {
|
||||
paint.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default().for_pattern());
|
||||
}
|
||||
};
|
||||
|
||||
let effects = graphic_types::Effects::from_operations(effects);
|
||||
render(size, |scene| {
|
||||
scene.draw_effects(&effects, fill, Some(square), &mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square));
|
||||
scene.draw_effects(&effects, fill, Some(square), &mut draw_paint, &mut |scene| {
|
||||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
@@ -461,6 +513,46 @@ fn inner_glows_satins_outlines_and_bevels_fall_where_they_should() {
|
||||
assert_eq!(pixel(&pixels, size, 55, 40), white, "the content inside is unlit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlays_stretch_unplaced_paints_across_the_content() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::Item;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||||
use graphic_types::{EffectOperation, Graphic};
|
||||
|
||||
let size = UVec2::new(128, 128);
|
||||
let overlay = |paint: Graphic| EffectOperation::PaintOverlay {
|
||||
paint,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
};
|
||||
let reddish = |[red, green, blue, alpha]: [u8; 4]| red > 200 && green < 64 && blue < 64 && alpha == 255;
|
||||
let bluish = |[red, green, blue, alpha]: [u8; 4]| blue > 200 && red < 64 && green < 64 && alpha == 255;
|
||||
|
||||
// A gradient from red to blue runs from the square's left edge to its right edge
|
||||
let stops = [(0., GraphicColor::RED), (1., GraphicColor::BLUE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||||
let Some(pixels) = render_square_with_effects(vec![overlay(Graphic::from(Gradient::new(stops)))], 1., 30., 80., size) else {
|
||||
return;
|
||||
};
|
||||
assert!(reddish(pixel(&pixels, size, 31, 55)), "the start at the left edge: {:?}", pixel(&pixels, size, 31, 55));
|
||||
assert!(bluish(pixel(&pixels, size, 78, 55)), "the end at the right edge: {:?}", pixel(&pixels, size, 78, 55));
|
||||
assert_eq!(pixel(&pixels, size, 25, 55)[3], 0, "nothing outside the content");
|
||||
|
||||
// An image of a red pixel beside a blue one covers the square, each pixel half of it
|
||||
let image = Image {
|
||||
width: 2,
|
||||
height: 1,
|
||||
data: vec![GraphicColor::RED, GraphicColor::BLUE],
|
||||
};
|
||||
let Some(pixels) = render_square_with_effects(vec![overlay(Graphic::from(Item::new_from_element(Raster::new_cpu(image))))], 1., 30., 80., size) else {
|
||||
return;
|
||||
};
|
||||
assert!(reddish(pixel(&pixels, size, 35, 40)), "the left half: {:?}", pixel(&pixels, size, 35, 40));
|
||||
assert!(bluish(pixel(&pixels, size, 75, 70)), "the right half: {:?}", pixel(&pixels, size, 75, 70));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_shadows_stack_over_earlier_ones_beneath_the_content() {
|
||||
use core_types::Color as GraphicColor;
|
||||
@@ -505,8 +597,10 @@ fn nested_effects_groups_render_inside_out() {
|
||||
gamma: false,
|
||||
}]);
|
||||
let draw = |scene: &mut VelloSceneBuilder| {
|
||||
scene.draw_effects(&shadow, 1., Some(square.inflate(12., 12.)), &mut |scene| {
|
||||
scene.draw_effects(&blur, 1., Some(square), &mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square));
|
||||
scene.draw_effects(&shadow, 1., Some(square.inflate(12., 12.)), &mut |_, _| {}, &mut |scene| {
|
||||
scene.draw_effects(&blur, 1., Some(square), &mut |_, _| {}, &mut |scene| {
|
||||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
@@ -617,6 +711,8 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
|
||||
use crate::raster_effects::evaluate_raster_effects;
|
||||
use crate::shader_runtime::raster_kernel_runtime::RasterKernelRuntime;
|
||||
use core_types::Color as GraphicColor;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::ATTR_GRADIENT_FORM;
|
||||
use core_types::list::{ATTR_EFFECTS, Item};
|
||||
use core_types::ops::{Convert, ConvertAsync};
|
||||
use core_types::transform::Footprint;
|
||||
@@ -624,8 +720,9 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
|
||||
use glam::DVec2;
|
||||
use graphic_types::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
|
||||
use graphic_types::raster_types::{CPU, GPU, Image, Raster, Storage};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientForm, GradientStop};
|
||||
use graphic_types::vector_types::vector::style::StrokeAlign;
|
||||
use graphic_types::{BevelDirection, BevelStyle, EffectOperation, Effects, GlowSource};
|
||||
use graphic_types::{BevelDirection, BevelStyle, EffectOperation, Effects, GlowSource, Graphic};
|
||||
|
||||
let size = UVec2::new(160, 160);
|
||||
let (min, max) = (50, 100);
|
||||
@@ -747,7 +844,62 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
|
||||
let pipeline = WgpuPipelineCache::default();
|
||||
executor.pipeline_init::<RasterKernelRuntime>(&pipeline);
|
||||
|
||||
for effects in cases {
|
||||
// Paint overlays over a colored backdrop, their paints placed on their own since the raster and the square fit unplaced paints to different bounds
|
||||
let backdrop = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: GraphicColor::from_rgbaf32_unchecked(0.3, 0.6, 0.2, 1.),
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let gradient = |form: GradientForm, transform: DAffine2| {
|
||||
let stops = [(0., [0.9, 0.1, 0.4, 1.]), (0.5, [0.2, 0.3, 0.9, 0.5]), (1., [1., 0.9, 0.7, 1.])].map(|(position, [red, green, blue, alpha])| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: GraphicColor::from_rgbaf32_unchecked(red, green, blue, alpha),
|
||||
});
|
||||
let item = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform);
|
||||
Graphic::from(item.with_attribute(ATTR_GRADIENT_FORM, form))
|
||||
};
|
||||
let linear = gradient(GradientForm::Linear, DAffine2::from_translation(DVec2::new(45., 60.)) * DAffine2::from_scale(DVec2::splat(60.)));
|
||||
let radial = gradient(GradientForm::Radial, DAffine2::from_translation(DVec2::splat(75.)) * DAffine2::from_scale(DVec2::splat(30.)));
|
||||
|
||||
// A checkerboard with a pixel for each of the square's, so sampling it needs no interpolation
|
||||
let checker = Image {
|
||||
width: 50,
|
||||
height: 50,
|
||||
data: (0..2500)
|
||||
.map(|index| match (index % 50 / 5 + index / 50 / 5) % 2 {
|
||||
0 => GraphicColor::RED,
|
||||
_ => GraphicColor::from_rgbaf32_unchecked(0., 0., 1., 0.5),
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let checker_placement = DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_scale(DVec2::splat(50.));
|
||||
let checker = Graphic::from(Item::new_from_element(Raster::new_cpu(checker)).with_attribute(ATTR_TRANSFORM, checker_placement));
|
||||
|
||||
let overlay = |paint: &Graphic, blend_mode, opacity| {
|
||||
vec![
|
||||
backdrop.clone(),
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: paint.clone(),
|
||||
blend_mode,
|
||||
opacity,
|
||||
},
|
||||
]
|
||||
};
|
||||
// Hard Mix's threshold and the hue of the gradient's grays turn the slightest rounding into large differences, so they take the checkerboard's exact colors instead
|
||||
let ill_conditioned = [BlendMode::HardMix, BlendMode::Hue];
|
||||
let mut paint_cases: Vec<_> = (BlendMode::list().into_iter().flatten())
|
||||
.filter(|blend_mode| !ill_conditioned.contains(blend_mode))
|
||||
.map(|&blend_mode| overlay(&linear, blend_mode, 100.))
|
||||
.collect();
|
||||
paint_cases.extend(ill_conditioned.map(|blend_mode| overlay(&checker, blend_mode, 100.)));
|
||||
paint_cases.extend([
|
||||
overlay(&linear, BlendMode::Normal, 40.),
|
||||
overlay(&radial, BlendMode::Multiply, 100.),
|
||||
overlay(&checker, BlendMode::Screen, 100.),
|
||||
]);
|
||||
|
||||
for effects in cases.into_iter().chain(paint_cases) {
|
||||
for fill in [1., 0.5] {
|
||||
let Some(rendered) = render_square_with_effects(effects.clone(), fill, min as f64, max as f64, size) else {
|
||||
return;
|
||||
@@ -792,7 +944,16 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(worst <= 2, "{effects:?} at fill {fill} differs from the render by up to {worst} levels");
|
||||
// Modes that divide, or land near black where the gamma encoding is steepest, amplify the rounding of the rendered paint's eight bits
|
||||
use BlendMode::*;
|
||||
let tolerance = match effects.last() {
|
||||
Some(EffectOperation::PaintOverlay {
|
||||
blend_mode: ColorBurn | LinearBurn | ColorDodge | HardLight | VividLight | LinearLight | PinLight,
|
||||
..
|
||||
}) => 8,
|
||||
_ => 2,
|
||||
};
|
||||
assert!(worst <= tolerance, "{effects:?} at fill {fill} differs from the render by up to {worst} levels");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -885,7 +1046,7 @@ fn effects_groups_carry_out_adjustments_like_their_kernels_map_colors() {
|
||||
let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment));
|
||||
let draw = |scene: &mut VelloSceneBuilder| {
|
||||
let bounds = Rect::new(0., 0., size.x as f64, size.y as f64);
|
||||
scene.draw_effects(&effects, 1., Some(bounds), &mut |scene| {
|
||||
scene.draw_effects(&effects, 1., Some(bounds), &mut |_, _| {}, &mut |scene| {
|
||||
scene.draw_raster(raster.clone(), peniko::ImageSampler::new(), Affine::IDENTITY)
|
||||
});
|
||||
};
|
||||
@@ -893,6 +1054,17 @@ fn effects_groups_carry_out_adjustments_like_their_kernels_map_colors() {
|
||||
|
||||
let mut worst = 0;
|
||||
for (index, color) in colors.iter().enumerate() {
|
||||
// A half-float raster rounds a color's gamma channels by up to about 0.0004, which can carry a luminance this close to a Threshold level across it
|
||||
let [r, g, b, _] = color.to_gamma_srgb_channels();
|
||||
let luminance = (4915. * r + 9667. * g + 1802. * b) / 16384.;
|
||||
let near_level = |level: f64| (luminance as f64 - level / 100.).abs() < 0.001;
|
||||
if run
|
||||
.iter()
|
||||
.any(|adjustment| matches!(adjustment, Adjustment::Threshold { min_luminance, max_luminance } if near_level(*min_luminance) || near_level(*max_luminance)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let mapped = run.iter().fold(*color, |color, adjustment| adjust_color(adjustment, color));
|
||||
let cpu = mapped.to_gamma_srgb_channels().map(|channel| (channel * 255.).round() as i32);
|
||||
for channel in 0..3 {
|
||||
@@ -914,7 +1086,7 @@ fn effects_groups_keep_the_empty_space_empty_when_an_adjustment_changes_alpha()
|
||||
let square = Rect::new(4., 4., 12., 12.);
|
||||
let effects = Effects::from_operations([EffectOperation::Adjustment(Adjustment::MakeOpaque)]);
|
||||
let draw = |scene: &mut VelloSceneBuilder| {
|
||||
scene.draw_effects(&effects, 1., Some(Rect::new(0., 0., 16., 16.)), &mut |scene| {
|
||||
scene.draw_effects(&effects, 1., Some(Rect::new(0., 0., 16., 16.)), &mut |_, _| {}, &mut |scene| {
|
||||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::new([1., 1., 1., 0.5]), None, &square)
|
||||
});
|
||||
};
|
||||
@@ -1102,3 +1274,97 @@ fn images_reveal_the_colors_of_transparent_pixels_when_adjusted() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A noise pattern with features a few units across.
|
||||
fn noise_pattern() -> graphic_types::generator::GeneratorPattern {
|
||||
use graphic_types::generator::*;
|
||||
|
||||
GeneratorPattern::Noise(NoiseSettings {
|
||||
seed: 11,
|
||||
scale: 6.,
|
||||
noise_type: NoiseType::OpenSimplex2,
|
||||
domain_warp_type: DomainWarpType::None,
|
||||
domain_warp_amplitude: 0.,
|
||||
fractal_type: FractalType::FBm,
|
||||
fractal_octaves: 3,
|
||||
fractal_lacunarity: 2.,
|
||||
fractal_gain: 0.5,
|
||||
fractal_weighted_strength: 0.,
|
||||
fractal_ping_pong_strength: 2.,
|
||||
cellular_distance_function: CellularDistanceFunction::Euclidean,
|
||||
cellular_return_type: CellularReturnType::Nearest,
|
||||
cellular_jitter: 1.,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generators_draw_their_pattern_at_the_resolution_in_view() {
|
||||
use crate::raster_kernel::render_generator;
|
||||
use core_types::ops::ConvertAsync;
|
||||
use core_types::transform::Footprint;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
|
||||
// Each unit of the pattern drawn across two pixels, so its tiles sample the pattern at every pixel's center
|
||||
let size = UVec2::new(80, 80);
|
||||
let pattern = noise_pattern();
|
||||
let Some(pixels) = render(size, |scene| scene.draw_generator(&pattern, Affine::translate((8., 8.)) * Affine::scale(2.))) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let executor = executor().unwrap();
|
||||
let _turn = take_turn();
|
||||
let kernel = render_generator(&pattern, [glam::DVec2::ZERO, glam::DVec2::splat(32.)], UVec2::splat(64), &executor.render_kernels()).unwrap();
|
||||
let kernel: Raster<CPU> = futures::executor::block_on(kernel.convert(Footprint::DEFAULT, executor.clone()));
|
||||
let (expected, _, _) = kernel.to_flat_u8();
|
||||
|
||||
let mut worst = 0;
|
||||
for y in 0..64 {
|
||||
for x in 0..64 {
|
||||
let drawn = pixel(&pixels, size, x + 8, y + 8);
|
||||
let sampled = &expected[((y * 64 + x) * 4) as usize..][..4];
|
||||
worst = (0..3).map(|channel| drawn[channel].abs_diff(sampled[channel])).fold(worst, u8::max);
|
||||
}
|
||||
}
|
||||
assert!(worst <= 2, "the drawn pattern differs from the kernel's own samples by up to {worst} levels");
|
||||
|
||||
// The pattern fills the plane, past the area compared
|
||||
assert_eq!(pixel(&pixels, size, 2, 2)[3], 255);
|
||||
assert_eq!(pixel(&pixels, size, 76, 76)[3], 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_tiles_are_reused_across_a_pan() {
|
||||
let Some(executor) = executor() else { return };
|
||||
let _turn = take_turn();
|
||||
let tiles = |canvas: &crate::VelloCanvas| {
|
||||
canvas
|
||||
.images
|
||||
.textures
|
||||
.values()
|
||||
.map(|image_texture| image_texture.texture.clone())
|
||||
.collect::<std::collections::HashSet<_>>()
|
||||
};
|
||||
|
||||
// A pattern drawn two pixels to a unit, in tiles of 256 pixels, panned by part of a tile
|
||||
let mut canvas = crate::VelloCanvas::default();
|
||||
let pattern = noise_pattern();
|
||||
let size = UVec2::splat(512);
|
||||
let target = executor.request_texture(size);
|
||||
let render = |canvas: &mut crate::VelloCanvas, offset: f64| {
|
||||
let mut draw = |scene: &mut VelloSceneBuilder| scene.draw_generator(&pattern, Affine::translate((offset, 0.)) * Affine::scale(2.));
|
||||
let context = executor.context();
|
||||
(executor.inner.vello_renderer)
|
||||
.render(canvas, &context.device, &context.queue, &executor.render_kernels(), &mut draw, Affine::IDENTITY, size, &target)
|
||||
.unwrap();
|
||||
};
|
||||
render(&mut canvas, 0.);
|
||||
let first = tiles(&canvas);
|
||||
assert!(!first.is_empty(), "the view should draw tiles");
|
||||
render(&mut canvas, 0.);
|
||||
assert_eq!(tiles(&canvas), first, "drawing the same view again renders no tiles");
|
||||
|
||||
render(&mut canvas, -100.);
|
||||
let panned = tiles(&canvas);
|
||||
assert!(panned.is_superset(&first), "panning keeps the tiles it has rendered");
|
||||
assert!(panned.len() < first.len() * 2, "panning renders only the tiles newly in view, not all {} again", first.len());
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use core_types::list::Item;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, BlendMode, Color, Ctx};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::Vector;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Generator, Graphic};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies the blend mode to the input graphics. Setting this allows for customizing how overlapping content is composited together.
|
||||
@@ -10,7 +10,7 @@ use vector_types::Gradient;
|
||||
fn blend_mode<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
#[implementations(Graphic, Vector, Raster<GPU>, Raster<CPU>, Color, Gradient, String)]
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
|
||||
blend_mode: Item<BlendMode>,
|
||||
@@ -29,7 +29,7 @@ fn blend_mode<T>(
|
||||
fn opacity<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
#[implementations(Graphic, Vector, Raster<GPU>, Raster<CPU>, Color, Gradient, String)]
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// Whether the *Opacity* property is enabled, multiplying the existing opacity by the chosen percentage.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
@@ -76,7 +76,7 @@ fn opacity<T>(
|
||||
fn clipping_mask<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
#[implementations(Graphic, Vector, Raster<GPU>, Raster<CPU>, Color, Gradient, String)]
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// Whether the content inherits the alpha of the content beneath it.
|
||||
clip: Item<bool>,
|
||||
|
||||
@@ -3,6 +3,7 @@ use core_types::transform::Footprint;
|
||||
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -85,20 +86,22 @@ fn step_real_time<T>(
|
||||
Context -> Item<DVec2>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> List<String>,
|
||||
Context -> List<f64>,
|
||||
Context -> List<DVec2>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
value: impl Node<Context<'static>, Output = T>,
|
||||
@@ -131,20 +134,22 @@ fn step_animation_time<T>(
|
||||
Context -> Item<DVec2>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> List<String>,
|
||||
Context -> List<f64>,
|
||||
Context -> List<DVec2>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
value: impl Node<Context<'static>, Output = T>,
|
||||
|
||||
@@ -5,6 +5,7 @@ use core_types::transform::Footprint;
|
||||
use core_types::{Color, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -25,11 +26,12 @@ fn context_modification<T>(
|
||||
Context -> Item<DVec2>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<NodeIdPath>,
|
||||
Context -> Item<AttributeValueDyn>,
|
||||
Context -> Item<AnimationCurve>,
|
||||
@@ -38,11 +40,12 @@ fn context_modification<T>(
|
||||
Context -> List<DVec2>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Artboard>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<AnimationCurve>,
|
||||
Context -> ListDyn,
|
||||
)]
|
||||
|
||||
@@ -2,6 +2,7 @@ use core_types::list::{Item, List};
|
||||
use core_types::transform::TransformMut;
|
||||
use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -16,10 +17,11 @@ fn create_artboard<T: IntoGraphicList>(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<String>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> Item<DAffine2>, // TODO: Remove this
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = T>,
|
||||
|
||||
@@ -7,7 +7,7 @@ use core_types::{
|
||||
};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
use graphic_types::{Artboard, Generator, Vector};
|
||||
use rand::SeedableRng;
|
||||
use rand::seq::SliceRandom;
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -30,10 +30,11 @@ fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: T,
|
||||
@@ -64,10 +65,11 @@ fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -102,10 +104,11 @@ fn filter<T: Send + Sync + Clone + 'static>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -135,10 +138,11 @@ fn reverse<T: Send + Sync + Clone + 'static>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -160,10 +164,11 @@ fn shift<T: Send + Sync + Clone + 'static>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -205,10 +210,11 @@ fn shuffle<T: Send + Sync + Clone + 'static>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -277,10 +283,11 @@ fn slice<T: Send + Sync + Clone + 'static>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -351,9 +358,9 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
|
||||
_: impl Ctx,
|
||||
/// The list of data to reorder.
|
||||
#[implementations(
|
||||
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<GPU>>, List<Raster<CPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<GPU>>, List<Raster<CPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<GPU>>, List<Raster<CPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
/// The optional list of orderable values, corresponding item-to-item with the input list, to sort by instead of the items' own values.
|
||||
@@ -412,10 +419,11 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
content: List<Item>,
|
||||
@@ -428,10 +436,11 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
Context -> List<DAffine2>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
mapped: impl Node<Context<'static>, Output = List<Item>>,
|
||||
@@ -489,8 +498,8 @@ fn mirror<T: BoundingBox + HasText + Send + Clone + 'static>(
|
||||
#[implementations(
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<String>,
|
||||
@@ -598,10 +607,11 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
List<BlendMode>,
|
||||
List<GradientForm>,
|
||||
@@ -911,10 +921,11 @@ fn extend<T: Send + Clone>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
List<Stroke>,
|
||||
)]
|
||||
@@ -930,10 +941,11 @@ fn extend<T: Send + Clone>(
|
||||
List<DAffine2>,
|
||||
List<Vector>,
|
||||
List<Graphic>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
List<Stroke>,
|
||||
)]
|
||||
@@ -951,9 +963,9 @@ fn extend<T: Send + Clone>(
|
||||
#[node_macro::node(category(""))]
|
||||
fn legacy_layer_extend<T: Send + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<GPU>>, List<Raster<CPU>>, List<Color>, List<Gradient>)] base: List<T>,
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Generator>)] base: List<T>,
|
||||
#[expose]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<GPU>>, List<Raster<CPU>>, List<Color>, List<Gradient>)]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Generator>)]
|
||||
new: List<T>,
|
||||
nested_node_path: Item<NodeIdPath>,
|
||||
) -> List<T> {
|
||||
@@ -981,10 +993,11 @@ fn into_group<T: Into<Graphic>>(
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<DVec2>,
|
||||
Item<DAffine2>, // TODO: Remove this
|
||||
|
||||
@@ -60,6 +60,10 @@ pub mod gradient {
|
||||
pub use vector_types::{Gradient, GradientStop};
|
||||
}
|
||||
|
||||
pub mod generator {
|
||||
pub use graphic_types::generator::*;
|
||||
}
|
||||
|
||||
pub mod transform {
|
||||
pub use core_types::transform::*;
|
||||
pub use vector_types::ReferencePoint;
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use core_types::Ctx;
|
||||
use core_types::NodeError;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::ops::{Convert, ConvertAsync};
|
||||
use core_types::ops::ConvertAsync;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, Interrupt, NodeError};
|
||||
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM};
|
||||
use glam::{DAffine2, UVec2};
|
||||
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
|
||||
pub use graph_craft::application_io::*;
|
||||
@@ -12,8 +13,8 @@ pub use graph_craft::document::value::RenderOutputType;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub use graphene_canvas_utils as canvas_utils;
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::raster_types::Image;
|
||||
use graphic_types::raster_types::{GPU, Raster, Storage};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster, Storage};
|
||||
use graphic_types::raster_types::{Image, ImageError};
|
||||
use raster_nodes::raster_kernel::raster_kernel_pipeline;
|
||||
use rendering::{Render, RenderParams};
|
||||
use std::sync::Arc;
|
||||
@@ -219,15 +220,14 @@ fn pending_resource(_primary: &(), _url: &Item<String>) -> Item<Resource> {
|
||||
///
|
||||
/// Supports the formats: PNG, JPG, GIF, WEBP, TIFF, BMP, TGA, ICO, HDR, EXR.
|
||||
#[node_macro::node(category("Data: I/O"), icon("NodeBytesToImage"), name("Bytes to Image"), memoize)]
|
||||
fn bytes_to_image(_: impl Ctx, data: Item<Resource>, #[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<::wgpu_executor::WgpuPipelineCache>) -> Result<Item<Raster<GPU>>, Interrupt> {
|
||||
fn bytes_to_image(_: impl Ctx, data: Item<Resource>) -> Result<Item<Raster<CPU>>, ImageError> {
|
||||
let data = data.into_element();
|
||||
if data.is_empty() {
|
||||
return Ok(Item::default());
|
||||
}
|
||||
let image = Image::from_encoded(data.as_ref()).map_err(NodeError::new)?;
|
||||
let image = Image::from_encoded(data.as_ref())?;
|
||||
|
||||
let executor = pipeline.element().executor().cloned().ok_or_else(|| NodeError::new("A GPU is required to load an image"))?;
|
||||
Ok(Item::new_from_element(Raster::new_cpu(image).convert(Footprint::DEFAULT, executor)))
|
||||
Ok(Item::new_from_element(Raster::new_cpu(image)))
|
||||
}
|
||||
|
||||
/// Renders a view of the input graphic within an area defined by the *Footprint*.
|
||||
@@ -325,7 +325,6 @@ mod tests {
|
||||
use super::*;
|
||||
use core_types::Color;
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::CPU;
|
||||
|
||||
#[tokio::test]
|
||||
async fn rasterize_renders_the_footprint_area_at_its_resolution() {
|
||||
|
||||
@@ -5,6 +5,7 @@ use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs};
|
||||
use core_types::{Color, Context, Ctx, ExtractFootprint, Interrupt, NodeError, OwnedContextImpl, WasmNotSend};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphene_application_io::{ExportFormat, RenderConfig};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster, Texture};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
@@ -30,10 +31,11 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
Context -> List<Artboard>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
data: impl Node<Context<'static>, Output = T>,
|
||||
|
||||
@@ -5,7 +5,7 @@ use core_types::{Color, Ctx, OwnedContextImpl, num_traits};
|
||||
use core_types::{Context, Interrupt};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use graphic_types::{Artboard, Generator, Graphic, Vector};
|
||||
use math_parser::ast;
|
||||
use math_parser::context::{EvalContext, NothingMap, ValueProvider};
|
||||
use math_parser::executer::EvalError;
|
||||
@@ -1609,10 +1609,11 @@ fn switch<T: Send>(
|
||||
Context -> Item<DAffine2>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Bundle<String>>,
|
||||
Context -> Item<Bundle<bool>>,
|
||||
@@ -1639,10 +1640,11 @@ fn switch<T: Send>(
|
||||
Context -> Item<DAffine2>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Bundle<String>>,
|
||||
Context -> Item<Bundle<bool>>,
|
||||
@@ -1814,11 +1816,25 @@ fn gradient_value(_: impl Ctx, _primary: (), #[default(Color::BLACK, Color::WHIT
|
||||
gradient
|
||||
}
|
||||
|
||||
/// Sets the form (linear or radial) of each gradient in the input list.
|
||||
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"))]
|
||||
fn gradient_form(_: impl Ctx, gradient: Item<Gradient>, gradient_form: Item<vector_types::GradientForm>) -> Item<Gradient> {
|
||||
/// Curves the contours at the start and end of each gradient in the input list between straight lines, circles, and points, with the contours between following along.
|
||||
///
|
||||
/// Each end runs from -1 to 1. At 0 its contour is a straight line, at 1 or -1 it shrinks to the end's own point, and between it is a circle through the end that bows toward the other end when positive or away from it when negative. A linear gradient is 0 at both ends, and a radial gradient is 1 at its start and 0.5 at its end.
|
||||
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"), inspector("gradient_curvature_inspector"))]
|
||||
fn gradient_curvature(
|
||||
_: impl Ctx,
|
||||
gradient: Item<Gradient>,
|
||||
/// The curve of the contour through the start.
|
||||
#[range]
|
||||
#[soft(-1..1)]
|
||||
start_curvature: Item<f64>,
|
||||
/// The curve of the contour through the end.
|
||||
#[range]
|
||||
#[soft(-1..1)]
|
||||
end_curvature: Item<f64>,
|
||||
) -> Item<Gradient> {
|
||||
let mut gradient = gradient;
|
||||
gradient.set_attribute(core_types::ATTR_GRADIENT_FORM, *gradient_form.element());
|
||||
gradient.set_attribute(core_types::ATTR_GRADIENT_START_CURVATURE, *start_curvature.element());
|
||||
gradient.set_attribute(core_types::ATTR_GRADIENT_END_CURVATURE, *end_curvature.element());
|
||||
gradient
|
||||
}
|
||||
|
||||
|
||||
@@ -281,9 +281,9 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> Result<List<Vector>, BooleanO
|
||||
boolean_operation_on_vector_list(&flattened, BooleanOperation::Union)?.into_iter().collect::<Vec<_>>()
|
||||
}
|
||||
}
|
||||
// Rasters, colors, and gradients bound no region, so they contribute no operand
|
||||
Graphic::None(_) | Graphic::NoneList(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) => Vec::new(),
|
||||
Graphic::RasterCPUList(_) | Graphic::RasterGPUList(_) | Graphic::ColorList(_) | Graphic::GradientList(_) => Vec::new(),
|
||||
// Rasters, colors, gradients, and generators bound no region, so they contribute no operand
|
||||
Graphic::None(_) | Graphic::NoneList(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) => Vec::new(),
|
||||
Graphic::RasterCPUList(_) | Graphic::RasterGPUList(_) | Graphic::ColorList(_) | Graphic::GradientList(_) | Graphic::GeneratorList(_) => Vec::new(),
|
||||
// Strokes have no vector outline representation; a brush node renders them to rasters
|
||||
Graphic::StrokeList(_) => Vec::new(),
|
||||
// Normalized to GraphicList above
|
||||
|
||||
@@ -17,7 +17,7 @@ use graphic_types::adjustment::{
|
||||
};
|
||||
pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute, SelectiveColorChoice};
|
||||
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use graphic_types::{Graphic, Vector};
|
||||
use graphic_types::{Generator, Graphic, Vector};
|
||||
use num_enum::{FromPrimitive, IntoPrimitive};
|
||||
use raster_kernels::color_lookup_table::parse_cached;
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -32,7 +32,7 @@ fn adjust<T: ApplyEffect>(item: Item<T>, adjustment: Adjustment, pipeline: Item<
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeDesaturate"))]
|
||||
fn desaturate<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
method: Item<DesaturateMethod>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<T>, Interrupt> {
|
||||
@@ -42,7 +42,7 @@ fn desaturate<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeGammaCorrection"))]
|
||||
fn gamma_correction<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[default(2.2)]
|
||||
#[range]
|
||||
#[hard(0.0001..)]
|
||||
@@ -116,7 +116,7 @@ impl MapColor for ExtractChannel {
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"))]
|
||||
fn make_opaque<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<T>, Interrupt> {
|
||||
adjust(input, Adjustment::MakeOpaque, pipeline)
|
||||
@@ -133,7 +133,7 @@ fn make_opaque<T: ApplyEffect>(
|
||||
#[node_macro::node(name("Brightness/Contrast"), category("Raster: Adjustment"), icon("NodeBrightnessContrast"), inspector("brightness_contrast_inspector"))]
|
||||
fn brightness_contrast<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(-150..150)]
|
||||
@@ -186,7 +186,7 @@ pub enum AdjustmentChannel {
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeLevels"), inspector("levels_inspector"))]
|
||||
fn levels<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
@@ -359,7 +359,7 @@ fn levels<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeCurves"), inspector("transfer_curves_inspector"))]
|
||||
fn curves<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
curve: Item<TransferCurve>,
|
||||
#[name("(Red) Curve")] red_curve: Item<TransferCurve>,
|
||||
#[name("(Green) Curve")] green_curve: Item<TransferCurve>,
|
||||
@@ -407,7 +407,7 @@ fn points_to_transfer_curve(
|
||||
#[node_macro::node(name("Black & White"), category("Raster: Adjustment"), icon("NodeBlackAndWhite"), inspector("black_and_white_inspector"))]
|
||||
fn black_and_white<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
use_tint: Item<bool>,
|
||||
#[default("#e1d3b3")] tint: Item<Color>,
|
||||
#[unit("%")]
|
||||
@@ -481,7 +481,7 @@ pub enum HueSaturationRange {
|
||||
#[node_macro::node(name("Hue/Saturation"), category("Raster: Adjustment"), icon("NodeHueSaturation"), inspector("hue_saturation_inspector"))]
|
||||
fn hue_saturation<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[unit("°")]
|
||||
#[range]
|
||||
#[soft(-180..180)]
|
||||
@@ -818,7 +818,7 @@ fn hue_saturation<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeInvert"))]
|
||||
fn invert<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<T>, Interrupt> {
|
||||
adjust(input, Adjustment::Invert, pipeline)
|
||||
@@ -829,7 +829,7 @@ fn invert<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeThreshold"), inspector("threshold_inspector"))]
|
||||
fn threshold<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
@@ -868,7 +868,7 @@ fn threshold<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeGradientMap"))]
|
||||
fn gradient_map<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[default(Color::BLACK, Color::WHITE)] gradient: Item<Gradient>,
|
||||
reverse: Item<bool>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
@@ -889,7 +889,7 @@ fn gradient_map<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeVibrance"), inspector("vibrance_inspector"))]
|
||||
fn vibrance<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(-100..100)]
|
||||
@@ -943,7 +943,7 @@ pub enum RedGreenBlueAlpha {
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeChannelMixer"), inspector("channel_mixer_inspector"))]
|
||||
fn channel_mixer<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
|
||||
monochrome: Item<bool>,
|
||||
|
||||
@@ -1077,7 +1077,7 @@ fn channel_mixer<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeSelectiveColor"), inspector("selective_color_inspector"))]
|
||||
fn selective_color<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
|
||||
mode: Item<RelativeAbsolute>,
|
||||
|
||||
@@ -1300,7 +1300,7 @@ fn selective_color<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodePosterize"))]
|
||||
fn posterize<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[default(4)]
|
||||
#[hard(2..)]
|
||||
levels: Item<i64>,
|
||||
@@ -1318,7 +1318,7 @@ fn posterize<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeExposure"), inspector("exposure_inspector"))]
|
||||
fn exposure<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[range]
|
||||
#[soft(-20..20)]
|
||||
exposure: Item<f64>,
|
||||
@@ -1364,7 +1364,7 @@ pub enum TonalRange {
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeColorBalance"), inspector("color_balance_inspector"))]
|
||||
fn color_balance<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
|
||||
#[name("(Shadows) Cyan-Red")]
|
||||
#[unit("%")]
|
||||
@@ -1441,7 +1441,7 @@ fn color_balance<T: ApplyEffect>(
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodePhotoFilter"))]
|
||||
fn photo_filter<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[default("#ec8a00")] color: Item<Color>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
@@ -1472,7 +1472,7 @@ fn photo_filter<T: ApplyEffect>(
|
||||
fn color_lookup<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The image whose colors are remapped by the LUT (lookup table).
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String)]
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)]
|
||||
image: Item<T>,
|
||||
/// A LUT (lookup table) file in the `.cube`, `.3dl`, `.look`, `.csp`, or `.icc` (*abstract* or *device link* ICC profile) format.
|
||||
#[name("LUT File")]
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
use crate::effects::ApplyEffect;
|
||||
use crate::raster_kernel::raster_kernel_pipeline;
|
||||
use core_types::Ctx;
|
||||
use core_types::Interrupt;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::Color;
|
||||
use core_types::list::Item;
|
||||
use graphic_types::{Adjustment, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
use wgpu_executor::WgpuPipelineCache;
|
||||
|
||||
pub use core_types::blending::{apply_blend_mode, blend_colors};
|
||||
|
||||
@@ -33,66 +26,10 @@ fn mix_colors(
|
||||
under
|
||||
}
|
||||
|
||||
// TODO: Rename to "Paint Overlay" and take a `Graphic` paint like the `Fill` node, enabling this to serve the cases of Color Overlay, Gradient Overlay, and Pattern Overlay.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"))]
|
||||
fn color_overlay<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
Graphic,
|
||||
Vector,
|
||||
Raster<GPU>,
|
||||
String,
|
||||
)]
|
||||
image: Item<T>,
|
||||
#[default(Color::BLACK)] color: Item<Color>,
|
||||
blend_mode: Item<BlendMode>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
opacity: Item<f64>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<T>, Interrupt> {
|
||||
let adjustment = Adjustment::ColorOverlay {
|
||||
color: color.into_element(),
|
||||
blend_mode: blend_mode.into_element(),
|
||||
opacity: opacity.into_element(),
|
||||
};
|
||||
Ok(T::apply_adjustment(image, adjustment, pipeline.element())?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::Color;
|
||||
use core_types::list::Item;
|
||||
|
||||
#[test]
|
||||
fn color_overlay_multiply() {
|
||||
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
|
||||
|
||||
// Color { red: 0., green: 1., blue: 0., alpha: 1. }
|
||||
let overlay_color = Color::GREEN;
|
||||
|
||||
// 100% of the output should come from the multiplied value
|
||||
let opacity = 100.;
|
||||
|
||||
let result = super::color_overlay(
|
||||
(),
|
||||
Item::new_from_element(image_color),
|
||||
overlay_color.into(),
|
||||
BlendMode::Multiply.into(),
|
||||
opacity.into(),
|
||||
Item::default(),
|
||||
);
|
||||
let result = result.unwrap().into_element();
|
||||
|
||||
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
|
||||
assert_eq!(result, Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mix_colors_paints_over_at_its_opacity() {
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
use crate::raster_kernel::raster_kernel_pipeline;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
|
||||
use core_types::ops::Convert;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{ATTR_OPACITY_FILL, Color, Ctx, Interrupt, NodeError};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item, List};
|
||||
use core_types::{ATTR_OPACITY_FILL, CacheHash, Color, Ctx, Interrupt, NodeError};
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Adjustment, BevelDirection, BevelStyle, Effect, EffectOperation, Effects, GlowSource, Graphic, Vector, stamp_effect};
|
||||
use graphic_types::{Adjustment, BevelDirection, BevelStyle, Effect, EffectOperation, Effects, Generator, GlowSource, Graphic, Vector, stamp_effect};
|
||||
use raster_kernels::adjustments::{adjust_color, adjust_gradient, preserves_alpha};
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use vector_types::vector::style::StrokeAlign;
|
||||
use vector_types::{Gradient, GradientSettings};
|
||||
use wgpu_executor::WgpuPipelineCache;
|
||||
use wgpu_executor::raster_effects::evaluate_raster_effects;
|
||||
use wgpu_executor::raster_effects::{evaluate_raster_effects, upload_raster};
|
||||
use wgpu_executor::raster_kernel::adjust_raster;
|
||||
|
||||
/// Content an effect can be carried out on. A GPU raster has the effect carried out into its pixels at once, with the same kernels the renderer uses,
|
||||
@@ -32,6 +33,7 @@ impl ApplyEffect for Graphic {}
|
||||
impl ApplyEffect for Vector {}
|
||||
impl ApplyEffect for Raster<CPU> {}
|
||||
impl ApplyEffect for String {}
|
||||
impl ApplyEffect for Generator {}
|
||||
|
||||
/// A color has no pixels for an effect to read, so an adjustment is carried out on the color itself with its kernel's mapping.
|
||||
impl ApplyEffect for Color {
|
||||
@@ -84,7 +86,7 @@ fn apply_effect<T: ApplyEffect>(content: Item<T>, operation: EffectOperation, pi
|
||||
fn blur<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to blur.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// How far the blur spreads each point of the content.
|
||||
#[unit(" px")]
|
||||
@@ -114,7 +116,7 @@ fn blur<T: ApplyEffect>(
|
||||
fn drop_shadow<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content casting the shadow.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The shadow's color, with its opacity.
|
||||
#[default("#00000080")]
|
||||
@@ -153,7 +155,7 @@ fn drop_shadow<T: ApplyEffect>(
|
||||
fn inner_shadow<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content the shadow falls inside.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The shadow's color, with its opacity.
|
||||
#[default("#00000080")]
|
||||
@@ -192,7 +194,7 @@ fn inner_shadow<T: ApplyEffect>(
|
||||
fn outer_glow<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to glow around.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The glow's color, with its opacity.
|
||||
#[default("#ffffbebf")]
|
||||
@@ -226,7 +228,7 @@ fn outer_glow<T: ApplyEffect>(
|
||||
fn inner_glow<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to glow within.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The glow's color, with its opacity.
|
||||
#[default("#ffffbebf")]
|
||||
@@ -263,7 +265,7 @@ fn inner_glow<T: ApplyEffect>(
|
||||
fn satin<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to shade.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The shading's color, with its opacity.
|
||||
#[default("#00000080")]
|
||||
@@ -301,7 +303,7 @@ fn satin<T: ApplyEffect>(
|
||||
fn outline<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to outline.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The outline's color, with its opacity.
|
||||
#[default(Color::BLACK)]
|
||||
@@ -334,7 +336,7 @@ fn outline<T: ApplyEffect>(
|
||||
fn bevel_and_emboss<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to raise.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// Where the slope lies: inside the edge, outside it, across it, or across it with the edge pressed in.
|
||||
style: Item<BevelStyle>,
|
||||
@@ -397,6 +399,40 @@ fn bevel_and_emboss<T: ApplyEffect>(
|
||||
)
|
||||
}
|
||||
|
||||
/// Paints over the input graphics within their shape, mixing the paint with their colors by a blend mode.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"))]
|
||||
fn paint_overlay<T: ApplyEffect>(
|
||||
_: impl Ctx,
|
||||
/// The content to paint over.
|
||||
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The color, gradient, image, or other graphic to paint with. A gradient or image without its own placement stretches across the content.
|
||||
#[default(Color::BLACK)]
|
||||
paint: Item<Graphic>,
|
||||
/// How the paint mixes with the content's colors.
|
||||
blend_mode: Item<BlendMode>,
|
||||
/// How strongly the paint shows.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
opacity: Item<f64>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<T>, Interrupt> {
|
||||
let (blend_mode, opacity) = (blend_mode.into_element(), opacity.into_element());
|
||||
|
||||
// The paint is the element alone, since the wire envelope's attributes would nest it as a group
|
||||
Ok(match paint.into_element() {
|
||||
Graphic::None(_) | Graphic::NoneList(_) => content,
|
||||
// A solid paint mixes the same into every pixel, as an adjustment
|
||||
Graphic::Color(color) => {
|
||||
let color = *color.element();
|
||||
T::apply_adjustment(content, Adjustment::ColorOverlay { color, blend_mode, opacity }, pipeline.element())?
|
||||
}
|
||||
paint => T::apply_effect(content, EffectOperation::PaintOverlay { paint, blend_mode, opacity }, pipeline.element())?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Uploads an image to the GPU and carries out its effects into the pixels, at the image's own resolution, for what comes next to run on the GPU right away.
|
||||
#[node_macro::node(category("Raster"), icon("NodeUploadTexture"))]
|
||||
fn eager(
|
||||
@@ -405,21 +441,56 @@ fn eager(
|
||||
image: Item<Raster<CPU>>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<Raster<GPU>>, Interrupt> {
|
||||
let pipeline = pipeline.element();
|
||||
let executor = pipeline.executor().cloned().ok_or_else(|| NodeError::new("A GPU is required to upload a raster"))?;
|
||||
Ok(upload_raster(image, pipeline.element())?)
|
||||
}
|
||||
|
||||
let (image, attributes) = image.into_parts();
|
||||
let uploaded: Raster<GPU> = image.convert(Footprint::DEFAULT, executor);
|
||||
/// The `input_adapter` row uploading a CPU raster wire for an input that only takes GPU rasters, by the same steps as the Eager node.
|
||||
/// The upload is kept until the wire carries other pixels or effects, so it's made once however often the consuming node runs.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn upload_item(_: impl Ctx, value: Item<Raster<CPU>>, pipeline: Item<WgpuPipelineCache>, #[data] cache: Arc<Mutex<Option<(u64, Item<Raster<GPU>>)>>>) -> Result<Item<Raster<GPU>>, Interrupt> {
|
||||
Ok(uploaded(cache, &value, || upload_raster(value.clone(), pipeline.element()))?)
|
||||
}
|
||||
|
||||
Ok(evaluate_raster_effects(Item::from_parts(uploaded, attributes), pipeline)?)
|
||||
/// The `List` counterpart of `upload_item`.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn upload_list(_: impl Ctx, value: List<Raster<CPU>>, pipeline: Item<WgpuPipelineCache>, #[data] cache: Arc<Mutex<Option<(u64, List<Raster<GPU>>)>>>) -> Result<List<Raster<GPU>>, Interrupt> {
|
||||
let upload = || value.clone().into_iter().map(|item| upload_raster(item, pipeline.element())).collect::<Result<List<_>, _>>();
|
||||
Ok(uploaded(cache, &value, upload)?)
|
||||
}
|
||||
|
||||
/// The `input_adapter` row passing a GPU raster wire through, taking the pipeline only since every row under one identifier takes the same inputs.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn pass_raster<'i, T: 'i + Send>(_: impl Ctx, value: T, _pipeline: Item<WgpuPipelineCache>) -> T {
|
||||
value
|
||||
}
|
||||
|
||||
/// The result of `upload` for `source`, reusing the last one if it was for the same pixels and effects.
|
||||
fn uploaded<S: CacheHash, T: Clone>(cache: &Mutex<Option<(u64, T)>>, source: &S, upload: impl FnOnce() -> Result<T, NodeError>) -> Result<T, NodeError> {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
source.cache_hash(&mut hasher);
|
||||
let hash = hasher.finish();
|
||||
|
||||
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some((_, result)) = cache.as_ref().filter(|(cached_hash, _)| *cached_hash == hash) {
|
||||
return Ok(result.clone());
|
||||
}
|
||||
|
||||
let result = upload()?;
|
||||
*cache = Some((hash, result.clone()));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::Node;
|
||||
use core_types::context::OwnedContextImpl;
|
||||
use core_types::list::ATTR_EFFECTS;
|
||||
use core_types::ops::ConvertAsync;
|
||||
use core_types::ops::{Convert, ConvertAsync};
|
||||
use core_types::poll::Poll;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::value::PrecomputedItemNode;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graphic_types::Effects;
|
||||
use graphic_types::raster_types::{Image, Storage};
|
||||
@@ -584,4 +655,74 @@ mod tests {
|
||||
assert_color(raster.data[0], Color::BLACK);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlay_multiplies_a_color_into_the_content() {
|
||||
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
|
||||
|
||||
let result = super::paint_overlay(
|
||||
(),
|
||||
Item::new_from_element(image_color),
|
||||
Item::new_from_element(Graphic::from(Color::GREEN)),
|
||||
BlendMode::Multiply.into(),
|
||||
100_f64.into(),
|
||||
Item::default(),
|
||||
);
|
||||
|
||||
// Multiplying by green keeps only the green channel, and the content keeps its own alpha
|
||||
assert_eq!(result.unwrap().into_element(), Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_input_adapter_uploads_a_raster_once_until_its_pixels_or_effects_change() {
|
||||
futures::executor::block_on(async {
|
||||
let Some(executor) = WgpuExecutor::new().await else { return };
|
||||
let pipeline = WgpuPipelineCache::default();
|
||||
executor.pipeline_init::<RasterKernelRuntime>(&pipeline);
|
||||
let pipeline = Item::new_from_element(pipeline);
|
||||
|
||||
let cache = Default::default();
|
||||
let upload = |item: &Item<Raster<CPU>>| super::upload_item((), &cache, item.clone(), pipeline.clone()).unwrap();
|
||||
|
||||
let plain = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE)));
|
||||
let first = upload(&plain);
|
||||
assert_eq!(upload(&plain).element().texture(), first.element().texture(), "the same pixels stay uploaded");
|
||||
|
||||
// Stamps carried out before anything reads the pixels, leaving none behind
|
||||
let inverted = Raster::<CPU>::apply_adjustment(plain, Adjustment::Invert, pipeline.element()).unwrap();
|
||||
let second = upload(&inverted);
|
||||
assert_ne!(second.element().texture(), first.element().texture(), "other effects are uploaded anew");
|
||||
assert!(second.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||
let raster: Raster<CPU> = second.into_element().convert(Footprint::DEFAULT, executor.clone()).await;
|
||||
assert_color(raster.data[0], Color::BLACK);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_input_adapter_keeps_its_upload_when_the_footprint_changes() {
|
||||
futures::executor::block_on(async {
|
||||
let Some(executor) = WgpuExecutor::new().await else { return };
|
||||
let pipeline = WgpuPipelineCache::default();
|
||||
executor.pipeline_init::<RasterKernelRuntime>(&pipeline);
|
||||
|
||||
let raster = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE)));
|
||||
let adapter = UploadItemNode::new(PrecomputedItemNode::new(raster), PrecomputedItemNode::new(Item::new_from_element(pipeline)));
|
||||
|
||||
let upload_under = |translation: DVec2| {
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_translation(translation),
|
||||
..Footprint::DEFAULT
|
||||
};
|
||||
let context = OwnedContextImpl::default().with_footprint(footprint).into_context();
|
||||
let Poll::Final(uploaded) = adapter.eval(&context) else {
|
||||
panic!("the upload should finish at once")
|
||||
};
|
||||
uploaded
|
||||
};
|
||||
|
||||
let first = upload_under(DVec2::ZERO);
|
||||
let panned = upload_under(DVec2::new(500., -300.));
|
||||
assert_eq!(panned.element().texture(), first.element().texture(), "panning shouldn't upload the raster again");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,17 @@ use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWar
|
||||
use crate::gpu_params;
|
||||
use crate::raster_kernel::{KernelFrame, RasterKernel, Wgsl, raster_kernel_pipeline, raster_placement, run_raster_kernel, union_frame};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::context::{Ctx, ExtractFootprint};
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::Item;
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::ops::Convert;
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::transform::Transform;
|
||||
use core_types::{Interrupt, NodeError};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::generator::{GeneratorPattern, NoiseSettings};
|
||||
use raster_types::Image;
|
||||
use raster_types::{GPU, Raster, Storage};
|
||||
use graphic_types::generator::{Generator, NoiseSettings};
|
||||
use raster_types::{CPU, GPU, Raster, Storage};
|
||||
use raster_types::{Image, ImageError};
|
||||
use wgpu_executor::WgpuPipelineCache;
|
||||
use wgpu_executor::raster_kernel::render_generator;
|
||||
|
||||
#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), name("Channels to Image"), memoize)]
|
||||
fn channels_to_image(
|
||||
@@ -204,25 +202,22 @@ fn image(
|
||||
/// The image file to display.
|
||||
#[widget(ParsedWidgetOverride::Custom = "image_file")]
|
||||
resource: Item<Resource>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<Raster<GPU>>, Interrupt> {
|
||||
) -> Result<Item<Raster<CPU>>, ImageError> {
|
||||
let resource = resource.into_element();
|
||||
if resource.is_empty() {
|
||||
return Ok(Item::default());
|
||||
}
|
||||
let image = Image::from_encoded(resource.as_ref()).map_err(NodeError::new)?;
|
||||
let image = Image::from_encoded(resource.as_ref())?;
|
||||
|
||||
let executor = pipeline.element().executor().cloned().ok_or_else(|| NodeError::new("A GPU is required to load an image"))?;
|
||||
Ok(Item::new_from_element(Raster::new_cpu(image).convert(Footprint::DEFAULT, executor)))
|
||||
Ok(Item::new_from_element(Raster::new_cpu(image)))
|
||||
}
|
||||
|
||||
/// Generates customizable procedural noise patterns.
|
||||
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn noise_pattern(
|
||||
ctx: impl ExtractFootprint + Ctx,
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[default(true)] clip: Item<bool>,
|
||||
#[hard(0..)] seed: Item<i64>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_scale")]
|
||||
#[default(10.)]
|
||||
@@ -252,90 +247,30 @@ fn noise_pattern(
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_cellular_jitter")]
|
||||
#[default(1.)]
|
||||
cellular_jitter: Item<f64>,
|
||||
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
|
||||
) -> Result<Item<Raster<GPU>>, Interrupt> {
|
||||
let (clip, seed, scale, domain_warp_amplitude) = (*clip.element(), *seed.element(), *scale.element(), *domain_warp_amplitude.element());
|
||||
let (fractal_octaves, fractal_lacunarity, fractal_gain) = (*fractal_octaves.element(), *fractal_lacunarity.element(), *fractal_gain.element());
|
||||
let (fractal_weighted_strength, fractal_ping_pong_strength, cellular_jitter) = (*fractal_weighted_strength.element(), *fractal_ping_pong_strength.element(), *cellular_jitter.element());
|
||||
let (noise_type, domain_warp_type, fractal_type) = (noise_type.into_element(), domain_warp_type.into_element(), fractal_type.into_element());
|
||||
let (cellular_distance_function, cellular_return_type) = (cellular_distance_function.into_element(), cellular_return_type.into_element());
|
||||
) -> Item<Generator> {
|
||||
let settings = NoiseSettings {
|
||||
seed: seed.into_element(),
|
||||
scale: scale.into_element(),
|
||||
noise_type: noise_type.into_element(),
|
||||
domain_warp_type: domain_warp_type.into_element(),
|
||||
domain_warp_amplitude: domain_warp_amplitude.into_element(),
|
||||
fractal_type: fractal_type.into_element(),
|
||||
fractal_octaves: fractal_octaves.into_element(),
|
||||
fractal_lacunarity: fractal_lacunarity.into_element(),
|
||||
fractal_gain: fractal_gain.into_element(),
|
||||
fractal_weighted_strength: fractal_weighted_strength.into_element(),
|
||||
fractal_ping_pong_strength: fractal_ping_pong_strength.into_element(),
|
||||
cellular_distance_function: cellular_distance_function.into_element(),
|
||||
cellular_return_type: cellular_return_type.into_element(),
|
||||
cellular_jitter: cellular_jitter.into_element(),
|
||||
};
|
||||
|
||||
let footprint = ctx.footprint();
|
||||
let viewport_bounds = footprint.viewport_bounds_in_local_space();
|
||||
|
||||
// TODO: Remove "clip" entirely (and its arbitrary 100x100 clipping square) once we have proper resolution-aware layer clipping
|
||||
const CLIPPING_SQUARE_SIZE: f64 = 100.;
|
||||
let logical_transform = if clip { DAffine2::from_scale(DVec2::splat(CLIPPING_SQUARE_SIZE)) } else { DAffine2::IDENTITY };
|
||||
|
||||
let mut size = viewport_bounds.size();
|
||||
let mut offset = viewport_bounds.start;
|
||||
if clip {
|
||||
let image_bounds = Bbox::from_transform(logical_transform).to_axis_aligned_bbox();
|
||||
let intersection = viewport_bounds.intersect(&image_bounds);
|
||||
|
||||
offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
|
||||
size = intersection.size();
|
||||
}
|
||||
|
||||
// If the image would not be visible, return an empty image
|
||||
if size.x <= 0. || size.y <= 0. {
|
||||
return Ok(Item::default().with_attribute(ATTR_TRANSFORM, logical_transform));
|
||||
}
|
||||
|
||||
let transform = DAffine2::from_translation(offset) * DAffine2::from_scale(size);
|
||||
|
||||
let footprint_scale = footprint.scale();
|
||||
let width = (size.x * footprint_scale.x) as u32;
|
||||
let height = (size.y * footprint_scale.y) as u32;
|
||||
if width == 0 || height == 0 {
|
||||
return Ok(Item::default().with_attribute(ATTR_TRANSFORM, logical_transform));
|
||||
}
|
||||
|
||||
let noise = GeneratorPattern::Noise(NoiseSettings {
|
||||
seed,
|
||||
scale,
|
||||
noise_type,
|
||||
domain_warp_type,
|
||||
domain_warp_amplitude,
|
||||
fractal_type,
|
||||
fractal_octaves,
|
||||
fractal_lacunarity,
|
||||
fractal_gain,
|
||||
fractal_weighted_strength,
|
||||
fractal_ping_pong_strength,
|
||||
cellular_distance_function,
|
||||
cellular_return_type,
|
||||
cellular_jitter,
|
||||
});
|
||||
let raster = render_generator(&noise, [offset, offset + size], UVec2::new(width, height), pipeline.element())?;
|
||||
|
||||
Ok(Item::new_from_element(raster.with_coverage(logical_transform.inverse() * transform)).with_attribute(ATTR_TRANSFORM, logical_transform))
|
||||
let mut generator = Item::new_from_element(Generator::Noise);
|
||||
settings.stamp(&mut generator);
|
||||
generator
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"))]
|
||||
fn mandelbrot(ctx: impl ExtractFootprint + Send, #[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>) -> Result<Item<Raster<GPU>>, Interrupt> {
|
||||
let footprint = ctx.footprint();
|
||||
let viewport_bounds = footprint.viewport_bounds_in_local_space();
|
||||
|
||||
let image_bounds = Bbox::from_transform(DAffine2::IDENTITY).to_axis_aligned_bbox();
|
||||
let intersection = viewport_bounds.intersect(&image_bounds);
|
||||
let size = intersection.size();
|
||||
|
||||
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
|
||||
|
||||
// If the image would not be visible, return an empty image
|
||||
if size.x <= 0. || size.y <= 0. {
|
||||
return Ok(Item::default());
|
||||
}
|
||||
|
||||
let scale = footprint.scale();
|
||||
let width = (size.x * scale.x) as u32;
|
||||
let height = (size.y * scale.y) as u32;
|
||||
if width == 0 || height == 0 {
|
||||
return Ok(Item::default());
|
||||
}
|
||||
|
||||
let raster = render_generator(&GeneratorPattern::Mandelbrot, [offset, offset + size], UVec2::new(width, height), pipeline.element())?;
|
||||
|
||||
Ok(Item::new_from_element(raster.with_coverage(DAffine2::from_translation(offset) * DAffine2::from_scale(size))))
|
||||
fn mandelbrot(_: impl Ctx, _primary: ()) -> Item<Generator> {
|
||||
Item::new_from_element(Generator::Mandelbrot)
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use core_types::list::{Item, List};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, Interrupt, LazyInput, Node, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
@@ -53,10 +54,11 @@ fn repeat<T: Send + Clone + 'static>(
|
||||
Context -> List<DAffine2>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
@@ -98,10 +100,11 @@ fn repeat_array<T: Send + Clone + 'static>(
|
||||
Context -> List<DAffine2>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
@@ -160,10 +163,11 @@ fn repeat_radial<T: Send + Clone + 'static>(
|
||||
Context -> List<DAffine2>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
@@ -220,10 +224,11 @@ fn repeat_on_points<T: Send + Clone + 'static>(
|
||||
Context -> List<DAffine2>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
|
||||
@@ -5,7 +5,7 @@ use core_types::transform::{ApplyTransform, ScaleType, Transform};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, Interrupt, LazyInput, ModifyFootprint, Node, OwnedContextImpl};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use graphic_types::{Artboard, Generator, Graphic, Vector};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies the specified transform to the input content.
|
||||
@@ -18,10 +18,11 @@ fn transform<T: Send + 'static>(
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<String>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = Item<T>>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: Item<DVec2>,
|
||||
@@ -95,8 +96,8 @@ fn reset_transform<T: 'static>(
|
||||
#[implementations(
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<String>,
|
||||
@@ -143,8 +144,8 @@ fn replace_transform<T: 'static>(
|
||||
#[implementations(
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<String>,
|
||||
@@ -182,7 +183,7 @@ fn replaced_transform_context<T, N: Node<Context<'static>, Output = Item<T>>>(
|
||||
|
||||
/// Obtains the transform of the input content.
|
||||
#[node_macro::node(category("Transform"), icon("NodeExtractTransform"), path(core_types::vector))]
|
||||
fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<GPU>, Raster<CPU>, Color, Gradient, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
|
||||
fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, Generator, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
|
||||
Item::new_from_element(content.attribute_cloned_or_default(ATTR_TRANSFORM))
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::Vector;
|
||||
use graphic_types::graphic::{bake_paint_transforms, is_paint_present};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Appearance, Cover, CoverPlacement, Coverage, Graphic, IntoGraphicList, stamp_coverage};
|
||||
use graphic_types::{Appearance, Cover, CoverPlacement, Coverage, Generator, Graphic, IntoGraphicList, stamp_coverage};
|
||||
use kurbo::simplify::{SimplifyOptions, simplify_bezpath};
|
||||
use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Shape};
|
||||
use rand::{Rng, SeedableRng};
|
||||
@@ -553,10 +553,11 @@ fn copy_to_points<I: Send + Clone>(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<String>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<I>>,
|
||||
/// Minimum range of randomized sizes given to each placed copy.
|
||||
@@ -1263,8 +1264,8 @@ fn pack_strips<T: Send + Clone>(
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<Raster<GPU>>,
|
||||
List<Raster<CPU>>,
|
||||
List<Raster<GPU>>,
|
||||
)]
|
||||
elements: List<T>,
|
||||
#[default(0.)]
|
||||
|
||||
@@ -25,6 +25,7 @@ interpreted-executor = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Workspace dependencies
|
||||
interpreted-executor = { workspace = true, features = ["gpu"] }
|
||||
core-types = { workspace = true }
|
||||
dyn-any = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
|
||||
@@ -216,8 +216,17 @@ impl Preprocessor {
|
||||
generated_nodes += 1;
|
||||
let mut original_location = OriginalLocation::default();
|
||||
original_location.auto_convert_index = Some(i);
|
||||
// An adapter whose rows also take a second input gets the pipeline, which it uploads a CPU raster wire with
|
||||
let takes_pipeline = into_node_registry
|
||||
.get(&input_adapter_identifier)
|
||||
.is_some_and(|rows| rows.keys().any(|node_io| node_io.inputs.len() == 2));
|
||||
let mut adapter_inputs = vec![NodeInput::import(generic!(X), i)];
|
||||
if takes_pipeline {
|
||||
adapter_inputs.push(NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER));
|
||||
}
|
||||
|
||||
let document_node = DocumentNode {
|
||||
inputs: vec![NodeInput::import(generic!(X), i)],
|
||||
inputs: adapter_inputs,
|
||||
implementation: DocumentNodeImplementation::ProtoNode(input_adapter_identifier),
|
||||
visible: true,
|
||||
compile_metadata: forwarding,
|
||||
@@ -689,6 +698,8 @@ pub fn input_adapter_identifier<Implementations>(input_types: &HashSet<Type>, no
|
||||
_ => collapse_item_list_pair(input_types)?,
|
||||
};
|
||||
let element_name = match input_type.nested_type() {
|
||||
// Type names drop the generics that tell a GPU raster from a CPU one
|
||||
Type::Item(element) | Type::List(element) if **element == concrete!(raster_types::Raster<raster_types::GPU>) => "Raster<GPU>".to_string(),
|
||||
Type::Item(element) | Type::List(element) => element.identifier_name(),
|
||||
nested if nested.identifier_name() == "ListDyn" => "ListDyn".to_string(),
|
||||
_ => return None,
|
||||
@@ -829,4 +840,83 @@ mod tests {
|
||||
assert!(compile_metadata(&identifier).forwards_input, "{identifier:?} should forward its input");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cpu_raster_wire_uploads_through_one_adapter_that_ignores_the_footprint() {
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::item;
|
||||
use graph_craft::proto::TypingContext;
|
||||
use graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline;
|
||||
use graphene_std::raster_nodes::std_nodes::channels_to_image;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct NoSpawner;
|
||||
impl Spawn for NoSpawner {
|
||||
fn spawn(&self, _: Task) {}
|
||||
}
|
||||
|
||||
// A CPU raster wired to all four of a node's inputs which only take GPU rasters
|
||||
let source = NodeId(0);
|
||||
let wire = || NodeInput::node(source, 0);
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
(
|
||||
source,
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::TypeDefault(item!(Raster<CPU>)), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ops::passthrough::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
NodeId(1),
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
wire(),
|
||||
wire(),
|
||||
wire(),
|
||||
wire(),
|
||||
NodeInput::scope(raster_kernel_pipeline::IDENTIFIER),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(channels_to_image::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let runtime = AsyncRuntime::new(Arc::new(NoSpawner), Arc::new(std::time::Instant::now()));
|
||||
let mut network = wrap_network_in_scope(network, Arc::new(PlatformEditorApi::default()), runtime.handle());
|
||||
Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = Compiler {}.compile_single(network).unwrap().network;
|
||||
|
||||
// The compiled graph type checks, since a CPU raster feeds the GPU-only inputs through the adapter
|
||||
let mut typing_context = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&proto_network).expect("the CPU raster wire should reach the GPU-only inputs");
|
||||
|
||||
let identifier = ProtoNodeIdentifier::new("input_adapter<Raster<GPU>>");
|
||||
let adapters: Vec<_> = proto_network.nodes.iter().filter(|(_, node)| node.identifier == identifier).collect();
|
||||
let distinct_ids: HashSet<_> = adapters.iter().map(|(id, _)| *id).collect();
|
||||
assert_eq!(
|
||||
distinct_ids.len(),
|
||||
1,
|
||||
"the identical adapters of the four inputs should share one stable ID, and so one node in the executor"
|
||||
);
|
||||
|
||||
let (_, adapter) = adapters[0];
|
||||
assert!(
|
||||
!adapter.upstream_context_features.contains(core_types::ContextFeatures::FOOTPRINT),
|
||||
"neither the adapter nor what feeds it should read the footprint, leaving it unaffected by panning"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user