mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7469ecce35 | ||
|
|
d69b21f035 | ||
|
|
7e2e1fe028 | ||
|
|
12daaf8ab0 | ||
|
|
c465a3ebea | ||
|
|
8bcafc9dec | ||
|
|
0fbc09eabd | ||
|
|
017234b15b | ||
|
|
5f48595604 | ||
|
|
7aba423a2e | ||
|
|
16774db9c2 | ||
|
|
a4c0cb5c31 |
No files matched your search
Generated
+5
-3
@@ -5772,12 +5772,14 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8084,7 +8086,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -8099,7 +8101,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -8113,7 +8115,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
|
||||
+3
-3
@@ -315,6 +315,6 @@ debug = true
|
||||
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
|
||||
fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
@@ -1,63 +0,0 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
GradientModel(GradientModel),
|
||||
GradientDirection(GradientDirection),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GradientModel {
|
||||
Standard,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GradientDirection {
|
||||
Along,
|
||||
}
|
||||
|
||||
/// 'Fill' gained the model and direction it gives the gradient it paints, set to the Standard model and the Along direction a gradient without them already has.
|
||||
#[migration("graphene_core::vector::FillNode"@2 => @3)]
|
||||
pub fn fill_v2(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// The model and the direction.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::GradientModel(GradientModel::Standard)), literal(Tagged::GradientDirection(GradientDirection::Along))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&FillV2, &contract());
|
||||
check_undo(&FillV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_the_default_model_and_direction() {
|
||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&FillV2);
|
||||
let fill = fixture.add(decl!("graphene_core::vector::FillNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&FillV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, fill), Some(decl!("graphene_core::vector::FillNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, fill), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Migrations of the nodes in `graphene_core`.
|
||||
|
||||
mod fill_v1;
|
||||
mod fill_v2;
|
||||
mod passthrough_from_read_attribute_gradient_form_node;
|
||||
mod passthrough_from_upload_texture_node;
|
||||
mod renames;
|
||||
|
||||
@@ -6,5 +6,6 @@ mod mandelbrot_v2;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod noise_pattern_v2;
|
||||
mod passthrough_from_extend_image_to_bounds;
|
||||
mod pattern_square;
|
||||
mod renames;
|
||||
@@ -0,0 +1,36 @@
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// 'Extend Image to Bounds' is gone, and the transparent pixels it padded an image with drew nothing, so it passes its image on and drops its bounds.
|
||||
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
||||
pub fn passthrough_from_extend_image_to_bounds(inputs: &mut Inputs) {
|
||||
inputs.truncate(1);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PassthroughFromExtendImageToBounds, &contract());
|
||||
check_undo(&PassthroughFromExtendImageToBounds, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_image_and_drops_the_bounds() {
|
||||
let (image, bounds) = (literal(1.), literal(2.));
|
||||
|
||||
let mut fixture = Fixture::new(&PassthroughFromExtendImageToBounds);
|
||||
let extend = fixture.add(decl!("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1), vec![image.clone(), bounds]);
|
||||
let migrated = fixture.migrate(&PassthroughFromExtendImageToBounds).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, extend), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, extend), [image]);
|
||||
}
|
||||
}
|
||||
@@ -4,3 +4,12 @@ use migration_core::rename;
|
||||
|
||||
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
|
||||
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
|
||||
|
||||
// 'Image to Channels' became 'Into Channels', taking and giving graphics, whose stored input and channel outputs keep their places
|
||||
rename!("raster_nodes::adjustments::ImageToChannelsNode"@1 => "raster_nodes::channels::IntoChannelsNode"@2);
|
||||
|
||||
// 'Channels to Image' became 'From Channels', taking and giving graphics, whose stored inputs and output keep their places
|
||||
rename!("raster_nodes::std_nodes::ChannelsToImageNode"@1 => "raster_nodes::channels::FromChannelsNode"@2);
|
||||
|
||||
// 'Median Filter' became an effect taking any graphic, whose stored image and radius keep their places
|
||||
rename!("raster_nodes::filter::MedianFilterNode"@1 => @2);
|
||||
@@ -148,24 +148,10 @@ pub const CURVATURE_COMB_MAX_TEETH_PER_SEGMENT: f64 = 128.;
|
||||
pub const CURVATURE_COMB_MAX_TOOTH_LENGTH: f64 = 2000.;
|
||||
|
||||
// GRADIENT TOOL
|
||||
pub const GRADIENT_LINE_WIDTH: f64 = 2.;
|
||||
// Half the height of a midpoint diamond across the gradient line
|
||||
pub const GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT: f64 = 5.;
|
||||
// Half the width of a midpoint diamond along the gradient line
|
||||
pub const GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH: f64 = 3.;
|
||||
// The radius of the circle approximating a midpoint diamond, which a press is measured against
|
||||
pub const GRADIENT_MIDPOINT_DIAMOND_RADIUS: f64 = 4.;
|
||||
// The radius of a color stop dot at its regular size, which a press is measured against
|
||||
pub const GRADIENT_STOP_RADIUS: f64 = MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1.;
|
||||
pub const GRADIENT_MIDPOINT_MIN: f64 = 0.01;
|
||||
pub const GRADIENT_MIDPOINT_MAX: f64 = 0.99;
|
||||
pub const GRADIENT_STOP_MIN_VIEWPORT_GAP: f64 = 10.;
|
||||
// In viewport pixels from a contour's dashed rim, within which a press takes hold of it
|
||||
pub const GRADIENT_CONTOUR_RIM_GRAB_DISTANCE: f64 = 5.;
|
||||
// In viewport pixels, within which a dragged contour handle snaps onto making its contour a line or a point
|
||||
pub const GRADIENT_CONTOUR_SNAP_DISTANCE: f64 = 4.;
|
||||
// In viewport pixels, the shortest an end circle's semi-minor axis lines are drawn, below which they have no aspect handles at their tips
|
||||
pub const GRADIENT_SEMI_MINOR_AXIS_MIN_LENGTH: f64 = 20.;
|
||||
|
||||
// PEN TOOL
|
||||
pub const CREATE_CURVE_THRESHOLD: f64 = 5.;
|
||||
|
||||
@@ -31,8 +31,8 @@ use graphene_std::vector::misc::{
|
||||
WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign,
|
||||
StrokeCap, StrokeJoin,
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
|
||||
StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{
|
||||
@@ -470,7 +470,6 @@ macro_rules! inspectable_types {
|
||||
Item<BlendMode>,
|
||||
Item<GradientForm>,
|
||||
Item<GradientModel>,
|
||||
Item<GradientDirection>,
|
||||
Item<GradientSpread>,
|
||||
Item<GradientSpace>,
|
||||
Item<GradientHueDirection>,
|
||||
@@ -1287,7 +1286,6 @@ impl_table_item_layout_for_choice_enum!(
|
||||
MinimumMaximumMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientDirection,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -1484,7 +1482,6 @@ macro_rules! known_item_types {
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientDirection,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
|
||||
@@ -7,7 +7,7 @@ use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, VectorModificationType};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -57,19 +57,6 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
gradient_form: GradientForm,
|
||||
},
|
||||
GradientCurvatureSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
/// The start and end curvatures.
|
||||
curvatures: [f64; 2],
|
||||
},
|
||||
GradientModelSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
model: GradientModel,
|
||||
},
|
||||
GradientDirectionSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
direction: GradientDirection,
|
||||
},
|
||||
GradientSpreadSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
gradient_spread: GradientSpread,
|
||||
|
||||
-15
@@ -86,21 +86,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
modify_inputs.gradient_form_set(gradient_form);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientCurvatureSet { layer, curvatures } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_curvature_set(curvatures);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientModelSet { layer, model } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_model_set(model);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientDirectionSet { layer, direction } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_direction_set(direction);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientSpreadSet { layer, gradient_spread } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_spread_set(gradient_spread);
|
||||
|
||||
@@ -6,8 +6,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{
|
||||
ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_fill_node_id_with_direct_fill_input, get_upstream_gradient_value_node_id, gradient_chain_target_input,
|
||||
gradient_curvature_values, replaceable_paint_chain,
|
||||
ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, gradient_curvature_values, replaceable_paint_chain,
|
||||
};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
@@ -16,7 +15,7 @@ use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, list};
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic};
|
||||
use kurbo::BezPath;
|
||||
@@ -493,8 +492,19 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
// Only a chosen form sets the curvatures, leaving any the graph feeds or that already make it
|
||||
if let Some(gradient_form) = gradient_form {
|
||||
self.write_fill_curvatures(fill_node_id, gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form));
|
||||
let curvatures = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
|
||||
if let Some(gradient_form) = gradient_form
|
||||
&& curvatures.is_some_and(|curvatures| GradientForm::from_curvatures(curvatures) != Some(gradient_form))
|
||||
{
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let [start_curvature, end_curvature] = gradient_form.curvatures();
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, StartCurvatureInput),
|
||||
NodeInput::value(TaggedValue::Number(start_curvature), false),
|
||||
true,
|
||||
);
|
||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end_curvature), false), true);
|
||||
}
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
|
||||
@@ -503,20 +513,6 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Write both curvatures to a Fill node's hidden curvature inputs unless the graph feeds them or its current ones are `already_written`, for the caller to then run the graph.
|
||||
fn write_fill_curvatures(&mut self, fill_node_id: NodeId, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) {
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let current = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
|
||||
if current.is_none_or(already_written) {
|
||||
return;
|
||||
}
|
||||
|
||||
let [start, end] = curvatures;
|
||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
|
||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), true);
|
||||
}
|
||||
|
||||
/// A freshly created Fill node lands at the chain start, downstream of any Stroke node, where it would
|
||||
/// paint over the stroke. This hops the stroke back downstream so it keeps painting above by default.
|
||||
fn restore_default_stroke_order(&mut self) {
|
||||
@@ -780,95 +776,27 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
/// 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`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched.
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
self.write_gradient_curvatures(gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form));
|
||||
}
|
||||
|
||||
/// Write both curvatures to the layer's gradient: a Fill node holding it, or else the last 'Gradient Curvature' node in its chain, inserting
|
||||
/// one only when they differ from the default form's (`Linear`). Curvatures fed from the graph (procedural authorship) are left untouched.
|
||||
pub fn gradient_curvature_set(&mut self, curvatures: [f64; 2]) {
|
||||
if let Some(output_layer) = self.get_output_layer()
|
||||
&& let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(output_layer, self.network_interface)
|
||||
{
|
||||
self.write_fill_curvatures(fill_node_id, curvatures, |current| current == curvatures);
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
return;
|
||||
}
|
||||
|
||||
self.write_gradient_curvatures(curvatures, |current| current == curvatures);
|
||||
}
|
||||
|
||||
/// Write these curvatures to the last 'Gradient Curvature' node in the chain unless its current ones are `already_written`.
|
||||
fn write_gradient_curvatures(&mut self, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let create_if_nonexistent = curvatures != GradientForm::default().curvatures();
|
||||
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 {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return };
|
||||
let Some(current) = gradient_curvature_values(node) else { return };
|
||||
if already_written(current) {
|
||||
let Some(curvatures) = gradient_curvature_values(node) else { return };
|
||||
if GradientForm::from_curvatures(curvatures) == Some(gradient_form) {
|
||||
return;
|
||||
}
|
||||
|
||||
let [start, end] = curvatures;
|
||||
let [start, end] = gradient_form.curvatures();
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
}
|
||||
|
||||
/// Set the model of the layer's gradient, as [`Self::gradient_choice_set`] sets a choice.
|
||||
pub fn gradient_model_set(&mut self, model: GradientModel) {
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::math_nodes::gradient_model;
|
||||
|
||||
let value = TaggedValue::GradientModel(model);
|
||||
let fill_input = graphene_std::vector::fill::ModelInput::INDEX;
|
||||
self.gradient_choice_set(fill_input, gradient_model::IDENTIFIER, gradient_model::ModelInput::INDEX, value, model == GradientModel::default());
|
||||
}
|
||||
|
||||
/// Set the direction of the layer's gradient, as [`Self::gradient_choice_set`] sets a choice.
|
||||
pub fn gradient_direction_set(&mut self, direction: GradientDirection) {
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::math_nodes::gradient_direction;
|
||||
|
||||
let value = TaggedValue::GradientDirection(direction);
|
||||
let fill_input = graphene_std::vector::fill::DirectionInput::INDEX;
|
||||
self.gradient_choice_set(
|
||||
fill_input,
|
||||
gradient_direction::IDENTIFIER,
|
||||
gradient_direction::DirectionInput::INDEX,
|
||||
value,
|
||||
direction == GradientDirection::default(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Set a choice of how the layer's gradient is drawn: in the Fill node's input at `fill_input` where the Fill holds the gradient as a value, or else in the input at
|
||||
/// `node_input` of the last node of this `identifier` in the chain, inserting one only for a value other than the default. A choice the graph feeds is left as it is.
|
||||
fn gradient_choice_set(&mut self, fill_input: usize, identifier: ProtoNodeIdentifier, node_input: usize, value: TaggedValue, is_default: bool) {
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let (node_id, input_index) = match get_fill_node_id_with_direct_fill_input(output_layer, self.network_interface) {
|
||||
Some(fill_node_id) => (fill_node_id, fill_input),
|
||||
None => {
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, !is_default) else {
|
||||
return;
|
||||
};
|
||||
(node_id, node_input)
|
||||
}
|
||||
};
|
||||
|
||||
let node = self.network_interface.document_network().nodes.get(&node_id);
|
||||
let current = node.and_then(|node| node.inputs.get(input_index)).and_then(NodeInput::as_non_exposed_value);
|
||||
if current.is_some_and(|current| *current != value) {
|
||||
self.set_input_with_refresh(InputConnector::node_at_index(node_id, input_index), NodeInput::value(value, false), false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||
pub fn gradient_spread_set(&mut self, gradient_spread: GradientSpread) {
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
@@ -37,8 +37,8 @@ use graphene_std::vector::misc::{
|
||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
FillChoice, Gradient, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops,
|
||||
StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign,
|
||||
StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
@@ -435,7 +435,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
// =========================
|
||||
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientModel>(x) => enum_choice::<GradientModel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientDirection>(x) => enum_choice::<GradientDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::consts::{
|
||||
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLACK, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_WHITE_05, COLOR_OVERLAY_YELLOW,
|
||||
COLOR_OVERLAY_YELLOW_DULL, COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, CURVATURE_COMB_DEFAULT_SCALE,
|
||||
DOWEL_PIN_RADIUS, GRADIENT_LINE_WIDTH, GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT, GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH, GRADIENT_STOP_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH,
|
||||
PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
|
||||
DOWEL_PIN_RADIUS, GRADIENT_MIDPOINT_DIAMOND_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET,
|
||||
SKEW_TRIANGLE_SIZE,
|
||||
};
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::hex_to_rgba_u8;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -24,7 +24,7 @@ use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::misc::point_to_dvec2;
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, Color, NodeParameter};
|
||||
use graphene_std::{ATTR_TRANSFORM, NodeParameter};
|
||||
use kurbo::{self, BezPath, ParamCurve};
|
||||
use kurbo::{Affine, PathSeg};
|
||||
use std::borrow::Cow;
|
||||
@@ -404,12 +404,6 @@ impl OverlayContext {
|
||||
self.record(move |overlays| overlays.dashed_polygon(&polygon, stroke_color.as_deref(), color_fill.as_deref(), dash_width, dash_gap_width, dash_offset));
|
||||
}
|
||||
|
||||
/// Strokes the open path through these points, unlike [`Self::dashed_polygon`], which closes it.
|
||||
pub fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
let (points, color) = (points.to_vec(), owned(color));
|
||||
self.record(move |overlays| overlays.dashed_polyline(&points, color.as_deref(), dash_width, dash_gap_width, dash_offset));
|
||||
}
|
||||
|
||||
pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.line(start, end, color.as_deref(), thickness));
|
||||
@@ -434,12 +428,6 @@ impl OverlayContext {
|
||||
self.record(move |overlays| overlays.manipulator_handle(position, selected, color.as_deref()));
|
||||
}
|
||||
|
||||
/// Draws a handle like [`Self::manipulator_handle`] outlined in `color`, and filled with it too where `selected`.
|
||||
pub fn colored_manipulator_handle(&mut self, position: DVec2, selected: bool, color: &str) {
|
||||
let color = color.to_owned();
|
||||
self.record(move |overlays| overlays.filled_manipulator_handle(position, if selected { &color } else { COLOR_OVERLAY_WHITE }, &color));
|
||||
}
|
||||
|
||||
pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.manipulator_anchor(position, selected, color.as_deref()));
|
||||
@@ -450,15 +438,8 @@ impl OverlayContext {
|
||||
self.record(move |overlays| overlays.gradient_color_stop(position, emphasis, &color, small));
|
||||
}
|
||||
|
||||
/// Draws a gradient midpoint's diamond filled with `color`, taller across the gradient line at `angle` than it is wide, bordered like a color stop's dot.
|
||||
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
|
||||
let color = color.to_owned();
|
||||
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, &color, angle));
|
||||
}
|
||||
|
||||
/// Draws a line in a gradient's own colors, from its color `stops` at fractions of the way from `start` to `end`, outlined in white and then black like its color stops.
|
||||
pub fn gradient_line(&mut self, start: DVec2, end: DVec2, stops: Vec<(f64, Color)>) {
|
||||
self.record(move |overlays| overlays.gradient_line(start, end, &stops));
|
||||
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
|
||||
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, angle));
|
||||
}
|
||||
|
||||
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
|
||||
@@ -804,24 +785,6 @@ impl OverlayContextInternal {
|
||||
self.stroke_in_view(&stroke, Self::parse_color(stroke_color), &path);
|
||||
}
|
||||
|
||||
fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
let mut points = points.iter().map(|&point| self.snap_to_physical_pixel_center(point));
|
||||
let Some(first) = points.next() else { return };
|
||||
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(kurbo::Point::new(first.x, first.y));
|
||||
for point in points {
|
||||
path.line_to(kurbo::Point::new(point.x, point.y));
|
||||
}
|
||||
|
||||
let mut stroke = kurbo::Stroke::new(1.);
|
||||
if let Some(dash_width) = dash_width {
|
||||
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap_width.unwrap_or(1.)]);
|
||||
}
|
||||
|
||||
self.stroke_in_view(&stroke, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), &path);
|
||||
}
|
||||
|
||||
fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
|
||||
self.dashed_line(start, end, color, thickness, None, None, None)
|
||||
}
|
||||
@@ -846,17 +809,16 @@ impl OverlayContextInternal {
|
||||
}
|
||||
|
||||
fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
|
||||
self.filled_manipulator_handle(position, fill, color.unwrap_or(COLOR_OVERLAY_BLUE));
|
||||
}
|
||||
|
||||
fn filled_manipulator_handle(&mut self, position: DVec2, fill: &str, stroke: &str) {
|
||||
let transform = self.get_transform();
|
||||
let position = self.snap_to_physical_pixel_center(position);
|
||||
|
||||
let circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.);
|
||||
|
||||
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &circle);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(stroke), None, &circle);
|
||||
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &circle);
|
||||
}
|
||||
|
||||
fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
|
||||
@@ -898,7 +860,7 @@ impl OverlayContextInternal {
|
||||
GizmoEmphasis::Active => 1.,
|
||||
};
|
||||
let stroke_width = radius_offset * 2. + 1.;
|
||||
let radius = (GRADIENT_STOP_RADIUS + radius_offset) * if small { 0.5 } else { 1. };
|
||||
let radius = (MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1. + radius_offset) * if small { 0.5 } else { 1. };
|
||||
|
||||
let mut draw_circle = |radius: f64, width: Option<f64>, color: &str| {
|
||||
let circle = kurbo::Circle::new((position.x, position.y), radius);
|
||||
@@ -916,59 +878,33 @@ impl OverlayContextInternal {
|
||||
draw_circle(radius, Some(stroke_width), COLOR_OVERLAY_WHITE);
|
||||
}
|
||||
|
||||
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
|
||||
let position = position.round() - DVec2::splat(0.5);
|
||||
let transform = self.get_transform() * kurbo::Affine::translate((position.x, position.y)) * kurbo::Affine::rotate(angle);
|
||||
|
||||
// Grown for emphasis with a thicker white border, as a color stop's dot is
|
||||
let radius_offset = match emphasis {
|
||||
GizmoEmphasis::Regular => 0.,
|
||||
GizmoEmphasis::Hovered => 0.5,
|
||||
GizmoEmphasis::Active => 1.,
|
||||
};
|
||||
let stroke_width = radius_offset * 2. + 1.;
|
||||
|
||||
// Taller across the gradient line than it is wide along it
|
||||
let (half_width, half_height) = (GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH + radius_offset, GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT + radius_offset);
|
||||
let mut diamond = BezPath::new();
|
||||
diamond.move_to((half_width, 0.));
|
||||
diamond.line_to((0., half_height));
|
||||
diamond.line_to((-half_width, 0.));
|
||||
diamond.line_to((0., -half_height));
|
||||
diamond.close_path();
|
||||
|
||||
// The black border shows half a pixel past the white one, as around a color stop's dot
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(stroke_width + 1.), transform, Self::parse_color(COLOR_OVERLAY_BLACK), None, &diamond);
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color), None, &diamond);
|
||||
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &diamond);
|
||||
}
|
||||
|
||||
fn gradient_line(&mut self, start: DVec2, end: DVec2, stops: &[(f64, Color)]) {
|
||||
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
|
||||
let transform = self.get_transform();
|
||||
let position = position.round() - DVec2::splat(0.5);
|
||||
|
||||
// Centered on whole pixels, the even widths have crisp edges
|
||||
let [start, end] = [start, end].map(|point| self.snap_to_physical_pixel(point));
|
||||
let line = kurbo::Line::new((start.x, start.y), (end.x, end.y));
|
||||
// Rotate diamond points by the gradient line angle
|
||||
let (sin, cos) = angle.sin_cos();
|
||||
let rotate = |dx: f64, dy: f64| DVec2::new(dx * cos - dy * sin, dx * sin + dy * cos);
|
||||
|
||||
// Bordered like a color stop's dot, by a pixel of white and then half a pixel of black
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH + 3.), transform, Self::parse_color(COLOR_OVERLAY_BLACK), None, &line);
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH + 2.), transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &line);
|
||||
let top = rotate(0., -GRADIENT_MIDPOINT_DIAMOND_RADIUS);
|
||||
let right = rotate(GRADIENT_MIDPOINT_DIAMOND_RADIUS, 0.);
|
||||
let bottom = rotate(0., GRADIENT_MIDPOINT_DIAMOND_RADIUS);
|
||||
let left = rotate(-GRADIENT_MIDPOINT_DIAMOND_RADIUS, 0.);
|
||||
|
||||
// Opaque like the stops' dots
|
||||
let stops = stops.iter().map(|&(offset, color)| {
|
||||
let [red, green, blue, _] = color.to_gamma_srgb_channels();
|
||||
peniko::ColorStop {
|
||||
offset: offset as f32,
|
||||
color: peniko::color::DynamicColor::from_alpha_color(peniko::Color::new([red, green, blue, 1.])),
|
||||
}
|
||||
});
|
||||
let mut gradient = peniko::Gradient::new_linear((start.x, start.y), (end.x, end.y));
|
||||
gradient.stops = peniko::ColorStops(stops.collect());
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(kurbo::Point::new(position.x + top.x, position.y + top.y));
|
||||
path.line_to(kurbo::Point::new(position.x + right.x, position.y + right.y));
|
||||
path.line_to(kurbo::Point::new(position.x + bottom.x, position.y + bottom.y));
|
||||
path.line_to(kurbo::Point::new(position.x + left.x, position.y + left.y));
|
||||
path.close_path();
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH), transform, &gradient, None, &line);
|
||||
let (fill, stroke_width) = match emphasis {
|
||||
GizmoEmphasis::Regular => (COLOR_OVERLAY_WHITE, 1.),
|
||||
GizmoEmphasis::Hovered => (COLOR_OVERLAY_WHITE, 2.),
|
||||
GizmoEmphasis::Active => (COLOR_OVERLAY_BLUE, 1.),
|
||||
};
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &path);
|
||||
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
|
||||
}
|
||||
|
||||
fn resize_handle(&mut self, position: DVec2, rotation: f64) {
|
||||
|
||||
@@ -975,7 +975,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
|
||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||
let fill_node = &network.nodes[&node_id];
|
||||
|
||||
assert_eq!(fill_node.inputs.len(), 10, "the legacy Fill should upgrade to the 10-input shape");
|
||||
assert_eq!(fill_node.inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape");
|
||||
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
|
||||
assert!(
|
||||
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
|
||||
@@ -1033,7 +1033,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
|
||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||
let fill_node = &network.nodes[&node_id];
|
||||
|
||||
assert_eq!(fill_node.inputs.len(), 10, "the eight-input Fill should come out in the modern 10-input shape");
|
||||
assert_eq!(fill_node.inputs.len(), 8, "the eight-input Fill should come out in the modern shape, which also has eight inputs");
|
||||
let curvatures = [graphene_std::vector::fill::StartCurvatureInput::INDEX, graphene_std::vector::fill::EndCurvatureInput::INDEX].map(|index| fill_node.inputs[index].as_value().cloned());
|
||||
assert_eq!(
|
||||
curvatures,
|
||||
|
||||
@@ -121,6 +121,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_std::raster::SampleImageNode",
|
||||
"graphene_std::raster::SampleNode",
|
||||
"raster_nodes::std_nodes::SampleImageNode",
|
||||
// The deleted Extend Image to Bounds passes its image through, since the transparent pixels it padded with drew nothing
|
||||
"graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
||||
"graphene_std::raster::ExtendImageToBoundsNode",
|
||||
"raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -545,8 +549,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::channels::into_channels::IDENTIFIER,
|
||||
aliases: &["raster_nodes::adjustments::ImageToChannelsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::channels::from_channels::IDENTIFIER,
|
||||
aliases: &[
|
||||
"raster_nodes::std_nodes::ChannelsToImageNode",
|
||||
"raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_std::raster::CombineChannelsNode",
|
||||
@@ -564,10 +573,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ExposureNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode", "graphene_std::raster::ExtendImageToBoundsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||
@@ -1564,13 +1569,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `image_to_channels` proto nodes.
|
||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `into_channels` proto nodes.
|
||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||
let split_wrapper_replacements = [
|
||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::channels::into_channels::IDENTIFIER),
|
||||
];
|
||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
@@ -1616,7 +1621,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Image to Channels" nodes.
|
||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Into Channels" nodes.
|
||||
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
||||
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
||||
const EXTRACT_CHANNEL: [&str; 4] = [
|
||||
@@ -1635,7 +1640,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if EXTRACT_XY.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||
Some((*node_id, path, graphene_std::raster_nodes::channels::into_channels::IDENTIFIER, "Extract Channel"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -3247,9 +3252,17 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
}
|
||||
|
||||
// Sample Image nodes, now passthroughs, drop their old title
|
||||
// Sample Image and Extend Image to Bounds nodes, now passthroughs, drop their old titles and any inputs past the first, like Extend Image to Bounds's bounds
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) {
|
||||
reset_default_display_name(document, node_id, network_path, "Sample Image");
|
||||
reset_default_display_name(document, node_id, network_path, "Extend Image to Bounds");
|
||||
|
||||
if inputs_count > 1 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize became As String, whose input converts a wired value to text, while a stored value keeps the JSON text Serialize made of it
|
||||
@@ -5663,19 +5676,8 @@ mod tests {
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&fill_id];
|
||||
let values: Vec<_> = node.inputs[4..].iter().map(|input| input.as_value().cloned()).collect();
|
||||
let expected = [
|
||||
TaggedValue::Number(-1.),
|
||||
TaggedValue::Number(0.5),
|
||||
TaggedValue::Bool(true),
|
||||
TaggedValue::DAffine2(placement),
|
||||
TaggedValue::GradientModel(Default::default()),
|
||||
TaggedValue::GradientDirection(Default::default()),
|
||||
]
|
||||
.map(Some);
|
||||
assert_eq!(
|
||||
values, expected,
|
||||
"the form should become its curvatures before the placement, followed by the default model and direction"
|
||||
);
|
||||
let expected = [TaggedValue::Number(-1.), TaggedValue::Number(0.5), TaggedValue::Bool(true), TaggedValue::DAffine2(placement)].map(Some);
|
||||
assert_eq!(values, expected, "the form should become its curvatures before the placement");
|
||||
}
|
||||
|
||||
// A Fill that held the radial form in its input before the transform ones opens with that form's curvatures, painting as a Fill given the form now does
|
||||
@@ -5720,7 +5722,6 @@ mod tests {
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_START_CURVATURE),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_END_CURVATURE),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_MODEL),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_DIRECTION),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_TRANSFORM),
|
||||
)),
|
||||
_ => None,
|
||||
@@ -5761,7 +5762,7 @@ mod tests {
|
||||
|
||||
let form = NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false);
|
||||
let mut old_inputs = NodeTemplate {
|
||||
inputs: [&inputs[..4], &[form], &inputs[6..8]].concat(),
|
||||
inputs: [&inputs[..4], &[form], &inputs[6..]].concat(),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_inputs(&fill_id, &[], &mut old_inputs);
|
||||
@@ -6330,6 +6331,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_image_to_bounds_opens_as_a_passthrough_of_its_image() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let (image, extend) = (NodeId(1), NodeId(2));
|
||||
let image_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
||||
.expect("the Image definition should exist")
|
||||
.default_node_template();
|
||||
let extend_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("raster_nodes::std_nodes::ExtendImageToBoundsNode")),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::DAffine2(DAffine2::IDENTITY), false)],
|
||||
display_name: "Extend Image to Bounds".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node(image, image_template, &[]);
|
||||
document.network_interface.insert_node(extend, extend_template, &[]);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(extend, 0), NodeInput::node(image, 0), &[]);
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let node = opened.network_interface.document_node(&extend, &[]).expect("the node should still exist");
|
||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||
assert!(matches!(node.inputs[..], [NodeInput::Node { node_id, output_index: 0, .. }] if node_id == image), "{:?}", node.inputs);
|
||||
assert_ne!(opened.network_interface.display_name(&extend, &[]), "Extend Image to Bounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
|
||||
@@ -1,454 +0,0 @@
|
||||
//! Geometry of the Gradient tool's gizmos, 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, set by its curvature, as described
|
||||
//! in [`graphene_std::vector::gradient_standard`].
|
||||
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature};
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
|
||||
/// The farthest a drawn contour bows from its chords between the points it's drawn through, in viewport pixels.
|
||||
const CONTOUR_SAG_TOLERANCE: f64 = 0.25;
|
||||
|
||||
/// The most chords a contour is drawn with.
|
||||
const CONTOUR_MAX_CHORDS: usize = 1024;
|
||||
|
||||
/// One of the gradient line's two ends, each with its own contour.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GradientEnd {
|
||||
Start,
|
||||
End,
|
||||
}
|
||||
|
||||
impl GradientEnd {
|
||||
/// Its index in a `[start, end]` pair of curvatures.
|
||||
pub fn index(self) -> usize {
|
||||
match self {
|
||||
Self::Start => 0,
|
||||
Self::End => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Its endpoint in gradient space.
|
||||
pub fn endpoint(self) -> DVec2 {
|
||||
match self {
|
||||
Self::Start => DVec2::ZERO,
|
||||
Self::End => DVec2::X,
|
||||
}
|
||||
}
|
||||
|
||||
/// Which way along the gradient line points toward the other end, which a positive curvature bows this end's contour toward.
|
||||
fn inward(self) -> f64 {
|
||||
match self {
|
||||
Self::Start => 1.,
|
||||
Self::End => -1.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The center of this end's contour in gradient space for its `curvature`, or `None` for a line.
|
||||
pub fn contour_center(end: GradientEnd, curvature: f64) -> Option<DVec2> {
|
||||
let radius = curvature_radius(curvature);
|
||||
radius.is_finite().then(|| end.endpoint() + DVec2::new(end.inward() * radius, 0.))
|
||||
}
|
||||
|
||||
/// The curvature that centers this end's contour at `axis_position` along the gradient line, as dragging its center dot there does.
|
||||
pub fn center_curvature(end: GradientEnd, axis_position: f64) -> f64 {
|
||||
radius_curvature((axis_position - end.endpoint().x) * end.inward())
|
||||
}
|
||||
|
||||
/// The curvature of this end's contour through `point`, the circle through it and the endpoint with its center on the gradient line,
|
||||
/// which is the line across the gradient line where `point` lies across from the endpoint. `None` at the endpoint itself.
|
||||
pub fn rim_curvature(end: GradientEnd, point: DVec2) -> Option<f64> {
|
||||
let offset = point - end.endpoint();
|
||||
let distance_squared = offset.length_squared();
|
||||
|
||||
// The inverse of the radius `|offset|² / 2 offset.x`, which stays finite where the radius doesn't
|
||||
(distance_squared > 0.).then(|| (2. * offset.x * end.inward() / distance_squared).atan() / FRAC_PI_2)
|
||||
}
|
||||
|
||||
/// The signed radius that resizes this end's contour (from its `curvature`) to bring the place on its rim nearest `grabbed` as near `pointer` as it gets,
|
||||
/// both in the space `unit_to_viewport` maps to, and where that place lands there. `None` for a line or a point, which no resizing moves a place on.
|
||||
pub fn rim_resized_toward(end: GradientEnd, curvature: f64, grabbed: DVec2, pointer: DVec2, unit_to_viewport: DAffine2) -> Option<(f64, DVec2)> {
|
||||
let radius = curvature_radius(curvature);
|
||||
if !radius.is_finite() || radius == 0. {
|
||||
return None;
|
||||
}
|
||||
let inward = DVec2::new(end.inward(), 0.);
|
||||
|
||||
// Each circle through the endpoint is the others scaled about it, so the place keeps its angle around them from the endpoint, measured at the center
|
||||
let to_endpoint = -radius * inward;
|
||||
let to_grabbed = unit_to_viewport.inverse().transform_point2(grabbed) - end.endpoint() - radius * inward;
|
||||
let angle = to_endpoint.perp_dot(to_grabbed).atan2(to_endpoint.dot(to_grabbed));
|
||||
|
||||
// At that angle, the place lies the radius times this from the endpoint, a line the pointer projects onto
|
||||
let direction = unit_to_viewport.transform_vector2(inward - DVec2::from_angle(angle).rotate(inward));
|
||||
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
|
||||
let resized = (pointer - endpoint).dot(direction) / direction.length_squared();
|
||||
resized.is_finite().then(|| (resized, endpoint + resized * direction))
|
||||
}
|
||||
|
||||
/// Whether a gradient with these curvatures has a focus to move: a point for its start contour and a circle for its end contour.
|
||||
pub fn has_focus(curvatures: [f64; 2]) -> bool {
|
||||
let end_radius = curvature_radius(curvatures[1]);
|
||||
curvature_radius(curvatures[0]) == 0. && end_radius.is_finite() && end_radius != 0.
|
||||
}
|
||||
|
||||
/// A gradient line in the gradient space of the line it replaces, with the curvature it gives the end contour.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RefocusedLine {
|
||||
pub start: DVec2,
|
||||
pub end: DVec2,
|
||||
pub end_curvature: f64,
|
||||
}
|
||||
|
||||
/// The line of a gradient whose start point (its focus) moves to `focus` while its end circle from `end_curvature` stays put: from the focus through the
|
||||
/// circle's center to its far side, with the end curvature keeping that circle. A focus on the center keeps `direction`. `None` unless the end is a circle.
|
||||
pub fn refocused_line(focus: DVec2, end_curvature: f64, direction: DVec2) -> Option<RefocusedLine> {
|
||||
let radius = curvature_radius(end_curvature);
|
||||
if !radius.is_finite() || radius == 0. {
|
||||
return None;
|
||||
}
|
||||
let (center, size) = (DVec2::new(1. - radius, 0.), radius.abs());
|
||||
|
||||
let to_center = center - focus;
|
||||
let distance = to_center.length();
|
||||
let direction = if distance > 0. { to_center / distance } else { direction.try_normalize()? };
|
||||
|
||||
Some(RefocusedLine {
|
||||
start: focus,
|
||||
end: center + direction * size,
|
||||
end_curvature: radius_curvature(size / (distance + size)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The transform placing a gradient along `line`, given in the gradient space of the `old` transform. Its frame turns and scales uniformly within
|
||||
/// that space, so a contour that's a circle there keeps its shape, even where `old` stretches it into an ellipse.
|
||||
pub fn transform_along(old: DAffine2, line: RefocusedLine) -> DAffine2 {
|
||||
let x_axis = line.end - line.start;
|
||||
old * DAffine2::from_cols(x_axis, x_axis.perp(), line.start)
|
||||
}
|
||||
|
||||
/// One side of the gradient line, across which its perpendicular axis points one way or the other.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LineSide {
|
||||
Positive,
|
||||
Negative,
|
||||
}
|
||||
|
||||
impl LineSide {
|
||||
/// Which way across the gradient line its perpendicular axis points to reach this side.
|
||||
pub fn sign(self) -> f64 {
|
||||
match self {
|
||||
Self::Positive => 1.,
|
||||
Self::Negative => -1.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The semi-minor axis to this side of this end's circle from its `curvature`, from the circle's center a radius across the gradient line to where
|
||||
/// a handle stretching the gradient across its line sits, in gradient space. `None` for a line or a point.
|
||||
pub fn aspect_axis(end: GradientEnd, curvature: f64, side: LineSide) -> Option<[DVec2; 2]> {
|
||||
let radius = curvature_radius(curvature).abs();
|
||||
let center = contour_center(end, curvature).filter(|_| radius > 0.)?;
|
||||
Some([center, center + DVec2::new(0., side.sign() * radius)])
|
||||
}
|
||||
|
||||
/// The transform stretched across its line so the point `handle` in its gradient space lies as far across the line as `pointer` does
|
||||
/// (in the transform's output space), keeping the line and how far its perpendicular axis leans along it. `None` where it would collapse.
|
||||
pub fn stretched_transform(transform: DAffine2, handle: DVec2, pointer: DVec2) -> Option<DAffine2> {
|
||||
let x_axis = transform.matrix2.x_axis;
|
||||
let along = x_axis.try_normalize()?;
|
||||
let across = along.perp();
|
||||
|
||||
// The handle lies `handle.y` times the perpendicular axis's span across the line
|
||||
let span_across = (pointer - transform.translation).dot(across) / handle.y;
|
||||
if !(span_across.abs() > 1e-9 * x_axis.length()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let y_axis = along * transform.matrix2.y_axis.dot(along) + across * span_across;
|
||||
Some(DAffine2::from_cols(x_axis, y_axis, transform.translation))
|
||||
}
|
||||
|
||||
/// The smallest factor `transform` scales any length by, the least singular value of its linear part.
|
||||
fn least_scale(transform: DAffine2) -> f64 {
|
||||
let [x_axis, y_axis] = [transform.matrix2.x_axis, transform.matrix2.y_axis];
|
||||
let determinant = transform.matrix2.determinant().abs();
|
||||
|
||||
// Of the singular values `√(mean ± √(mean² - determinant²))`, the least is the determinant over the greatest, which avoids cancellation
|
||||
let mean = (x_axis.length_squared() + y_axis.length_squared()) / 2.;
|
||||
let greatest = (mean + (mean * mean - determinant * determinant).max(0.).sqrt()).sqrt();
|
||||
if greatest > 0. { determinant / greatest } else { 0. }
|
||||
}
|
||||
|
||||
/// Points through which this end's contour is drawn in the viewport, from `unit_to_viewport`, as far as `reach` viewport pixels from
|
||||
/// its endpoint along it (or around the whole circle if that's shorter). Empty for a point, or where the transform collapses.
|
||||
pub fn contour_polyline(end: GradientEnd, curvature: f64, unit_to_viewport: DAffine2, reach: f64) -> Vec<DVec2> {
|
||||
let radius = curvature_radius(curvature);
|
||||
let endpoint = end.endpoint();
|
||||
|
||||
let least_scale = least_scale(unit_to_viewport);
|
||||
if radius == 0. || least_scale <= 0. {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// A line runs straight across the gradient line through the endpoint
|
||||
if radius.is_infinite() {
|
||||
let Some(direction) = unit_to_viewport.transform_vector2(DVec2::Y).try_normalize() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let viewport_endpoint = unit_to_viewport.transform_point2(endpoint);
|
||||
return vec![viewport_endpoint - direction * reach, viewport_endpoint + direction * reach];
|
||||
}
|
||||
|
||||
// Sweep from the endpoint both ways around the circle, by the angle reaching `reach` pixels at the least scale
|
||||
let size = radius.abs();
|
||||
let sweep = (reach / (size * least_scale)).min(PI);
|
||||
|
||||
// Uniform steps small enough that each chord stays within the sag tolerance, even at twice the longest axis's scale (which bounds the greatest)
|
||||
let viewport_radius_bound = size * unit_to_viewport.matrix2.x_axis.length().max(unit_to_viewport.matrix2.y_axis.length()) * 2.;
|
||||
let step = (8. * CONTOUR_SAG_TOLERANCE / viewport_radius_bound).sqrt();
|
||||
let chords_each_way = ((sweep / step).ceil() as usize).clamp(4, CONTOUR_MAX_CHORDS / 2);
|
||||
let chords = 2 * chords_each_way;
|
||||
|
||||
// Measured from the endpoint rather than the center, the points stay precise on huge circles
|
||||
(0..=chords)
|
||||
.map(|index| {
|
||||
let angle = sweep * (2. * index as f64 / chords as f64 - 1.);
|
||||
let half_sine = (angle / 2.).sin();
|
||||
let offset = DVec2::new(2. * end.inward() * radius * half_sine * half_sine, size * angle.sin());
|
||||
unit_to_viewport.transform_point2(endpoint + offset)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The distance from `point` to the nearest place on the polyline through `points`, or `None` if it has none.
|
||||
pub fn distance_to_polyline(points: &[DVec2], point: DVec2) -> Option<f64> {
|
||||
if let [only] = points {
|
||||
return Some(only.distance(point));
|
||||
}
|
||||
|
||||
points
|
||||
.windows(2)
|
||||
.map(|pair| {
|
||||
let (start, end) = (pair[0], pair[1]);
|
||||
let along = (point - start).dot(end - start) / (end - start).length_squared();
|
||||
let nearest = if along.is_finite() { start.lerp(end, along.clamp(0., 1.)) } else { start };
|
||||
nearest.distance(point)
|
||||
})
|
||||
.min_by(f64::total_cmp)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Curvatures through circles of each size and bend, both lines, and the points.
|
||||
fn curvatures() -> impl Iterator<Item = f64> {
|
||||
(-20..=20).map(|step| step as f64 * 0.05)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rim_dragged_to_a_point_takes_the_curvature_of_the_circle_through_it() {
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for point in [DVec2::new(0.3, 0.4), DVec2::new(-0.7, 1.2), DVec2::new(2.5, -0.25), DVec2::new(0.5, 3.)] {
|
||||
let curvature = rim_curvature(end, point).unwrap();
|
||||
|
||||
// The contour of that curvature passes through the point, centered on the gradient line
|
||||
let center = contour_center(end, curvature).unwrap();
|
||||
assert!(center.y == 0.);
|
||||
let radius = center.distance(end.endpoint());
|
||||
assert!((center.distance(point) - radius).abs() < 1e-9 * radius.max(1.), "{end:?} through {point}: curvature {curvature}");
|
||||
}
|
||||
|
||||
// Straight across from the endpoint is the line, and either side of it bends toward that side
|
||||
let across = end.endpoint() + DVec2::Y;
|
||||
assert_eq!(rim_curvature(end, across), Some(0.));
|
||||
let inward = DVec2::new(end.inward() * 0.1, 0.);
|
||||
assert!(rim_curvature(end, across + inward).unwrap() > 0.);
|
||||
assert!(rim_curvature(end, across - inward).unwrap() < 0.);
|
||||
|
||||
// The endpoint is on every contour, so it sets none
|
||||
assert_eq!(rim_curvature(end, end.endpoint()), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rim_dragged_along_its_own_contour_keeps_its_curvature() {
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for curvature in curvatures().filter(|curvature| curvature.abs() != 1.) {
|
||||
for point in contour_polyline(end, curvature, DAffine2::IDENTITY, 3.) {
|
||||
// Every point but the endpoint sets the curvature back, as a line's points beside the endpoint do
|
||||
if point.distance(end.endpoint()) < 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let found = rim_curvature(end, point).unwrap();
|
||||
assert!((found - curvature).abs() < 1e-9, "{end:?} curvature {curvature} at {point}: {found}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_center_dragged_along_the_line_takes_the_curvature_centered_there() {
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for curvature in curvatures().filter(|&curvature| curvature != 0.) {
|
||||
let center = contour_center(end, curvature).unwrap();
|
||||
let found = center_curvature(end, center.x);
|
||||
|
||||
// A point is both -1 and 1, which the drag settles at -1
|
||||
let expected = if curvature.abs() == 1. { -1. } else { curvature };
|
||||
assert!((found - expected).abs() < 1e-9, "{end:?} curvature {curvature}: {found}");
|
||||
}
|
||||
|
||||
// Toward the other end bows toward it, and onto the endpoint is a point
|
||||
assert!(center_curvature(end, 0.5) > 0.);
|
||||
assert!(center_curvature(end, end.endpoint().x - end.inward()) < 0.);
|
||||
assert_eq!(center_curvature(end, end.endpoint().x), -1.);
|
||||
}
|
||||
|
||||
// The start contour centered at the end point, and the end contour at the start point, are each the circle of radius 1 between them
|
||||
assert!((center_curvature(GradientEnd::Start, 1.) - 0.5).abs() < 1e-12);
|
||||
assert!((center_curvature(GradientEnd::End, 0.) - 0.5).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// The center and radius of the end circle of a gradient along `line`, in the gradient space `line` is given in.
|
||||
fn end_circle(line: RefocusedLine) -> (DVec2, f64) {
|
||||
let radius = curvature_radius(line.end_curvature);
|
||||
(line.start.lerp(line.end, 1. - radius), radius.abs() * line.start.distance(line.end))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_focus_keeps_the_end_circle_in_place() {
|
||||
// The end circle of radius 0.75 centered at 0.25, with foci inside it, outside it, and behind its center
|
||||
let end_curvature = radius_curvature(0.75);
|
||||
let (center, radius) = (DVec2::new(0.25, 0.), 0.75);
|
||||
for focus in [DVec2::new(0.1, 0.3), DVec2::new(-0.2, -0.4), DVec2::new(3., 2.), DVec2::new(0.9, 0.), DVec2::new(-5., 0.)] {
|
||||
let line = refocused_line(focus, end_curvature, DVec2::X).unwrap();
|
||||
assert_eq!(line.start, focus);
|
||||
|
||||
let (new_center, new_radius) = end_circle(line);
|
||||
assert!(new_center.distance(center) < 1e-12 && (new_radius - radius).abs() < 1e-12, "focus {focus}: {line:?}");
|
||||
|
||||
// The line runs on through the center to the circle's far side
|
||||
assert!((line.end.distance(focus) - (focus.distance(center) + radius)).abs() < 1e-12, "focus {focus}: {line:?}");
|
||||
}
|
||||
|
||||
// A focus off the circle's line still aims the line through its center
|
||||
let line = refocused_line(DVec2::new(0.25, 2.), end_curvature, DVec2::X).unwrap();
|
||||
assert!(line.end.abs_diff_eq(DVec2::new(0.25, -0.75), 1e-12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_focus_on_the_center_keeps_the_direction_and_makes_the_radial_form() {
|
||||
let end_curvature = radius_curvature(0.75);
|
||||
let line = refocused_line(contour_center(GradientEnd::End, end_curvature).unwrap(), end_curvature, DVec2::new(0., 2.)).unwrap();
|
||||
assert_eq!(line.end_curvature, 0.5);
|
||||
assert!(line.end.abs_diff_eq(DVec2::new(0.25, 0.75), 1e-12));
|
||||
assert_eq!(
|
||||
graphene_std::vector::style::GradientForm::from_curvatures([-1., line.end_curvature]),
|
||||
Some(graphene_std::vector::style::GradientForm::Radial)
|
||||
);
|
||||
|
||||
// Only an end circle has a focus to move around
|
||||
assert!(has_focus([-1., 0.5]) && has_focus([1., -0.3]));
|
||||
assert!(!has_focus([0., 0.5]) && !has_focus([-1., 0.]) && !has_focus([-1., 1.]));
|
||||
assert_eq!(refocused_line(DVec2::ZERO, 0., DVec2::X), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refocused_transform_keeps_an_elliptical_end_contour_in_place() {
|
||||
// A radial gradient squashed to half its height and skewed, whose focus moves off its line
|
||||
let old = DAffine2::from_cols(DVec2::new(100., 20.), DVec2::new(-5., 50.), DVec2::new(30., 40.));
|
||||
let line = refocused_line(DVec2::new(0.3, 0.4), 0.5, DVec2::X).unwrap();
|
||||
let new = transform_along(old, line);
|
||||
|
||||
// The end contour's points land on the same ellipse before and after (within its chords' sag), though spread differently around it
|
||||
let before = contour_polyline(GradientEnd::End, 0.5, old, 1e6);
|
||||
let after = contour_polyline(GradientEnd::End, line.end_curvature, new, 1e6);
|
||||
for point in after {
|
||||
assert!(distance_to_polyline(&before, point).unwrap() <= CONTOUR_SAG_TOLERANCE, "{point} left the ellipse");
|
||||
}
|
||||
assert!(new.transform_point2(DVec2::ZERO).abs_diff_eq(old.transform_point2(DVec2::new(0.3, 0.4)), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_end_circle_has_an_aspect_handle_a_radius_to_either_side_of_its_center() {
|
||||
use LineSide::{Negative, Positive};
|
||||
|
||||
// The radial form's end circle around the start point, but not its start point
|
||||
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Positive), Some([DVec2::ZERO, DVec2::Y]));
|
||||
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Negative), Some([DVec2::ZERO, -DVec2::Y]));
|
||||
assert_eq!(aspect_axis(GradientEnd::Start, -1., Positive), None);
|
||||
|
||||
// Each of two crossing circles, and a huge nearly flat one
|
||||
let radius = curvature_radius(0.6);
|
||||
assert_eq!(aspect_axis(GradientEnd::Start, 0.6, Positive), Some([DVec2::new(radius, 0.), DVec2::new(radius, radius)]));
|
||||
assert_eq!(aspect_axis(GradientEnd::End, 0.6, Negative), Some([DVec2::new(1. - radius, 0.), DVec2::new(1. - radius, -radius)]));
|
||||
assert!(aspect_axis(GradientEnd::End, 1e-3, Positive).is_some_and(|[_, handle]| handle.y > 100.));
|
||||
|
||||
// Lines and points have none
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for curvature in [0., 1., -1.] {
|
||||
for side in [Positive, Negative] {
|
||||
assert_eq!(aspect_axis(end, curvature, side), None, "{end:?} curvature {curvature} {side:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stretching_moves_each_aspect_handle_across_the_line_and_keeps_the_line() {
|
||||
// A skewed gradient, its perpendicular axis leaning along the line
|
||||
let transform = DAffine2::from_cols(DVec2::new(80., 60.), DVec2::new(-50., 70.), DVec2::new(10., 20.));
|
||||
let along = transform.matrix2.x_axis.normalize();
|
||||
|
||||
// The radial form's handles and those of two crossing circles of different sizes, each pulled to its own side of the line
|
||||
let axes = [(GradientEnd::End, 0.5), (GradientEnd::Start, 0.6), (GradientEnd::End, 0.3)];
|
||||
let handles = axes
|
||||
.into_iter()
|
||||
.flat_map(|(end, curvature)| [LineSide::Positive, LineSide::Negative].map(|side| (aspect_axis(end, curvature, side).unwrap()[1], side)));
|
||||
for (handle, side) in handles {
|
||||
let pointer = transform.transform_point2(DVec2::new(0.4, side.sign() * 0.7));
|
||||
let stretched = stretched_transform(transform, handle, pointer).unwrap();
|
||||
assert!(stretched.matrix2.determinant() * transform.matrix2.determinant() > 0., "the gradient shouldn't mirror");
|
||||
for point in [DVec2::ZERO, DVec2::X] {
|
||||
assert!(stretched.transform_point2(point).abs_diff_eq(transform.transform_point2(point), 1e-9));
|
||||
}
|
||||
|
||||
// The handle lands as far across the line as the pointer, sliding only across it, and the lean along the line stays
|
||||
let (old_handle, new_handle) = (transform.transform_point2(handle), stretched.transform_point2(handle));
|
||||
assert!(((new_handle - transform.translation).dot(along.perp()) - (pointer - transform.translation).dot(along.perp())).abs() < 1e-9);
|
||||
assert!((new_handle - old_handle).dot(along).abs() < 1e-9);
|
||||
assert!((stretched.matrix2.y_axis.dot(along) - transform.matrix2.y_axis.dot(along)).abs() < 1e-9);
|
||||
|
||||
// Onto the line, it would collapse
|
||||
assert_eq!(stretched_transform(transform, handle, transform.transform_point2(DVec2::new(0.5, 0.))), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contours_are_drawn_through_their_endpoints_out_to_their_reach() {
|
||||
let unit_to_viewport = DAffine2::from_scale_angle_translation(DVec2::new(200., 100.), 0.3, DVec2::new(40., 60.));
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
|
||||
|
||||
// A point draws nothing, and a line is one long chord through the endpoint
|
||||
assert!(contour_polyline(end, 1., unit_to_viewport, 500.).is_empty());
|
||||
let line = contour_polyline(end, 0., unit_to_viewport, 500.);
|
||||
assert_eq!(line.len(), 2);
|
||||
assert!(distance_to_polyline(&line, endpoint).unwrap() < 1e-9);
|
||||
|
||||
// A small circle is drawn whole, closing on itself, and a huge one only as far as its reach, nearly straight
|
||||
let small = contour_polyline(end, 0.5, unit_to_viewport, 500.);
|
||||
assert!(small.first().unwrap().distance(*small.last().unwrap()) < 1e-6);
|
||||
let huge = contour_polyline(end, 1e-6, unit_to_viewport, 500.);
|
||||
let farthest = huge.iter().map(|point| point.distance(endpoint)).fold(0., f64::max);
|
||||
assert!((400. ..=1000.).contains(&farthest), "a huge circle should reach about 500 pixels, not {farthest}");
|
||||
|
||||
for polyline in [small, huge] {
|
||||
assert!(distance_to_polyline(&polyline, endpoint).unwrap() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::style::{FillChoice, GradientDirection, GradientModel, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||
use graphene_std::vector::{Gradient, GradientForm, GradientRamp, GradientSettings, PointId, SegmentId, VectorModificationType};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use std::collections::VecDeque;
|
||||
@@ -859,9 +859,6 @@ pub struct FillNodeGradient {
|
||||
pub curvatures: Option<[f64; 2]>,
|
||||
/// The form its curvatures make, which is linear for any that make neither.
|
||||
pub gradient_form: GradientForm,
|
||||
/// Its model and direction, each unless the graph feeds it.
|
||||
pub model: Option<GradientModel>,
|
||||
pub direction: Option<GradientDirection>,
|
||||
pub settings: GradientSettings,
|
||||
pub transform: DAffine2,
|
||||
/// Whether the transform input holds a plain value (so it may be written to) rather than a wire.
|
||||
@@ -879,14 +876,6 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
let stops = Gradient::from(ramp);
|
||||
let curvatures = fill_node_curvatures(fill_node);
|
||||
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default();
|
||||
let model = match fill_node.input(fill::ModelInput).and_then(NodeInput::as_non_exposed_value) {
|
||||
Some(&TaggedValue::GradientModel(model)) => Some(model),
|
||||
_ => None,
|
||||
};
|
||||
let direction = match fill_node.input(fill::DirectionInput).and_then(NodeInput::as_non_exposed_value) {
|
||||
Some(&TaggedValue::GradientDirection(direction)) => Some(direction),
|
||||
_ => None,
|
||||
};
|
||||
let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
|
||||
let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
|
||||
let transform = match (has_transform, transform_input) {
|
||||
@@ -899,8 +888,6 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
stops,
|
||||
curvatures,
|
||||
gradient_form,
|
||||
model,
|
||||
direction,
|
||||
settings,
|
||||
transform,
|
||||
transform_is_value: transform_input.is_some(),
|
||||
|
||||
@@ -3,7 +3,6 @@ pub mod color_selector;
|
||||
pub mod compass_rose;
|
||||
pub mod edit_target;
|
||||
pub mod gizmos;
|
||||
pub mod gradient_gizmos;
|
||||
pub mod graph_modification_utils;
|
||||
pub mod layer_origin_cross;
|
||||
pub mod measure;
|
||||
|
||||
@@ -92,8 +92,6 @@ pub struct PointOptions {
|
||||
pub box_features: Option<BoxFeatures>,
|
||||
/// Whether the grid is left out, as for a turn, which the grid would otherwise step at odd angles.
|
||||
pub ignores_grid: bool,
|
||||
/// Whether the tool marks where a press would land in its own way, so nothing marks it there unless a snap is named.
|
||||
pub marked_by_tool: bool,
|
||||
}
|
||||
|
||||
/// Which features of a gesture make up a box.
|
||||
@@ -124,8 +122,6 @@ pub struct Shown {
|
||||
pub features: Vec<DVec2>,
|
||||
/// The index of the feature the pointer carries.
|
||||
pub lead: usize,
|
||||
/// Whether the tool marks where a press would land, as [`PointOptions::marked_by_tool`] tells.
|
||||
pub marked_by_tool: bool,
|
||||
}
|
||||
|
||||
/// What a kept set of constructions was found for, which it stays good for.
|
||||
@@ -325,7 +321,6 @@ impl SnapSession {
|
||||
features: features.iter().map(|feature| feature.position(parameters)).collect(),
|
||||
lead,
|
||||
outcome,
|
||||
marked_by_tool: options.marked_by_tool,
|
||||
});
|
||||
|
||||
// A crossing, or the grid, can hold the box anywhere along the track that evens out its gaps, so they are measured again where it landed
|
||||
@@ -404,7 +399,6 @@ impl SnapSession {
|
||||
features: vec![position_of(snapped)],
|
||||
lead: 0,
|
||||
outcome,
|
||||
marked_by_tool: false,
|
||||
});
|
||||
|
||||
snapped
|
||||
|
||||
@@ -19,24 +19,14 @@ impl SnapSession {
|
||||
self.draw_awake(target, to_viewport, overlay_context);
|
||||
}
|
||||
|
||||
let Some(Shown {
|
||||
outcome,
|
||||
features,
|
||||
lead,
|
||||
marked_by_tool,
|
||||
}) = &self.shown
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(Shown { outcome, features, lead, .. }) = &self.shown else { return };
|
||||
|
||||
// Before a press, the point is marked where the press would place it, even with no snap to name
|
||||
if matches!(outcome.snap, Snap::Grid | Snap::Free)
|
||||
&& self.gesture.is_none()
|
||||
&& let Some(&position) = features.get(*lead)
|
||||
{
|
||||
if !marked_by_tool {
|
||||
overlay_context.square(to_viewport.transform_point2(position), Some(4.), Some(COLOR_OVERLAY_BLUE), Some(COLOR_OVERLAY_BLUE));
|
||||
}
|
||||
overlay_context.square(to_viewport.transform_point2(position), Some(4.), Some(COLOR_OVERLAY_BLUE), Some(COLOR_OVERLAY_BLUE));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -571,7 +571,6 @@ tagged_value! {
|
||||
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
||||
GradientForm(vector::style::GradientForm),
|
||||
GradientModel(vector::style::GradientModel),
|
||||
GradientDirection(vector::style::GradientDirection),
|
||||
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
|
||||
GradientSpread(vector::style::GradientSpread),
|
||||
GradientSpace(vector::style::GradientSpace),
|
||||
|
||||
@@ -26,9 +26,7 @@ use graphene_std::vector::misc::{
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||
WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
DashPattern, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
@@ -273,7 +271,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
StrokeCap,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientDirection,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -519,7 +516,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(Item<BlendMode>),
|
||||
attribute_value_node!(Item<GradientForm>),
|
||||
attribute_value_node!(Item<GradientModel>),
|
||||
attribute_value_node!(Item<GradientDirection>),
|
||||
attribute_value_node!(Item<GradientSpread>),
|
||||
attribute_value_node!(Item<GradientSpace>),
|
||||
attribute_value_node!(Item<GradientHueDirection>),
|
||||
|
||||
@@ -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_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
|
||||
ATTR_GRADIENT_MODEL, 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,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL,
|
||||
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;
|
||||
|
||||
@@ -67,8 +67,6 @@ pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
|
||||
/// Gradient's `GradientModel` (`Standard` or `Apollonian`), how the contours between its curved ends are laid out: as SVG 2's cone
|
||||
/// between the end circles, or as the family of circles the ends span. Absent, it's `Standard`.
|
||||
pub const ATTR_GRADIENT_MODEL: &str = "gradient_model";
|
||||
/// Gradient's `GradientDirection` (`Along` or `Across`), whether its colors run from one end contour to the other or around each contour. Absent, it's `Along`.
|
||||
pub const ATTR_GRADIENT_DIRECTION: &str = "gradient_direction";
|
||||
/// 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
|
||||
|
||||
@@ -86,6 +86,8 @@ pub enum Adjustment {
|
||||
opacity: f64,
|
||||
},
|
||||
Solarize,
|
||||
/// Shows the alpha as a gray of the same gamma-encoded level, keeping the alpha, so a luminance mask of the gray shows as much as the alpha.
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl Adjustment {
|
||||
@@ -112,6 +114,17 @@ impl Adjustment {
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Solarize => EffectKind::Solarize,
|
||||
Self::AlphaToGray => EffectKind::AlphaToGray,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the adjustment might change a color's alpha, which only Make Opaque and the alpha records of Levels and Curves do.
|
||||
pub fn may_change_alpha(&self) -> bool {
|
||||
match self {
|
||||
Self::MakeOpaque { .. } => true,
|
||||
Self::Levels(settings) => !settings.alpha.is_identity(),
|
||||
Self::Curves(settings) => settings.alpha != TransferCurve::default(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,7 +154,7 @@ impl Adjustment {
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
||||
Self::Invert | Self::Solarize => {}
|
||||
Self::Invert | Self::Solarize | Self::AlphaToGray => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
@@ -486,6 +499,20 @@ fn grouped_key(group: &str, parameter: &str) -> String {
|
||||
}
|
||||
|
||||
impl LevelsRecord {
|
||||
/// The record leaving every value as it is, as its node's defaults do.
|
||||
pub const IDENTITY: Self = Self {
|
||||
shadows: 0.,
|
||||
midtones: 1.,
|
||||
highlights: 100.,
|
||||
output_minimums: 0.,
|
||||
output_maximums: 100.,
|
||||
};
|
||||
|
||||
/// Whether the record leaves every value as it is.
|
||||
pub fn is_identity(&self) -> bool {
|
||||
*self == Self::IDENTITY
|
||||
}
|
||||
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
||||
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
||||
|
||||
@@ -490,6 +490,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Median { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
|
||||
@@ -15,7 +15,7 @@ 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, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, List};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, ItemAttributeValues, List};
|
||||
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
@@ -60,6 +60,8 @@ pub enum EffectKind {
|
||||
FindEdges,
|
||||
/// Spreads each pixel's darkest or lightest neighboring colors.
|
||||
MinimumMaximum,
|
||||
/// Gives each pixel the middle value of each channel among those around it, removing specks while keeping edges.
|
||||
Median,
|
||||
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
||||
Sharpen,
|
||||
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
||||
@@ -117,6 +119,8 @@ pub enum EffectKind {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
/// Shows the content's alpha as a gray, as 'Into Channels' does for its alpha output.
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
@@ -137,6 +141,7 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::Emboss => "Emboss",
|
||||
Self::FindEdges => "Find Edges",
|
||||
Self::MinimumMaximum => "Minimum/Maximum",
|
||||
Self::Median => "Median",
|
||||
Self::Sharpen => "Sharpen",
|
||||
Self::HighPass => "High Pass",
|
||||
Self::Speckle => "Speckle",
|
||||
@@ -175,6 +180,7 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
Self::Solarize => "Solarize",
|
||||
Self::AlphaToGray => "Alpha to Gray",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -218,6 +224,9 @@ pub enum MinimumMaximumMode {
|
||||
Maximum,
|
||||
}
|
||||
|
||||
/// The most pixels a median's square reaches out from its center on its grid, whose cost grows with the square's area. Past it, the grid coarsens instead.
|
||||
pub const MAX_MEDIAN_GRID_RADIUS: f64 = 16.;
|
||||
|
||||
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct EffectCapture {
|
||||
@@ -454,6 +463,17 @@ impl Effects {
|
||||
self.operations().all(|operation| operation.changes_nothing())
|
||||
}
|
||||
|
||||
/// Whether the effects might change the content's alpha, as any but an adjustment keeping it (see [`Adjustment::may_change_alpha`]) can unless it changes nothing.
|
||||
pub fn may_change_alpha(&self) -> bool {
|
||||
self.operations().any(|operation| {
|
||||
!operation.changes_nothing()
|
||||
&& match &operation {
|
||||
EffectOperation::Adjustment(adjustment) => adjustment.may_change_alpha(),
|
||||
_ => true,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The effects of the given range of rows decoded into operations, in order.
|
||||
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
|
||||
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
|
||||
@@ -475,17 +495,30 @@ impl Effects {
|
||||
self.operations().map(|operation| operation.required_reach()).sum()
|
||||
}
|
||||
|
||||
/// How many pixels per unit of their effect space a run of these effects renders at, at most, if any of them works on the content's own grid (see [`EffectOperation::works_on_content_grid`]).
|
||||
/// It's one, except that a median reaching past [`MAX_MEDIAN_GRID_RADIUS`] whole units coarsens the grid to bound its cost.
|
||||
pub fn content_grid_resolution(&self) -> Option<f64> {
|
||||
let grid_resolution = |operation: EffectOperation| match operation {
|
||||
EffectOperation::Median { radius } => (MAX_MEDIAN_GRID_RADIUS / radius.floor()).min(1.),
|
||||
_ => 1.,
|
||||
};
|
||||
self.operations().filter(EffectOperation::works_on_content_grid).map(grid_resolution).reduce(f64::min)
|
||||
}
|
||||
|
||||
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
||||
/// A transform applied between two effects starts a new run, which renders around the result of those before it.
|
||||
/// A transform applied between two effects, or an effect on the content's own grid (which runs alone at its grid's resolution), starts a new run around the result of those before it.
|
||||
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
||||
pub fn runs(&self) -> Vec<(DAffine2, Range<usize>)> {
|
||||
let mut runs: Vec<(DAffine2, Range<usize>)> = Vec::new();
|
||||
let mut run_changes_something = false;
|
||||
let (mut run_changes_something, mut run_on_content_grid) = (false, false);
|
||||
for (index, effect) in self.effects().enumerate() {
|
||||
let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let changes_something = !effect.operation().changes_nothing();
|
||||
let operation = effect.operation();
|
||||
let (changes_something, on_content_grid) = (!operation.changes_nothing(), operation.works_on_content_grid());
|
||||
|
||||
let shares_grid = !(on_content_grid && run_changes_something) && !(run_on_content_grid && changes_something);
|
||||
if let Some((transform, rows)) = runs.last_mut()
|
||||
&& shares_grid
|
||||
&& (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2))
|
||||
{
|
||||
if changes_something && !run_changes_something {
|
||||
@@ -493,9 +526,10 @@ impl Effects {
|
||||
}
|
||||
rows.end = index + 1;
|
||||
run_changes_something |= changes_something;
|
||||
run_on_content_grid |= on_content_grid;
|
||||
} else {
|
||||
runs.push((stamped_transform, index..index + 1));
|
||||
run_changes_something = changes_something;
|
||||
(run_changes_something, run_on_content_grid) = (changes_something, on_content_grid);
|
||||
}
|
||||
}
|
||||
runs
|
||||
@@ -835,8 +869,14 @@ pub fn contour_gradient_position(distance: f32, start: f32, span: f32) -> f32 {
|
||||
/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point.
|
||||
/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect.
|
||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||
let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS)
|
||||
stamp_effect_on(item.attributes_mut(), effect);
|
||||
}
|
||||
|
||||
/// Like [`stamp_effect`], given the item's attributes.
|
||||
pub fn stamp_effect_on(attributes: &mut ItemAttributeValues, effect: Effect) {
|
||||
let transform = stamped_transform(attributes.get::<DAffine2>(ATTR_TRANSFORM).copied().unwrap_or_default());
|
||||
attributes
|
||||
.get_or_insert_default_mut::<Effects>(ATTR_EFFECTS)
|
||||
.0
|
||||
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
||||
}
|
||||
@@ -1086,6 +1126,11 @@ pub enum EffectOperation {
|
||||
radius: f64,
|
||||
mode: MinimumMaximumMode,
|
||||
},
|
||||
/// Carried out on the content's own grid of pixels (see [`Self::works_on_content_grid`]), then resampled to the view.
|
||||
Median {
|
||||
/// How many pixels the square neighborhood reaches out from its center, of which the whole pixels count.
|
||||
radius: f64,
|
||||
},
|
||||
Sharpen {
|
||||
/// Percent.
|
||||
amount: f64,
|
||||
@@ -1287,6 +1332,7 @@ impl EffectOperation {
|
||||
Self::Emboss { .. } => EffectKind::Emboss,
|
||||
Self::FindEdges => EffectKind::FindEdges,
|
||||
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
||||
Self::Median { .. } => EffectKind::Median,
|
||||
Self::Sharpen { .. } => EffectKind::Sharpen,
|
||||
Self::HighPass { .. } => EffectKind::HighPass,
|
||||
Self::Speckle { .. } => EffectKind::Speckle,
|
||||
@@ -1387,6 +1433,8 @@ impl EffectOperation {
|
||||
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
||||
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
||||
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
||||
// Only whole pixels count, so one of less than a pixel reads the pixel alone
|
||||
Self::Median { radius } => *radius < 1.,
|
||||
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
|
||||
}
|
||||
}
|
||||
@@ -1413,7 +1461,7 @@ impl EffectOperation {
|
||||
Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => {
|
||||
true
|
||||
}
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Median { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
|
||||
Self::DropShadow { .. }
|
||||
| Self::InnerShadow { .. }
|
||||
@@ -1427,6 +1475,12 @@ impl EffectOperation {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this operation is carried out on the content's own grid of pixels, one to each unit of its effect space, and the result resampled to the view, since it doesn't commute with resampling.
|
||||
/// So it looks the same at every zoom, and on an image at its own size when stamped, it reads the image's pixels.
|
||||
pub fn works_on_content_grid(&self) -> bool {
|
||||
matches!(self, Self::Median { .. }) && !self.changes_nothing()
|
||||
}
|
||||
|
||||
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
||||
pub fn painted_reach(&self) -> f64 {
|
||||
let keeps_coverage = matches!(
|
||||
@@ -1440,6 +1494,8 @@ impl EffectOperation {
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
..
|
||||
}
|
||||
// Its coverage is the window's middle one, which past the content's bounds comes from a window at least half beyond them
|
||||
| Self::Median { .. }
|
||||
| Self::Sharpen { .. }
|
||||
| Self::HighPass { .. }
|
||||
);
|
||||
@@ -1482,6 +1538,7 @@ impl EffectOperation {
|
||||
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
||||
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
||||
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
||||
Self::Median { radius } => radius.max(0.).floor() + 1.,
|
||||
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
||||
Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3.,
|
||||
// They reach as far as `Effects::reach_around` measures from where the content lies
|
||||
@@ -1576,7 +1633,7 @@ impl EffectOperation {
|
||||
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
||||
Self::Feather { distance } => finite(distance),
|
||||
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
||||
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
|
||||
Self::MinimumMaximum { radius, .. } | Self::Median { radius } | Self::HighPass { radius } => finite(radius),
|
||||
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
||||
Self::Speckle { amount, .. } => finite(amount),
|
||||
Self::Dissolve { opacity, .. } => finite(opacity),
|
||||
@@ -1747,6 +1804,7 @@ impl EffectOperation {
|
||||
radius: 0.,
|
||||
mode: MinimumMaximumMode::default(),
|
||||
},
|
||||
EffectKind::Median => Self::Median { radius: 0. },
|
||||
EffectKind::Sharpen => Self::Sharpen {
|
||||
amount: 0.,
|
||||
radius: 0.,
|
||||
@@ -1875,6 +1933,7 @@ impl EffectOperation {
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
||||
EffectKind::AlphaToGray => Self::Adjustment(Adjustment::AlphaToGray),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2088,6 +2147,7 @@ impl EffectOperation {
|
||||
visitor.parameter("radius", radius, 1.);
|
||||
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
||||
}
|
||||
Self::Median { radius } => visitor.parameter("radius", radius, 0.),
|
||||
Self::Sharpen {
|
||||
amount,
|
||||
radius,
|
||||
@@ -2390,6 +2450,7 @@ mod tests {
|
||||
radius: 7.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Median { radius: 3.5 },
|
||||
EffectOperation::Adjustment(Adjustment::Solarize),
|
||||
EffectOperation::Sharpen {
|
||||
amount: 180.,
|
||||
@@ -2888,6 +2949,7 @@ mod tests {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
AlphaToGray,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
@@ -2987,6 +3049,7 @@ mod tests {
|
||||
radius: 3.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Median { radius: 3.5 },
|
||||
EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 3.,
|
||||
@@ -3010,6 +3073,28 @@ mod tests {
|
||||
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_median_works_on_the_content_grid_coarsened_past_its_largest_radius() {
|
||||
let median = |radius| Effects::from_operations([EffectOperation::Median { radius }]);
|
||||
assert_eq!(median(0.5).content_grid_resolution(), None, "less than a whole pixel changes nothing");
|
||||
assert_eq!(median(5.9).content_grid_resolution(), Some(1.));
|
||||
assert_eq!(median(64.).content_grid_resolution(), Some(MAX_MEDIAN_GRID_RADIUS / 64.));
|
||||
assert_eq!(Effects::from_operations([EffectOperation::FindEdges]).content_grid_resolution(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_median_runs_alone_at_its_own_grid_resolution() {
|
||||
let median = |radius| EffectOperation::Median { radius };
|
||||
let nothing = median(0.);
|
||||
let effects = Effects::from_operations([nothing.clone(), median(1.), median(64.), nothing, EffectOperation::FindEdges, median(2.)]);
|
||||
|
||||
// Effects changing nothing join a median's run, but nothing else does
|
||||
let runs: Vec<_> = effects.runs().into_iter().map(|(_, rows)| rows).collect();
|
||||
assert_eq!(runs, vec![0..2, 2..4, 4..5, 5..6]);
|
||||
let resolutions: Vec<_> = runs.into_iter().map(|rows| effects.run(rows).content_grid_resolution()).collect();
|
||||
assert_eq!(resolutions, [Some(1.), Some(MAX_MEDIAN_GRID_RADIUS / 64.), None, Some(1.)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baking_the_content_placement_into_its_geometry_keeps_its_mask_in_place() {
|
||||
fn nested_placement(graphic: &Graphic) -> DAffine2 {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the CPU, GPU, and SVG each carry out.
|
||||
|
||||
use crate::effects::{EffectOperation, Effects};
|
||||
use crate::effects::EffectOperation;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
||||
@@ -164,6 +164,7 @@ pub fn is_filter(operation: &EffectOperation) -> bool {
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Median { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
@@ -181,12 +182,6 @@ pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
|
||||
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
||||
}
|
||||
|
||||
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
|
||||
/// The random field filters change endless content without its neighbors (see [`is_random_field_filter`]).
|
||||
pub fn has_filters(effects: &Effects) -> bool {
|
||||
effects.operations().any(|operation| reads_neighbors(&operation) && !operation.changes_nothing())
|
||||
}
|
||||
|
||||
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
|
||||
pub const SOBEL_TAPS: [(DVec2, [f64; 2]); 8] = [
|
||||
(DVec2::new(-1., -1.), [-1., -1.]),
|
||||
|
||||
@@ -10,8 +10,8 @@ use core_types::none;
|
||||
use core_types::ops::FromAnchorPosition;
|
||||
use core_types::transform::Transform;
|
||||
use core_types::{
|
||||
ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY,
|
||||
ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color,
|
||||
ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM,
|
||||
Color,
|
||||
};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
@@ -19,7 +19,7 @@ use raster_types::{CPU, GPU, Raster};
|
||||
pub use vector_types::Vector;
|
||||
use vector_types::gradient_standard::GradientShape;
|
||||
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
|
||||
use vector_types::{Gradient, GradientDirection, GradientModel, GradientSpread};
|
||||
use vector_types::{Gradient, GradientModel, GradientSpread};
|
||||
|
||||
/// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node.
|
||||
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
|
||||
@@ -630,16 +630,17 @@ impl Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_reduce_to_clip_path(&self) -> bool {
|
||||
/// Whether this graphic clips as its outline would, with `inherited_appearance` cascading from an ancestor to vectors lacking their own.
|
||||
pub fn can_reduce_to_clip_path(&self, inherited_appearance: Option<&Appearance>) -> bool {
|
||||
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
||||
match self {
|
||||
Graphic::Vector(item) => {
|
||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing)
|
||||
&& vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
|
||||
let appearance = Appearance::cascade(item.attribute(ATTR_APPEARANCE), inherited_appearance);
|
||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), appearance)
|
||||
}
|
||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing)
|
||||
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
||||
let appearance = Appearance::cascade(list.attribute(ATTR_APPEARANCE, index), inherited_appearance);
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), appearance)
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
@@ -648,16 +649,22 @@ impl Graphic {
|
||||
pub fn is_guaranteed_fully_opaque(&self) -> bool {
|
||||
match self {
|
||||
Graphic::None(_) | Graphic::NoneList(_) => false,
|
||||
// The group's own opacity scales whatever it wraps, so full alpha there is a precondition
|
||||
Graphic::Graphic(item) => item_opacity_is_full(item) && item.element().is_guaranteed_fully_opaque(),
|
||||
Graphic::GraphicList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque),
|
||||
Graphic::Vector(item) => vector_is_guaranteed_fully_opaque(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
),
|
||||
// The group's own opacity and effects act on whatever it wraps, so they must keep it at full alpha
|
||||
Graphic::Graphic(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_opaque(),
|
||||
Graphic::GraphicList(list) => {
|
||||
!list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque)
|
||||
}
|
||||
Graphic::Vector(item) => {
|
||||
!item_effects_may_change_alpha(item)
|
||||
&& vector_is_guaranteed_fully_opaque(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
)
|
||||
}
|
||||
Graphic::VectorList(list) => {
|
||||
!list.is_empty()
|
||||
&& !list_effects_may_change_alpha(list)
|
||||
&& (0..list.len()).all(|index| {
|
||||
vector_is_guaranteed_fully_opaque(
|
||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||
@@ -669,11 +676,12 @@ 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()),
|
||||
Graphic::Color(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_opaque(),
|
||||
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
||||
// A `Clear` spread cuts off to transparency past the ends, and curved contours may leave gaps, leaving the rest of the region unpainted
|
||||
Graphic::Gradient(item) => {
|
||||
item_opacity_is_full(item)
|
||||
&& !item_effects_may_change_alpha(item)
|
||||
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
|
||||
&& gradient_paints_everywhere(&|key| item.attributes().get_any(key))
|
||||
&& item.element().iter().all(|stop| stop.color.is_opaque())
|
||||
@@ -681,6 +689,7 @@ impl Graphic {
|
||||
Graphic::GradientList(list) => {
|
||||
!list.is_empty()
|
||||
&& every_item_has_full_opacity(list)
|
||||
&& !list_effects_may_change_alpha(list)
|
||||
&& (0..list.len()).all(|index| {
|
||||
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
|
||||
&& gradient_paints_everywhere(&|key| list.attribute_any(key, index))
|
||||
@@ -693,27 +702,41 @@ impl Graphic {
|
||||
}
|
||||
|
||||
pub fn is_guaranteed_fully_transparent(&self) -> bool {
|
||||
// An effect that might change alpha, like Make Opaque or a shadow, can show content its paints leave transparent, so only its opacity can hide it
|
||||
match self {
|
||||
Graphic::None(_) | Graphic::NoneList(_) => true,
|
||||
Graphic::Graphic(item) => item_opacity_is_zero(item) || item.element().is_guaranteed_fully_transparent(),
|
||||
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent),
|
||||
Graphic::Vector(item) => vector_is_guaranteed_fully_transparent(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
),
|
||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||
vector_is_guaranteed_fully_transparent(
|
||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
||||
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
||||
)
|
||||
}),
|
||||
Graphic::Color(item) => item_opacity_is_zero(item) || item.element().a() == 0.,
|
||||
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|color| color.a() == 0.),
|
||||
Graphic::Graphic(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_transparent()),
|
||||
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent)),
|
||||
Graphic::Vector(item) => {
|
||||
item_opacity_is_zero(item)
|
||||
|| (!item_effects_may_change_alpha(item)
|
||||
&& vector_is_guaranteed_fully_transparent(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
item.attribute::<Effects>(ATTR_EFFECTS),
|
||||
))
|
||||
}
|
||||
Graphic::VectorList(list) => {
|
||||
every_item_has_zero_opacity(list)
|
||||
|| (!list_effects_may_change_alpha(list)
|
||||
&& (0..list.len()).all(|index| {
|
||||
vector_is_guaranteed_fully_transparent(
|
||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
||||
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index),
|
||||
)
|
||||
}))
|
||||
}
|
||||
Graphic::Color(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().a() == 0.),
|
||||
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.a() == 0.)),
|
||||
// A stopless ramp paints as solid black, matching `Gradient::evaluate`, so it counts as transparent only once it has stops
|
||||
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
||||
Graphic::GradientList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)),
|
||||
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && !item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
||||
Graphic::GradientList(list) => {
|
||||
every_item_has_zero_opacity(list)
|
||||
|| (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)))
|
||||
}
|
||||
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
||||
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
||||
@@ -806,12 +829,13 @@ fn vector_is_guaranteed_fully_opaque(opacity: f64, opacity_fill: f64, appearance
|
||||
}
|
||||
|
||||
/// Whether a vector object draws nothing visible, either through its opacity or through its paint.
|
||||
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>) -> bool {
|
||||
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>, effects: Option<&Effects>) -> bool {
|
||||
if opacity <= f64::EPSILON {
|
||||
return true;
|
||||
}
|
||||
|
||||
let fills_invisible = opacity_fill <= f64::EPSILON
|
||||
// Fill opacity fades the paints but not what effects paint at full strength, like overlays and shadows
|
||||
let fills_invisible = (opacity_fill <= f64::EPSILON && effects.is_none_or(Effects::change_nothing))
|
||||
|| appearance.is_none_or(|appearance| {
|
||||
appearance
|
||||
.covers_with_paints()
|
||||
@@ -829,6 +853,16 @@ fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appea
|
||||
fills_invisible && strokes_invisible
|
||||
}
|
||||
|
||||
/// Whether a lone item's effects might change its alpha, so its element's own alpha can't vouch for it being opaque or transparent.
|
||||
fn item_effects_may_change_alpha<T>(item: &Item<T>) -> bool {
|
||||
item.attribute::<Effects>(ATTR_EFFECTS).is_some_and(Effects::may_change_alpha)
|
||||
}
|
||||
|
||||
/// Whether the effects of any item of a list might change its alpha (see [`item_effects_may_change_alpha`]).
|
||||
fn list_effects_may_change_alpha<T>(list: &List<T>) -> bool {
|
||||
(0..list.len()).any(|index| list.attribute::<Effects>(ATTR_EFFECTS, index).is_some_and(Effects::may_change_alpha))
|
||||
}
|
||||
|
||||
/// Whether a lone item's opacity zeroes it out, independent of what its element holds.
|
||||
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
|
||||
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) <= f64::EPSILON
|
||||
@@ -859,7 +893,6 @@ fn gradient_paints_everywhere<'a>(attribute: &dyn Fn(&str) -> Option<&'a dyn std
|
||||
read::<f64>(attribute, ATTR_GRADIENT_START_CURVATURE).copied().unwrap_or_default(),
|
||||
read::<f64>(attribute, ATTR_GRADIENT_END_CURVATURE).copied().unwrap_or_default(),
|
||||
read::<GradientModel>(attribute, ATTR_GRADIENT_MODEL).copied().unwrap_or_default(),
|
||||
read::<GradientDirection>(attribute, ATTR_GRADIENT_DIRECTION).copied().unwrap_or_default(),
|
||||
read::<DAffine2>(attribute, ATTR_TRANSFORM).copied().unwrap_or_default(),
|
||||
)
|
||||
.paints_everywhere()
|
||||
@@ -1309,4 +1342,64 @@ mod graphic_is_opaque_tests {
|
||||
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
|
||||
assert!(!Graphic::Graphic(Box::new(reduced)).is_guaranteed_fully_opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_that_might_change_alpha_leave_content_neither_known_opaque_nor_known_transparent() {
|
||||
use crate::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
|
||||
use crate::effects::EffectOperation;
|
||||
use crate::vector_types::vector::style::Stroke;
|
||||
|
||||
let effected = |graphic: Graphic, operation: EffectOperation| Item::new_from_element(graphic).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]));
|
||||
let colors = |alpha: f64, operation: EffectOperation| {
|
||||
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
|
||||
Graphic::ColorList(List::new_from_item(Item::new_from_element(color).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]))))
|
||||
};
|
||||
let make_opaque = || EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
|
||||
let dissolve = || EffectOperation::Dissolve { opacity: 50., seed: 0 };
|
||||
let levels = |record: LevelsRecord, alpha: LevelsRecord| {
|
||||
EffectOperation::Adjustment(Adjustment::Levels(Box::new(LevelsSettings {
|
||||
composite: record,
|
||||
red: LevelsRecord::IDENTITY,
|
||||
green: LevelsRecord::IDENTITY,
|
||||
blue: LevelsRecord::IDENTITY,
|
||||
alpha,
|
||||
})))
|
||||
};
|
||||
let identity = LevelsRecord::IDENTITY;
|
||||
let darkened = LevelsRecord { output_maximums: 50., ..identity };
|
||||
|
||||
// Adjustments keeping alpha leave paints as opaque or transparent as their colors
|
||||
assert!(colors(1., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_opaque());
|
||||
assert!(colors(0., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_transparent());
|
||||
assert!(colors(1., levels(darkened, identity)).is_guaranteed_fully_opaque());
|
||||
|
||||
// Effects that might fade a paint, or show a transparent one, leave it unknown
|
||||
assert!(!colors(1., dissolve()).is_guaranteed_fully_opaque());
|
||||
assert!(!colors(1., levels(identity, darkened)).is_guaranteed_fully_opaque());
|
||||
assert!(!colors(0., make_opaque()).is_guaranteed_fully_transparent());
|
||||
assert!(!colors(0., make_opaque()).is_guaranteed_to_cover_opaquely());
|
||||
|
||||
// A group's own effects act on all it wraps, though its zero opacity still hides it
|
||||
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(1.), dissolve()))).is_guaranteed_fully_opaque());
|
||||
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()))).is_guaranteed_fully_transparent());
|
||||
assert!(Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()).with_attribute(ATTR_OPACITY, 0.))).is_guaranteed_fully_transparent());
|
||||
|
||||
// A vector's own effects, like a shadow cast by a shape with no visible paint, do too
|
||||
let mut shape = Item::new_from_element(Vector::default());
|
||||
shape.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_stroke(&Stroke::new(4.)), color_graphic(0.)));
|
||||
assert!(Graphic::Vector(Box::new(shape.clone())).is_guaranteed_fully_transparent());
|
||||
let shadowed = shape
|
||||
.clone()
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::default_for(crate::effects::EffectKind::DropShadow)]));
|
||||
assert!(!Graphic::Vector(Box::new(shadowed)).is_guaranteed_fully_transparent());
|
||||
|
||||
// Zero fill opacity hides a vector's paints but not an overlay its effects paint over them, though that keeps alpha
|
||||
let mut filled = Item::new_from_element(Vector::default()).with_attribute(ATTR_OPACITY_FILL, 0.);
|
||||
filled.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), color_graphic(1.)));
|
||||
assert!(Graphic::Vector(Box::new(filled.clone())).is_guaranteed_fully_transparent());
|
||||
let overlay = EffectOperation::default_for(crate::effects::EffectKind::PaintOverlay);
|
||||
assert!(matches!(overlay, EffectOperation::Adjustment(Adjustment::ColorOverlay { .. })), "{overlay:?}");
|
||||
let overlaid = filled.with_attribute(ATTR_EFFECTS, Effects::from_operations([overlay]));
|
||||
assert!(!Graphic::Vector(Box::new(overlaid)).is_guaranteed_fully_transparent());
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ pub use artboard::Artboard;
|
||||
pub use blend_if::BlendIfChannel;
|
||||
pub use effects::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||
stamp_effect, stamped_transform,
|
||||
stamp_effect, stamp_effect_on, stamped_transform,
|
||||
};
|
||||
pub use filters::NoiseDistribution;
|
||||
pub use generator::Generator;
|
||||
|
||||
@@ -1715,10 +1715,10 @@ impl EffectOperation {
|
||||
FrameWarp::of(self).is_some() || warp_of(self).is_some()
|
||||
}
|
||||
|
||||
/// Whether this operation takes the content's frame, which displacements and lattices measure from, unless it changes nothing.
|
||||
/// Whether this operation takes the content's frame, which displacements and lattices measure from and a median reads within, unless it changes nothing.
|
||||
pub fn takes_frame(&self) -> bool {
|
||||
match self {
|
||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } => !self.changes_nothing(),
|
||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } | Self::Median { .. } => !self.changes_nothing(),
|
||||
Self::Twirl { .. }
|
||||
| Self::Pinch { .. }
|
||||
| Self::Spherize { .. }
|
||||
|
||||
@@ -30,11 +30,12 @@ pub enum StepKind {
|
||||
ColorLookup,
|
||||
ColorOverlay,
|
||||
Solarize,
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl StepKind {
|
||||
/// Every kind, in the order of their codes.
|
||||
pub const ALL: [StepKind; 21] = [
|
||||
pub const ALL: [StepKind; 22] = [
|
||||
StepKind::Desaturate,
|
||||
StepKind::GammaCorrection,
|
||||
StepKind::MakeOpaque,
|
||||
@@ -56,6 +57,7 @@ impl StepKind {
|
||||
StepKind::ColorLookup,
|
||||
StepKind::ColorOverlay,
|
||||
StepKind::Solarize,
|
||||
StepKind::AlphaToGray,
|
||||
];
|
||||
|
||||
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
||||
@@ -269,6 +271,7 @@ mod tests {
|
||||
opacity: 50.,
|
||||
},
|
||||
Adjustment::Solarize,
|
||||
Adjustment::AlphaToGray,
|
||||
];
|
||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||
|
||||
|
||||
@@ -226,6 +226,7 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
||||
}
|
||||
Adjustment::Invert => visitor.visit(Invert),
|
||||
Adjustment::Solarize => visitor.visit(Solarize),
|
||||
Adjustment::AlphaToGray => visitor.visit(AlphaToGray),
|
||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||
min_luminance: (min_luminance / 100.) as f32,
|
||||
max_luminance: (max_luminance / 100.) as f32,
|
||||
@@ -1121,6 +1122,20 @@ impl MapColor for Solarize {
|
||||
}
|
||||
}
|
||||
|
||||
/// Grays each color to the gamma-encoded level of its alpha, keeping the alpha.
|
||||
struct AlphaToGray;
|
||||
|
||||
impl MapColor for AlphaToGray {
|
||||
fn map_cpu(&self, color: Color) -> Color {
|
||||
let gray = srgb_to_linear(color.a());
|
||||
color.map_rgb(|_| gray)
|
||||
}
|
||||
|
||||
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
||||
steps.push(StepKind::AlphaToGray, []);
|
||||
}
|
||||
}
|
||||
|
||||
struct Threshold {
|
||||
min_luminance: f32,
|
||||
max_luminance: f32,
|
||||
@@ -2007,4 +2022,69 @@ mod tests {
|
||||
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustments_changing_alpha_are_known_to_without_running_their_kernels() {
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use glam::DVec2;
|
||||
use graphic_types::effects::{EffectKind, EffectOperation};
|
||||
|
||||
let kinds = [
|
||||
EffectKind::Desaturate,
|
||||
EffectKind::GammaCorrection,
|
||||
EffectKind::MakeOpaque,
|
||||
EffectKind::BrightnessContrast,
|
||||
EffectKind::Levels,
|
||||
EffectKind::Curves,
|
||||
EffectKind::BlackAndWhite,
|
||||
EffectKind::HueSaturation,
|
||||
EffectKind::Invert,
|
||||
EffectKind::Threshold,
|
||||
EffectKind::GradientMap,
|
||||
EffectKind::Vibrance,
|
||||
EffectKind::ChannelMixer,
|
||||
EffectKind::SelectiveColor,
|
||||
EffectKind::Posterize,
|
||||
EffectKind::Exposure,
|
||||
EffectKind::ColorBalance,
|
||||
EffectKind::PhotoFilter,
|
||||
EffectKind::ColorLookup,
|
||||
EffectKind::Solarize,
|
||||
];
|
||||
let defaults = kinds.map(|kind| match EffectOperation::default_for(kind) {
|
||||
EffectOperation::Adjustment(adjustment) => adjustment,
|
||||
operation => panic!("{kind} isn't an adjustment: {operation:?}"),
|
||||
});
|
||||
|
||||
// Levels and Curves change alpha by their alpha records and curves, and nothing else of theirs
|
||||
let identity = settings::LevelsRecord::IDENTITY;
|
||||
let darkened = settings::LevelsRecord { output_maximums: 50., ..identity };
|
||||
let levels = |composite, alpha| {
|
||||
Adjustment::Levels(Box::new(settings::LevelsSettings {
|
||||
composite,
|
||||
red: identity,
|
||||
green: identity,
|
||||
blue: identity,
|
||||
alpha,
|
||||
}))
|
||||
};
|
||||
let curve = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(1., 0.5)]);
|
||||
let curves = |composite: TransferCurve, alpha: TransferCurve| {
|
||||
Adjustment::Curves(Box::new(settings::CurvesSettings {
|
||||
composite,
|
||||
alpha,
|
||||
..Default::default()
|
||||
}))
|
||||
};
|
||||
let settings = [
|
||||
levels(darkened, identity),
|
||||
levels(identity, darkened),
|
||||
curves(curve.clone(), TransferCurve::default()),
|
||||
curves(TransferCurve::default(), curve),
|
||||
];
|
||||
|
||||
for adjustment in defaults.iter().chain(&settings) {
|
||||
assert_eq!(adjustment.may_change_alpha(), !preserves_alpha(adjustment), "{adjustment:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The pixel filters on the CPU, which mirror the renderer's GPU passes on premultiplied gamma-encoded channels.
|
||||
|
||||
use crate::effect_kernels::{BlurKernel, Plane};
|
||||
use crate::resample_kernels::sample_bilinear;
|
||||
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use graphic_types::effects::{MAX_MEDIAN_GRID_RADIUS, spans_along_axes};
|
||||
use graphic_types::filters::{
|
||||
Convolution, FieldSampling, GAUSSIAN_NOISE_LIMIT, HIGH_PASS_GRAY, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, average_weight,
|
||||
edge_gain, fill_shifts, neighborhood_radii, noise_extent, unsharp, unsharp_change,
|
||||
@@ -10,6 +11,7 @@ use graphic_types::filters::{
|
||||
use graphic_types::generator::pcg3d;
|
||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Carries out a filter effect on premultiplied gamma-encoded pixels, which `pixels_to_effect` places in the effect space, or returns them as they are for any other operation.
|
||||
/// The pixels visible in the `full`-strength content (the plane itself for `None`) are those whose colors the filter reads.
|
||||
@@ -475,6 +477,105 @@ fn window_extremes(source: &[[f32; 4]], target: &mut [[f32; 4]], radius: usize,
|
||||
}
|
||||
}
|
||||
|
||||
/// The GPU's median of `radius` whole effect-space units, which `pixels_per_length` makes pixels along each axis, on a grid of a pixel to each unit coarsened past [`MAX_MEDIAN_GRID_RADIUS`] as the GPU's is.
|
||||
/// The `image` is the range of pixels along each axis holding the image, whose own pixels read only each other, and `origin` its corner, where the coarse grid starts.
|
||||
pub fn median_on_content_grid(plane: &Plane<[f32; 4]>, radius: f64, pixels_per_length: DVec2, origin: DVec2, image: [Range<usize>; 2]) -> Plane<[f32; 4]> {
|
||||
let whole = radius.max(0.).floor();
|
||||
let coarsening = (MAX_MEDIAN_GRID_RADIUS / whole).min(1.);
|
||||
if coarsening >= 1. {
|
||||
let radii = (pixels_per_length * whole).round().min(DVec2::new(plane.width as f64, plane.height as f64));
|
||||
return match radii == DVec2::ZERO {
|
||||
true => plane.clone(),
|
||||
false => median(plane, [radii.x as usize, radii.y as usize], image),
|
||||
};
|
||||
}
|
||||
|
||||
// The coarse grid's texels, each spanning this many pixels, lie on a lattice from the image's corner, as the GPU's lattice lies from the content's origin
|
||||
let texel = pixels_per_length / coarsening;
|
||||
let first = ((DVec2::ZERO - origin) / texel).floor();
|
||||
let end = ((DVec2::new(plane.width as f64, plane.height as f64) - origin) / texel).ceil();
|
||||
let size = (end - first).max(DVec2::ONE);
|
||||
let texel_center = |index: DVec2| origin + (first + index + 0.5) * texel;
|
||||
|
||||
// The content drawn onto the coarse grid by sampling it at each texel's center, as the GPU draws it
|
||||
let (coarse_width, coarse_height) = (size.x as usize, size.y as usize);
|
||||
let mut coarse = Plane::new(coarse_width, coarse_height);
|
||||
fill_rows(&mut coarse.data, coarse_width, |y, row| {
|
||||
for (x, texel) in row.iter_mut().enumerate() {
|
||||
*texel = sample_bilinear(plane, texel_center(DVec2::new(x as f64, y as f64)));
|
||||
}
|
||||
});
|
||||
|
||||
// The texels whose centers lie within the image, and the median over a window of the radius in texels, then resampled back onto the pixels
|
||||
let within = |axis: usize, count: usize| {
|
||||
let inside = |index: usize| image[axis].contains(&(texel_center(DVec2::splat(index as f64))[axis].floor().max(0.) as usize));
|
||||
let start = (0..count).find(|&index| inside(index)).unwrap_or(count);
|
||||
let end = (start..count).find(|&index| !inside(index)).unwrap_or(count);
|
||||
start..end
|
||||
};
|
||||
let radius_in_texels = (coarsening * whole).round() as usize;
|
||||
let medians = median(&coarse, [radius_in_texels; 2], [within(0, coarse_width), within(1, coarse_height)]);
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let center = DVec2::new(x as f64, y as f64) + 0.5;
|
||||
*pixel = sample_bilinear(&medians, (center - origin) / texel - first);
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// The median of each pixel's window reaching `across` and `down` pixels, as the GPU's median finds it: the alpha's among the window's pixels, with those past the plane's edges transparent,
|
||||
/// and each straight color's among those with coverage, taking the upper median of an even count. A pixel within the `within` range along each axis reads only pixels within it. O(width × height × across × down).
|
||||
pub fn median(plane: &Plane<[f32; 4]>, [across, down]: [usize; 2], within: [Range<usize>; 2]) -> Plane<[f32; 4]> {
|
||||
let inside = |x: isize, y: isize| x >= 0 && y >= 0 && within[0].contains(&(x as usize)) && within[1].contains(&(y as usize));
|
||||
let upper_median = |values: &mut [f32]| *values.select_nth_unstable_by(values.len() / 2, f32::total_cmp).1;
|
||||
let window_capacity = (2 * across + 1) * (2 * down + 1);
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
// Allocated once for the row and reused for each of its pixels
|
||||
let mut alphas: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut colors: [Vec<f32>; 3] = std::array::from_fn(|_| Vec::with_capacity(window_capacity));
|
||||
|
||||
let y = y as isize;
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let x = x as isize;
|
||||
alphas.clear();
|
||||
colors.iter_mut().for_each(Vec::clear);
|
||||
|
||||
let clips = inside(x, y);
|
||||
for read_y in y - down as isize..=y + down as isize {
|
||||
for read_x in x - across as isize..=x + across as isize {
|
||||
if clips && !inside(read_x, read_y) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let on_plane = read_x >= 0 && read_y >= 0 && (read_x as usize) < plane.width && (read_y as usize) < plane.height;
|
||||
let [red, green, blue, alpha] = if on_plane { plane.data[read_y as usize * plane.width + read_x as usize] } else { [0.; 4] };
|
||||
alphas.push(alpha.min(1.));
|
||||
if alpha > 0. {
|
||||
// Kept within the finite range of the GPU's half floats
|
||||
let straight = |channel: f32| (channel / alpha).max(0.).min(65504.);
|
||||
colors.iter_mut().zip([red, green, blue]).for_each(|(values, channel)| values.push(straight(channel)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let alpha = upper_median(&mut alphas);
|
||||
*pixel = match colors[0].is_empty() || !(alpha > 0.) {
|
||||
true => [0.; 4],
|
||||
false => {
|
||||
let [red, green, blue] = colors.each_mut().map(|values| upper_median(values));
|
||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// A value strictly between 0 and 1 from the top 23 bits of a hash, which an f32 holds exactly with the half added, matching the GPU's.
|
||||
fn unit_interval(hash: u32) -> f32 {
|
||||
((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32
|
||||
|
||||
@@ -18,4 +18,4 @@ pub mod warp_kernels;
|
||||
|
||||
pub use kernel::*;
|
||||
pub use raster_effects::evaluate_raster_effects;
|
||||
pub use value_effects::{evaluate_color_effects, evaluate_gradient_effects};
|
||||
pub use value_effects::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
|
||||
@@ -13,7 +13,7 @@ use crate::warp_kernels::WarpRasterizer;
|
||||
use core_types::FallibleVec2Operations;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE, Item, List};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE, Item, List};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
@@ -550,6 +550,16 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
}
|
||||
// An image of its own has nothing beneath it to blur, or for Blend If to read, which fades the content where it acts
|
||||
EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => {}
|
||||
EffectOperation::Median { radius } => {
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
let origin = DVec2::new(margin_x as f64, margin_y as f64);
|
||||
let median = |plane: &Plane<[f32; 4]>| {
|
||||
let image = [margin_x..margin_x + width, margin_y..margin_y + height];
|
||||
crate::filter_kernels::median_on_content_grid(plane, radius, pixels_per_length, origin, image)
|
||||
};
|
||||
full = median(&full);
|
||||
filled = filled.map(|filled| median(&filled));
|
||||
}
|
||||
// A solid paint overlay paints within the content alone, like any other paint overlay
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => {
|
||||
let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32));
|
||||
@@ -1510,7 +1520,6 @@ fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> Optio
|
||||
item.attribute_cloned_or_default(ATTR_GRADIENT_START_CURVATURE),
|
||||
item.attribute_cloned_or_default(ATTR_GRADIENT_END_CURVATURE),
|
||||
item.attribute_cloned_or_default(ATTR_GRADIENT_MODEL),
|
||||
item.attribute_cloned_or_default(ATTR_GRADIENT_DIRECTION),
|
||||
placement,
|
||||
);
|
||||
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
|
||||
@@ -1537,10 +1546,6 @@ fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> Optio
|
||||
let to_unit = to_unit?;
|
||||
Some(Box::new(move |point| Some(parameters.t(to_unit.transform_point2(point)))))
|
||||
}
|
||||
GradientShape::Across(across) => {
|
||||
let to_unit = to_unit?;
|
||||
Some(Box::new(move |point| across.chart.v(to_unit.transform_point2(point))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1627,33 +1632,6 @@ mod tests {
|
||||
assert!(alpha_at(5, 5) > 0.9, "{}", alpha_at(5, 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradients_read_across_their_contours_take_positions_around_them() {
|
||||
use std::f64::consts::TAU;
|
||||
use vector_types::gradient::GradientDirection;
|
||||
|
||||
// A sheared placement, which the linear form read across its line follows in full
|
||||
let placement = DAffine2::from_cols(DVec2::new(40., 10.), DVec2::new(-5., 25.), DVec2::new(7., 3.));
|
||||
let across = |[start, end]: [f64; 2]| {
|
||||
Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
|
||||
.with_attribute(ATTR_TRANSFORM, placement)
|
||||
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start)
|
||||
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end)
|
||||
.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across)
|
||||
};
|
||||
let (Some(linear), Some(radial)) = (gradient_position(&across([0., 0.])), gradient_position(&across([-1., 0.5]))) else {
|
||||
panic!("both forms should be read across their contours");
|
||||
};
|
||||
|
||||
for unit in [DVec2::new(0.3, 0.2), DVec2::new(-0.5, 0.7), DVec2::new(0.9, -0.4)] {
|
||||
let point = placement.transform_point2(unit);
|
||||
assert!(linear(point).is_some_and(|v| (v - unit.y).abs() < 1e-9), "linear at {unit}");
|
||||
|
||||
let angle = unit.y.atan2(unit.x).rem_euclid(TAU) / TAU;
|
||||
assert!(radial(point).is_some_and(|v| (v - angle).abs() < 1e-9), "radial at {unit}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_paints_fade_by_their_fill_once_with_effects_of_their_own() {
|
||||
use graphic_types::EffectKind;
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::adjustments::{PreparedAdjustment, adjust_color};
|
||||
use crate::blending::overlay_paint;
|
||||
use core_types::Color;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_OPACITY, ATTR_OPACITY_FILL, Item};
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
|
||||
use graphic_types::effects::{EffectOperation, Effects};
|
||||
@@ -258,9 +258,24 @@ pub fn adjusted_gradient_with_blend_ifs(
|
||||
Some((resampled, resampled_settings))
|
||||
}
|
||||
|
||||
/// Whether [`color_after_effects`] and [`gradient_after_effects`] carry out every one of the effects, since each changes every color on its own:
|
||||
/// an adjustment, a Blend If reading only the value's own colors, or an effect that changes nothing.
|
||||
pub fn carries_out_every_effect(effects: &Effects) -> bool {
|
||||
effects.operations().all(|operation| match operation {
|
||||
EffectOperation::Adjustment(_) => true,
|
||||
EffectOperation::BlendIf(ranges) => ranges.underlying.show_everything(),
|
||||
_ => operation.changes_nothing(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
|
||||
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
|
||||
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||
filled_color_after_effects(color, effects, 1.)
|
||||
}
|
||||
|
||||
/// Like [`color_after_effects`], carried out over the color faded by a `fill`, which leaves the paint overlays among them at full strength, as the renderers fade content.
|
||||
pub fn filled_color_after_effects(color: Color, effects: &Effects, fill: f32) -> Color {
|
||||
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), fill)
|
||||
}
|
||||
|
||||
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
|
||||
@@ -270,10 +285,15 @@ pub fn prepared_color_after_effects(effects: &Effects) -> Box<dyn Fn(Color) -> C
|
||||
|
||||
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
|
||||
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
|
||||
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||
filled_gradient_after_effects(gradient, settings, effects, 1.)
|
||||
}
|
||||
|
||||
/// The color with its effects carried out as [`color_after_effects`] does and consumed, for nodes that read the color.
|
||||
/// Like [`gradient_after_effects`], carried out along the ramp faded by a `fill` as [`filled_color_after_effects`] carries them out on a color.
|
||||
pub fn filled_gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects, fill: f32) -> Option<(Gradient, GradientSettings)> {
|
||||
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), fill)
|
||||
}
|
||||
|
||||
/// The color with its effects carried out as [`color_after_effects`] does and consumed, though not its opacity (see [`evaluate_color_parameter`]).
|
||||
/// A color without the effects attribute is returned as it is.
|
||||
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
||||
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
|
||||
@@ -286,6 +306,27 @@ pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
||||
item
|
||||
}
|
||||
|
||||
/// The color as the renderers show it, for a node reading it as a parameter: its effects carried out over it faded by its fill, then its opacity fading it all, each consumed.
|
||||
/// Every node reading one color goes through this, so those attributes mean the same to all of them.
|
||||
pub fn evaluate_color_parameter(item: Item<Color>) -> Item<Color> {
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
|
||||
let (adjustments, blend_ifs) = item
|
||||
.attribute::<Effects>(ATTR_EFFECTS)
|
||||
.map(|effects| (adjustments(effects), content_blend_ifs(effects)))
|
||||
.unwrap_or_default();
|
||||
|
||||
let shown = filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill);
|
||||
let mut item = item;
|
||||
*item.element_mut() = shown.with_alpha(shown.a() * opacity);
|
||||
|
||||
// Consumed so a node passing the item on doesn't get them carried out twice where it's drawn
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item.remove_attribute::<f64>(ATTR_OPACITY);
|
||||
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
|
||||
item
|
||||
}
|
||||
|
||||
/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors.
|
||||
/// A gradient without the effects attribute is returned as it is.
|
||||
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
||||
@@ -351,6 +392,21 @@ mod tests {
|
||||
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_parameters_fill_fades_it_beneath_its_paint_overlays_and_its_opacity_over_them() {
|
||||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let unfilled = Item::new_from_element(Color::BLACK)
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([red]))
|
||||
.with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||||
|
||||
assert!(close(gamma(*evaluate_color_parameter(unfilled.clone()).element()), [1., 0., 0., 1.]));
|
||||
assert!(close(gamma(*evaluate_color_parameter(unfilled.with_attribute(ATTR_OPACITY, 0.5_f64)).element()), [1., 0., 0., 0.5]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::renderer::{
|
||||
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, painted_gradient, spread_adjusted_samples,
|
||||
svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
|
||||
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, paint_draws_by_its_colors, painted_gradient,
|
||||
spread_adjusted_samples, svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
|
||||
};
|
||||
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||
use core_types::color::SRGBA8;
|
||||
@@ -88,7 +88,7 @@ impl RenderExt for List<Color> {
|
||||
|
||||
/// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing.
|
||||
/// One painted through a mask fills a pattern spanning `bounds`, which `stroke_transform` places in the painted element's space.
|
||||
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
|
||||
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_fill_and_opacity`] explains.
|
||||
fn render_gradient_paint(
|
||||
item: Option<ItemRef<'_, Gradient>>,
|
||||
svg_defs: &mut String,
|
||||
@@ -101,14 +101,13 @@ fn render_gradient_paint(
|
||||
let mut stop = String::new();
|
||||
|
||||
let item = item?;
|
||||
let (stops, settings) = painted_gradient(item)?;
|
||||
let (stops, settings, paint_opacity) = painted_gradient(item, for_mask)?;
|
||||
let shape = gradient_shape(item);
|
||||
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
|
||||
let mut samples = spread_adjusted_samples(&stops, settings, shape);
|
||||
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
|
||||
with_two_stops_at_least(shape, &mut samples);
|
||||
|
||||
let paint_opacity = item.paint_opacity(for_mask);
|
||||
if paint_opacity < 1. {
|
||||
for (_, color, _) in &mut samples {
|
||||
*color = color.with_alpha(color.a() * paint_opacity);
|
||||
@@ -303,10 +302,11 @@ impl RenderExt for Graphic {
|
||||
target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
let paint_attr = target.paint_attr();
|
||||
let by_colors = paint_draws_by_its_colors(self);
|
||||
|
||||
match self {
|
||||
Graphic::Color(item) => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
||||
Graphic::ColorList(color_list) => color_list.render(
|
||||
Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
||||
Graphic::ColorList(color_list) if by_colors => color_list.render(
|
||||
svg_defs,
|
||||
user_to_document,
|
||||
paint_reach,
|
||||
@@ -317,11 +317,11 @@ impl RenderExt for Graphic {
|
||||
render_params,
|
||||
target,
|
||||
),
|
||||
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
|
||||
Graphic::Gradient(item) if by_colors => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
|
||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
|
||||
Graphic::GradientList(gradient_list) if gradient_list.len() <= 1 => gradient_list
|
||||
Graphic::GradientList(gradient_list) if by_colors => gradient_list
|
||||
.render(
|
||||
svg_defs,
|
||||
user_to_document,
|
||||
@@ -336,7 +336,10 @@ impl RenderExt for Graphic {
|
||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
|
||||
Graphic::Graphic(_)
|
||||
Graphic::Color(_)
|
||||
| Graphic::ColorList(_)
|
||||
| Graphic::Gradient(_)
|
||||
| Graphic::Graphic(_)
|
||||
| Graphic::Vector(_)
|
||||
| Graphic::RasterCPU(_)
|
||||
| Graphic::RasterGPU(_)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -98,6 +98,8 @@ impl SvgFilterPrimitives {
|
||||
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
||||
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
|
||||
// No SVG primitive ranks values, and the GPU's median runs on the content's own grid besides
|
||||
EffectOperation::Median { .. } => self.map_showing(capture, image),
|
||||
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
|
||||
EffectOperation::Speckle { amount, distribution, .. } => self.speckle(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
||||
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
|
||||
|
||||
@@ -11,7 +11,7 @@ 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::{ApollonianGradient, Image, ImageSource, PaintType, PolarGradient, TextureId, TextureRegion};
|
||||
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;
|
||||
@@ -100,9 +100,7 @@ pub enum SceneBrush<'b> {
|
||||
/// A solid color, gradient, or image.
|
||||
Peniko(BrushRef<'b>),
|
||||
/// A gradient whose contours are Apollonian circles, which only Vello GPU's fork draws.
|
||||
Apollonian(&'b ApollonianGradient),
|
||||
/// A gradient whose position runs around its contours, which only Vello GPU's fork draws.
|
||||
Polar(&'b PolarGradient),
|
||||
Apollonian(&'b PencilGradient),
|
||||
}
|
||||
|
||||
impl<'b> From<BrushRef<'b>> for SceneBrush<'b> {
|
||||
@@ -135,18 +133,12 @@ impl From<&peniko::Color> for SceneBrush<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'b> From<&'b ApollonianGradient> for SceneBrush<'b> {
|
||||
fn from(gradient: &'b ApollonianGradient) -> Self {
|
||||
impl<'b> From<&'b PencilGradient> for SceneBrush<'b> {
|
||||
fn from(gradient: &'b PencilGradient) -> Self {
|
||||
Self::Apollonian(gradient)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'b> From<&'b PolarGradient> for SceneBrush<'b> {
|
||||
fn from(gradient: &'b PolarGradient) -> Self {
|
||||
Self::Polar(gradient)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels behind an image the scene draws.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SceneImage {
|
||||
@@ -592,9 +584,12 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
square && !operation.changes_nothing()
|
||||
});
|
||||
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
|
||||
let (frame_to_device, lengths_to_frame) = match follows_viewport {
|
||||
true => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
||||
false => {
|
||||
// Effects that don't commute with resampling, like a median, work on the content's own grid of a texel to each unit of the effect space, then resample to the view
|
||||
let content_grid_resolution = effects.content_grid_resolution();
|
||||
let (frame_to_device, lengths_to_frame) = match (content_grid_resolution, follows_viewport) {
|
||||
(Some(_), _) => (effect_to_device, DMat2::IDENTITY),
|
||||
(None, true) => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
||||
(None, false) => {
|
||||
let density = largest_stretch(effect_to_device.matrix2);
|
||||
(effect_to_device * DAffine2::from_scale(DVec2::splat(1. / density)), DMat2::from_diagonal(DVec2::splat(density)))
|
||||
}
|
||||
@@ -655,7 +650,15 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
// A region too large for one texture, or for its memory, renders at a lower resolution, which the blurs and shadows that make it so large hide.
|
||||
// Its size rounds up to a size class so a group that moves between renders keeps reusing the same textures.
|
||||
let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt()).min(1.);
|
||||
let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt());
|
||||
let resolution = resolution.min(content_grid_resolution.unwrap_or(1.)).min(1.);
|
||||
|
||||
// A coarsened content grid keeps its texels on one lattice of the effect space, so they don't slide across the content as the view pans
|
||||
if content_grid_resolution.is_some() && resolution < 1. {
|
||||
let snap = |coordinate: f64| (coordinate * resolution).floor() / resolution;
|
||||
region = Rect::new(snap(region.x0), snap(region.y0), region.x1, region.y1);
|
||||
}
|
||||
|
||||
let size_along = |length: f64| ((length * resolution).ceil() as u32).next_multiple_of(EFFECTS_SIZE_CLASS).min(max_size);
|
||||
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
||||
let origin = region.origin().to_vec2();
|
||||
@@ -752,11 +755,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
fn set_paint(&mut self, brush: SceneBrush<'_>) -> Option<Affine> {
|
||||
let (paint, paint_to_brush) = match brush {
|
||||
SceneBrush::Apollonian(gradient) => {
|
||||
self.scene.set_apollonian_gradient_paint(gradient.clone());
|
||||
return Some(Affine::IDENTITY);
|
||||
}
|
||||
SceneBrush::Polar(gradient) => {
|
||||
self.scene.set_polar_gradient_paint(gradient.clone());
|
||||
self.scene.set_pencil_gradient_paint(gradient.clone());
|
||||
return Some(Affine::IDENTITY);
|
||||
}
|
||||
SceneBrush::Peniko(BrushRef::Solid(color)) => (PaintType::Solid(color), Affine::IDENTITY),
|
||||
|
||||
@@ -211,7 +211,7 @@ fn a_clip_path_becomes_a_hidden_clipper_beneath_the_content_it_clips() -> Result
|
||||
let content = converted(r#"<clipPath id="clip"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)"><rect width="8" height="8"/></g>"#)?;
|
||||
|
||||
let clipped = group(&content, 0);
|
||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
|
||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
|
||||
assert_eq!(clipped.and_then(|clipped| clipped.attribute::<f64>(ATTR_OPACITY_FILL, 0)), Some(&0.));
|
||||
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||
Ok(())
|
||||
@@ -314,7 +314,7 @@ fn a_mask_region_that_cuts_its_content_clips_the_masked_content() -> Result<(),
|
||||
let within_region = group(&content, 0).and_then(|masked| masked.element(1));
|
||||
assert!(within_region.is_some_and(Graphic::had_clip_enabled));
|
||||
let clipped = within_region.and_then(Graphic::as_graphic_list);
|
||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
|
||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
|
||||
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1856,19 +1856,6 @@ pub enum GradientModel {
|
||||
Apollonian,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[widget(Radio)]
|
||||
pub enum GradientDirection {
|
||||
/// Reads the colors from start to end, each contour taking one color.
|
||||
#[default]
|
||||
Along,
|
||||
/// Reads the colors around each contour instead, once clockwise around curved ones, or beside the gradient line in the linear form. Except for the linear form, SVG exports include it as an image, and PDF exports show an approximation.
|
||||
Across,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
|
||||
@@ -1,479 +0,0 @@
|
||||
//! Gradients read across their contours rather than along them, where each point's position `v` runs around or beside the contour through it.
|
||||
//!
|
||||
//! Everything here is in gradient space, laid out as in [`crate::gradient_standard`], and `v` increases toward +y (clockwise on screen for an
|
||||
//! unreflected placement). A winding chart measures an angle in turns within `[0, 1)`, wrapping at a seam on the +x side where the spread has no
|
||||
//! effect. The others measure from the gradient line, 0 on it and one unit per gradient length across its midpoint, which the spread then repeats.
|
||||
|
||||
use crate::gradient::{GradientForm, GradientModel};
|
||||
use crate::gradient_apollonian::{AxisCircle, CircleFamily, Homogeneous};
|
||||
use crate::gradient_standard::{Cone, GradientStandard, HalfPlane, NEAR_LINE_RADIUS, curvature_radius};
|
||||
use glam::DVec2;
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
/// How far apart a cone's two centers may be, relative to its size, for it to be drawn as concentric circles.
|
||||
const CONCENTRIC_TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// A gradient read across its contours.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct GradientAcross {
|
||||
pub chart: AcrossChart,
|
||||
/// The form its curvatures make, if either.
|
||||
pub form: Option<GradientForm>,
|
||||
}
|
||||
|
||||
/// How each point of a gradient read across its contours finds its position `v`, in gradient space.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum AcrossChart {
|
||||
/// The linear form's: `v = y`.
|
||||
Linear,
|
||||
/// Concentric circles': the angle around their shared center at `(center, 0)`, from the +x ray.
|
||||
Concentric { center: f64 },
|
||||
/// SVG 2's cone's: the angle of the point around the center of the cone's circle through it, unpainted where the cone is and past `keep`'s line.
|
||||
Cone { cone: Cone, keep: Option<HalfPlane> },
|
||||
/// Apollonian circles nesting around two limit points: the angle of `M(z) = (n₀ z + n₁) / (d₀ z + d₁)`, which sends the limit point the
|
||||
/// end contour encloses to 0 and the other to infinity, so each contour of constant `v` is an arc from one limit point to the other.
|
||||
Mobius { numerator: [f64; 2], denominator: [f64; 2] },
|
||||
/// Apollonian circles crossing at `(center_x, ±half_height)`: `scale · ln(|z - (center_x, -half_height)| / |z - (center_x, half_height)|)`,
|
||||
/// the bipolar coordinate whose contours are the circles around the two crossings.
|
||||
Bipolar { center_x: f64, half_height: f64, scale: f64 },
|
||||
/// Unpainted everywhere, as SVG 2 leaves identical end circles.
|
||||
Nothing,
|
||||
}
|
||||
|
||||
impl AcrossChart {
|
||||
/// The chart of a gradient with these curvatures, which must be finite and within -1 to 1, and model.
|
||||
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel) -> Self {
|
||||
match (GradientForm::from_curvatures([start_curvature, end_curvature]), model) {
|
||||
(Some(GradientForm::Linear), _) => Self::Linear,
|
||||
(Some(GradientForm::Radial), _) => Self::Concentric { center: 0. },
|
||||
(None, GradientModel::Standard) => Self::standard(start_curvature, end_curvature),
|
||||
(None, GradientModel::Apollonian) => Self::apollonian(start_curvature, end_curvature),
|
||||
}
|
||||
}
|
||||
|
||||
/// The angle around SVG 2's circles, painting where the Standard model's gradient read along them paints.
|
||||
fn standard(start_curvature: f64, end_curvature: f64) -> Self {
|
||||
match GradientStandard::new(start_curvature, end_curvature) {
|
||||
GradientStandard::Cone(cone) => Self::cone(cone, None),
|
||||
// A line end and a nearly flat cone, drawn as a profile along the gradient line, measure around the cone that's drawn at the flattest radius
|
||||
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => Self::cone(near_line_cone(start_curvature, end_curvature), keep),
|
||||
GradientStandard::Profile { .. } => Self::cone(near_line_cone(start_curvature, end_curvature), None),
|
||||
GradientStandard::Nothing => Self::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
fn cone(cone: Cone, keep: Option<HalfPlane>) -> Self {
|
||||
let size = cone.start_center.abs().max(cone.end_center.abs()).max(cone.start_radius).max(cone.end_radius);
|
||||
let concentric = (cone.end_center - cone.start_center).abs() <= CONCENTRIC_TOLERANCE * size;
|
||||
|
||||
match keep {
|
||||
None if concentric => Self::Concentric { center: cone.start_center },
|
||||
_ => Self::Cone { cone, keep },
|
||||
}
|
||||
}
|
||||
|
||||
/// The angle around the limit points of the Apollonian circles, or the bipolar coordinate beside their crossings.
|
||||
fn apollonian(start_curvature: f64, end_curvature: f64) -> Self {
|
||||
// Identical end circles span no family of circles, and draw the linear form's plain ramp
|
||||
let (start_radius, end_radius) = (curvature_radius(start_curvature), curvature_radius(end_curvature));
|
||||
if start_radius.is_finite() && end_radius.is_finite() && Cone::between(start_radius, end_radius).is_identical() {
|
||||
return Self::Linear;
|
||||
}
|
||||
|
||||
let (start, end) = (AxisCircle::start(start_curvature), AxisCircle::end(end_curvature));
|
||||
match CircleFamily::of(start, end) {
|
||||
CircleFamily::Crossing { radical_x } => Self::bipolar(start, end, radical_x),
|
||||
CircleFamily::Nesting { limit_points } => Self::mobius(start, end, limit_points),
|
||||
}
|
||||
}
|
||||
|
||||
fn bipolar(start: AxisCircle, end: AxisCircle, radical_x: f64) -> Self {
|
||||
// The crossings lie on whichever end contour is rounder, which places them most precisely
|
||||
let circle = if start.a.abs() >= end.a.abs() { start } else { end };
|
||||
let half_height = (-(circle.b * radical_x + circle.c) / circle.a - radical_x * radical_x).max(0.).sqrt().max(f64::MIN_POSITIVE);
|
||||
|
||||
// The coordinate's rate across the gradient line at its midpoint is `half_height / (half_height² + (1/2 - radical_x)²)` before this scale
|
||||
let midpoint_offset = 0.5 - radical_x;
|
||||
let scale = (half_height * half_height + midpoint_offset * midpoint_offset) / (2. * half_height);
|
||||
|
||||
Self::Bipolar {
|
||||
center_x: radical_x,
|
||||
half_height,
|
||||
scale,
|
||||
}
|
||||
}
|
||||
|
||||
fn mobius(start: AxisCircle, end: AxisCircle, limit_points: [Homogeneous; 2]) -> Self {
|
||||
// With nonnegative denominators, a point's sign on a contour doesn't depend on how it's scaled
|
||||
let oriented = |point: Homogeneous| {
|
||||
let sign = if point.denominator < 0. { -1. } else { 1. };
|
||||
Homogeneous {
|
||||
numerator: point.numerator * sign,
|
||||
denominator: point.denominator * sign,
|
||||
}
|
||||
};
|
||||
let [first, second] = limit_points.map(oriented);
|
||||
|
||||
// The limit point inside the end contour, or the start contour where the end is a line, is negative on it (or zero, for a point contour on it)
|
||||
let inside = |circle: AxisCircle, point: Homogeneous| {
|
||||
let Homogeneous { numerator, denominator } = point;
|
||||
circle.a * (circle.a * numerator * numerator + circle.b * numerator * denominator + circle.c * denominator * denominator)
|
||||
};
|
||||
let enclosing = if end.a != 0. { end } else { start };
|
||||
let (enclosed, other) = if inside(enclosing, first) <= inside(enclosing, second) {
|
||||
(first, second)
|
||||
} else {
|
||||
(second, first)
|
||||
};
|
||||
|
||||
// Concentric circles have their other limit point at infinity, about which the angle is around their shared center
|
||||
let Some(center) = enclosed.value() else { return Self::Linear };
|
||||
if other.denominator == 0. {
|
||||
return Self::Concentric { center };
|
||||
}
|
||||
|
||||
// `M(z) = ±(z - enclosed) / (other - z)`, signed so `M` is positive on the +x ray from the enclosed limit point as `other` passes through infinity
|
||||
let product = other.numerator * enclosed.denominator - enclosed.numerator * other.denominator;
|
||||
let sign = if product < 0. { -1. } else { 1. };
|
||||
Self::Mobius {
|
||||
numerator: [sign * enclosed.denominator, -sign * enclosed.numerator],
|
||||
denominator: [-other.denominator, other.numerator],
|
||||
}
|
||||
}
|
||||
|
||||
/// The position at `point`, or `None` where it's unpainted.
|
||||
pub fn v(&self, point: DVec2) -> Option<f64> {
|
||||
match *self {
|
||||
Self::Linear => Some(point.y),
|
||||
Self::Concentric { center } => Some(turns(point.y, point.x - center)),
|
||||
Self::Cone { cone, keep } => {
|
||||
if keep.is_some_and(|keep| !keep.keeps(point.x)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let t = cone.t(point)?;
|
||||
let center = cone.start_center + t * (cone.end_center - cone.start_center);
|
||||
Some(turns(point.y, point.x - center))
|
||||
}
|
||||
Self::Mobius { numerator, denominator } => {
|
||||
// The angle of `numerator / denominator` is that of `numerator · conj(denominator)`
|
||||
let affine = |[slope, intercept]: [f64; 2]| DVec2::new(slope * point.x + intercept, slope * point.y);
|
||||
let (numerator, denominator) = (affine(numerator), affine(denominator));
|
||||
Some(turns(numerator.y * denominator.x - numerator.x * denominator.y, numerator.dot(denominator)))
|
||||
}
|
||||
Self::Bipolar { center_x, half_height, scale } => {
|
||||
// The squared distances to the crossings differ by `4 half_height y`, whose ratio's logarithm keeps its precision near the gradient line
|
||||
let to_upper = DVec2::new(point.x - center_x, point.y - half_height).length_squared();
|
||||
Some(scale * 0.5 * (4. * half_height * point.y / to_upper).ln_1p())
|
||||
}
|
||||
Self::Nothing => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether it measures an angle, wrapping from 1 back to 0 at a seam, rather than a distance from the gradient line.
|
||||
pub fn winds(&self) -> bool {
|
||||
matches!(self, Self::Concentric { .. } | Self::Cone { .. } | Self::Mobius { .. })
|
||||
}
|
||||
|
||||
/// Whether it paints every point, rather than leaving some unpainted.
|
||||
pub fn paints_everywhere(&self) -> bool {
|
||||
match self {
|
||||
Self::Linear | Self::Concentric { .. } | Self::Mobius { .. } | Self::Bipolar { .. } => true,
|
||||
Self::Cone { cone, keep } => keep.is_none() && cone.is_nested(),
|
||||
Self::Nothing => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether SVG draws it exactly, which only the linear form's ramp across the gradient line is (and nothing at all).
|
||||
pub fn svg_draws_exactly(&self) -> bool {
|
||||
matches!(self, Self::Linear | Self::Nothing)
|
||||
}
|
||||
}
|
||||
|
||||
/// The cone between the end contours with these curvatures, each a nearly flat circle or a line drawn at the flattest radius a cone is (a line bowing toward the other end).
|
||||
fn near_line_cone(start_curvature: f64, end_curvature: f64) -> Cone {
|
||||
let near_line_radius = |curvature: f64| {
|
||||
let radius = curvature_radius(curvature);
|
||||
if radius.is_infinite() {
|
||||
NEAR_LINE_RADIUS
|
||||
} else {
|
||||
radius.clamp(-NEAR_LINE_RADIUS, NEAR_LINE_RADIUS)
|
||||
}
|
||||
};
|
||||
Cone::between(near_line_radius(start_curvature), near_line_radius(end_curvature))
|
||||
}
|
||||
|
||||
/// The angle of `(x, y)` from the +x axis toward the +y axis, in turns within `[0, 1)`.
|
||||
fn turns(y: f64, x: f64) -> f64 {
|
||||
let turns = y.atan2(x).rem_euclid(TAU) / TAU;
|
||||
if turns >= 1. { 0. } else { turns }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::gradient::{LINEAR_CURVATURES, RADIAL_CURVATURES};
|
||||
use crate::gradient_apollonian::GradientApollonian;
|
||||
use crate::gradient_standard::radius_curvature;
|
||||
|
||||
/// Points spread over a view around the gradient line, kept off its exact rational coordinates.
|
||||
fn sample_points() -> impl Iterator<Item = DVec2> {
|
||||
(-30..=40).flat_map(|x| (-25..=25).map(move |y| DVec2::new(x as f64 * 0.1 + 0.0013, y as f64 * 0.1 + 0.0007)))
|
||||
}
|
||||
|
||||
/// The distance between two angles in turns, the short way around.
|
||||
fn turn_distance(first: f64, second: f64) -> f64 {
|
||||
let distance = (first - second).rem_euclid(1.);
|
||||
distance.min(1. - distance)
|
||||
}
|
||||
|
||||
/// Curvature pairs of every kind: circles crossing, nested, apart, and concentric, lines and points beside them, and nearly flat circles.
|
||||
fn curvature_pairs() -> Vec<[f64; 2]> {
|
||||
let mut pairs: Vec<[f64; 2]> = [
|
||||
(0., 0.75),
|
||||
(0.2, 1.5),
|
||||
(2., -0.5),
|
||||
(0.6, 0.6),
|
||||
(-0.3, -0.3),
|
||||
(0., -0.4),
|
||||
(2., -1.),
|
||||
(-0.5, 1.5),
|
||||
(0.8, 1e9),
|
||||
(-0.3, 1e9),
|
||||
(1e9, 0.25),
|
||||
(1e9, 2.),
|
||||
(3000., -2500.),
|
||||
(0.3, 2500.),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(start, end)| [radius_curvature(start), radius_curvature(end)])
|
||||
.collect();
|
||||
pairs.extend([[1., 0.3], [1., 1.], [0.8, -1.], [0.4, 0.], [0., -0.4], [-0.3, 0.]]);
|
||||
pairs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_linear_form_reads_across_the_gradient_line() {
|
||||
for model in [GradientModel::Standard, GradientModel::Apollonian] {
|
||||
let chart = AcrossChart::new(LINEAR_CURVATURES[0], LINEAR_CURVATURES[1], model);
|
||||
assert_eq!(chart, AcrossChart::Linear);
|
||||
for point in sample_points() {
|
||||
assert_eq!(chart.v(point), Some(point.y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_radial_form_reads_the_angle_around_its_center() {
|
||||
for model in [GradientModel::Standard, GradientModel::Apollonian] {
|
||||
let chart = AcrossChart::new(RADIAL_CURVATURES[0], RADIAL_CURVATURES[1], model);
|
||||
for point in sample_points() {
|
||||
let expected = point.y.atan2(point.x).rem_euclid(TAU) / TAU;
|
||||
assert!(turn_distance(chart.v(point).unwrap(), expected) < 1e-12, "{model:?} at {point}");
|
||||
}
|
||||
|
||||
// Clockwise on screen, from the seam along the gradient line
|
||||
assert!((chart.v(DVec2::new(0., 1.)).unwrap() - 0.25).abs() < 1e-12);
|
||||
assert!(chart.v(DVec2::new(0.5, 1e-9)).unwrap() < 1e-6 && chart.v(DVec2::new(0.5, -1e-9)).unwrap() > 1. - 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_models_read_concentric_circles_around_their_center() {
|
||||
// The start circle centered at its radius and the end at 1 minus its own share a center, with the end circle outside or inside the start circle
|
||||
for start_radius in [-1., -0.5, 0.25, 2., 3.] {
|
||||
let curvatures = [radius_curvature(start_radius), radius_curvature(1. - start_radius)];
|
||||
let [standard, apollonian] = [GradientModel::Standard, GradientModel::Apollonian].map(|model| AcrossChart::new(curvatures[0], curvatures[1], model));
|
||||
let cone = AcrossChart::Cone {
|
||||
cone: Cone::between(start_radius, 1. - start_radius),
|
||||
keep: None,
|
||||
};
|
||||
|
||||
assert!(matches!(standard, AcrossChart::Concentric { .. }), "{standard:?}");
|
||||
assert!(matches!(apollonian, AcrossChart::Concentric { .. }), "{apollonian:?}");
|
||||
for point in sample_points() {
|
||||
let expected = (point.y).atan2(point.x - start_radius).rem_euclid(TAU) / TAU;
|
||||
for (chart, name) in [(standard, "Standard"), (apollonian, "Apollonian"), (cone, "cone")] {
|
||||
let v = chart.v(point).unwrap_or_else(|| panic!("{name} leaves {point} unpainted with start radius {start_radius}"));
|
||||
assert!(turn_distance(v, expected) < 1e-9, "{name} with start radius {start_radius} at {point}: {v} rather than {expected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_contours_of_constant_position_are_rays_from_the_apex() {
|
||||
// Off-center pairs with an apex where the cone's circles shrink to a point
|
||||
for (start, end) in [(0., 0.75), (0.2, 1.5), (0.6, 0.3), (-0.3, -0.6), (2., -0.5)] {
|
||||
let cone = Cone::between(start, end);
|
||||
let chart = AcrossChart::new(radius_curvature(start), radius_curvature(end), GradientModel::Standard);
|
||||
assert!(matches!(chart, AcrossChart::Cone { .. }), "({start}, {end}) should be a cone, not {chart:?}");
|
||||
|
||||
let delta_radius = cone.end_radius - cone.start_radius;
|
||||
let apex_t = -cone.start_radius / delta_radius;
|
||||
let apex = DVec2::new(cone.start_center + apex_t * (cone.end_center - cone.start_center), 0.);
|
||||
|
||||
for angle in (0..24).map(|step| (step as f64 + 0.37) * TAU / 24.) {
|
||||
let direction = DVec2::from_angle(angle);
|
||||
let positions: Vec<f64> = [0.2, 0.5, 1., 2., 4.].into_iter().filter_map(|distance| chart.v(apex + direction * distance)).collect();
|
||||
for &v in &positions {
|
||||
assert!(turn_distance(v, positions[0]) < 1e-9, "({start}, {end}) along the ray at {angle}: {positions:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn across_paints_exactly_where_along_does() {
|
||||
for curvatures in curvature_pairs() {
|
||||
let standard = GradientStandard::new(curvatures[0], curvatures[1]);
|
||||
let chart = AcrossChart::new(curvatures[0], curvatures[1], GradientModel::Standard);
|
||||
|
||||
// A line end's cut and a nearly flat cone's split are drawn as straight lines across the gradient line, which the cone drawn at the flattest radius only nears
|
||||
let cut = match standard {
|
||||
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => keep.map(|keep| keep.at),
|
||||
GradientStandard::Profile { split, .. } => Some(split),
|
||||
_ => None,
|
||||
};
|
||||
for point in sample_points() {
|
||||
if cut.is_some_and(|cut| (point.x - cut).abs() < 0.1 * point.y.abs().max(0.1)) {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(chart.v(point).is_some(), standard.t(point).is_some(), "Standard curvatures {curvatures:?} at {point}: {chart:?}");
|
||||
}
|
||||
|
||||
// Apollonian circles paint everywhere, read along or across them
|
||||
let chart = AcrossChart::new(curvatures[0], curvatures[1], GradientModel::Apollonian);
|
||||
assert!(chart.paints_everywhere(), "Apollonian curvatures {curvatures:?}: {chart:?}");
|
||||
assert!(sample_points().all(|point| chart.v(point).is_some()), "Apollonian curvatures {curvatures:?}: {chart:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positions_change_continuously_except_at_seams_and_where_contours_meet() {
|
||||
const STEP: f64 = 0.01;
|
||||
|
||||
for curvatures in curvature_pairs() {
|
||||
for model in [GradientModel::Standard, GradientModel::Apollonian] {
|
||||
let chart = AcrossChart::new(curvatures[0], curvatures[1], model);
|
||||
|
||||
// Where every contour of constant position meets, and a cut across the gradient line
|
||||
let mut singular_points = Vec::new();
|
||||
let mut cut = None;
|
||||
match chart {
|
||||
AcrossChart::Concentric { center } => singular_points.push(DVec2::new(center, 0.)),
|
||||
AcrossChart::Cone { cone, keep } => {
|
||||
let apex_t = -cone.start_radius / (cone.end_radius - cone.start_radius);
|
||||
singular_points.push(DVec2::new(cone.start_center + apex_t * (cone.end_center - cone.start_center), 0.));
|
||||
cut = keep.map(|keep| keep.at);
|
||||
}
|
||||
AcrossChart::Mobius { numerator, denominator } => {
|
||||
singular_points.push(DVec2::new(-numerator[1] / numerator[0], 0.));
|
||||
singular_points.push(DVec2::new(-denominator[1] / denominator[0], 0.));
|
||||
}
|
||||
AcrossChart::Bipolar { center_x, half_height, .. } => {
|
||||
singular_points.push(DVec2::new(center_x, half_height));
|
||||
singular_points.push(DVec2::new(center_x, -half_height));
|
||||
}
|
||||
AcrossChart::Linear | AcrossChart::Nothing => {}
|
||||
}
|
||||
let near_singular = |point: DVec2| singular_points.iter().any(|singular| (point - *singular).length() < 0.2) || cut.is_some_and(|cut| (point.x - cut).abs() < 0.02);
|
||||
|
||||
for point in sample_points().filter(|&point| !near_singular(point)) {
|
||||
for neighbor in [point + DVec2::new(STEP, 0.), point + DVec2::new(0., STEP)] {
|
||||
if near_singular(neighbor) {
|
||||
continue;
|
||||
}
|
||||
let (Some(v), Some(neighbor_v)) = (chart.v(point), chart.v(neighbor)) else { continue };
|
||||
|
||||
let change = if chart.winds() { turn_distance(v, neighbor_v) } else { (v - neighbor_v).abs() };
|
||||
assert!(change < 0.05, "{model:?} curvatures {curvatures:?} from {point} to {neighbor}: {v} to {neighbor_v} in {chart:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bipolar_chart_nears_the_linear_forms_as_crossing_curvatures_flatten() {
|
||||
// Over the view, the chart strays from `y` in proportion to the curvatures
|
||||
for curvature in [1e-3, 1e-4, 1e-6] {
|
||||
let tolerance = 300. * curvature;
|
||||
for [start, end] in [[curvature, curvature], [curvature, 2. * curvature], [3. * curvature, curvature]] {
|
||||
let chart = AcrossChart::new(start, end, GradientModel::Apollonian);
|
||||
assert!(matches!(chart, AcrossChart::Bipolar { .. }), "({start}, {end}) should cross, not {chart:?}");
|
||||
for point in sample_points() {
|
||||
let v = chart.v(point).unwrap();
|
||||
assert!((v - point.y).abs() < tolerance, "({start}, {end}) at {point}: {v}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Zero on the gradient line, and one unit per gradient length across its midpoint
|
||||
let chart = AcrossChart::new(0.6, 0.4, GradientModel::Apollonian);
|
||||
assert!(chart.v(DVec2::new(0.3, 0.)).unwrap().abs() < 1e-15);
|
||||
let rate = (chart.v(DVec2::new(0.5, 1e-6)).unwrap() - chart.v(DVec2::new(0.5, -1e-6)).unwrap()) / 2e-6;
|
||||
assert!((rate - 1.).abs() < 1e-6, "{rate}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apollonian_angles_run_around_the_limit_point_inside_the_end_contour() {
|
||||
// The start point inside the end circle, which encloses the start point as its limit point
|
||||
let start_point = AcrossChart::new(-1., 0.3, GradientModel::Apollonian);
|
||||
let AcrossChart::Mobius { numerator, .. } = start_point else { panic!("{start_point:?}") };
|
||||
assert!((-numerator[1] / numerator[0]).abs() < 1e-12, "{start_point:?}");
|
||||
|
||||
// The end a point, which is its own limit point
|
||||
let end_point = AcrossChart::new(0.8, 1., GradientModel::Apollonian);
|
||||
let AcrossChart::Mobius { numerator, .. } = end_point else { panic!("{end_point:?}") };
|
||||
assert!((-numerator[1] / numerator[0] - 1.).abs() < 1e-9, "{end_point:?}");
|
||||
|
||||
// Near the enclosed limit point, the position is the angle around it, from the seam on the +x side
|
||||
for angle in [0.1, 1., 2., 3., 4., 5., 6.] {
|
||||
let point = DVec2::from_angle(angle) * 1e-7;
|
||||
assert!(turn_distance(start_point.v(point).unwrap(), angle / TAU) < 1e-5, "at angle {angle}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_apollonian_chart_is_found_for_every_curvature_pair() {
|
||||
for start_step in -10..=10 {
|
||||
for end_step in -10..=10 {
|
||||
let (start, end) = (start_step as f64 / 10., end_step as f64 / 10.);
|
||||
let chart = AcrossChart::new(start, end, GradientModel::Apollonian);
|
||||
let along = GradientApollonian::new(start, end);
|
||||
for point in sample_points() {
|
||||
let v = chart.v(point);
|
||||
assert!(v.is_some_and(|v| !v.is_nan()), "({start}, {end}) at {point}: {v:?} in {chart:?}");
|
||||
assert!(!along.t(point).is_nan());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extreme_curvatures_compute_finitely() {
|
||||
let extremes = [4e-309, -4e-309, 1e-300, 6e-31, -6e-31, 7e-31, -7e-31, 1e-17, -1e-17];
|
||||
let curvatures = extremes.iter().flat_map(|&extreme| {
|
||||
[
|
||||
[extreme, 0.],
|
||||
[0., extreme],
|
||||
[extreme, 0.3],
|
||||
[-0.3, extreme],
|
||||
[extreme, extreme],
|
||||
[extreme, -extreme],
|
||||
[extreme, 1. - 1e-16],
|
||||
]
|
||||
});
|
||||
|
||||
for [start, end] in curvatures {
|
||||
for model in [GradientModel::Standard, GradientModel::Apollonian] {
|
||||
let chart = AcrossChart::new(start, end, model);
|
||||
for point in sample_points() {
|
||||
let v = chart.v(point);
|
||||
assert!(v.is_none_or(|v| !v.is_nan()), "{model:?} curvatures ({start}, {end}) at {point}: {chart:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,20 +60,20 @@ impl AxisCircle {
|
||||
|
||||
/// 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)]
|
||||
pub(crate) struct Homogeneous {
|
||||
pub(crate) numerator: f64,
|
||||
pub(crate) denominator: f64,
|
||||
struct Homogeneous {
|
||||
numerator: f64,
|
||||
denominator: f64,
|
||||
}
|
||||
|
||||
impl Homogeneous {
|
||||
pub(crate) const INFINITY: Self = Self { numerator: 1., denominator: 0. };
|
||||
const INFINITY: Self = Self { numerator: 1., denominator: 0. };
|
||||
|
||||
pub(crate) fn value(&self) -> Option<f64> {
|
||||
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.
|
||||
pub(crate) fn normalized(self) -> Self {
|
||||
fn normalized(self) -> Self {
|
||||
let scale = self.numerator.abs().max(self.denominator.abs());
|
||||
if scale == 0. {
|
||||
return self;
|
||||
@@ -85,51 +85,6 @@ impl Homogeneous {
|
||||
}
|
||||
}
|
||||
|
||||
/// How the family of circles two end contours span is laid out.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(crate) enum CircleFamily {
|
||||
/// The end contours cross, so every member passes through the two points where the line member at `radical_x` meets them.
|
||||
Crossing { radical_x: f64 },
|
||||
/// The members nest around two limit points (normalized), which coincide where the end contours touch.
|
||||
Nesting { limit_points: [Homogeneous; 2] },
|
||||
}
|
||||
|
||||
impl CircleFamily {
|
||||
pub(crate) fn of(start: AxisCircle, end: AxisCircle) -> Self {
|
||||
// The members of the family 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 family 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);
|
||||
return Self::Crossing { radical_x: -line.c / line.b };
|
||||
}
|
||||
|
||||
// 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()
|
||||
});
|
||||
|
||||
Self::Nesting { limit_points }
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.);
|
||||
@@ -184,10 +139,37 @@ impl GradientApollonian {
|
||||
let start = AxisCircle::start(start_curvature);
|
||||
let end = AxisCircle::end(end_curvature);
|
||||
|
||||
let limit_points = match CircleFamily::of(start, end) {
|
||||
CircleFamily::Crossing { radical_x } => return Self::with_band(start, end, CrossingSelection::SameSideAs { radical_x }, None, 0., 1., svg_stand_in),
|
||||
CircleFamily::Nesting { limit_points } => limit_points,
|
||||
};
|
||||
// The members of the family 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 family 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., svg_stand_in);
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
@@ -10,8 +10,7 @@
|
||||
//! Where SVG 2 leaves the plane unpainted, so does it. A line end takes SVG 2's own limit as that end's circle flattens bowing
|
||||
//! toward the other end. The Apollonian drawing of the same curvatures is in [`crate::gradient_apollonian`].
|
||||
|
||||
use crate::gradient::{GradientDirection, GradientForm, GradientModel, wrapped_curvature};
|
||||
use crate::gradient_across::{AcrossChart, GradientAcross};
|
||||
use crate::gradient::{GradientForm, GradientModel, wrapped_curvature};
|
||||
use crate::gradient_apollonian::GradientApollonian;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
@@ -346,7 +345,7 @@ impl GradientStandard {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a gradient's contours are laid out, decided by its curvatures and model, and how its colors run, decided by its direction.
|
||||
/// How a gradient's contours are laid out, decided by its curvatures and model.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum GradientShape {
|
||||
/// The linear form: both ends are lines.
|
||||
@@ -357,27 +356,19 @@ pub enum GradientShape {
|
||||
Standard(GradientStandard),
|
||||
/// Any other curvatures, drawn as Apollonian circles.
|
||||
Apollonian(GradientApollonian),
|
||||
/// Any curvatures, with the colors running around the contours rather than from one end to the other.
|
||||
Across(GradientAcross),
|
||||
}
|
||||
|
||||
impl GradientShape {
|
||||
/// The shape of a gradient with these curvatures, each wrapped like [`wrapped_curvature`] and a line where it isn't finite, placed by `transform`.
|
||||
/// With curvatures other than a form's, a collapsed placement (like a zero-length gradient line) leaves the last stop's color, as SVG does.
|
||||
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel, direction: GradientDirection, transform: DAffine2) -> Self {
|
||||
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel, transform: DAffine2) -> Self {
|
||||
let [start, end] = [start_curvature, end_curvature].map(|curvature| wrapped_curvature(curvature, 0.));
|
||||
let form = GradientForm::from_curvatures([start, end]);
|
||||
let collapsed = !transform.matrix2.determinant().recip().is_finite();
|
||||
|
||||
match (form, direction) {
|
||||
(None, _) if collapsed => Self::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }),
|
||||
(_, GradientDirection::Across) => Self::Across(GradientAcross {
|
||||
chart: AcrossChart::new(start, end, model),
|
||||
form,
|
||||
}),
|
||||
(Some(GradientForm::Linear), GradientDirection::Along) => Self::Linear,
|
||||
(Some(GradientForm::Radial), GradientDirection::Along) => Self::Radial,
|
||||
(None, GradientDirection::Along) if model == GradientModel::Apollonian => {
|
||||
match GradientForm::from_curvatures([start, end]) {
|
||||
Some(GradientForm::Linear) => Self::Linear,
|
||||
Some(GradientForm::Radial) => Self::Radial,
|
||||
None if !transform.matrix2.determinant().recip().is_finite() => Self::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }),
|
||||
None if model == GradientModel::Apollonian => {
|
||||
// Identical end circles span no family of circles, so they draw the plain ramp
|
||||
let (start_radius, end_radius) = (curvature_radius(start), curvature_radius(end));
|
||||
if start_radius.is_finite() && end_radius.is_finite() && Cone::between(start_radius, end_radius).is_identical() {
|
||||
@@ -386,22 +377,13 @@ impl GradientShape {
|
||||
|
||||
Self::Apollonian(GradientApollonian::new(start, end))
|
||||
}
|
||||
(None, GradientDirection::Along) => Self::Standard(GradientStandard::new(start, end)),
|
||||
None => Self::Standard(GradientStandard::new(start, end)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether its position can fall before the start, which a radial gradient's distance from its center and an angle around the contours can't.
|
||||
/// Whether its position can fall before the start, which only a radial gradient's can't since its distance from the center never goes below zero.
|
||||
pub fn reaches_before_start(&self) -> bool {
|
||||
match self {
|
||||
Self::Radial => false,
|
||||
Self::Across(across) => !across.chart.winds(),
|
||||
Self::Linear | Self::Standard(_) | Self::Apollonian(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether its position can fall past the end, which an angle around the contours can't.
|
||||
pub fn reaches_past_end(&self) -> bool {
|
||||
!matches!(self, Self::Across(across) if across.chart.winds())
|
||||
!matches!(self, Self::Radial)
|
||||
}
|
||||
|
||||
/// Whether it paints every point, rather than leaving some unpainted.
|
||||
@@ -409,15 +391,11 @@ impl GradientShape {
|
||||
match self {
|
||||
Self::Linear | Self::Radial | Self::Apollonian(_) => true,
|
||||
Self::Standard(gradient) => gradient.paints_everywhere(),
|
||||
Self::Across(across) => across.chart.paints_everywhere(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether SVG draws it exactly, which it does unless it's Apollonian circles (other than those between concentric end circles drawn as SVG 2's cone), or read across contours other than the linear form's.
|
||||
/// Whether SVG draws it exactly, which it does unless it's Apollonian circles, other than those between concentric end circles drawn as SVG 2's cone.
|
||||
pub fn svg_draws_exactly(&self) -> bool {
|
||||
if let Self::Across(across) = self {
|
||||
return across.chart.svg_draws_exactly();
|
||||
}
|
||||
let Self::Apollonian(GradientApollonian { start, end, svg_stand_in, .. }) = self else {
|
||||
return true;
|
||||
};
|
||||
@@ -765,7 +743,7 @@ mod tests {
|
||||
fn a_zero_length_gradient_line_leaves_the_last_stop_once_curved() {
|
||||
let collapsed = DAffine2::from_cols(DVec2::ZERO, DVec2::Y, DVec2::new(3., 4.));
|
||||
for model in [GradientModel::Standard, GradientModel::Apollonian] {
|
||||
let shape = |[start, end]: [f64; 2]| GradientShape::new(start, end, model, GradientDirection::Along, collapsed);
|
||||
let shape = |[start, end]: [f64; 2]| GradientShape::new(start, end, model, collapsed);
|
||||
|
||||
assert_eq!(shape([0.3, 0.2]), GradientShape::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }));
|
||||
// The forms keep drawing as they always have
|
||||
@@ -777,7 +755,7 @@ mod tests {
|
||||
#[test]
|
||||
fn apollonian_gradients_stand_in_for_svg_with_its_own_drawing_where_that_paints_everywhere() {
|
||||
let placement = DAffine2::IDENTITY;
|
||||
let stand_in = |curvatures: [f64; 2]| match GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, placement) {
|
||||
let stand_in = |curvatures: [f64; 2]| match GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, placement) {
|
||||
GradientShape::Apollonian(apollonian) => apollonian.svg_stand_in,
|
||||
shape => panic!("curvatures {curvatures:?} should draw Apollonian circles, not {shape:?}"),
|
||||
};
|
||||
@@ -795,25 +773,22 @@ mod tests {
|
||||
|
||||
// Identical end circles span no family of circles, so they draw the plain ramp everywhere
|
||||
let identical = radius_curvature(0.5);
|
||||
assert_eq!(
|
||||
GradientShape::new(identical, identical, GradientModel::Apollonian, GradientDirection::Along, placement),
|
||||
GradientShape::Standard(plain_ramp)
|
||||
);
|
||||
assert_eq!(GradientShape::new(identical, identical, GradientModel::Apollonian, placement), GradientShape::Standard(plain_ramp));
|
||||
|
||||
// The forms stay native under either model
|
||||
assert_eq!(GradientShape::new(0., 0., GradientModel::Apollonian, GradientDirection::Along, placement), GradientShape::Linear);
|
||||
assert_eq!(GradientShape::new(-1., 0.5, GradientModel::Apollonian, GradientDirection::Along, placement), GradientShape::Radial);
|
||||
assert_eq!(GradientShape::new(0., 0., GradientModel::Apollonian, placement), GradientShape::Linear);
|
||||
assert_eq!(GradientShape::new(-1., 0.5, GradientModel::Apollonian, placement), GradientShape::Radial);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_draws_every_shape_exactly_but_apollonian_circles_it_cant_draw_as_a_cone() {
|
||||
let exact = |curvatures: [f64; 2], model: GradientModel| GradientShape::new(curvatures[0], curvatures[1], model, GradientDirection::Along, DAffine2::IDENTITY).svg_draws_exactly();
|
||||
let exact = |curvatures: [f64; 2], model: GradientModel| GradientShape::new(curvatures[0], curvatures[1], model, DAffine2::IDENTITY).svg_draws_exactly();
|
||||
|
||||
// Concentric end circles, the start centered at its radius and the end at 1 minus its own, have Apollonian circles that are SVG 2's cone
|
||||
for [start, end] in [[2., -1.], [-0.5, 1.5], [0.25, 0.75]] {
|
||||
let curvatures = [radius_curvature(start), radius_curvature(end)];
|
||||
assert!(matches!(
|
||||
GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, DAffine2::IDENTITY),
|
||||
GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, DAffine2::IDENTITY),
|
||||
GradientShape::Apollonian(_)
|
||||
));
|
||||
assert!(exact(curvatures, GradientModel::Apollonian), "radii {start} and {end}");
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
extern crate log;
|
||||
|
||||
pub mod gradient;
|
||||
pub mod gradient_across;
|
||||
pub mod gradient_apollonian;
|
||||
pub mod gradient_standard;
|
||||
pub mod math;
|
||||
@@ -10,9 +9,7 @@ pub mod vector;
|
||||
|
||||
// Re-export commonly used types at the crate root
|
||||
pub use core_types as gcore;
|
||||
pub use gradient::{
|
||||
Gradient, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop,
|
||||
};
|
||||
pub use gradient::{Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
|
||||
pub use math::QuadExt;
|
||||
pub use vector::Vector;
|
||||
pub use vector::reference_point::ReferencePoint;
|
||||
|
||||
@@ -109,6 +109,7 @@ fn step_function(kind: StepKind) -> (&'static str, Option<[Encoding; 2]>) {
|
||||
StepKind::ColorLookup => ("color_lookup", Some([Gamma, Gamma])),
|
||||
StepKind::ColorOverlay => ("color_overlay", Some([Gamma, Gamma])),
|
||||
StepKind::Solarize => ("solarize", Some([Gamma, Gamma])),
|
||||
StepKind::AlphaToGray => ("alpha_to_gray", Some([Gamma, Gamma])),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -365,6 +365,11 @@ fn solarize(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||
return vec4<f32>(min(color.rgb, 1. - color.rgb), color.a);
|
||||
}
|
||||
|
||||
// The alpha as a gray of the same gamma-encoded level, keeping the alpha
|
||||
fn alpha_to_gray(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||
return vec4<f32>(vec3<f32>(color.a), color.a);
|
||||
}
|
||||
|
||||
// Matches `apply_levels` with the gamma of 1 that every caller here passes, so its power is left out
|
||||
fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, output_minimum: f32, output_maximum: f32) -> f32 {
|
||||
let highlights_minus_shadows = clamp(input_highlights - input_shadows, F32_EPSILON, 1.);
|
||||
|
||||
@@ -853,6 +853,18 @@ impl EffectPasses {
|
||||
capture_plane(recorder, plane, map, true)
|
||||
});
|
||||
}
|
||||
// The fill's plane takes a median of its own, which an SVG takes as its map where the fill forks the content
|
||||
EffectOperation::Median { radius } => {
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
let median_full = recorder.median(full.as_ref().unwrap_or(content), radius, lengths_to_pixels, frame.as_ref());
|
||||
capture_plane(&mut recorder, 0, &median_full, true);
|
||||
if let Some(filled) = filled.as_mut() {
|
||||
let median_filled = recorder.median(filled, radius, lengths_to_pixels, frame.as_ref());
|
||||
capture_plane(&mut recorder, 1, &median_filled, true);
|
||||
recorder.replace(filled, median_filled);
|
||||
}
|
||||
recorder.replace_or_fill(&mut full, median_full);
|
||||
}
|
||||
EffectOperation::MotionBlur { angle, distance, gamma } => {
|
||||
// Anchored at the effect space's origin, which is the content's, so the shear moves with it
|
||||
let Some(shear) = MotionBlurShear::new(angle, distance, lengths_to_pixels, effect_to_pixels.translation) else {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! The GPU passes of the filter effects, matching the CPU's `filter_kernels`.
|
||||
|
||||
use super::{PARAMETER_TAPS, Parameters, PassRecorder, SUMS_FORMAT, WORKING_FORMAT};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use glam::{DAffine2, DMat2, DVec2, UVec2};
|
||||
use graphic_types::effects::{MAX_MEDIAN_GRID_RADIUS, spans_along_axes};
|
||||
use graphic_types::filters::{
|
||||
Convolution, FieldSampling, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, neighborhood_radii, noise_extent, sharpens_coverage, unsharp,
|
||||
};
|
||||
use graphic_types::resampling::EffectFrame;
|
||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||
use raster_kernels::effect_kernels::BlurKernel;
|
||||
use raster_kernels::filter_kernels::pixel_fill_shifts;
|
||||
@@ -13,6 +14,11 @@ use raster_kernels::filter_kernels::pixel_fill_shifts;
|
||||
/// The most texels a neighborhood's first pass reads each way, beyond which each further pass at most doubles its reach by reading two texels.
|
||||
const MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS: u32 = 8;
|
||||
|
||||
/// How many bits a median ranks the values of half floats by: their 32-bit float bit patterns without the low 13 bits a half float leaves empty, which order as the values do.
|
||||
const MEDIAN_KEY_BITS: u32 = 18;
|
||||
/// How many bits of each median's key a median pass decides, by three thresholds for each channel.
|
||||
const MEDIAN_BITS_PER_PASS: u32 = 2;
|
||||
|
||||
/// The `convolution`'s shifts mapped onto texels by `lengths_to_pixels`, with their weights divided by its divisor.
|
||||
fn convolution_taps(convolution: &Convolution, lengths_to_pixels: DMat2) -> Vec<[f32; 4]> {
|
||||
let tap = |&(shift, weight): &(DVec2, f64)| {
|
||||
@@ -455,6 +461,48 @@ impl PassRecorder<'_> {
|
||||
}
|
||||
widened
|
||||
}
|
||||
|
||||
/// The image with each texel's alpha the median of those in the square of `radius` whole document pixels around it, and each straight color the median among those with coverage,
|
||||
/// a texel inside the content's `frame` reading only those inside it. Exact, deciding two more bits of the medians' keys (see [`MEDIAN_KEY_BITS`]) a pass.
|
||||
/// O(width × height × radius²), with the radius in texels at most [`MAX_MEDIAN_GRID_RADIUS`], past which the content's grid coarsens instead.
|
||||
pub(super) fn median(&mut self, image: &wgpu::Texture, radius: f64, lengths_to_pixels: DMat2, frame: Option<&EffectFrame>) -> wgpu::Texture {
|
||||
let radii = (spans_along_axes(lengths_to_pixels) * radius.max(0.).floor()).round().min(DVec2::splat(MAX_MEDIAN_GRID_RADIUS));
|
||||
let radii = radii.as_uvec2().min(self.size);
|
||||
if radii == UVec2::ZERO {
|
||||
return self.scale(image, 1.);
|
||||
}
|
||||
|
||||
let prepared = self.run("median_prepare", WORKING_FORMAT, self.size, image, None, None, Parameters::default());
|
||||
|
||||
// The frame's unit square, which a texel center within the frame lies in, placed on the texels
|
||||
let (pixels_to_frame, clips) = match frame {
|
||||
Some(frame) => (frame.to_pixels.inverse(), 1.),
|
||||
None => (DAffine2::IDENTITY, 0.),
|
||||
};
|
||||
let [x_axis, y_axis] = [pixels_to_frame.matrix2.x_axis, pixels_to_frame.matrix2.y_axis].map(|axis| axis.as_vec2());
|
||||
|
||||
// Each pass decides more bits of every channel's median, carried between passes as whole numbers in 32-bit floats
|
||||
let passes = MEDIAN_KEY_BITS / MEDIAN_BITS_PER_PASS;
|
||||
let mut decided: Option<wgpu::Texture> = None;
|
||||
for pass in 0..passes {
|
||||
let last = pass + 1 == passes;
|
||||
let lowest_bit = MEDIAN_KEY_BITS - MEDIAN_BITS_PER_PASS * (pass + 1);
|
||||
let flag = |on: bool| if on { 1. } else { 0. };
|
||||
let parameters = Parameters {
|
||||
step: radii.as_vec2().to_array(),
|
||||
offset: pixels_to_frame.translation.as_vec2().to_array(),
|
||||
color: [x_axis.x, x_axis.y, y_axis.x, y_axis.y],
|
||||
values: [lowest_bit as f32, flag(decided.is_some()), flag(last), clips],
|
||||
..Default::default()
|
||||
};
|
||||
let format = if last { WORKING_FORMAT } else { SUMS_FORMAT };
|
||||
let next = self.run("median_bisect", format, self.size, &prepared, None, decided.as_ref(), parameters);
|
||||
self.replace_or_fill(&mut decided, next);
|
||||
}
|
||||
|
||||
self.textures.release(prepared);
|
||||
decided.unwrap_or_else(|| self.scale(image, 1.))
|
||||
}
|
||||
}
|
||||
|
||||
/// The radii a window of extremes widens through from `from` texels each way to `to`, each at most double the one before it, or from none, at most [`MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS`].
|
||||
|
||||
@@ -492,3 +492,92 @@ fn dissolve(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let shown = select(0., field.x, color.a * 255. > field.y + 0.5);
|
||||
return vec4<f32>(color.rgb / color.a * shown, shown);
|
||||
}
|
||||
|
||||
// The straight colors and alpha a median ranks, as half floats kept within their finite range at or above 0, where their bit patterns order as their values do, or nothing without coverage
|
||||
@fragment
|
||||
fn median_prepare(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let color = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if !(color.a > 0.) {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
let straight = color.rgb / color.a;
|
||||
return vec4<f32>(min(select(vec3<f32>(0.), straight, straight > vec3<f32>(0.)), vec3<f32>(65504.)), min(color.a, 1.));
|
||||
}
|
||||
|
||||
// The 32-bit float bit patterns of the four half float values at or above 0, without the low 13 bits a half float leaves empty, which order as the values do
|
||||
fn median_keys(values: vec4<f32>) -> vec4<u32> {
|
||||
return bitcast<vec4<u32>>(values) >> vec4<u32>(13u);
|
||||
}
|
||||
|
||||
// Whether a texel's center lies within the content's frame, whose unit square the linear part `color` (by columns) and `offset` place texels in
|
||||
fn median_in_frame(texel: vec2<i32>) -> bool {
|
||||
let unit = mat2x2<f32>(parameters.color.xy, parameters.color.zw) * (vec2<f32>(texel) + 0.5) + parameters.offset;
|
||||
return all(unit >= vec2<f32>(0.)) && all(unit < vec2<f32>(1.));
|
||||
}
|
||||
|
||||
// Two more bits (from bit `values.x` up) of each channel's median as `median_keys` (of `source`): the alpha's among the window's texels, and each straight color's among those with coverage,
|
||||
// in the window reaching `step` texels across and down, taking the upper median of an even count. A pass after the first (`values.y` 1) goes on from the bits decided before it (`content`),
|
||||
// and the last (`values.z` 1) writes the medians as a premultiplied color. With `values.w` 1, a texel within the content's frame reads only the texels within it.
|
||||
@fragment
|
||||
fn median_bisect(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let last = vec2<i32>(textureDimensions(source)) - 1;
|
||||
let radii = vec2<i32>(parameters.step);
|
||||
let width = 1u << u32(parameters.values.x);
|
||||
|
||||
var decided = vec4<u32>(0u);
|
||||
if parameters.values.y > 0.5 {
|
||||
decided = vec4<u32>(textureLoad(content, pixel, 0));
|
||||
}
|
||||
let first_threshold = decided + width;
|
||||
let second_threshold = decided + 2u * width;
|
||||
let third_threshold = decided + 3u * width;
|
||||
|
||||
// Only a window crossing the frame's edge has its texels tested, since the frame is convex
|
||||
var clips = parameters.values.w > 0.5 && median_in_frame(pixel);
|
||||
if clips {
|
||||
let corners_within = median_in_frame(pixel - radii) && median_in_frame(pixel + radii) && median_in_frame(pixel + vec2<i32>(radii.x, -radii.y)) && median_in_frame(pixel + vec2<i32>(-radii.x, radii.y));
|
||||
clips = !corners_within;
|
||||
}
|
||||
|
||||
var below_first = vec4<u32>(0u);
|
||||
var below_second = vec4<u32>(0u);
|
||||
var below_third = vec4<u32>(0u);
|
||||
var counted = 0u;
|
||||
var visible = 0u;
|
||||
for (var y = -radii.y; y <= radii.y; y++) {
|
||||
for (var x = -radii.x; x <= radii.x; x++) {
|
||||
let texel = pixel + vec2<i32>(x, y);
|
||||
if clips && !median_in_frame(texel) {
|
||||
continue;
|
||||
}
|
||||
counted += 1u;
|
||||
|
||||
// Past the texture's edges lies nothing, and a texel without coverage has no colors to rank
|
||||
let within = all(texel >= vec2<i32>(0)) && all(texel <= last);
|
||||
let keys = median_keys(select(vec4<f32>(0.), textureLoad(source, clamp(texel, vec2<i32>(0), last), 0), within));
|
||||
// Counts convert from booleans, since WebGL's GLSL can't select between integers
|
||||
let shown = u32(keys.a > 0u);
|
||||
visible += shown;
|
||||
let hidden = (1u - shown) * 0xffffffffu;
|
||||
let ranked = keys | vec4<u32>(hidden, hidden, hidden, 0u);
|
||||
|
||||
below_first += vec4<u32>(ranked < first_threshold);
|
||||
below_second += vec4<u32>(ranked < second_threshold);
|
||||
below_third += vec4<u32>(ranked < third_threshold);
|
||||
}
|
||||
}
|
||||
|
||||
// The median lies past each threshold that fewer keys than its rank lie below
|
||||
let rank = vec4<u32>(vec3<u32>(visible / 2u + 1u), counted / 2u + 1u);
|
||||
decided += (vec4<u32>(below_first < rank) + vec4<u32>(below_second < rank) + vec4<u32>(below_third < rank)) * width;
|
||||
if parameters.values.z < 0.5 {
|
||||
return vec4<f32>(decided);
|
||||
}
|
||||
|
||||
let medians = bitcast<vec4<f32>>(decided << vec4<u32>(13u));
|
||||
if visible == 0u || !(medians.a > 0.) {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
return vec4<f32>(medians.rgb * medians.a, medians.a);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use crate::WgpuExecutor;
|
||||
use core_types::blending::BlendMode;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graphic_types::MinimumMaximumMode;
|
||||
use graphic_types::vector_types::gradient::{GradientDirection, GradientModel, GradientSpread};
|
||||
use graphic_types::vector_types::gradient::{GradientModel, GradientSpread};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use vello_gpu::kurbo::{Affine, BezPath, Line, ParamCurve, PathSeg, Point, Rect, Stroke, Vec2};
|
||||
use vello_gpu::peniko::{self, Color, Fill};
|
||||
@@ -555,7 +555,7 @@ fn apollonian_gradients_match_their_cpu_evaluation() {
|
||||
[0.9, 0.6],
|
||||
[0.6, 1.],
|
||||
] {
|
||||
let GradientShape::Apollonian(parameters) = GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, placement) else {
|
||||
let GradientShape::Apollonian(parameters) = GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, placement) else {
|
||||
panic!("curvatures {curvatures:?} should draw Apollonian circles");
|
||||
};
|
||||
let graphic = curved_black_to_white_gradient(placement, Some(curvatures), GradientModel::Apollonian);
|
||||
@@ -575,114 +575,6 @@ fn apollonian_gradients_match_their_cpu_evaluation() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn across_gradients_match_their_cpu_evaluation() {
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::gradient_standard::radius_curvature;
|
||||
use std::fmt::Write;
|
||||
|
||||
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100), and then sheared
|
||||
let placements = [
|
||||
DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.)),
|
||||
DAffine2::from_cols(DVec2::new(50., 10.), DVec2::new(15., 35.), DVec2::new(60., 100.)),
|
||||
];
|
||||
|
||||
let radius = radius_curvature;
|
||||
let (standard, apollonian) = (GradientModel::Standard, GradientModel::Apollonian);
|
||||
let settings = [
|
||||
([0., 0.], standard, "the linear form"),
|
||||
([-1., 0.5], standard, "the radial form"),
|
||||
([radius(2.), radius(-1.)], standard, "concentric circles"),
|
||||
([-1., radius(0.75)], standard, "a focal point inside the end circle, off its center"),
|
||||
([radius(0.2), radius(1.5)], standard, "a focal circle nested inside the end circle"),
|
||||
([radius(0.6), radius(0.6)], standard, "crossing circles"),
|
||||
([radius(-0.2), radius(-0.4)], standard, "separate circles"),
|
||||
([radius(0.8), 0.], standard, "an end line beside a start circle reaching past the end"),
|
||||
([radius(0.45), 0.], standard, "an end line beside a start circle nearly reaching the end"),
|
||||
([radius(0.6), 0.], standard, "an end line beside a start circle just past the end"),
|
||||
([radius(3000.), radius(-4000.)], standard, "both ends nearly flat around an apex"),
|
||||
([radius(2.), radius(-1.)], apollonian, "concentric Apollonian circles"),
|
||||
([1., 0.3], apollonian, "Apollonian circles around the start point"),
|
||||
([0.9, 0.2], apollonian, "nested Apollonian circles"),
|
||||
([0.8, 1.], apollonian, "Apollonian circles around the end point"),
|
||||
([1., 1.], apollonian, "Apollonian circles of two points"),
|
||||
([0.6, 0.6], apollonian, "crossing Apollonian circles"),
|
||||
([0.5, 0.25], apollonian, "crossing Apollonian circles of different sizes"),
|
||||
];
|
||||
|
||||
let mut report = String::new();
|
||||
for (curvatures, model, setting) in settings {
|
||||
for placement in placements {
|
||||
for spread in [GradientSpread::Pad, GradientSpread::Repeat] {
|
||||
let Some(line) = compare_across_gradient_with_cpu(curvatures, model, placement, spread, setting) else {
|
||||
return;
|
||||
};
|
||||
let _ = writeln!(report, "{line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("{report}");
|
||||
}
|
||||
|
||||
/// Renders a black to white gradient read across its contours, with these curvatures and model, placed by `placement` and read with `spread`, into a
|
||||
/// 200 by 200 view, and checks each pixel against the CPU's evaluation, returning a line describing how they compare, or `None` without a GPU.
|
||||
fn compare_across_gradient_with_cpu(curvatures: [f64; 2], model: GradientModel, placement: DAffine2, spread: GradientSpread, setting: &str) -> Option<String> {
|
||||
use core_types::list::{ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_SPREAD};
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::gradient_standard::GradientShape;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(200, 200);
|
||||
let graphic = match curved_black_to_white_gradient(placement, Some(curvatures), model) {
|
||||
graphic_types::Graphic::Gradient(item) => {
|
||||
graphic_types::Graphic::Gradient(item.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across).with_attribute(ATTR_GRADIENT_SPREAD, spread))
|
||||
}
|
||||
graphic => graphic,
|
||||
};
|
||||
let pixels = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?;
|
||||
|
||||
// The CPU's level at a point on the screen, or `None` where it's unpainted, which the spread repeats only where the position doesn't wind
|
||||
let GradientShape::Across(across) = GradientShape::new(curvatures[0], curvatures[1], model, GradientDirection::Across, placement) else {
|
||||
panic!("{setting} should be read across its contours");
|
||||
};
|
||||
let to_gradient = placement.inverse();
|
||||
let level_at = |point: DVec2| {
|
||||
let v = across.chart.v(to_gradient.transform_point2(point))?;
|
||||
let position = match spread {
|
||||
_ if across.chart.winds() => v,
|
||||
GradientSpread::Repeat => v - v.floor(),
|
||||
_ => v.clamp(0., 1.),
|
||||
};
|
||||
Some((position * 255.).round() as i32)
|
||||
};
|
||||
let expected = |x: i32, y: i32| level_at(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
|
||||
|
||||
// Each pixel takes the level at its center, except within two pixels of a seam where the position wraps, a step, or an edge of the painted area, which only rounding and antialiasing tell apart
|
||||
let (mut worst, mut beside_steps, mut disagreements) = (0, 0, 0);
|
||||
for y in 2..size.y as i32 - 2 {
|
||||
for x in 2..size.x as i32 - 2 {
|
||||
let neighborhood: Vec<Option<i32>> = (-2..=2).flat_map(|dy| (-2..=2).map(move |dx| (x + dx, y + dy))).map(|(x, y)| expected(x, y)).collect();
|
||||
let painted_neighbors = neighborhood.iter().filter(|level| level.is_some()).count();
|
||||
let levels = neighborhood.iter().flatten();
|
||||
let (lowest, highest) = (*levels.clone().min().unwrap_or(&0), *levels.max().unwrap_or(&255));
|
||||
let [red, _, _, alpha] = pixel(&pixels, size, x as u32, y as u32);
|
||||
|
||||
match (alpha, expected(x, y)) {
|
||||
(0, None) => {}
|
||||
(255, Some(level)) if painted_neighbors == 25 && highest - lowest <= 64 => worst = worst.max((red as i32 - level).abs()),
|
||||
(255, Some(_)) => beside_steps += 1,
|
||||
_ if painted_neighbors != 0 && painted_neighbors != 25 => {}
|
||||
_ => disagreements += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let context = format!("{setting} {curvatures:?}, {spread:?}, placed by {placement:?}");
|
||||
assert!(worst <= 3, "{context}: up to {worst} levels from the CPU");
|
||||
assert_eq!(disagreements, 0, "{context}: pixels disagreeing with the CPU on being painted");
|
||||
Some(format!("{context}: within {worst} levels, {beside_steps} pixels beside seams and steps"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_stop_curved_gradients_leave_their_gaps_unpainted() {
|
||||
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, Item};
|
||||
@@ -1823,6 +1715,250 @@ fn endless_layers_clip_to_the_shape_beneath_them() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Black on the left half of a render 140 across and white on the right, with nothing between, its effects measured in its own space spanning the render.
|
||||
fn hard_edged_gradient() -> core_types::list::Item<graphic_types::vector_types::gradient::Gradient> {
|
||||
use core_types::list::{ATTR_GRADIENT_INTERPOLATION, Item};
|
||||
use core_types::{ATTR_TRANSFORM, Color};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientInterpolation};
|
||||
|
||||
Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE, Color::WHITE]))
|
||||
.with_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Stepped)
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::splat(140.)))
|
||||
}
|
||||
|
||||
/// Pixelate with cells 10 across in a gradient's space spanning a render 140 across.
|
||||
fn pixelated_by_tens() -> graphic_types::EffectOperation {
|
||||
graphic_types::EffectOperation::Pixelate {
|
||||
cell_size: 10. / 140.,
|
||||
offset: glam::DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
/// A Gaussian blur of radius 4 in a gradient's space spanning a render 140 across.
|
||||
fn blurred_by_four() -> graphic_types::EffectOperation {
|
||||
graphic_types::EffectOperation::Blur {
|
||||
radius_mask: graphic_types::Graphic::default(),
|
||||
radius: 4. / 140.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endless_gradients_pixelate_and_blur_over_the_view() {
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_INTERPOLATION};
|
||||
use core_types::{ATTR_TRANSFORM, Color};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientInterpolation};
|
||||
use graphic_types::{Effects, Graphic};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(140, 140);
|
||||
let draw = |graphic: &Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
|
||||
|
||||
// A smooth black-to-white ramp across the render bands into cells 10 across, each one color
|
||||
let ramp = core_types::list::Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
|
||||
.with_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Linear)
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::splat(140.)))
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([pixelated_by_tens()]));
|
||||
let Some(pixelated) = draw(&Graphic::Gradient(ramp)) else { return };
|
||||
for cell in 1..13 {
|
||||
let first = pixel(&pixelated, size, cell * 10 + 1, 70);
|
||||
assert!((cell * 10 + 2..cell * 10 + 9).all(|x| pixel(&pixelated, size, x, 70) == first), "cell {cell} is one color");
|
||||
assert_ne!(first, pixel(&pixelated, size, cell * 10 + 11, 70), "cell {cell} differs from the next");
|
||||
}
|
||||
|
||||
// The hard edge halfway across softens, from gray just beside it to black and white farther away
|
||||
let blurred = draw(&Graphic::Gradient(hard_edged_gradient().with_attribute(ATTR_EFFECTS, Effects::from_operations([blurred_by_four()])))).unwrap();
|
||||
let gray = |x: u32| pixel(&blurred, size, x, 70)[0];
|
||||
assert!(gray(66) > 10 && gray(66) < 128 && gray(73) > 128 && gray(73) < 245, "{} and {}", gray(66), gray(73));
|
||||
assert!(gray(50) < 3 && gray(90) > 252, "{} and {}", gray(50), gray(90));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paints_with_effects_beyond_their_colors_show_them_within_the_shape() {
|
||||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::gradient::Gradient;
|
||||
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
|
||||
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, MaskMode, NoiseDistribution, Vector};
|
||||
use rendering::{Render, RenderParams};
|
||||
use vello_gpu::kurbo::Shape;
|
||||
|
||||
let size = UVec2::new(140, 140);
|
||||
let draw = |graphic: &Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
|
||||
let square_covered_by = |coverage: Coverage, paint: Graphic| {
|
||||
let mut square = Vector::item_from_bezpath(&Rect::new(20., 20., 120., 120.).to_path(0.1));
|
||||
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
|
||||
Graphic::VectorList(List::new_from_item(square))
|
||||
};
|
||||
let close = |a: [u8; 4], b: [u8; 4]| a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 2);
|
||||
|
||||
// A color and a gradient across the render, grained, twirled, and masked to its left half, with the gradient's effects measured in its own space that spans the render
|
||||
let color = || Item::new_from_element(GraphicColor::from_gamma_srgb_channels(0.8, 0.2, 0.4, 1.));
|
||||
let gradient = || Item::new_from_element(Gradient::from(vec![GraphicColor::BLACK, GraphicColor::WHITE])).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(140.)));
|
||||
let speckle = EffectOperation::Speckle {
|
||||
amount: 50.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
seed: 0,
|
||||
};
|
||||
let twirl = EffectOperation::Twirl {
|
||||
angle: 180.,
|
||||
transform: DAffine2::from_scale_angle_translation(DVec2::splat(100. / 140.), 0., DVec2::splat(0.5)),
|
||||
};
|
||||
let mut left_half = Vector::item_from_bezpath(&Rect::new(0., 0., 0.5, 1.).to_path(0.001));
|
||||
left_half.set_attribute(
|
||||
ATTR_APPEARANCE,
|
||||
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))),
|
||||
);
|
||||
let mask = EffectOperation::Mask {
|
||||
mask: Graphic::VectorList(List::new_from_item(left_half)),
|
||||
mode: MaskMode::Luminance,
|
||||
density: 100.,
|
||||
feather: 0.,
|
||||
invert: false,
|
||||
};
|
||||
let effected = |operation: &EffectOperation| Effects::from_operations([operation.clone()]);
|
||||
let paints = [
|
||||
("speckled color", Graphic::Color(color().with_attribute(ATTR_EFFECTS, effected(&speckle))), Graphic::Color(color())),
|
||||
(
|
||||
"speckled gradient",
|
||||
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&speckle))),
|
||||
Graphic::Gradient(gradient()),
|
||||
),
|
||||
(
|
||||
"twirled gradient",
|
||||
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&twirl))),
|
||||
Graphic::Gradient(gradient()),
|
||||
),
|
||||
(
|
||||
"masked gradient",
|
||||
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&mask))),
|
||||
Graphic::Gradient(gradient()),
|
||||
),
|
||||
(
|
||||
"pixelated gradient",
|
||||
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&pixelated_by_tens()))),
|
||||
Graphic::Gradient(gradient()),
|
||||
),
|
||||
(
|
||||
"blurred hard-edged gradient",
|
||||
Graphic::Gradient(hard_edged_gradient().with_attribute(ATTR_EFFECTS, effected(&blurred_by_four()))),
|
||||
Graphic::Gradient(hard_edged_gradient()),
|
||||
),
|
||||
];
|
||||
|
||||
for (name, paint, plain) in paints {
|
||||
// The paint drawn as a layer filling everything, which the shape's paint matches where it covers it
|
||||
let Some(layer) = draw(&paint) else { return };
|
||||
|
||||
// A fill shows the effect within the square and nothing past it
|
||||
let filled = draw(&square_covered_by(Coverage::new_fill(), paint.clone())).unwrap();
|
||||
let plain_filled = draw(&square_covered_by(Coverage::new_fill(), plain.clone())).unwrap();
|
||||
for (x, y) in (22..118).flat_map(|x| (22..118).map(move |y| (x, y))) {
|
||||
assert!(close(pixel(&filled, size, x, y), pixel(&layer, size, x, y)), "{name}: the fill matches the layer at ({x}, {y})");
|
||||
}
|
||||
for (x, y) in [(10, 70), (130, 70), (70, 10), (70, 130)] {
|
||||
assert_eq!(pixel(&filled, size, x, y)[3], 0, "{name}: nothing is filled at ({x}, {y}), past the square");
|
||||
}
|
||||
let changed = (0..filled.len()).filter(|&index| !close(filled[index], plain_filled[index])).count();
|
||||
assert!(changed > 500, "{name}: the effect changes the fill at {changed} pixels");
|
||||
|
||||
// A stroke shows it within its band, wherever its alignment places it along the square's left edge
|
||||
for (align, band) in [(StrokeAlign::Center, 16..24), (StrokeAlign::Inside, 21..29), (StrokeAlign::Outside, 11..19)] {
|
||||
let stroked = draw(&square_covered_by(Coverage::new_stroke(&Stroke { align, ..Stroke::new(10.) }), paint.clone())).unwrap();
|
||||
for (x, y) in band.clone().flat_map(|x| (40..100).map(move |y| (x, y))) {
|
||||
assert!(
|
||||
close(pixel(&stroked, size, x, y), pixel(&layer, size, x, y)),
|
||||
"{name}, {align:?}: the stroke matches the layer at ({x}, {y})"
|
||||
);
|
||||
}
|
||||
for x in [band.start - 4, band.end + 3] {
|
||||
assert_eq!(pixel(&stroked, size, x, 70)[3], 0, "{name}, {align:?}: nothing is stroked at ({x}, 70), past the band");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_filled_paint_made_opaque_looks_the_same_whether_drawn_by_its_color_or_as_content() {
|
||||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||
use core_types::{ATTR_OPACITY_FILL, Color as GraphicColor};
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector};
|
||||
use rendering::{Render, RenderParams};
|
||||
use vello_gpu::kurbo::Shape;
|
||||
|
||||
let size = UVec2::new(140, 140);
|
||||
let filled_square = |operations: Vec<EffectOperation>| {
|
||||
let paint = Item::new_from_element(GraphicColor::RED)
|
||||
.with_attribute(ATTR_OPACITY_FILL, 0.5)
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations(operations));
|
||||
let mut square = Vector::item_from_bezpath(&Rect::new(20., 20., 120., 120.).to_path(0.1));
|
||||
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::Color(paint)));
|
||||
Graphic::VectorList(List::new_from_item(square))
|
||||
};
|
||||
|
||||
// The fill fades the red before Make Opaque restores it, alike when a blur of the flat color draws it as content
|
||||
let make_opaque = EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 4.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
for operations in [vec![make_opaque.clone()], vec![make_opaque, blur]] {
|
||||
let count = operations.len();
|
||||
let Some(pixels) = render(size, |scene| filled_square(operations.clone()).render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
for (x, y) in [(70, 70), (25, 70), (115, 115)] {
|
||||
assert_eq!(pixel(&pixels, size, x, y), [255, 0, 0, 255], "{count} effects at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paints_own_blend_mode_composites_within_the_paint_rather_than_onto_what_lies_beneath_the_shape() {
|
||||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||
use core_types::{ATTR_BLEND_MODE, Color as GraphicColor};
|
||||
use graphic_types::vector_types::vector::style::Stroke;
|
||||
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector};
|
||||
use rendering::{Render, RenderParams};
|
||||
use vello_gpu::kurbo::Shape;
|
||||
|
||||
let size = UVec2::new(140, 140);
|
||||
let shape = |rect: Rect, coverage: Coverage, paint: Graphic| {
|
||||
let mut vector = Vector::item_from_bezpath(&rect.to_path(0.1));
|
||||
vector.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
|
||||
Graphic::VectorList(List::new_from_item(vector))
|
||||
};
|
||||
let background = shape(Rect::new(0., 0., 140., 140.), Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::RED)));
|
||||
|
||||
// Green multiplied with nothing beneath it in its paint stays green, whatever lies beneath the shape, as in SVG's pattern, though a blur of it draws it as content
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 4.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let green = Item::new_from_element(GraphicColor::GREEN)
|
||||
.with_attribute(ATTR_BLEND_MODE, BlendMode::Multiply)
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([blur]));
|
||||
for (coverage, inside) in [(Coverage::new_fill(), (70, 70)), (Coverage::new_stroke(&Stroke::new(10.)), (20, 70))] {
|
||||
let square = shape(Rect::new(20., 20., 120., 120.), coverage, Graphic::Color(green.clone()));
|
||||
let Some(pixels) = render(size, |scene| {
|
||||
background.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
||||
square.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
let (x, y) = inside;
|
||||
assert_eq!(pixel(&pixels, size, x, y), [0, 255, 0, 255], "green at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feathers_fade_the_content_to_nothing_at_its_edges() {
|
||||
use graphic_types::EffectOperation;
|
||||
@@ -4735,6 +4871,191 @@ fn gpu_neighborhood_extremes_match_the_cpu_kernels() {
|
||||
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
||||
}
|
||||
|
||||
/// The exact result of a Median of `radius` whole texels on premultiplied `texels` (`width` across) with nothing past their edges: the upper median of each window's alphas,
|
||||
/// and of each straight color among the texels with coverage, which the passes hold as half floats. O(texels × radius² log radius).
|
||||
fn median_reference(texels: &[[f32; 4]], width: usize, radius: isize) -> Vec<[f32; 4]> {
|
||||
use half::f16;
|
||||
|
||||
let height = (texels.len() / width) as isize;
|
||||
let straight: Vec<[f32; 4]> = (texels.iter())
|
||||
.map(|&[red, green, blue, alpha]| match alpha > 0. {
|
||||
true => [red / alpha, green / alpha, blue / alpha, alpha].map(|value| f16::from_f32(value).to_f32()),
|
||||
false => [0.; 4],
|
||||
})
|
||||
.collect();
|
||||
let upper_median = |mut values: Vec<f32>| {
|
||||
values.sort_by(f32::total_cmp);
|
||||
values[values.len() / 2]
|
||||
};
|
||||
|
||||
(0..texels.len())
|
||||
.map(|index| {
|
||||
let (x, y) = ((index % width) as isize, (index / width) as isize);
|
||||
let mut alphas = Vec::new();
|
||||
let mut colors: [Vec<f32>; 3] = Default::default();
|
||||
for (shift_x, shift_y) in (-radius..=radius).flat_map(|shift_y| (-radius..=radius).map(move |shift_x| (shift_x, shift_y))) {
|
||||
let (read_x, read_y) = (x + shift_x, y + shift_y);
|
||||
let within = (0..width as isize).contains(&read_x) && (0..height).contains(&read_y);
|
||||
let texel = if within { straight[(read_y * width as isize + read_x) as usize] } else { [0.; 4] };
|
||||
alphas.push(texel[3]);
|
||||
if texel[3] > 0. {
|
||||
colors.iter_mut().zip(texel).for_each(|(channel, value)| channel.push(value));
|
||||
}
|
||||
}
|
||||
|
||||
let alpha = upper_median(alphas);
|
||||
if alpha <= 0. || colors[0].is_empty() {
|
||||
return [0.; 4];
|
||||
}
|
||||
let [red, green, blue] = colors.map(upper_median);
|
||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_medians_match_the_exact_reference() {
|
||||
use graphic_types::{EffectOperation, Effects};
|
||||
use half::f16;
|
||||
|
||||
// Random colors, opaque but for a fully transparent band and a translucent one, so some windows rank colors among fewer texels than alphas
|
||||
let (width, height) = (37, 23);
|
||||
let texels: Vec<[f16; 4]> = (0..width * height)
|
||||
.map(|index| {
|
||||
let (x, y) = (index % width, index / width);
|
||||
let alpha = match (x, y) {
|
||||
(10..14, _) => 0.,
|
||||
(_, 5..8) => 0.4,
|
||||
_ => 1.,
|
||||
};
|
||||
let random = |seed: u32| ((index as u32).wrapping_mul(2_654_435_761).wrapping_add(seed.wrapping_mul(40_503)) >> 24) as f32 / 255.;
|
||||
[random(1) * alpha, random(2) * alpha, random(3) * alpha, alpha].map(f16::from_f32)
|
||||
})
|
||||
.collect();
|
||||
let unrounded: Vec<[f32; 4]> = texels.iter().map(|texel| texel.map(f16::to_f32)).collect();
|
||||
|
||||
let mut strays = Vec::new();
|
||||
for radius in [1, 2, 3, 6] {
|
||||
let effects = Effects::from_operations([EffectOperation::Median { radius: radius as f64 + 0.5 }]);
|
||||
let Some(gpu) = gpu_effect_texels(&effects, &texels, width, &[]) else { return };
|
||||
let reference = median_reference(&unrounded, width, radius);
|
||||
|
||||
// In 8-bit levels, within the rounding of half floats
|
||||
let levels = (gpu.iter().zip(&reference))
|
||||
.flat_map(|(gpu, reference)| (0..4).map(|channel| (gpu[channel] - reference[channel]).abs() * 255.))
|
||||
.fold(0_f32, f32::max);
|
||||
if levels > 0.5 {
|
||||
strays.push(format!("a median of radius {radius} strays from the exact one by {levels} levels"));
|
||||
}
|
||||
}
|
||||
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medians_work_on_an_images_own_pixels_at_any_zoom() {
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::list::{Item, List};
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
// A square of 2×2 white pixels on black, which a median of radius 1 removes, since it fills under half of each 3×3 window
|
||||
let mut image = Image::new(6, 6, core_types::Color::BLACK);
|
||||
for (x, y) in [(2, 2), (3, 2), (2, 3), (3, 3)] {
|
||||
image.data[y * 6 + x] = core_types::Color::WHITE;
|
||||
}
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(6.)));
|
||||
stamp_effect(&mut item, Effect::new(&EffectOperation::Median { radius: 1. }));
|
||||
let list = List::new_from_item(item);
|
||||
|
||||
// Zoomed in, a median of the view's pixels would keep the square, which then fills most of each window
|
||||
for zoom in [1., 4.] {
|
||||
let size = UVec2::splat((6. * zoom) as u32);
|
||||
let view = DAffine2::from_scale(DVec2::splat(zoom));
|
||||
let Some(pixels) = render_in_view(size, view, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
let center = (3. * zoom) as u32;
|
||||
assert_eq!(pixel(&pixels, size, center, center), [0, 0, 0, 255], "at a zoom of {zoom}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medians_read_within_an_images_rectangle() {
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::list::{Item, List};
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
// An opaque white image a pixel in from the render's corner
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(8.), 0., DVec2::ONE);
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(8, 8, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, placement);
|
||||
stamp_effect(&mut item, Effect::new(&EffectOperation::Median { radius: 2. }));
|
||||
let list = List::new_from_item(item);
|
||||
|
||||
let size = UVec2::splat(10);
|
||||
let Some(pixels) = render(size, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Its corners keep their pixels, read as if the image were all there is, and nothing spreads past it
|
||||
assert_eq!(pixel(&pixels, size, 1, 1), [255; 4]);
|
||||
assert_eq!(pixel(&pixels, size, 8, 8), [255; 4]);
|
||||
assert_eq!(pixel(&pixels, size, 0, 0)[3], 0);
|
||||
assert_eq!(pixel(&pixels, size, 9, 4)[3], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_median_baked_for_pixel_readers_matches_its_gpu_render() {
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::list::{Item, List};
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::{CPU, Image, Raster};
|
||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
// Random colors with a fully transparent band, a pixel in from the render's corner, on the content's own grid and on one coarsened past its largest radius
|
||||
let (width, height) = (40, 30);
|
||||
let data = (0..width * height)
|
||||
.map(|index| {
|
||||
let random = |seed: u32| ((index as u32).wrapping_mul(2_654_435_761).wrapping_add(seed.wrapping_mul(40_503)) >> 24) as f32 / 255.;
|
||||
let alpha = if (12..16).contains(&(index % width)) { 0. } else { 1. };
|
||||
core_types::Color::from_gamma_srgb_channels(random(1), random(2), random(3), alpha)
|
||||
})
|
||||
.collect();
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(width as f64, height as f64), 0., DVec2::ONE);
|
||||
let image = Item::new_from_element(Raster::new_cpu(Image {
|
||||
width: width as u32,
|
||||
height: height as u32,
|
||||
data,
|
||||
}))
|
||||
.with_attribute(ATTR_TRANSFORM, placement);
|
||||
|
||||
let size = UVec2::new(width as u32 + 2, height as u32 + 2);
|
||||
let draw = |item: Item<Raster<CPU>>| {
|
||||
let list = List::new_from_item(item);
|
||||
render(size, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||||
};
|
||||
for radius in [2., 20.] {
|
||||
let mut item = image.clone();
|
||||
stamp_effect(&mut item, Effect::new(&EffectOperation::Median { radius }));
|
||||
|
||||
// A reader bakes the effect into the image's pixels, which must draw as the GPU draws the effect
|
||||
let baked = raster_kernels::evaluate_raster_effects(item.clone());
|
||||
let (Some(gpu), Some(baked)) = (draw(item), draw(baked)) else { return };
|
||||
// Compared premultiplied, since the straight colors of nearly transparent pixels read back in steps as coarse as their alpha, within the rounding of half floats and 8 bits
|
||||
let premultiplied = |[red, green, blue, alpha]: [u8; 4]| [red, green, blue].map(|channel| channel as f32 * alpha as f32 / 255.).into_iter().chain([alpha as f32]);
|
||||
let stray = (gpu.iter().zip(&baked))
|
||||
.flat_map(|(gpu, baked)| premultiplied(*gpu).zip(premultiplied(*baked)).map(|(gpu, baked)| (gpu - baked).abs()))
|
||||
.fold(0_f32, f32::max);
|
||||
assert!(stray <= 3., "a median of radius {radius} baked strays from its GPU render by {stray} levels");
|
||||
assert_ne!(baked, draw(image.clone()).unwrap_or_default(), "the median changes the pixels");
|
||||
}
|
||||
}
|
||||
|
||||
/// Colors across the RGB cube, among them black, white, grays, and saturated and near-black colors, each opaque, with some also translucent or fully transparent.
|
||||
fn adjustment_test_colors() -> Vec<core_types::Color> {
|
||||
const LEVELS: [f32; 12] = [0., 1. / 255., 4. / 255., 0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95, 254. / 255., 1.];
|
||||
@@ -5143,9 +5464,20 @@ fn gpu_color_adjustments_match_the_cpu_kernels() {
|
||||
("Photo Filter", photo_filter(warming, 25., true)),
|
||||
("Photo Filter at full density", photo_filter(cooling, 100., false)),
|
||||
("Photo Filter at full density preserving luminosity", photo_filter(cooling, 100., true)),
|
||||
("Alpha to Gray", Adjustment::AlphaToGray),
|
||||
];
|
||||
let mut runs: Vec<(String, Vec<Adjustment>)> = runs.into_iter().map(|(name, adjustment)| (name.to_string(), vec![adjustment])).collect();
|
||||
|
||||
// The opaque grays of one channel each that 'Into Channels' outputs
|
||||
let opaque = Adjustment::MakeOpaque { strength: 100. };
|
||||
let green_gray = Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||
monochrome: true,
|
||||
monochrome_mix: row(0., 100., 0., 0.),
|
||||
..Default::default()
|
||||
}));
|
||||
runs.push(("Green as an opaque gray".to_string(), vec![green_gray, opaque.clone()]));
|
||||
runs.push(("Alpha as an opaque gray".to_string(), vec![Adjustment::AlphaToGray, opaque]));
|
||||
|
||||
// Every blend mode, overlaying an opaque color and a translucent one, each with a luma apart from every test color's, which Darker Color and Lighter Color compare, and off Hard Mix's steep ramp over them
|
||||
for blend_mode in BlendMode::list().into_iter().flatten().chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha]) {
|
||||
for (color, opacity) in [
|
||||
|
||||
@@ -3,13 +3,13 @@ use core_types::blending::BlendMode;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use core_types::{ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color, Ctx};
|
||||
use core_types::{ATTR_TRANSFORM, Color, Ctx};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectOperation, Generator, GlowSource, GlowTechnique, Graphic, Vector, linked_to_content, paint_with_envelope_effects, stamp_effect,
|
||||
};
|
||||
use raster_kernels::{evaluate_color_effects, evaluate_gradient_effects};
|
||||
use raster_kernels::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
|
||||
use vector_types::Gradient;
|
||||
use vector_types::vector::style::{StrokeAlign, initial_gradient_transform_for_bounding_box};
|
||||
|
||||
@@ -99,7 +99,7 @@ fn drop_shadow<T>(
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::DropShadow {
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
color: evaluate_color_parameter(color).into_element(),
|
||||
blend_mode: *blend_mode.element(),
|
||||
angle: *angle.element(),
|
||||
distance: *distance.element(),
|
||||
@@ -155,7 +155,7 @@ fn inner_shadow<T>(
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::InnerShadow {
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
color: evaluate_color_parameter(color).into_element(),
|
||||
blend_mode: *blend_mode.element(),
|
||||
angle: *angle.element(),
|
||||
distance: *distance.element(),
|
||||
@@ -468,7 +468,7 @@ fn satin<T>(
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::Satin {
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
color: evaluate_color_parameter(color).into_element(),
|
||||
blend_mode: *blend_mode.element(),
|
||||
angle: *angle.element(),
|
||||
distance: *distance.element(),
|
||||
@@ -620,9 +620,9 @@ fn bevel_and_emboss<T: PaintFitBounds>(
|
||||
soften: *soften.element(),
|
||||
angle: *angle.element(),
|
||||
altitude: *altitude.element(),
|
||||
highlight_color: evaluate_color_effects(highlight_color).into_element(),
|
||||
highlight_color: evaluate_color_parameter(highlight_color).into_element(),
|
||||
highlight_blend_mode: *highlight_blend_mode.element(),
|
||||
shadow_color: evaluate_color_effects(shadow_color).into_element(),
|
||||
shadow_color: evaluate_color_parameter(shadow_color).into_element(),
|
||||
shadow_blend_mode: *shadow_blend_mode.element(),
|
||||
texture,
|
||||
texture_depth: *texture_depth.element(),
|
||||
@@ -661,11 +661,7 @@ fn paint_overlay<T: PaintFitBounds>(
|
||||
let paint = match paint_with_envelope_effects(paint) {
|
||||
Graphic::None(_) | Graphic::NoneList(_) => return content,
|
||||
// A solid paint becomes a bare color, so its own opacity fades the color's alpha
|
||||
Graphic::Color(color) => {
|
||||
let opacity = color.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) * color.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.);
|
||||
let color = evaluate_color_effects(color).into_element();
|
||||
Graphic::from(color.with_alpha(color.a() * opacity as f32))
|
||||
}
|
||||
Graphic::Color(color) => Graphic::from(evaluate_color_parameter(color).into_element()),
|
||||
paint => paint_with_placement(&content, paint, _has_transform, _transform),
|
||||
};
|
||||
|
||||
@@ -775,6 +771,33 @@ mod test {
|
||||
assert!(color.r() > 0.05 && color.r() < 0.95, "half the black paint leaves {color:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_shadow_fades_its_color_by_the_colors_own_opacity() {
|
||||
use core_types::ATTR_OPACITY;
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use graphic_types::EffectOperation;
|
||||
|
||||
let number = |value: f64| Item::new_from_element(value);
|
||||
let shadowed = super::drop_shadow(
|
||||
(),
|
||||
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::WHITE))),
|
||||
Item::new_from_element(Color::BLACK).with_attribute(ATTR_OPACITY, 0.5_f64),
|
||||
BlendMode::Normal.into(),
|
||||
number(120.),
|
||||
number(5.),
|
||||
number(0.),
|
||||
number(5.),
|
||||
Item::new_from_element(TransferCurve::default()),
|
||||
true.into(),
|
||||
);
|
||||
|
||||
let operation = shadowed.attribute::<Effects>(ATTR_EFFECTS).and_then(|effects| effects.operations().next());
|
||||
let Some(EffectOperation::DropShadow { color, .. }) = operation else {
|
||||
panic!("expected a drop shadow, got {operation:?}")
|
||||
};
|
||||
assert_eq!(color, Color::BLACK.with_alpha(0.5));
|
||||
}
|
||||
|
||||
type PaintEffectNode<T> = fn(Item<T>, Graphic, bool, DAffine2) -> Item<T>;
|
||||
|
||||
fn paint_effect_nodes<T: super::PaintFitBounds>() -> [(&'static str, PaintEffectNode<T>); 3] {
|
||||
|
||||
@@ -53,7 +53,7 @@ fn create_artboard<T: IntoGraphicList>(
|
||||
let normalized_location = location.min(location + dimensions);
|
||||
let normalized_dimensions = dimensions.abs().max(DVec2::ONE);
|
||||
|
||||
let background = raster_kernels::evaluate_color_effects(background).into_element();
|
||||
let background = raster_kernels::evaluate_color_parameter(background).into_element();
|
||||
|
||||
// Name is not stored here, it's resolved live from the parent layer's display name
|
||||
Ok(Item::new_from_element(Artboard::new(content))
|
||||
|
||||
@@ -1142,7 +1142,9 @@ fn flatten_gradient(_: impl Ctx, content: List<Graphic>) -> List<Gradient> {
|
||||
/// Constructs a gradient from a `Color[]`, where each color becomes a gradient stop. A `position` attribute on the colors places their stops along the ramp and a `midpoint` attribute skews each transition, while colors carrying neither are distributed evenly across the 0 to 1 range.
|
||||
#[node_macro::node(category("Gradient"), icon("NodeColorsToGradient"), name("Colors to Gradient"))]
|
||||
fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Item<Gradient> {
|
||||
Item::new_from_element(Gradient::from(colors.into_flattened_list::<Color>()))
|
||||
// Each color's own effects and opacity go into it before it becomes a stop
|
||||
let colors: List<Color> = colors.into_flattened_list::<Color>().into_iter().map(value_effects::evaluate_color_parameter).collect();
|
||||
Item::new_from_element(Gradient::from(colors))
|
||||
}
|
||||
|
||||
/// Unwraps a gradient into a `Color[]` of its stops, keeping any `position` and `midpoint` attributes that place them along the ramp. Attributes belonging to the gradient as a whole (like spread and interpolation), rather than its individual color stops, are not preserved.
|
||||
@@ -1423,4 +1425,18 @@ mod test {
|
||||
expected.set_positions(&[0.25, 0.75]);
|
||||
assert_eq!(colors_to_gradient((), embed_colors(colors)).element(), &expected, "each stop should keep its place");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_to_gradient_carries_out_each_colors_effects_and_opacity() {
|
||||
use core_types::ATTR_OPACITY;
|
||||
use graphic_types::{Adjustment, EffectOperation};
|
||||
|
||||
let inverted = Item::new_from_element(Color::BLACK).with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::Adjustment(Adjustment::Invert)]));
|
||||
let half_opacity = Item::new_from_element(Color::RED).with_attribute(ATTR_OPACITY, 0.5_f64);
|
||||
let colors: List<Color> = [inverted, half_opacity].into_iter().collect();
|
||||
|
||||
let gradient = colors_to_gradient((), embed_colors(colors));
|
||||
let expected = Gradient::from(vec![Color::WHITE, Color::RED.with_alpha(0.5)]);
|
||||
assert_eq!(gradient.element(), &expected, "the inverted black should become a white stop, and the half-opaque red a half-alpha one");
|
||||
}
|
||||
}
|
||||
@@ -1952,14 +1952,6 @@ fn gradient_model(_: impl Ctx, gradient: Item<Gradient>, model: Item<vector_type
|
||||
gradient
|
||||
}
|
||||
|
||||
/// Sets which way the colors of each gradient in the input list run: Along, from the start contour to the end contour, or Across, around each contour.
|
||||
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"))]
|
||||
fn gradient_direction(_: impl Ctx, gradient: Item<Gradient>, direction: Item<vector_types::GradientDirection>) -> Item<Gradient> {
|
||||
let mut gradient = gradient;
|
||||
gradient.set_attribute(core_types::ATTR_GRADIENT_DIRECTION, *direction.element());
|
||||
gradient
|
||||
}
|
||||
|
||||
/// Sets how each gradient in the input list extends past its endpoints: Pad, Reflect, Repeat, or Clear.
|
||||
#[node_macro::node(category("Gradient"), icon("NodeGradientSpread"))]
|
||||
fn gradient_spread(_: impl Ctx, gradient: Item<Gradient>, gradient_spread: Item<vector_types::GradientSpread>) -> Item<Gradient> {
|
||||
|
||||
@@ -53,5 +53,10 @@ tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Local dependencies
|
||||
rendering = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
tokio = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
@@ -14,8 +14,8 @@ use graphic_types::adjustment::{
|
||||
pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute};
|
||||
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
||||
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||
use raster_kernels::{evaluate_color_effects, evaluate_gradient_effects};
|
||||
use raster_types::{CPU, GPU, Image, Raster};
|
||||
use raster_kernels::{evaluate_color_parameter, evaluate_gradient_effects};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Stamps the adjustment onto the item's effects, to be carried out wherever its content is rendered or read.
|
||||
@@ -50,42 +50,6 @@ fn gamma_correction<T>(
|
||||
)
|
||||
}
|
||||
|
||||
/// The red, green, blue, and alpha channels of an image, split into separate node outputs.
|
||||
#[derive(Debug, Clone, dyn_any::DynAny, node_macro::Destructure)]
|
||||
pub struct ImageChannels {
|
||||
/// The red channel of the image, as a grayscale image.
|
||||
pub red: Item<Raster<CPU>>,
|
||||
/// The green channel of the image, as a grayscale image.
|
||||
pub green: Item<Raster<CPU>>,
|
||||
/// The blue channel of the image, as a grayscale image.
|
||||
pub blue: Item<Raster<CPU>>,
|
||||
/// The alpha channel of the image, as a grayscale image.
|
||||
pub alpha: Item<Raster<CPU>>,
|
||||
}
|
||||
|
||||
/// Separates an image into its red, green, blue, and alpha channels, each provided as a grayscale image.
|
||||
#[node_macro::node(category("Raster"), icon("NodeImageToChannels"), name("Image to Channels"))]
|
||||
fn image_to_channels(_: impl Ctx, image: Item<Raster<CPU>>) -> ImageChannels {
|
||||
let (image, attributes) = raster_kernels::evaluate_raster_effects(image).into_parts();
|
||||
let (width, height) = (image.width, image.height);
|
||||
|
||||
// O(4 × pixels), since all four channels are written even when only some outputs are connected
|
||||
let mut channels: [Vec<Color>; 4] = core::array::from_fn(|_| Vec::with_capacity(image.data.len()));
|
||||
for color in &image.data {
|
||||
for (channel, value) in channels.iter_mut().zip([color.r(), color.g(), color.b(), color.a()]) {
|
||||
channel.push(Color::from_rgbaf32_unchecked(value, value, value, 1.));
|
||||
}
|
||||
}
|
||||
|
||||
// Each channel image keeps the source image's attributes, such as its transform
|
||||
let [red, green, blue, alpha] = channels.map(|data| {
|
||||
let channel_image = Image { width, height, data };
|
||||
Item::from_parts(Raster::new_cpu(channel_image), attributes.clone())
|
||||
});
|
||||
|
||||
ImageChannels { red, green, blue, alpha }
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"), version(2))]
|
||||
fn make_opaque<T>(
|
||||
_: impl Ctx,
|
||||
@@ -414,7 +378,7 @@ fn black_and_white<T>(
|
||||
) -> Item<T> {
|
||||
let settings = BlackAndWhiteSettings {
|
||||
use_tint: use_tint.into_element(),
|
||||
tint: evaluate_color_effects(tint).into_element(),
|
||||
tint: evaluate_color_parameter(tint).into_element(),
|
||||
reds: reds.into_element(),
|
||||
yellows: yellows.into_element(),
|
||||
greens: greens.into_element(),
|
||||
@@ -1417,7 +1381,7 @@ fn photo_filter<T>(
|
||||
adjust(
|
||||
image,
|
||||
Adjustment::PhotoFilter {
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
color: evaluate_color_parameter(color).into_element(),
|
||||
density: density.into_element(),
|
||||
preserve_luminosity: preserve_luminosity.into_element(),
|
||||
},
|
||||
@@ -1460,6 +1424,8 @@ mod _graphene_hash_impls {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use raster_kernels::evaluate_color_effects;
|
||||
use raster_types::Image;
|
||||
|
||||
/// Matched to within one 8-bit level.
|
||||
fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
|
||||
|
||||
@@ -18,8 +18,8 @@ fn mix_colors(
|
||||
#[default(100.)]
|
||||
opacity: Item<f64>,
|
||||
) -> Item<Color> {
|
||||
let mut under = raster_kernels::evaluate_color_effects(under);
|
||||
let over = raster_kernels::evaluate_color_effects(over);
|
||||
let mut under = raster_kernels::evaluate_color_parameter(under);
|
||||
let over = raster_kernels::evaluate_color_parameter(over);
|
||||
let blend_mode = blend_mode.into_element();
|
||||
let opacity = (opacity.into_element() / 100.) as f32;
|
||||
|
||||
@@ -41,4 +41,20 @@ mod test {
|
||||
|
||||
assert_eq!(mixed, Color::from_rgbaf32_unchecked(0.25, 0., 0.75, 1.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mix_colors_fades_each_color_by_its_opacity() {
|
||||
use core_types::ATTR_OPACITY;
|
||||
use core_types::list::Item;
|
||||
|
||||
let half_opacity = |color: Color| Item::new_from_element(color).with_attribute(ATTR_OPACITY, 0.5_f64);
|
||||
let mix = |under: Item<Color>, over: Item<Color>| super::mix_colors((), under, over, BlendMode::Normal.into(), 100_f64.into());
|
||||
|
||||
assert_eq!(*mix(Color::TRANSPARENT.into(), half_opacity(Color::RED)).element(), Color::RED.with_alpha(0.5));
|
||||
|
||||
// The under color's opacity goes into its alpha, so the result carries none to fade it twice
|
||||
let mixed = mix(half_opacity(Color::BLUE), Color::TRANSPARENT.into());
|
||||
assert_eq!(*mixed.element(), Color::BLUE.with_alpha(0.5));
|
||||
assert_eq!(mixed.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 1.);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::{ATTR_EFFECTS, Item, ItemAttributeValues, List};
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL};
|
||||
use glam::DAffine2;
|
||||
use graphic_types::adjustment::{Adjustment, ChannelMixerRow, ChannelMixerSettings};
|
||||
use graphic_types::{Effect, EffectOperation, Effects, Graphic, MaskMode, linked_to_content, stamp_effect_on};
|
||||
|
||||
/// The red, green, blue, and alpha channels of a graphic, split into separate node outputs.
|
||||
#[derive(Debug, Clone, dyn_any::DynAny, node_macro::Destructure)]
|
||||
pub struct Channels {
|
||||
/// The red channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||
pub red: Item<Graphic>,
|
||||
/// The green channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||
pub green: Item<Graphic>,
|
||||
/// The blue channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||
pub blue: Item<Graphic>,
|
||||
/// The alpha channel of the graphic as an opaque grayscale graphic, from black where the graphic is transparent to white where it's opaque.
|
||||
pub alpha: Item<Graphic>,
|
||||
}
|
||||
|
||||
/// Separates the input graphic into its red, green, blue, and alpha channels, each as a grayscale graphic.
|
||||
///
|
||||
/// The color channels keep the graphic's transparency, while the alpha channel is opaque, so it masks by its luminance as the alpha did.
|
||||
#[node_macro::node(category("Raster"), icon("NodeImageToChannels"), version(2))]
|
||||
fn into_channels(_: impl Ctx, content: Item<Graphic>) -> Channels {
|
||||
// Each output is the content with adjustments graying it by one channel, carried out wherever it's rendered or read
|
||||
let channel = |grays: &[Adjustment]| {
|
||||
let mut channel = content.clone();
|
||||
with_effects_holder(&mut channel, |attributes| grays.iter().for_each(|gray| stamp_adjustment(attributes, gray.clone())));
|
||||
channel
|
||||
};
|
||||
|
||||
Channels {
|
||||
red: channel(&[channel_gray([100., 0., 0.])]),
|
||||
green: channel(&[channel_gray([0., 100., 0.])]),
|
||||
blue: channel(&[channel_gray([0., 0., 100.])]),
|
||||
alpha: channel(&[Adjustment::AlphaToGray, Adjustment::MakeOpaque { strength: 100. }]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Combines graphics into the red, green, blue, and alpha channels of one graphic. Each color channel comes from the same channel of its input, and the alpha from the alpha input's red channel, so grayscale graphics like those from 'Into Channels' recombine exactly.
|
||||
///
|
||||
/// The inputs line up where they lie in the document, and the result covers them all, transparent where none lies. Unconnected color channels are black, and an unconnected alpha leaves the result opaque.
|
||||
#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), version(2))]
|
||||
fn from_channels(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
/// The graphic whose red channel becomes the red channel.
|
||||
#[expose]
|
||||
red: Item<Graphic>,
|
||||
/// The graphic whose green channel becomes the green channel.
|
||||
#[expose]
|
||||
green: Item<Graphic>,
|
||||
/// The graphic whose blue channel becomes the blue channel.
|
||||
#[expose]
|
||||
blue: Item<Graphic>,
|
||||
/// The graphic whose red channel becomes the alpha, from transparent where it's black to opaque where it's white. Past its edges, the result is transparent.
|
||||
#[expose]
|
||||
alpha: Item<Graphic>,
|
||||
) -> Item<Graphic> {
|
||||
// An unconnected channel arrives as a graphic drawing nothing, which counts as absent
|
||||
let present = |channel: Item<Graphic>| (!channel.element().draws_nothing()).then_some(channel);
|
||||
let [red, green, blue, alpha] = [red, green, blue, alpha].map(present);
|
||||
|
||||
// Each input made opaque, keeping only its own color channel, or none for the alpha, which also masks the group by a gray of its red channel
|
||||
let opaque = |channel: Item<Graphic>, keep: Adjustment| {
|
||||
let mut channel = without_compositing(channel);
|
||||
with_effects_holder(&mut channel, |attributes| {
|
||||
stamp_adjustment(attributes, Adjustment::MakeOpaque { strength: 100. });
|
||||
stamp_adjustment(attributes, keep);
|
||||
});
|
||||
channel
|
||||
};
|
||||
let mask = alpha.clone().map(|alpha| opaque(alpha, channel_gray([100., 0., 0.])));
|
||||
let kept = [Some(0), Some(1), Some(2), None].map(kept_channel);
|
||||
let channels = [red, green, blue, alpha].into_iter().zip(kept).filter_map(|(channel, keep)| Some(opaque(channel?, keep)));
|
||||
|
||||
// Each channel adds onto those before it, holding none of their channels, so the group covers every input
|
||||
let mut group = List::default();
|
||||
for (index, mut channel) in channels.enumerate() {
|
||||
if index > 0 {
|
||||
channel.set_attribute(ATTR_BLEND_MODE, BlendMode::LinearDodge);
|
||||
}
|
||||
group.push(channel);
|
||||
}
|
||||
if group.is_empty() {
|
||||
return Item::default();
|
||||
}
|
||||
let mut result = Item::new_from_element(Graphic::GraphicList(group));
|
||||
|
||||
// The alpha's gray shows the group by its luminance, which for a gray is its level, or else the group is made opaque.
|
||||
// Either effect also renders the group apart from what lies beneath, so its channels add only onto each other.
|
||||
let effect = match mask {
|
||||
Some(mask) => EffectOperation::Mask {
|
||||
mask: linked_to_content(Graphic::Graphic(Box::new(mask)), DAffine2::IDENTITY),
|
||||
mode: MaskMode::Luminance,
|
||||
density: 100.,
|
||||
feather: 0.,
|
||||
invert: false,
|
||||
},
|
||||
None => EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. }),
|
||||
};
|
||||
stamp_effect_on(result.attributes_mut(), Effect::new(&effect));
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// The graphic without the opacity, fill, blend mode, and clipping a channel takes no part in, on its envelope and the one item it may hold.
|
||||
fn without_compositing(mut graphic: Item<Graphic>) -> Item<Graphic> {
|
||||
let strip = |attributes: &mut ItemAttributeValues| {
|
||||
attributes.remove::<f64>(ATTR_OPACITY);
|
||||
attributes.remove::<f64>(ATTR_OPACITY_FILL);
|
||||
attributes.remove::<BlendMode>(ATTR_BLEND_MODE);
|
||||
attributes.remove::<bool>(ATTR_CLIPPING_MASK);
|
||||
};
|
||||
strip(graphic.attributes_mut());
|
||||
if let Some(attributes) = lone_item_attributes(graphic.element_mut()) {
|
||||
strip(attributes);
|
||||
}
|
||||
graphic
|
||||
}
|
||||
|
||||
/// A Channel Mixer keeping only the red, green, or blue channel by its `index`, or none for black.
|
||||
fn kept_channel(index: Option<usize>) -> Adjustment {
|
||||
let row = |row_index: usize| {
|
||||
let weight = |channel: usize| if index == Some(row_index) && channel == row_index { 100. } else { 0. };
|
||||
ChannelMixerRow {
|
||||
red: weight(0),
|
||||
green: weight(1),
|
||||
blue: weight(2),
|
||||
constant: 0.,
|
||||
}
|
||||
};
|
||||
|
||||
Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||
monochrome: false,
|
||||
monochrome_mix: ChannelMixerRow {
|
||||
red: 40.,
|
||||
green: 40.,
|
||||
blue: 20.,
|
||||
constant: 0.,
|
||||
},
|
||||
red: row(0),
|
||||
green: row(1),
|
||||
blue: row(2),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Gives `edit` the attributes of the item a graphic's effects go on.
|
||||
/// That's the one item the graphic holds, which keeps the handling of its own kind (an image's adjustments reach even its fully transparent pixels) and stays an image for 'Flatten Raster' to take out,
|
||||
/// unless the graphic's own effects or fill, which act before effects appended to the graphic, would then act after them.
|
||||
fn with_effects_holder<R>(graphic: &mut Item<Graphic>, edit: impl FnOnce(&mut ItemAttributeValues) -> R) -> R {
|
||||
let envelope_has_effects = graphic.attribute::<Effects>(ATTR_EFFECTS).is_some_and(|effects| !effects.is_empty());
|
||||
let envelope_acts_first = envelope_has_effects || graphic.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) != 1.;
|
||||
|
||||
if !envelope_acts_first && let Some(attributes) = lone_item_attributes(graphic.element_mut()) {
|
||||
return edit(attributes);
|
||||
}
|
||||
edit(graphic.attributes_mut())
|
||||
}
|
||||
|
||||
/// The attributes of the one item a graphic holds, or `None` if it holds a list.
|
||||
fn lone_item_attributes(graphic: &mut Graphic) -> Option<&mut ItemAttributeValues> {
|
||||
Some(match graphic {
|
||||
Graphic::Graphic(item) => item.attributes_mut(),
|
||||
Graphic::Vector(item) => item.attributes_mut(),
|
||||
Graphic::RasterCPU(item) => item.attributes_mut(),
|
||||
Graphic::RasterGPU(item) => item.attributes_mut(),
|
||||
Graphic::Color(item) => item.attributes_mut(),
|
||||
Graphic::Gradient(item) => item.attributes_mut(),
|
||||
Graphic::Generator(item) => item.attributes_mut(),
|
||||
Graphic::Text(item) => item.attributes_mut(),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Stamps the adjustment onto the effects in these attributes.
|
||||
fn stamp_adjustment(attributes: &mut ItemAttributeValues, adjustment: Adjustment) {
|
||||
stamp_effect_on(attributes, Effect::new(&EffectOperation::Adjustment(adjustment)));
|
||||
}
|
||||
|
||||
/// A monochrome Channel Mixer graying each color by its red, green, and blue channels weighted by the `weights` in percent.
|
||||
fn channel_gray(weights: [f64; 3]) -> Adjustment {
|
||||
let row = |[red, green, blue]: [f64; 3]| ChannelMixerRow { red, green, blue, constant: 0. };
|
||||
|
||||
// The rows a monochrome mixer ignores keep the node's defaults, so they stamp nothing
|
||||
Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||
monochrome: true,
|
||||
monochrome_mix: row(weights),
|
||||
red: row([100., 0., 0.]),
|
||||
green: row([0., 100., 0.]),
|
||||
blue: row([0., 0., 100.]),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::color::Color;
|
||||
use glam::{DVec2, UVec2};
|
||||
use raster_types::{CPU, Image, Raster};
|
||||
|
||||
/// An image of `pixels` in one row, one pixel per document unit, embedded in a graphic as a wire of images embeds it.
|
||||
fn image(pixels: &[Color]) -> Item<Graphic> {
|
||||
let image = Image {
|
||||
width: pixels.len() as u32,
|
||||
height: 1,
|
||||
data: pixels.to_vec(),
|
||||
};
|
||||
let raster = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(pixels.len() as f64, 1.)));
|
||||
Item::new_from_element(Graphic::from(raster))
|
||||
}
|
||||
|
||||
/// The image a graphic holds alone.
|
||||
fn lone_image(graphic: &Item<Graphic>) -> &Item<Raster<CPU>> {
|
||||
let Graphic::RasterCPU(raster) = graphic.element() else { panic!("expected a lone image") };
|
||||
raster
|
||||
}
|
||||
|
||||
/// The graphic's rendered pixels as straight-alpha RGBA8, one pixel per document unit from its origin across a `size` view, or `None` without a GPU.
|
||||
fn rendered(graphic: &Item<Graphic>, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?;
|
||||
let list = core_types::list::List::new_from_item(graphic.clone());
|
||||
let draw = &mut |scene: &mut rendering::vello_scene_builder::VelloSceneBuilder| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
||||
let texture = executor.render_vello(size, DAffine2::IDENTITY, draw).expect("the graphic should render");
|
||||
let pixels = executor.read_texture_pixels(&texture).expect("the render should read back");
|
||||
Some(pixels.as_chunks::<4>().0.to_vec())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_grays_each_color_keeping_its_alpha_and_makes_the_alpha_opaque() {
|
||||
use raster_kernels::adjustments::adjust_color;
|
||||
|
||||
// A translucent pixel and a fully transparent one, whose hidden color its channels still gray
|
||||
let pixels = [Color::from_rgbaf32_unchecked(0.75, 0.1, 0.3, 0.6), Color::from_rgbaf32_unchecked(0.25, 0.5, 1., 0.)];
|
||||
let Channels { red, green, blue, alpha } = into_channels((), image(&pixels));
|
||||
|
||||
// Each output is the image itself, still an image, with adjustments graying each pixel to one channel's gamma-encoded level, or the alpha's
|
||||
for (channel, output) in [red, green, blue, alpha].into_iter().enumerate() {
|
||||
assert_eq!(output.attributes().iter_any().count(), 0, "the envelope stays empty");
|
||||
let raster = lone_image(&output);
|
||||
assert_eq!(raster.element().data, pixels, "the pixels are left alone");
|
||||
let effects = raster.attribute::<Effects>(ATTR_EFFECTS).cloned().unwrap_or_default();
|
||||
|
||||
for pixel in pixels {
|
||||
let gray = effects.operations().fold(pixel, |color, operation| match operation {
|
||||
EffectOperation::Adjustment(adjustment) => adjust_color(&adjustment, color),
|
||||
operation => panic!("{operation:?} isn't an adjustment"),
|
||||
});
|
||||
|
||||
// The colors keep the pixel's alpha, and the alpha is opaque
|
||||
let (level, kept_alpha) = match channel {
|
||||
3 => (pixel.a(), 1.),
|
||||
_ => (pixel.to_gamma_srgb_channels()[channel], pixel.a()),
|
||||
};
|
||||
let [r, g, b, a] = gray.to_gamma_srgb_channels();
|
||||
assert!(
|
||||
[r, g, b].iter().all(|gray| (gray - level).abs() < 1e-5) && (a - kept_alpha).abs() < 1e-6,
|
||||
"channel {channel} of {pixel:?} grays to {gray:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_color_outputs_keep_the_sources_transparency() {
|
||||
// Half transparent white, then fully transparent red, then opaque white
|
||||
let Channels { red, .. } = into_channels((), image(&[Color::WHITE.with_alpha(0.5), Color::from_rgbaf32_unchecked(1., 0., 0., 0.), Color::WHITE]));
|
||||
|
||||
let Some(pixels) = rendered(&red, UVec2::new(3, 1)) else { return };
|
||||
assert!(pixels[0][..3] == [255; 3] && pixels[0][3].abs_diff(128) <= 1, "{:?}", pixels[0]);
|
||||
assert_eq!(pixels[1][3], 0, "the transparent pixel stays transparent");
|
||||
assert_eq!(pixels[2], [255; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_adjusts_a_graphic_by_its_envelope_where_its_fill_acts_first() {
|
||||
use graphic_types::EffectKind::{AlphaToGray, MakeOpaque};
|
||||
|
||||
let kinds = |effects: Option<&Effects>| effects.map_or(Vec::new(), |effects| effects.effects().map(|effect| effect.kind()).collect::<Vec<_>>());
|
||||
|
||||
// A placement alone leaves the image within to take the effects, so a placement left at its default acts as no placement
|
||||
let placed = image(&[Color::WHITE]).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(3., 0.)));
|
||||
let Channels { alpha, .. } = into_channels((), placed);
|
||||
assert_eq!(kinds(lone_image(&alpha).attribute(ATTR_EFFECTS)), [AlphaToGray, MakeOpaque]);
|
||||
|
||||
// The envelope's fill fades the image before the effects appended to the graphic, so they go on the envelope
|
||||
let faded = image(&[Color::WHITE]).with_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||
let Channels { alpha, .. } = into_channels((), faded);
|
||||
assert_eq!(kinds(alpha.attribute(ATTR_EFFECTS)), [AlphaToGray, MakeOpaque]);
|
||||
assert!(lone_image(&alpha).attribute::<Effects>(ATTR_EFFECTS).is_none(), "the image within is left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_renders_an_images_alpha_opaque_across_its_rectangle() {
|
||||
// A half transparent pixel, which shows middle gray, then a fully transparent one, which shows black rather than nothing
|
||||
let Channels { alpha, .. } = into_channels((), image(&[Color::WHITE.with_alpha(0.5), Color::TRANSPARENT]));
|
||||
|
||||
let Some(pixels) = rendered(&alpha, UVec2::new(3, 1)) else { return };
|
||||
assert!(pixels[0][..3].iter().all(|level| level.abs_diff(128) <= 1) && pixels[0][3] == 255, "{:?}", pixels[0]);
|
||||
assert_eq!(pixels[1], [0, 0, 0, 255]);
|
||||
assert_eq!(pixels[2][3], 0, "past the image");
|
||||
}
|
||||
|
||||
/// A square image of `size` pixels filled with one straight color, placed at `x` with one pixel per document unit, embedded in a graphic as a wire of images embeds it.
|
||||
fn filled(size: u32, color: Color, x: f64) -> Item<Graphic> {
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(size as f64), 0., DVec2::new(x, 0.));
|
||||
Item::new_from_element(Graphic::from(
|
||||
Item::new_from_element(Raster::new_cpu(Image::new(size, size, color))).with_attribute(ATTR_TRANSFORM, placement),
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_channels_groups_each_input_keeping_only_its_own_channel() {
|
||||
use core_types::ATTR_OPACITY;
|
||||
use graphic_types::EffectKind::{ChannelMixer, MakeOpaque, Mask};
|
||||
|
||||
let gray = |value: f32| filled(2, Color::from_rgbaf32_unchecked(value, value, value, 1.), 0.);
|
||||
let kinds = |effects: Option<&Effects>| effects.map_or(Vec::new(), |effects| effects.effects().map(|effect| effect.kind()).collect::<Vec<_>>());
|
||||
let members = |graphic: &Item<Graphic>| match graphic.element() {
|
||||
Graphic::GraphicList(group) => group.clone(),
|
||||
element => panic!("expected a group, found {element:?}"),
|
||||
};
|
||||
|
||||
// Each input in turn, made opaque with only its own channel, its opacity left out, and those after the first added on, all masked by the alpha
|
||||
let mut red = gray(0.25);
|
||||
red.set_attribute(ATTR_OPACITY, 0.5);
|
||||
let result = from_channels((), (), red, gray(0.5), gray(0.75), gray(1.));
|
||||
let group = members(&result);
|
||||
assert_eq!(group.len(), 4);
|
||||
for (index, member) in (0..group.len()).filter_map(|index| group.clone_item(index)).enumerate() {
|
||||
let blend_mode = member.attribute_cloned_or_default::<BlendMode>(ATTR_BLEND_MODE);
|
||||
assert_eq!(blend_mode, if index == 0 { BlendMode::Normal } else { BlendMode::LinearDodge });
|
||||
assert_eq!(member.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 1.);
|
||||
let Graphic::RasterCPU(raster) = member.element() else { panic!("expected an image") };
|
||||
assert_eq!(kinds(raster.attribute(ATTR_EFFECTS)), [MakeOpaque, ChannelMixer]);
|
||||
}
|
||||
assert_eq!(kinds(result.attribute(ATTR_EFFECTS)), [Mask]);
|
||||
|
||||
// Without the alpha, the group is made opaque, and the alpha alone gives black it masks
|
||||
let opaque = from_channels((), (), gray(0.25), Item::default(), Item::default(), Item::default());
|
||||
assert_eq!((members(&opaque).len(), kinds(opaque.attribute(ATTR_EFFECTS))), (1, vec![MakeOpaque]));
|
||||
let alpha = from_channels((), (), Item::default(), Item::default(), Item::default(), gray(0.5));
|
||||
assert_eq!((members(&alpha).len(), kinds(alpha.attribute(ATTR_EFFECTS))), (1, vec![Mask]));
|
||||
assert!(from_channels((), (), Item::default(), Item::default(), Item::default(), Item::default()).element().draws_nothing());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_and_back_from_channels_reproduces_the_image_with_its_partial_alpha() {
|
||||
// Colors across each channel, with every third pixel half transparent
|
||||
let data = (0..64)
|
||||
.map(|index| {
|
||||
let (x, y) = ((index % 8) as f32, (index / 8) as f32);
|
||||
let alpha = if index % 3 == 0 { 0.5 } else { 1. };
|
||||
Color::from_gamma_srgb_channels(x / 7., y / 7., (x + y) / 14., alpha)
|
||||
})
|
||||
.collect();
|
||||
let raster = Item::new_from_element(Raster::new_cpu(Image { width: 8, height: 8, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.)));
|
||||
let image = Item::new_from_element(Graphic::from(raster));
|
||||
|
||||
let Channels { red, green, blue, alpha } = into_channels((), image.clone());
|
||||
let recombined = from_channels((), (), red, green, blue, alpha);
|
||||
|
||||
let size = UVec2::splat(8);
|
||||
let (Some(original), Some(recombined)) = (rendered(&image, size), rendered(&recombined, size)) else {
|
||||
return;
|
||||
};
|
||||
for (index, (original, recombined)) in original.iter().zip(&recombined).enumerate() {
|
||||
let stray = original.iter().zip(recombined).map(|(original, recombined)| original.abs_diff(*recombined)).max().unwrap_or_default();
|
||||
assert!(stray <= 2, "pixel {index} renders as {recombined:?} rather than {original:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_channels_lines_up_its_inputs_where_they_lie_in_the_document() {
|
||||
// Red and green overlap by half, and a half gray alpha starts a pixel in from the red
|
||||
let half_gray = Color::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.);
|
||||
let result = from_channels((), (), filled(4, Color::WHITE, 0.), filled(4, Color::WHITE, 2.), Item::default(), filled(4, half_gray, 1.));
|
||||
|
||||
let size = UVec2::new(8, 4);
|
||||
let Some(pixels) = rendered(&result, size) else { return };
|
||||
let at = |x: u32| pixels[(size.x + x) as usize];
|
||||
let half_shown = |[red, green, blue, alpha]: [u8; 4], expected: [u8; 3]| [red, green, blue] == expected && alpha.abs_diff(128) <= 1;
|
||||
assert_eq!(at(0)[3], 0, "outside the alpha");
|
||||
assert!(half_shown(at(1), [255, 0, 0]), "red alone, half shown: {:?}", at(1));
|
||||
assert!(half_shown(at(3), [255, 255, 0]), "red and green: {:?}", at(3));
|
||||
assert_eq!(at(5)[3], 0, "outside the alpha");
|
||||
}
|
||||
|
||||
/// Red over the left four of a 12 by 4 render and green over the right four, past the red's rectangle, without an alpha.
|
||||
fn red_and_green_apart() -> Item<Graphic> {
|
||||
from_channels((), (), filled(4, Color::WHITE, 0.), filled(4, Color::WHITE, 8.), Item::default(), Item::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_channels_covers_a_green_input_shifted_past_the_red() {
|
||||
// Over a gray beneath, which the channels don't add onto
|
||||
let beneath = filled(12, Color::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.), 0.);
|
||||
let group: List<Graphic> = [beneath, red_and_green_apart()].into_iter().collect();
|
||||
|
||||
let size = UVec2::new(12, 4);
|
||||
let Some(pixels) = rendered(&Item::new_from_element(Graphic::GraphicList(group)), size) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(pixels[(size.x + 1) as usize], [255, 0, 0, 255]);
|
||||
assert_eq!(pixels[(size.x + 10) as usize], [0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_channels_leaves_what_no_input_covers_transparent() {
|
||||
let size = UVec2::new(12, 4);
|
||||
let Some(pixels) = rendered(&red_and_green_apart(), size) else { return };
|
||||
assert_eq!(pixels[(size.x + 1) as usize], [255, 0, 0, 255]);
|
||||
assert_eq!(pixels[(size.x + 6) as usize][3], 0, "between the inputs");
|
||||
}
|
||||
}
|
||||
@@ -1,95 +1,27 @@
|
||||
use core_types::color::Color;
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::Item;
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
use raster_types::Bitmap;
|
||||
use raster_types::Image;
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{CPU, Raster};
|
||||
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies a median filter to reduce noise while preserving edges.
|
||||
#[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"), memoize)]
|
||||
fn median_filter(
|
||||
/// Applies a median filter to reduce noise while preserving edges, giving each pixel the middle value of each channel among the pixels in a square around it.
|
||||
///
|
||||
/// It works on an image's own pixels, or the document's pixels for other graphics, so it looks the same at any zoom.
|
||||
#[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"), version(2))]
|
||||
fn median_filter<T>(
|
||||
_: impl Ctx,
|
||||
/// The image to be filtered.
|
||||
image_frame: Item<Raster<CPU>>,
|
||||
/// The radius of the filter kernel. Larger values remove more noise but may blur fine details.
|
||||
/// The content to be filtered.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// How far the square around each pixel reaches, in whole pixels. Larger values remove more noise but may blur fine details.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..50)]
|
||||
radius: Item<f64>,
|
||||
) -> Item<Raster<CPU>> {
|
||||
let radius = *radius.element();
|
||||
|
||||
let (image, attributes) = evaluate_raster_effects(image_frame).into_parts();
|
||||
|
||||
// TODO: Scale the radius through the footprint so it acts as the document-space length its Pixels unit promises, with a
|
||||
// window that varies continuously rather than snapping to whole source pixels
|
||||
let filtered_image = if radius < 0.5 {
|
||||
// Minimum filter radius
|
||||
image
|
||||
} else {
|
||||
Raster::new_cpu(median_filter_algorithm(image.into_data(), radius as u32))
|
||||
};
|
||||
|
||||
Item::from_parts(filtered_image, attributes)
|
||||
}
|
||||
|
||||
fn median_filter_algorithm(original_buffer: Image<Color>, radius: u32) -> Image<Color> {
|
||||
let (width, height) = original_buffer.dimensions();
|
||||
let mut output = Image::new(width, height, Color::TRANSPARENT);
|
||||
|
||||
let window_span = |extent: u32| (radius as usize).saturating_mul(2).saturating_add(1).min(extent as usize);
|
||||
let window_capacity = window_span(width) * window_span(height);
|
||||
|
||||
fill_rows(&mut output.data, width as usize, |y, row| {
|
||||
let y = y as u32;
|
||||
|
||||
// Allocated once for the row and reused for each of its pixels
|
||||
let mut r_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut g_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut b_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut a_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
|
||||
for (x, output_pixel) in row.iter_mut().enumerate() {
|
||||
let x = x as u32;
|
||||
r_vals.clear();
|
||||
g_vals.clear();
|
||||
b_vals.clear();
|
||||
a_vals.clear();
|
||||
|
||||
// Use saturating_add to avoid potential overflow in extreme cases
|
||||
let y_max = y.saturating_add(radius).min(height - 1);
|
||||
let x_max = x.saturating_add(radius).min(width - 1);
|
||||
|
||||
for ny in y.saturating_sub(radius)..=y_max {
|
||||
for nx in x.saturating_sub(radius)..=x_max {
|
||||
if let Some(px) = original_buffer.get_pixel(nx, ny) {
|
||||
r_vals.push(px.r());
|
||||
g_vals.push(px.g());
|
||||
b_vals.push(px.b());
|
||||
a_vals.push(px.a());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let r = median_quickselect(&mut r_vals);
|
||||
let g = median_quickselect(&mut g_vals);
|
||||
let b = median_quickselect(&mut b_vals);
|
||||
let a = median_quickselect(&mut a_vals);
|
||||
|
||||
*output_pixel = Color::from_rgbaf32_unchecked(r, g, b, a);
|
||||
}
|
||||
});
|
||||
|
||||
output
|
||||
}
|
||||
/// Finds the median of a slice using quickselect for O(n) average case performance.
|
||||
/// This is more efficient than sorting the entire slice which would be O(n log n).
|
||||
fn median_quickselect(values: &mut [f32]) -> f32 {
|
||||
let mid: usize = values.len() / 2;
|
||||
// nth_unstable is like quickselect: average O(n)
|
||||
// Use total_cmp for safe NaN handling instead of partial_cmp().unwrap()
|
||||
*values.select_nth_unstable_by(mid, |a, b| a.total_cmp(b)).1
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(&mut content, Effect::new(&EffectOperation::Median { radius: *radius.element() }));
|
||||
content
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod adjustments;
|
||||
pub mod blending_nodes;
|
||||
pub mod channels;
|
||||
pub use raster_kernels::color_lookup_table;
|
||||
pub mod dehaze;
|
||||
pub mod filter;
|
||||
|
||||
@@ -1,17 +1,10 @@
|
||||
use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::color::Color;
|
||||
use core_types::color::{AlphaMut, LinearChannel, Luminance, RGBMut};
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::Item;
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::transform::Transform;
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use glam::DVec2;
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::generator::{Generator, MandelbrotSettings, NoiseSettings};
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
use raster_types::{Bitmap, BitmapMut};
|
||||
use raster_types::{CPU, Raster};
|
||||
use raster_types::{Image, ImageError};
|
||||
use std::fmt::Debug;
|
||||
@@ -29,156 +22,6 @@ impl From<std::io::Error> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two rasters that must line up pixel for pixel but differ in size.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("{first} and {second} must be the same size, but {first} is {}×{} pixels and {second} is {}×{}", .first_size.x, .first_size.y, .second_size.x, .second_size.y)]
|
||||
pub struct SizeMismatchError {
|
||||
pub first: &'static str,
|
||||
pub first_size: UVec2,
|
||||
pub second: &'static str,
|
||||
pub second_size: UVec2,
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), name("Channels to Image"), memoize)]
|
||||
fn channels_to_image(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[expose] red: Item<Raster<CPU>>,
|
||||
#[expose] green: Item<Raster<CPU>>,
|
||||
#[expose] blue: Item<Raster<CPU>>,
|
||||
#[expose] alpha: Item<Raster<CPU>>,
|
||||
) -> Result<Item<Raster<CPU>>, SizeMismatchError> {
|
||||
// An unconnected channel arrives as the default zero-sized raster, which counts as absent
|
||||
let present = |channel: Item<Raster<CPU>>| (channel.element().width > 0 && channel.element().height > 0).then_some(channel);
|
||||
let channels = [red, green, blue, alpha].map(present);
|
||||
|
||||
// All present channels must share the same dimensions
|
||||
let dimensions = |channel: &Item<Raster<CPU>>| UVec2::new(channel.element().width, channel.element().height);
|
||||
let mut present_channels = ["Red", "Green", "Blue", "Alpha"]
|
||||
.into_iter()
|
||||
.zip(&channels)
|
||||
.filter_map(|(name, channel)| Some((name, channel.as_ref()?)));
|
||||
let Some((first, first_channel)) = present_channels.next() else {
|
||||
return Ok(Item::default());
|
||||
};
|
||||
let (first_size, transform) = (dimensions(first_channel), first_channel.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM));
|
||||
if let Some((second, second_channel)) = present_channels.find(|(_, channel)| dimensions(channel) != first_size) {
|
||||
return Err(SizeMismatchError {
|
||||
first,
|
||||
first_size,
|
||||
second,
|
||||
second_size: dimensions(second_channel),
|
||||
});
|
||||
}
|
||||
let (width, height) = (first_size.x, first_size.y);
|
||||
|
||||
// A channel's effects grow it by the margin they cast past its edges, so every channel is placed within the widest margin
|
||||
let channels = channels.map(|channel| channel.map(evaluate_raster_effects));
|
||||
let margin = |channel: &Item<Raster<CPU>>| ((channel.element().width - width) / 2, (channel.element().height - height) / 2);
|
||||
let (margin_x, margin_y) = channels
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(margin)
|
||||
.fold((0, 0), |(x, y), (channel_x, channel_y)| (x.max(channel_x), y.max(channel_y)));
|
||||
|
||||
// Take this item's blending attributes from the first present channel, whose effects are carried out by now
|
||||
let Some(mut attributes) = channels.iter().flatten().next().map(|channel| channel.attributes().clone()) else {
|
||||
return Ok(Item::default());
|
||||
};
|
||||
let size = DVec2::new(width as f64, height as f64);
|
||||
let unit_margin = DVec2::new(margin_x as f64, margin_y as f64) / size;
|
||||
attributes.insert(
|
||||
ATTR_TRANSFORM,
|
||||
transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin),
|
||||
);
|
||||
|
||||
// A channel's value at a pixel of the output, with nothing past its own edges, or `None` if the channel is absent
|
||||
let value = |channel: &Option<Item<Raster<CPU>>>, x: u32, y: u32| {
|
||||
channel.as_ref().map(|channel| {
|
||||
let (channel_margin_x, channel_margin_y) = margin(channel);
|
||||
let (x, y) = ((x + channel_margin_x).checked_sub(margin_x), (y + channel_margin_y).checked_sub(margin_y));
|
||||
x.zip(y).and_then(|(x, y)| channel.element().get_pixel(x, y)).map_or(0., |pixel| pixel.l().cast_linear_channel())
|
||||
})
|
||||
};
|
||||
|
||||
// Set each output pixel's channels from the present inputs, defaulting absent color channels to 0 and absent alpha to 1
|
||||
let [red, green, blue, alpha] = &channels;
|
||||
let mut image = Image::new(width + 2 * margin_x, height + 2 * margin_y, Color::TRANSPARENT);
|
||||
for y in 0..image.height() {
|
||||
for x in 0..image.width() {
|
||||
let image_pixel = image.get_pixel_mut(x, y).unwrap();
|
||||
|
||||
image_pixel.set_red(value(red, x, y).unwrap_or(0.));
|
||||
image_pixel.set_green(value(green, x, y).unwrap_or(0.));
|
||||
image_pixel.set_blue(value(blue, x, y).unwrap_or(0.));
|
||||
image_pixel.set_alpha(value(alpha, x, y).unwrap_or(1.));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Item::from_parts(Raster::new_cpu(image), attributes))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn extend_image_to_bounds(_: impl Ctx, image: Item<Raster<CPU>>, bounds: Item<DAffine2>) -> Result<Item<Raster<CPU>>, (Item<Raster<CPU>>, ImageError)> {
|
||||
let image = evaluate_raster_effects(image);
|
||||
let bounds = *bounds.element();
|
||||
|
||||
let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let image_aabb = Bbox::unit().affine_transform(image_transform).to_axis_aligned_bbox();
|
||||
let bounds_aabb = Bbox::unit().affine_transform(bounds.transform()).to_axis_aligned_bbox();
|
||||
if image_aabb.contains(bounds_aabb.start) && image_aabb.contains(bounds_aabb.end) {
|
||||
return Ok(image);
|
||||
}
|
||||
|
||||
let (image_width, image_height) = (image.element().width, image.element().height);
|
||||
if image_width == 0 || image_height == 0 {
|
||||
return empty_image(bounds, Color::TRANSPARENT).map_err(|error| (image, error));
|
||||
}
|
||||
if image_transform.matrix2.determinant() == 0. {
|
||||
return Ok(image);
|
||||
}
|
||||
|
||||
let orig_image_scale = DVec2::new(image_width as f64, image_height as f64);
|
||||
let layer_to_image_space = DAffine2::from_scale(orig_image_scale) * image_transform.inverse();
|
||||
let bounds_in_image_space = Bbox::unit().affine_transform(layer_to_image_space * bounds).to_axis_aligned_bbox();
|
||||
|
||||
let new_start = bounds_in_image_space.start.floor().min(DVec2::ZERO);
|
||||
let new_end = bounds_in_image_space.end.ceil().max(orig_image_scale);
|
||||
let new_scale = new_end - new_start;
|
||||
|
||||
// Copy over original image into enlarged image.
|
||||
let mut new_image = match Image::try_new(new_scale.x as u32, new_scale.y as u32, Color::TRANSPARENT) {
|
||||
Ok(new_image) => new_image,
|
||||
Err(error) => return Err((image, error)),
|
||||
};
|
||||
let (image, mut attributes) = image.into_parts();
|
||||
let offset_in_new_image = (-new_start).as_uvec2();
|
||||
for y in 0..image_height {
|
||||
let old_start = y * image_width;
|
||||
let new_start = (y + offset_in_new_image.y) * new_image.width + offset_in_new_image.x;
|
||||
let old_row = &image.data[old_start as usize..(old_start + image_width) as usize];
|
||||
let new_row = &mut new_image.data[new_start as usize..(new_start + image_width) as usize];
|
||||
new_row.copy_from_slice(old_row);
|
||||
}
|
||||
|
||||
// Compute new transform.
|
||||
// let layer_to_new_texture_space = (DAffine2::from_scale(1. / new_scale) * DAffine2::from_translation(new_start) * layer_to_image_space).inverse();
|
||||
let new_texture_to_layer_space = image_transform * DAffine2::from_scale(1. / orig_image_scale) * DAffine2::from_translation(new_start) * DAffine2::from_scale(new_scale);
|
||||
|
||||
attributes.insert(ATTR_TRANSFORM, new_texture_to_layer_space);
|
||||
Ok(Item::from_parts(Raster::new_cpu(new_image), attributes))
|
||||
}
|
||||
|
||||
/// Creates an image filled with one color, sized in pixels by the transform's scale and placed by the transform.
|
||||
fn empty_image(transform: DAffine2, color: Color) -> Result<Item<Raster<CPU>>, ImageError> {
|
||||
let width = transform.transform_vector2(DVec2::new(1., 0.)).length() as u32;
|
||||
let height = transform.transform_vector2(DVec2::new(0., 1.)).length() as u32;
|
||||
|
||||
let image = Image::try_new(width, height, color)?;
|
||||
|
||||
Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform))
|
||||
}
|
||||
|
||||
/// Displays an image from a file.
|
||||
///
|
||||
/// Reads PNG, JPG, GIF, WEBP, TIFF, BMP, TGA, ICO, HDR, and EXR files. Light brighter than white, as HDR and EXR files can hold, is clipped to white.
|
||||
@@ -318,40 +161,3 @@ fn mandelbrot(
|
||||
settings.stamp(&mut generator);
|
||||
generator
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channels_stay_aligned_when_effects_grow_only_one() {
|
||||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||||
|
||||
let gray = |value: f32| {
|
||||
let image = Image::new(8, 8, Color::from_rgbaf32_unchecked(value, value, value, 1.));
|
||||
Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.)))
|
||||
};
|
||||
|
||||
// Only the red channel is blurred, which grows it by the blur's margin
|
||||
let mut red = gray(1.);
|
||||
stamp_effect(
|
||||
&mut red,
|
||||
Effect::new(&EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 1.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
}),
|
||||
);
|
||||
let image = channels_to_image((), (), red, gray(0.5), gray(0.25), gray(1.)).unwrap();
|
||||
|
||||
// The other channels are placed within the same margin, and the whole image keeps its place in the document
|
||||
let raster = image.element();
|
||||
assert!(raster.width > 8 && raster.height > 8, "the image grows to hold the blur, rather than coming out empty");
|
||||
let transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * transform.inverse();
|
||||
let center = to_pixels.transform_point2(DVec2::splat(4.)).as_uvec2();
|
||||
let pixel = raster.get_pixel(center.x, center.y).unwrap();
|
||||
assert!((pixel.g() - 0.5).abs() < 1e-6 && (pixel.b() - 0.25).abs() < 1e-6, "the unblurred channels line up: {pixel:?}");
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,8 @@ use core_types::math::spread::spread_factors;
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{
|
||||
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE,
|
||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx, ExtractAll, InjectFootprint, OwnedContextImpl,
|
||||
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL,
|
||||
ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx, ExtractAll, InjectFootprint, OwnedContextImpl,
|
||||
};
|
||||
use core_types::{Interrupt, NodeError};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
@@ -24,7 +24,7 @@ use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArcle
|
||||
use rand::{RngExt, SeedableRng};
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use vector_types::gradient::{GradientDirection, GradientModel, build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box};
|
||||
use vector_types::gradient::{build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box};
|
||||
use vector_types::vector::SetVectorPaths;
|
||||
use vector_types::vector::algorithms::bezpath_algorithms::{
|
||||
self, PoissonDiskError, PoissonDiskSampler, SampleCountError, TValue, bezpath_area_centroid_and_area, bezpath_length_centroid_and_length, eval_pathseg_euclidean, evaluate_bezpath, split_bezpath,
|
||||
@@ -408,7 +408,7 @@ fn vary_cover_colors<T: VectorListIterMut>(
|
||||
}
|
||||
|
||||
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
|
||||
#[node_macro::node(category("Vector: Style"), icon("NodeFill"), path(graphene_core::vector), inspector("fill_inspector"), version(3))]
|
||||
#[node_macro::node(category("Vector: Style"), icon("NodeFill"), path(graphene_core::vector), inspector("fill_inspector"), version(2))]
|
||||
fn fill<V>(
|
||||
_: impl Ctx,
|
||||
/// The content with vector paths to apply the fill style to.
|
||||
@@ -421,22 +421,19 @@ fn fill<V>(
|
||||
_end_curvature: Item<f64>,
|
||||
_has_transform: Item<bool>,
|
||||
_transform: Item<DAffine2>,
|
||||
_model: Item<GradientModel>,
|
||||
_direction: Item<GradientDirection>,
|
||||
) -> Item<V>
|
||||
where
|
||||
Item<V>: VectorItemMut + Send,
|
||||
{
|
||||
let (_start_curvature, _end_curvature) = (_start_curvature.into_element(), _end_curvature.into_element());
|
||||
let (_has_transform, _transform) = (_has_transform.into_element(), *_transform.element());
|
||||
let (_model, _direction) = (_model.into_element(), _direction.into_element());
|
||||
|
||||
let mut content = content;
|
||||
// Keeping the wire envelope's attributes would nest the paint as a group, changing how it renders, so only its effects carry over
|
||||
let mut paint = paint_with_envelope_effects(paint);
|
||||
|
||||
// Stamp the gradient styling inputs onto any gradient paint missing them, whether the paint arrived as a picker value or a wire
|
||||
// TODO: Stop reading whether the gradient has curvatures, a model, a direction, or a transform, since an absent attribute should mean the same as its default.
|
||||
// TODO: Stop reading whether the gradient has curvatures or a transform, since an absent attribute should mean the same as its default.
|
||||
// These reads tell a gradient picked in a widget, which needs styling and placing, from a wired one carrying its own, until paint inputs can tell those apart by type.
|
||||
let (needs_curvatures, needs_transform) = match &paint {
|
||||
Graphic::Gradient(item) => (
|
||||
@@ -449,18 +446,6 @@ where
|
||||
),
|
||||
_ => (false, false),
|
||||
};
|
||||
// The model and direction are stamped only when they differ from the default an absent attribute already reads as
|
||||
let (needs_model, needs_direction) = match &paint {
|
||||
Graphic::Gradient(item) => (
|
||||
_model != GradientModel::default() && item.attribute::<GradientModel>(ATTR_GRADIENT_MODEL).is_none(),
|
||||
_direction != GradientDirection::default() && item.attribute::<GradientDirection>(ATTR_GRADIENT_DIRECTION).is_none(),
|
||||
),
|
||||
Graphic::GradientList(list) => (
|
||||
_model != GradientModel::default() && list.iter_attribute_values::<GradientModel>(ATTR_GRADIENT_MODEL).is_none(),
|
||||
_direction != GradientDirection::default() && list.iter_attribute_values::<GradientDirection>(ATTR_GRADIENT_DIRECTION).is_none(),
|
||||
),
|
||||
_ => (false, false),
|
||||
};
|
||||
|
||||
let stamped_transform = needs_transform.then(|| {
|
||||
// Without an explicit placement, derive one covering the paint target's bounding box (the CSS `auto` behavior)
|
||||
@@ -498,12 +483,6 @@ where
|
||||
if let Some(transform) = stamped_transform {
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
}
|
||||
if needs_model {
|
||||
item.set_attribute(ATTR_GRADIENT_MODEL, _model);
|
||||
}
|
||||
if needs_direction {
|
||||
item.set_attribute(ATTR_GRADIENT_DIRECTION, _direction);
|
||||
}
|
||||
}
|
||||
Graphic::GradientList(list) => {
|
||||
if needs_curvatures {
|
||||
@@ -518,13 +497,6 @@ where
|
||||
*value = transform;
|
||||
}
|
||||
}
|
||||
if needs_model {
|
||||
list.iter_attribute_values_mut_or_default::<GradientModel>(ATTR_GRADIENT_MODEL).for_each(|value| *value = _model);
|
||||
}
|
||||
if needs_direction {
|
||||
list.iter_attribute_values_mut_or_default::<GradientDirection>(ATTR_GRADIENT_DIRECTION)
|
||||
.for_each(|value| *value = _direction);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -4972,51 +4944,6 @@ mod test {
|
||||
assert!(appearance.has_painted_cover(Cover::Fill), "the fill of a rank-0 vector should be styled like a list element");
|
||||
}
|
||||
|
||||
// Fill gives a gradient it paints its model and direction where the gradient lacks them, unless they're the defaults an absent one reads as
|
||||
#[test]
|
||||
fn fill_stamps_a_gradients_model_and_direction_only_where_missing() {
|
||||
let filled = |gradient: Item<Gradient>, model: GradientModel, direction: GradientDirection| {
|
||||
let square = create_vector_item(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY), DAffine2::IDENTITY);
|
||||
let filled = super::fill(
|
||||
Footprint::default(),
|
||||
square,
|
||||
item(Graphic::Gradient(gradient)),
|
||||
item(Color::BLACK),
|
||||
item(Gradient::default()),
|
||||
item(0.),
|
||||
item(0.),
|
||||
item(false),
|
||||
item(DAffine2::IDENTITY),
|
||||
item(model),
|
||||
item(direction),
|
||||
);
|
||||
let appearance = filled.attribute::<Appearance>(ATTR_APPEARANCE).expect("the fill should give the square an appearance");
|
||||
let Some(Graphic::Gradient(gradient)) = appearance.first_paint_of(Cover::Fill) else {
|
||||
panic!("the fill should paint the gradient")
|
||||
};
|
||||
(
|
||||
gradient.attribute::<GradientModel>(ATTR_GRADIENT_MODEL).copied(),
|
||||
gradient.attribute::<GradientDirection>(ATTR_GRADIENT_DIRECTION).copied(),
|
||||
)
|
||||
};
|
||||
let plain = item(Gradient::from(vec![Color::BLACK, Color::WHITE]));
|
||||
|
||||
assert_eq!(filled(plain.clone(), GradientModel::Standard, GradientDirection::Along), (None, None));
|
||||
assert_eq!(
|
||||
filled(plain.clone(), GradientModel::Apollonian, GradientDirection::Across),
|
||||
(Some(GradientModel::Apollonian), Some(GradientDirection::Across))
|
||||
);
|
||||
|
||||
// A gradient's own model and direction stay, even at their defaults
|
||||
let own = plain
|
||||
.with_attribute(ATTR_GRADIENT_MODEL, GradientModel::Standard)
|
||||
.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Along);
|
||||
assert_eq!(
|
||||
filled(own, GradientModel::Apollonian, GradientDirection::Across),
|
||||
(Some(GradientModel::Standard), Some(GradientDirection::Along))
|
||||
);
|
||||
}
|
||||
|
||||
// Fill's automatic gradient placement measures rank-0 vector content instead of falling back to the unit box
|
||||
#[test]
|
||||
fn vector_item_mut_reaches_a_rank_0_vector_graphic() {
|
||||
|
||||
Reference in new issue
Block a user