diff --git a/document/migrations/nodes/src/blending_nodes/mod.rs b/document/migrations/nodes/src/blending_nodes/mod.rs index 627125cfcb..7b2a605a3b 100644 --- a/document/migrations/nodes/src/blending_nodes/mod.rs +++ b/document/migrations/nodes/src/blending_nodes/mod.rs @@ -14,5 +14,6 @@ mod outline_v2; mod outline_v3; mod paint_overlay_from_color_overlay; mod paint_overlay_v2; +mod radial_blur_v1; mod renames; mod satin_v1; diff --git a/document/migrations/nodes/src/blending_nodes/radial_blur_v1.rs b/document/migrations/nodes/src/blending_nodes/radial_blur_v1.rs new file mode 100644 index 0000000000..dee0d8ced1 --- /dev/null +++ b/document/migrations/nodes/src/blending_nodes/radial_blur_v1.rs @@ -0,0 +1,92 @@ +use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration}; +use serde::{Deserialize, Serialize}; + +const CENTER: u32 = 3; + +/// Frozen mirror of the `TaggedValue` variants this migration reads and writes. +#[derive(Serialize, Deserialize)] +enum Tagged { + DVec2([f64; 2]), + DAffine2([f64; 6]), +} + +/// 'Radial Blur' takes a transform placing a circle in place of its center, which the transform's translation keeps. +/// A wired center can't be read before it runs, so it becomes the identity, the circle at the content's origin. +#[migration("blending_nodes::distortions::RadialBlurNode"@1 => @2)] +pub fn radial_blur_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> { + let Some(center) = node.inputs().get(CENTER as usize) else { + return Err(MigrationError::invariant("Radial Blur has a Center input")); + }; + + inputs.set(CENTER, transform_input(¢er.input)); + Ok(()) +} + +/// The transform input placing the circle at the old `center`, shown in the graph if it was exposed or wired. +fn transform_input(center: &NodeInput) -> NodeInput { + let ([x, y], exposed) = match center { + NodeInput::Value { exposed, .. } => match literal_of::(center) { + Some(Tagged::DVec2(center)) => (center, *exposed), + _ => ([0., 0.], *exposed), + }, + _ => ([0., 0.], true), + }; + + NodeInput::Value { + value: encode(&Tagged::DAffine2([1., 0., 0., 1., x, y])), + exposed, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use migration_core::{decl, literal}; + use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo}; + + const CENTER_SLOT: usize = CENTER as usize; + + fn contract() -> SourceContract { + SourceContract::new(5, |random, slot| match slot { + CENTER_SLOT => literal(Tagged::DVec2([random.below(10) as f64, random.below(10) as f64])), + _ => literal(random.below(10) as f64), + }) + } + + fn radial_blur_inputs(center: NodeInput) -> Vec { + let mut inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect(); + inputs[CENTER_SLOT] = center; + inputs + } + + #[test] + fn rewrites_history() { + check_commutation(&RadialBlurV1, &contract()); + check_undo(&RadialBlurV1, &contract()); + } + + #[test] + fn the_center_becomes_the_translation_of_the_transform_in_its_place() { + let mut fixture = Fixture::new(&RadialBlurV1); + let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(literal(Tagged::DVec2([12.5, -4.])))); + let migrated = fixture.migrate(&RadialBlurV1).unwrap(); + + let expected = radial_blur_inputs(literal(Tagged::DAffine2([1., 0., 0., 1., 12.5, -4.]))); + assert_eq!(fixture.declaration_of(&migrated, radial_blur), Some(decl!("blending_nodes::distortions::RadialBlurNode"@2))); + assert_eq!(fixture.inputs(&migrated, radial_blur), expected); + } + + #[test] + fn a_wired_center_becomes_the_identity_shown_in_the_graph() { + let mut fixture = Fixture::new(&RadialBlurV1); + let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new()); + let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(NodeInput::Node { id: source, index: 0 })); + let migrated = fixture.migrate(&RadialBlurV1).unwrap(); + + let identity = NodeInput::Value { + value: encode(&Tagged::DAffine2([1., 0., 0., 1., 0., 0.])), + exposed: true, + }; + assert_eq!(fixture.inputs(&migrated, radial_blur), radial_blur_inputs(identity)); + } +} diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index af462eb669..c3e8cfe193 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -394,7 +394,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, false => text_widget(default_info).into(), }, Some(x) if id_is::(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false), - Some(x) if id_is::(x) => transform_widget(default_info, &mut extra_widgets), + Some(x) if id_is::(x) => transform_widget(default_info, unit, &mut extra_widgets), Some(x) if id_is::(x) => color_widget(default_info, ColorInput::default().allow_none(false)), Some(x) if id_is::(x) => color_widget(default_info, ColorInput::default().allow_none(false)), Some(x) if id_is::(x) => color_widget(default_info, ColorInput::default()), @@ -790,8 +790,10 @@ pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg last.clone() } -pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec) -> LayoutGroup { +/// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size. +pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec) -> LayoutGroup { let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info; + let size_unit = size_unit.unwrap_or("x"); let mut location_widgets = start_widgets(¶meter_widgets_info); location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance()); @@ -858,7 +860,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg scale_widgets.extend_from_slice(&[ NumberInput::new(Some(scale.x)) .label("W") - .unit("x") + .unit(size_unit) .on_update(update_value_at_index( move |w: &NumberInput| { let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix; @@ -872,7 +874,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg Separator::new(SeparatorStyle::Related).widget_instance(), NumberInput::new(Some(scale.y)) .label("H") - .unit("x") + .unit(size_unit) .on_update(update_value_at_index( move |h: &NumberInput| { let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix; diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index ed281160d8..e13d39939d 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -682,18 +682,24 @@ impl TaggedValue { None } - // The Inspector's X, Y, W, H (e.g. "0., 0., 1000., 1000."), rendered at 100% resolution - fn to_footprint(input: &str) -> Option { + // The Inspector's X, Y, W, H (e.g. "0., 0., 1000., 1000."), as a transform's translation and scale + fn to_daffine2(input: &str) -> Option { let values: Option> = input.split(',').map(to_number).collect(); let Some(&[x, y, width, height]) = values.as_deref() else { - log::error!("Invalid Footprint default, which needs X, Y, W, H: {input}"); + log::error!("Invalid default, which needs X, Y, W, H: {input}"); return None; }; - let size = DVec2::new(width, height); + + Some(DAffine2::from_scale_angle_translation(DVec2::new(width, height), 0., DVec2::new(x, y))) + } + + // The Inspector's X, Y, W, H, rendered at 100% resolution + fn to_footprint(input: &str) -> Option { + let transform = to_daffine2(input)?; Some(Footprint { - transform: DAffine2::from_scale_angle_translation(size, 0., DVec2::new(x, y)), - resolution: size.as_uvec2(), + transform, + resolution: transform.matrix2.diagonal().as_uvec2(), ..Default::default() }) } @@ -750,6 +756,7 @@ impl TaggedValue { () if ty == TypeId::of::() => to_number(string).map(TaggedValue::Number)?, () if ty == TypeId::of::() => to_number(string).map(TaggedValue::Integer)?, () if ty == TypeId::of::() => to_dvec2(string).map(TaggedValue::DVec2)?, + () if ty == TypeId::of::() => to_daffine2(string).map(TaggedValue::DAffine2)?, () if ty == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?, () if ty == TypeId::of::() => to_color(string).map(TaggedValue::Color)?, // The Fill/Stroke paint wires carry `Graphic` or `Gradient` elements, so a paint default parses through the element recursion as a color or gradient literal @@ -1124,6 +1131,13 @@ mod number_default_parsing { ); assert_eq!(TaggedValue::from_primitive_string("1., 2., 3.", &item!(Footprint)), None); } + + #[test] + fn transform_defaults_parse_as_x_y_width_height() { + let expected = DAffine2::from_scale_angle_translation(DVec2::new(500., 400.), 0., DVec2::new(250., -20.)); + assert_eq!(TaggedValue::from_primitive_string("250., - 20., 500., 400.", &item!(DAffine2)), Some(TaggedValue::DAffine2(expected))); + assert_eq!(TaggedValue::from_primitive_string("1., 2.", &item!(DAffine2)), None); + } } #[cfg(test)] diff --git a/node-graph/libraries/graphic-types/src/effect_layers.rs b/node-graph/libraries/graphic-types/src/effect_layers.rs index 43d9637c90..b56e36094f 100644 --- a/node-graph/libraries/graphic-types/src/effect_layers.rs +++ b/node-graph/libraries/graphic-types/src/effect_layers.rs @@ -282,7 +282,15 @@ pub fn is_pixel_filter(operation: &EffectOperation) -> bool { match operation { // TODO: Make a mask between other effects fade each layer drawn before it too, as the trailing masks do, rather than flattening those layers. // TODO: Likewise for a trailing feather, faded by the footprint of every layer drawn together (not the content's alone, which would erase shadows past it). - EffectOperation::Blur { .. } | EffectOperation::MotionBlur { .. } | EffectOperation::RadialBlur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } => true, + EffectOperation::Blur { .. } + | EffectOperation::MotionBlur { .. } + | EffectOperation::RadialBlur { .. } + | EffectOperation::Twirl { .. } + | EffectOperation::Pinch { .. } + | EffectOperation::Spherize { .. } + | EffectOperation::PolarCoordinates { .. } + | EffectOperation::Mask { .. } + | EffectOperation::Feather { .. } => true, operation if crate::filters::is_filter(operation) => true, EffectOperation::Adjustment(adjustment) => !matches!(adjustment, Adjustment::ColorOverlay { .. }), _ => false, @@ -382,6 +390,10 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM EffectOperation::Blur { .. } | EffectOperation::MotionBlur { .. } | EffectOperation::RadialBlur { .. } + | EffectOperation::Twirl { .. } + | EffectOperation::Pinch { .. } + | EffectOperation::Spherize { .. } + | EffectOperation::PolarCoordinates { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } | EffectOperation::ConvolutionKernel { .. } diff --git a/node-graph/libraries/graphic-types/src/effects.rs b/node-graph/libraries/graphic-types/src/effects.rs index 54026e013c..7b57222f97 100644 --- a/node-graph/libraries/graphic-types/src/effects.rs +++ b/node-graph/libraries/graphic-types/src/effects.rs @@ -70,6 +70,14 @@ pub enum EffectKind { MotionBlur, /// Smears the content around a center or toward it. RadialBlur, + /// Turns the content within a circle, the most at its center. + Twirl, + /// Squeezes the content toward the center of a circle, or pushes it out. + Pinch, + /// Bulges the content out from the center of a circle as if wrapped around a ball, or sinks it. + Spherize, + /// Wraps the content within a square around its center, or unwraps it. + PolarCoordinates, // The adjustments, which change each color of the content on its own, as their nodes of the same names do Desaturate, GammaCorrection, @@ -117,6 +125,10 @@ impl std::fmt::Display for EffectKind { Self::Dissolve => "Dissolve", Self::MotionBlur => "Motion Blur", Self::RadialBlur => "Radial Blur", + Self::Twirl => "Twirl", + Self::Pinch => "Pinch", + Self::Spherize => "Spherize", + Self::PolarCoordinates => "Polar Coordinates", Self::Desaturate => "Desaturate", Self::GammaCorrection => "Gamma Correction", Self::MakeOpaque => "Make Opaque", @@ -463,7 +475,7 @@ impl Effects { runs } - /// Moves the transforms the effects were stamped at onto content whose `baked` transform went into its geometry, and the graphics and radial blur centers that follow the content with them. + /// Moves the transforms the effects were stamped at onto content whose `baked` transform went into its geometry, and the graphics and the circles and squares of radial blurs and warps that follow the content with them. pub fn rebase_stamped_transforms(&mut self, baked: DAffine2) { if let Some(transforms) = self.0.iter_attribute_values_mut::(ATTR_TRANSFORM) { transforms.for_each(|transform| *transform = rebased_stamped_transform(*transform, baked)); @@ -486,13 +498,16 @@ impl Effects { } } - // A radial blur's center is a position measured from the effect space's origin, which moves by the translation `baked` took from the content + // A radial blur's or warp's transform is placed from the effect space's origin, which moves by the translation `baked` took from the content for index in 0..self.0.len() { let stamped_transform = self.0.attribute_cloned_or_default::(ATTR_TRANSFORM, index); if let Some(effect) = self.0.element_mut(index) - && matches!(effect.kind(), EffectKind::RadialBlur) - { - *effect.0.attribute_mut_or_insert_default::("center") += stamped_transform.matrix2 * baked.translation; + && matches!( + effect.kind(), + EffectKind::RadialBlur | EffectKind::Twirl | EffectKind::Pinch | EffectKind::Spherize | EffectKind::PolarCoordinates + ) { + let transform = effect.0.attribute_mut_or_insert_default::("transform"); + transform.translation += stamped_transform.matrix2 * baked.translation; } } } @@ -556,6 +571,11 @@ fn same_linear_part(first: DMat2, second: DMat2) -> bool { first.abs_diff_eq(second, 1e-9 * scale) } +/// Whether a transform flattens what it places onto a line or a point, so nothing can be measured within it. +pub(crate) fn collapses(transform: &DAffine2) -> bool { + !transform.matrix2.determinant().is_normal() +} + /// For PSD interop, an outer glow filled with a gradient fades out once its strength before range and contour falls below this. pub const GRADIENT_GLOW_FADE: f64 = 0.12; @@ -966,7 +986,7 @@ pub enum EffectOperation { MotionBlur { /// The direction of the line, in degrees counterclockwise from the right. angle: f64, - /// How long the line each point is smeared along is. + /// How long the line each point is smeared along is, ignoring its sign. distance: f64, /// Whether to blend the colors with their gamma encoding rather than in linear light. gamma: bool, @@ -976,11 +996,36 @@ pub enum EffectOperation { method: RadialBlurMethod, /// How far the blur smears, by the degrees of a spin or twice the percentage of the distance to the center of a zoom, up to 360. amount: f64, - /// The point the blur spins around or zooms toward, measured from the effect space's origin (the content's). - center: DVec2, + /// Places the unit circle (of diameter 1, centered at the origin) in the effect space, measured from its origin (the content's). + /// Its translation is the center the blur spins around or zooms toward, and a spin follows the ellipses it makes of circles around that center. + transform: DAffine2, /// Whether to blend the colors with their gamma encoding rather than in linear light. gamma: bool, }, + /// Acts within the ellipse its `transform` makes of the unit circle (of diameter 1, centered at the origin) in the effect space, like Pinch and Spherize. + Twirl { + /// Degrees, which the center turns through. + angle: f64, + transform: DAffine2, + }, + Pinch { + /// Percent. + amount: f64, + transform: DAffine2, + }, + /// If `cylindrical`, acts within an endless band as wide as the square around the ellipse, bending along the transform's x axis. + Spherize { + /// Percent. + amount: f64, + cylindrical: bool, + transform: DAffine2, + }, + /// Wraps the square from -0.5 to 0.5 that its `transform` places in the effect space around the ellipse inscribed in it, clearing what lies outside the square. + PolarCoordinates { + /// Whether it unwraps the content from around the square's center rather than wrapping it around. + inverse: bool, + transform: DAffine2, + }, Adjustment(Adjustment), } @@ -1028,6 +1073,10 @@ impl EffectOperation { Self::Dissolve { .. } => EffectKind::Dissolve, Self::MotionBlur { .. } => EffectKind::MotionBlur, Self::RadialBlur { .. } => EffectKind::RadialBlur, + Self::Twirl { .. } => EffectKind::Twirl, + Self::Pinch { .. } => EffectKind::Pinch, + Self::Spherize { .. } => EffectKind::Spherize, + Self::PolarCoordinates { .. } => EffectKind::PolarCoordinates, Self::Adjustment(adjustment) => adjustment.kind(), } } @@ -1071,8 +1120,13 @@ impl EffectOperation { .. } => (highlight_color.a() <= 0. && shadow_color.a() <= 0.) || (*size <= 0. && gloss_contour.is_identity()), Self::PaintOverlay { opacity, .. } => *opacity <= 0., - Self::MotionBlur { distance, .. } => *distance <= 0., - Self::RadialBlur { amount, .. } => *amount <= 0., + Self::MotionBlur { distance, .. } => *distance == 0., + // A transform collapsing its circle or square onto a line leaves nothing to act within + Self::RadialBlur { amount, transform, .. } => *amount <= 0. || collapses(transform), + Self::Twirl { angle, transform } => *angle == 0. || collapses(transform), + Self::Pinch { amount, transform } | Self::Spherize { amount, transform, .. } => *amount == 0. || collapses(transform), + // It clears what lies outside its square, which is everything where the square collapses + Self::PolarCoordinates { .. } => false, Self::Adjustment(Adjustment::ColorOverlay { color, opacity, .. }) => color.a() <= 0. || *opacity <= 0., Self::Mask { density, .. } => *density <= 0., Self::Feather { distance } => *distance <= 0., @@ -1090,10 +1144,11 @@ impl EffectOperation { matches!(self, Self::Blur { radius_mask, .. } if !radius_mask.draws_nothing()) } - /// Whether this operation reads the pixels around each one of the image the effects before it leave, like a blur, rather than casting from the content's shape or changing each pixel alone. + /// Whether this operation reads the pixels around each one of the image the effects before it leave, like a blur or a warp, rather than casting from the content's shape or changing each pixel alone. pub fn reads_pixels_around(&self) -> bool { match self { Self::Blur { .. } | Self::MotionBlur { .. } | Self::RadialBlur { .. } => true, + Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } => true, Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true, // Cast from the content's shape, reading a mask's own image or a feather's map, or changing each pixel alone Self::DropShadow { .. } @@ -1163,9 +1218,9 @@ impl EffectOperation { Self::FindEdges => std::f64::consts::SQRT_2 + 2., Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 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.max(0.) / 2. + 3., - // It reaches farther from content lying farther from its center, which `Effects::reach_around` measures - Self::RadialBlur { .. } => 0., + Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3., + // They reach as far as `Effects::reach_around` measures from where the content lies + Self::RadialBlur { .. } | Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } => 0., Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => 0., } } @@ -1206,6 +1261,11 @@ impl EffectOperation { *length = 0.; } }; + let finite_transform = |transform: &mut DAffine2| { + let mut values = transform.to_cols_array(); + values.iter_mut().for_each(finite); + *transform = DAffine2::from_cols_array(&values); + }; match &mut self { Self::Blur { radius, .. } => finite(radius), @@ -1237,7 +1297,19 @@ impl EffectOperation { Self::AddNoise { amount, .. } => finite(amount), Self::Dissolve { opacity, .. } => finite(opacity), Self::MotionBlur { angle, distance, .. } => [angle, distance].into_iter().for_each(finite), - Self::RadialBlur { amount, center, .. } => [amount, &mut center.x, &mut center.y].into_iter().for_each(finite), + Self::RadialBlur { amount, transform, .. } => { + finite(amount); + finite_transform(transform); + } + Self::Twirl { angle, transform } => { + finite(angle); + finite_transform(transform); + } + Self::Pinch { amount, transform } | Self::Spherize { amount, transform, .. } => { + finite(amount); + finite_transform(transform); + } + Self::PolarCoordinates { transform, .. } => finite_transform(transform), Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::Adjustment(_) => {} } self @@ -1375,9 +1447,26 @@ impl EffectOperation { EffectKind::RadialBlur => Self::RadialBlur { method: RadialBlurMethod::default(), amount: 0., - center: DVec2::ZERO, + transform: DAffine2::IDENTITY, gamma: false, }, + EffectKind::Twirl => Self::Twirl { + angle: 0., + transform: DAffine2::IDENTITY, + }, + EffectKind::Pinch => Self::Pinch { + amount: 0., + transform: DAffine2::IDENTITY, + }, + EffectKind::Spherize => Self::Spherize { + amount: 0., + cylindrical: false, + transform: DAffine2::IDENTITY, + }, + EffectKind::PolarCoordinates => Self::PolarCoordinates { + inverse: false, + transform: DAffine2::IDENTITY, + }, EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }), EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }), EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque), @@ -1642,12 +1731,29 @@ impl EffectOperation { visitor.parameter("distance", distance, 10.); visitor.parameter("gamma", gamma, false); } - Self::RadialBlur { method, amount, center, gamma } => { + Self::RadialBlur { method, amount, transform, gamma } => { visitor.parameter("method", method, RadialBlurMethod::default()); visitor.parameter("amount", amount, 10.); - visitor.parameter("center", center, DVec2::ZERO); + visitor.parameter("transform", transform, DAffine2::IDENTITY); visitor.parameter("gamma", gamma, false); } + Self::Twirl { angle, transform } => { + visitor.parameter("angle", angle, 50.); + visitor.parameter("transform", transform, DAffine2::IDENTITY); + } + Self::Pinch { amount, transform } => { + visitor.parameter("amount", amount, 50.); + visitor.parameter("transform", transform, DAffine2::IDENTITY); + } + Self::Spherize { amount, cylindrical, transform } => { + visitor.parameter("amount", amount, 100.); + visitor.parameter("cylindrical", cylindrical, false); + visitor.parameter("transform", transform, DAffine2::IDENTITY); + } + Self::PolarCoordinates { inverse, transform } => { + visitor.parameter("inverse", inverse, false); + visitor.parameter("transform", transform, DAffine2::IDENTITY); + } Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor), } } @@ -1817,10 +1923,27 @@ mod tests { EffectOperation::RadialBlur { method: RadialBlurMethod::Zoom, amount: 40., - center: DVec2::new(10., -25.), + transform: DAffine2::from_translation(DVec2::new(10., -25.)), gamma: false, }, EffectOperation::default_for(EffectKind::RadialBlur), + EffectOperation::Twirl { + angle: -200., + transform: DAffine2::from_scale_angle_translation(DVec2::new(80., 40.), 0.3, DVec2::new(5., 6.)), + }, + EffectOperation::Pinch { + amount: -30., + transform: DAffine2::from_scale(DVec2::splat(50.)), + }, + EffectOperation::Spherize { + amount: 60., + cylindrical: true, + transform: DAffine2::from_translation(DVec2::new(-3., 4.)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_2), + }, + EffectOperation::PolarCoordinates { + inverse: true, + transform: DAffine2::from_cols_array(&[30., 0., 10., 20., 15., 10.]), + }, ]; for operation in operations { @@ -2205,30 +2328,60 @@ mod tests { } #[test] - fn baking_the_content_placement_into_its_geometry_keeps_radial_blur_centers_in_place() { + fn baking_the_content_placement_into_its_geometry_keeps_radial_blur_and_warp_transforms_in_place() { // Stamped on stretched and turned content, which `placement` then moves before going into the content's geometry let stamped = DAffine2::from_scale_angle_translation(DVec2::new(1.5, 0.5), 0.1, DVec2::ZERO); let placement = DAffine2::from_scale_angle_translation(DVec2::new(2., 3.), 0.5, DVec2::new(200., 100.)); + let transform = DAffine2::from_scale_angle_translation(DVec2::new(30., 12.), -0.4, DVec2::new(5., 7.)); - for method in [RadialBlurMethod::Spin, RadialBlurMethod::Zoom] { - let mut effects = Effects::from_operations([EffectOperation::RadialBlur { - method, + let operations = [ + EffectOperation::RadialBlur { + method: RadialBlurMethod::Spin, amount: 10., - center: DVec2::new(5., 7.), + transform, gamma: false, - }]); + }, + EffectOperation::RadialBlur { + method: RadialBlurMethod::Zoom, + amount: 10., + transform, + gamma: false, + }, + EffectOperation::Twirl { angle: 90., transform }, + EffectOperation::Pinch { amount: 50., transform }, + EffectOperation::Spherize { + amount: 50., + cylindrical: false, + transform, + }, + EffectOperation::PolarCoordinates { inverse: false, transform }, + ]; + for operation in operations { + let mut effects = Effects::from_operations([operation.clone()]); effects.0.set_attribute(ATTR_TRANSFORM, 0, stamped); - let pivot = |effects: &Effects, content_transform: DAffine2| { - let Some(EffectOperation::RadialBlur { center, .. }) = effects.operations().next() else { - panic!("the row should stay a radial blur") + + // Where the circle's center and the ends of its axes lie in the space the content is placed in + let placed = |effects: &Effects, content_transform: DAffine2| { + let transform = match effects.operations().next() { + Some( + EffectOperation::RadialBlur { transform, .. } + | EffectOperation::Twirl { transform, .. } + | EffectOperation::Pinch { transform, .. } + | EffectOperation::Spherize { transform, .. } + | EffectOperation::PolarCoordinates { transform, .. }, + ) => transform, + _ => panic!("the row should stay the same effect"), }; - effect_space(content_transform, effects.0.attribute_cloned_or_default(ATTR_TRANSFORM, 0)).transform_point2(center) + let space = effect_space(content_transform, effects.0.attribute_cloned_or_default(ATTR_TRANSFORM, 0)); + [DVec2::ZERO, DVec2::X, DVec2::Y].map(|point| (space * transform).transform_point2(point)) }; - let before = pivot(&effects, placement); + let before = placed(&effects, placement); effects.rebase_stamped_transforms(placement); - let after = pivot(&effects, DAffine2::IDENTITY); - assert!(after.abs_diff_eq(before, 1e-9), "{method:?}: {before} moved to {after}"); + let after = placed(&effects, DAffine2::IDENTITY); + for (before, after) in before.into_iter().zip(after) { + assert!(after.abs_diff_eq(before, 1e-9), "{operation:?}: {before} moved to {after}"); + } } } } diff --git a/node-graph/libraries/graphic-types/src/generator.rs b/node-graph/libraries/graphic-types/src/generator.rs index 9a32e9801b..ef384ad05b 100644 --- a/node-graph/libraries/graphic-types/src/generator.rs +++ b/node-graph/libraries/graphic-types/src/generator.rs @@ -315,3 +315,21 @@ impl GeneratorPattern { Self::decode(*item.element(), &|key| item.attributes().get_any(key)) } } + +/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result. +pub fn pcg3d(input: [u32; 3]) -> [u32; 3] { + let mix = |[x, y, z]: [u32; 3]| { + let x = x.wrapping_add(y.wrapping_mul(z)); + let y = y.wrapping_add(z.wrapping_mul(x)); + let z = z.wrapping_add(x.wrapping_mul(y)); + [x, y, z] + }; + + let v = mix(input.map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223))); + mix(v.map(|value| value ^ (value >> 16))) +} + +/// A hash's top 24 bits as a fraction from 0 to 1, which an f32 holds exactly. +pub fn hash_fraction(hash: u32) -> f32 { + (hash >> 8) as f32 / (1_u32 << 24) as f32 +} diff --git a/node-graph/libraries/graphic-types/src/resampling.rs b/node-graph/libraries/graphic-types/src/resampling.rs index d97cff7a0d..671cce0d4a 100644 --- a/node-graph/libraries/graphic-types/src/resampling.rs +++ b/node-graph/libraries/graphic-types/src/resampling.rs @@ -1,7 +1,7 @@ -//! Effects that resample the content from elsewhere than nearby, like blurs along lines and arcs, and the frame of reference that those relative to the content's extent take. -//! The frame is the content's bounds in its own space, carried through its transform, so a frame-relative effect moves rigidly with the content. +//! Effects that resample the content from elsewhere than nearby, like blurs along lines and arcs, and the frames of reference that warps and those relative to the content's extent take. +//! The content's frame is its bounds in its own space, carried through its transform, so a frame-relative effect moves rigidly with the content. A warp's is the square its transform places. -use crate::effects::{EffectOperation, Effects, effect_space, spans_along_axes}; +use crate::effects::{EffectOperation, Effects, collapses, effect_space, spans_along_axes}; use core_types::graphene_hash::CacheHash; use dyn_any::DynAny; use glam::{DAffine2, DMat2, DVec2}; @@ -46,7 +46,7 @@ pub fn frame_of_bounds([min, max]: [DVec2; 2], transform: DAffine2) -> DAffine2 transform * DAffine2::from_translation(min) * DAffine2::from_scale(max - min) } -/// The frame of reference of an effect relative to the content's extent: a parallelogram placed in the pixels the effect runs on. +/// The frame of reference of an effect, like the content's extent or a warp's square: a parallelogram placed in the pixels the effect runs on. /// Positions within it are measured in the effect space's units from its center along its sides, its local space. #[derive(Clone, Copy, Debug, PartialEq)] pub struct EffectFrame { @@ -61,7 +61,13 @@ impl EffectFrame { pub fn new(placement: DAffine2, effect_to_pixels: DAffine2) -> Option { let size = DVec2::new(placement.matrix2.x_axis.length(), placement.matrix2.y_axis.length()); let to_pixels = effect_to_pixels * placement; - (placement.is_finite() && to_pixels.matrix2.determinant().is_normal()).then_some(Self { to_pixels, size }) + + // The placement is tested alone too, since a turned space can leave a rounding residue in the product where its own determinant is 0 + if !placement.is_finite() || collapses(&placement) || collapses(&to_pixels) { + return None; + } + + Some(Self { to_pixels, size }) } /// The bounding box of the frame in the pixels. @@ -88,6 +94,18 @@ impl EffectFrame { self.local_to_pixels().inverse() } + /// Half a pixel along each of the frame's sides, in its local space. + pub fn half_pixel(&self) -> DVec2 { + let local_to_pixels = self.local_to_pixels().matrix2; + 0.5 / DVec2::new(local_to_pixels.x_axis.length(), local_to_pixels.y_axis.length()) + } + + /// How far a pixel reaches from its center along each of the frame's sides, in its local space: half a pixel on an upright frame, and farther on a turned one, which its corners reach past. + pub fn pixel_extent(&self) -> DVec2 { + let pixels_to_local = self.pixels_to_local().matrix2; + 0.5 * (pixels_to_local.x_axis.abs() + pixels_to_local.y_axis.abs()) + } + /// Whether a point in the local space lies within the frame. pub fn contains(&self, local: DVec2) -> bool { let half = self.size / 2.; @@ -99,35 +117,69 @@ impl EffectFrame { #[derive(Clone, Copy, Debug, PartialEq)] pub struct RadialBlur { pub method: RadialBlurMethod, - /// The point the blur spins around or zooms toward, in the effect space, measured from its origin (the content's). - pub center: DVec2, + /// Places the unit circle in the effect space, measured from its origin (the content's), with the blur's center as its translation. A spin's arcs follow circles about that center in the circle's space. + /// Its size changes nothing, so its linear part is scaled to an area of 1, and a zoom keeps only the center, since lines through a point stay so in any linear space. + pub transform: DAffine2, /// The angle a spin's arcs span, in radians, or the share of each point's distance from the center that a zoom's lines span, each centered on the point. pub extent: f64, + /// The inverse of the transform's linear part, carrying offsets from the center into the circle's space. + to_circle: DMat2, + /// The most the transform's linear part stretches a length, which bounds how much longer an arc is in the effect space than in the circle's. + stretch: f64, } impl RadialBlur { - /// The blur of `amount` (up to [`MAX_RADIAL_BLUR_AMOUNT`]) about the `center`, a point in the effect space. - pub fn new(method: RadialBlurMethod, amount: f64, center: DVec2) -> Self { + /// The blur of `amount` (up to [`MAX_RADIAL_BLUR_AMOUNT`]) about the circle its `transform` places in the effect space, or a round one about its center where it collapses. + pub fn new(method: RadialBlurMethod, amount: f64, transform: DAffine2) -> Self { let amount = amount.clamp(0., MAX_RADIAL_BLUR_AMOUNT); let extent = match method { RadialBlurMethod::Spin => (amount * SPIN_DEGREES_PER_AMOUNT).to_radians(), RadialBlurMethod::Zoom => amount * ZOOM_FRACTION_PER_AMOUNT, }; - Self { method, center, extent } + let unit_area = transform.matrix2 * transform.matrix2.determinant().abs().sqrt().recip(); + let linear = match method { + RadialBlurMethod::Spin if !collapses(&transform) && unit_area.is_finite() => unit_area, + _ => DMat2::IDENTITY, + }; + + Self { + method, + transform: DAffine2::from_mat2_translation(linear, transform.translation), + extent, + to_circle: linear.inverse(), + stretch: stretches(linear).1, + } } - /// How far past the content the blur can paint, given the `farthest` the content reaches from its center: a spin's arcs carry that point along a chord, and a zoom's lines carry it outward. - pub fn reach(&self, farthest: f64) -> f64 { - match self.method { + /// The point the blur spins around or zooms toward, in the effect space. + pub fn center(&self) -> DVec2 { + self.transform.translation + } + + /// The most the circle's space stretches a length into the effect space, which a spin's arcs are at most that much longer in. + pub fn longest_stretch(&self) -> f64 { + self.stretch + } + + /// How far past the content the blur can paint, given the `corners` of the content's bounds in the effect space and how far what's `painted` reaches past them. + /// A spin's arcs carry each point along a chord of its ellipse, and a zoom's lines carry it outward. + pub fn reach_around(&self, corners: [DVec2; 4], painted: f64) -> f64 { + // The farthest anything painted lies from the center in the circle's space, where the arcs are round + let (shortest, longest) = stretches(self.transform.matrix2); + let to_circle = |corner: DVec2| (self.to_circle * (corner - self.center())).length(); + let farthest = corners.map(to_circle).into_iter().fold(0., f64::max) + painted / shortest; + + let reach = match self.method { RadialBlurMethod::Spin => 2. * farthest * (self.extent.min(std::f64::consts::TAU) / 4.).sin(), RadialBlurMethod::Zoom => farthest * (self.extent / 2.) / (1. - self.extent / 2.), - } + }; + reach * longest } /// How many samples the `point` (in the effect space) averages, spread along its arc or line by [`RADIAL_SAMPLES_PER_PIXEL`], given how many pixels each unit of the effect space spans. pub fn sample_count(&self, point: DVec2, pixels_per_length: f64) -> u32 { - let length = (point - self.center).length() * self.extent * pixels_per_length * RADIAL_SAMPLES_PER_PIXEL; + let length = (self.to_circle * (point - self.center())).length() * self.stretch * self.extent * pixels_per_length * RADIAL_SAMPLES_PER_PIXEL; if !length.is_finite() { return 1; } @@ -141,12 +193,13 @@ impl RadialBlur { /// The point a share `along` the arc or line through the `point`, which centers on it, from -0.5 at one end to 0.5 at the other. pub fn point_along(&self, point: DVec2, along: f64) -> DVec2 { - let offset = point - self.center; + let offset = self.to_circle * (point - self.center()); - match self.method { - RadialBlurMethod::Spin => self.center + DVec2::from_angle(self.extent * along).rotate(offset), - RadialBlurMethod::Zoom => self.center + offset * (1. - self.extent * along), - } + let moved = match self.method { + RadialBlurMethod::Spin => DVec2::from_angle(self.extent * along).rotate(offset), + RadialBlurMethod::Zoom => offset * (1. - self.extent * along), + }; + self.center() + self.transform.matrix2 * moved } /// The part of its input, in pixels, that the blur reads to produce `output` (in pixels), given the map from the effect space into the pixels and how many pixels each unit of that space spans. @@ -166,6 +219,343 @@ impl RadialBlur { } } +/// For PSD interop, how much farther than itself the center of a full pinch reads from. +pub const PINCH_STRENGTH: f64 = 100. / 128.; + +/// For PSD interop, the twirl angle in degrees matching PSD's whole-degree `angle`, which PSD turns by as if a radian were 57 degrees. +pub fn twirl_angle_from_psd(angle: i32) -> f64 { + (angle as f64 / 57.).to_degrees() +} + +/// The frame a warp acts within: the square from -0.5 to 0.5 that its `transform` places in the effect space, holding the ellipse it makes of the unit circle. +/// It's placed in the pixels that `effect_to_pixels` maps that space into, and is `None` where it collapses. +pub fn warp_frame(transform: DAffine2, effect_to_pixels: DAffine2) -> Option { + EffectFrame::new(transform * DAffine2::from_translation(DVec2::splat(-0.5)), effect_to_pixels) +} + +/// How many sides the polygon around a warp's ellipse has, bounding where it paints to within half a percent of the ellipse's size. +const ELLIPSE_BOUND_SIDES: usize = 32; + +/// How many pixels apart a warp's frame's opposite sides lie at least for tracing the boundary of a region within it to bound what the region reads. +/// Across a thinner frame, the traced samples lie too far apart in it to follow the warp, like wrapping turning a whole revolution between two. +const MIN_TRACED_FRAME_PIXELS: f64 = 2.; + +/// Where Spherize reads a point `distance` from its middle from, as a share of the way to its edge (from 0 to 1), for an `amount` bending fully at 1 or -1. +/// Below -1 it reads past the edge, and above about 2.75 it reads across the middle, where it's negative. +fn spherize_bend(distance: f64, amount: f64) -> f64 { + match amount >= 0. { + true => distance + amount * ((2. / std::f64::consts::PI) * distance.asin() - distance), + false => distance - amount * ((std::f64::consts::FRAC_PI_2 * distance).sin() - distance), + } +} + +/// The most a Spherize cylinder of `amount` moves a point along its row, as a share of half its band's width, among points from `near` to `far` of the way out from the band's middle. +/// The shift grows from none at the middle to its peak, where the bend's slope is 1, then falls back to none at the edge, so it's largest at the peak or the end nearer it. +fn largest_bend_shift(amount: f64, near: f64, far: f64) -> f64 { + let steepest = 2. / std::f64::consts::PI; + let peak = if amount >= 0. { (1. - steepest * steepest).sqrt() } else { steepest * steepest.acos() }; + + let shift = |distance: f64| (spherize_bend(distance, amount) - distance).abs(); + [near, far, peak.clamp(near, far)].into_iter().map(shift).fold(0., f64::max) +} + +/// A warp within its frame (see [`warp_frame`]), which shows at each point the content from where [`FrameWarp::source`] maps it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum FrameWarp { + /// Turns the content around the frame's center by up to an angle in radians, the most at the center and none at the edge of the ellipse inscribed in the frame, which turns as if it were a circle. + Twirl { angle: f64 }, + /// Squeezes the content toward the frame's center within the ellipse inscribed in it, or pushes it out for a negative amount, as PSD does from -1 to 1. Past them, it grows stronger until it folds the content over, reading from past the ellipse or across its center. + Pinch { amount: f64 }, + // For PSD interop, PSD's Normal mode is a sphere, its Horizontal Only is a cylinder, and its Vertical Only is a cylinder with the transform turned 90° + /// Bulges the content out from the frame's center within the ellipse inscribed in it, or sinks it for a negative amount, as PSD does from -1 to 1. Past them, it grows stronger until it folds the content over (see [`spherize_bend`]). + /// If `cylindrical`, it bends only along the frame's x axis, within a band as wide as the frame. + Spherize { amount: f64, cylindrical: bool }, + /// Wraps the content around the frame's center, its top edge gathering at the center and its bottom edge running around the rim, or unwraps it from there if `inverse`. It clears what lies outside the frame. + Polar { inverse: bool }, +} + +impl FrameWarp { + /// The warp an operation carries out, if it's one of the frame warps, with the transform placing its frame (see [`warp_frame`]). + pub fn of(operation: &EffectOperation) -> Option<(Self, DAffine2)> { + Some(match *operation { + EffectOperation::Twirl { angle, transform } => (Self::Twirl { angle: angle.to_radians() }, transform), + EffectOperation::Pinch { amount, transform } => (Self::Pinch { amount: amount / 100. }, transform), + EffectOperation::Spherize { amount, cylindrical, transform } => (Self::Spherize { amount: amount / 100., cylindrical }, transform), + EffectOperation::PolarCoordinates { inverse, transform } => (Self::Polar { inverse }, transform), + _ => return None, + }) + } + + /// How far past the content the warp can paint in the effect space, on top of what's `painted` past the `corners` of its bounds there, given the `transform` placing its frame there. + /// Unwrapping paints across the frame, a cylinder across its band along the rows through what's painted, and the others within its ellipse, bounded by a polygon around it. + fn reach_around(&self, transform: DAffine2, corners: [DVec2; 4], painted: f64) -> f64 { + // A collapsed frame paints nothing + if collapses(&transform) { + return 0.; + } + + let outline: Vec = match *self { + Self::Polar { inverse: true } => [DVec2::ZERO, DVec2::X, DVec2::ONE, DVec2::Y].map(|corner| corner - 0.5).to_vec(), + Self::Spherize { cylindrical: true, .. } => { + // The band's rows from the first through what's painted to the last, in the frame's unit square + let to_unit = transform.inverse(); + let rows = corners.map(|corner| to_unit.transform_point2(corner).y); + let spread = painted * to_unit.matrix2.row(1).length(); + let first = rows.into_iter().fold(f64::INFINITY, f64::min) - spread; + let last = rows.into_iter().fold(f64::NEG_INFINITY, f64::max) + spread; + + vec![DVec2::new(-0.5, first), DVec2::new(0.5, first), DVec2::new(-0.5, last), DVec2::new(0.5, last)] + } + _ => { + // Its corners lie half a side's turn off the axes, so those beside each axis lie on the frame's sides rather than past them + let sides = ELLIPSE_BOUND_SIDES as f64; + let radius = 0.5 / (std::f64::consts::PI / sides).cos(); + let corner = |index: usize| DVec2::from_angle(std::f64::consts::TAU * (index as f64 + 0.5) / sides) * radius; + (0..ELLIPSE_BOUND_SIDES).map(corner).collect() + } + }; + + outline.into_iter().map(|point| distance_outside(transform.transform_point2(point), corners)).fold(0., f64::max) + } + + /// The part of its input, in pixels, that the warp reads to produce `output` (in pixels), within its `frame` there. + pub fn source_region(&self, output: [DVec2; 2], frame: &EffectFrame) -> [DVec2; 2] { + let (to_local, to_pixels) = (frame.pixels_to_local(), frame.local_to_pixels()); + + let read = match *self { + // Each row of a cylinder's band reads from along itself, however far the band runs past the frame + Self::Spherize { cylindrical: true, amount } => { + let half = frame.size.x / 2.; + let [min, max] = local_bounds(output, to_local); + if min.x >= half || max.x <= -half { + return output; + } + + // How far out from the band's middle the output reaches across it, within the band + let (low, high) = (min.x.max(-half) / half, max.x.min(half) / half); + let near = if low <= 0. && high >= 0. { 0. } else { low.abs().min(high.abs()) }; + let far = low.abs().max(high.abs()); + + // It moves those points along their rows by at most the bend's largest shift among them, plus a pixel that interpolating reads past it + let shift = largest_bend_shift(amount, near, far) * half; + let reach = (to_pixels.matrix2.x_axis * shift).abs() + 1.; + [output[0] - reach, output[1] + reach] + } + Self::Pinch { .. } | Self::Spherize { cylindrical: false, .. } => match self.radial_source_region(output, frame) { + Some(read) => read, + None => return output, + }, + _ => { + // Only the output within a pixel of the frame reads elsewhere, as past it the content stays as it is or clears + let [frame_min, frame_max] = frame.pixel_bounds(); + let within = intersection(output, [frame_min - 1., frame_max + 1.]); + if within[0].cmpgt(within[1]).any() { + return output; + } + + // Where the warp tears, or across a frame too thin for the traced samples to follow how fast the warp changes, the boundary doesn't bound what it reads, which may lie anywhere in the frame. + // How thin it is is the least distance between its opposite sides, its area over the length of the longest side. + let sides = frame.to_pixels.matrix2; + let thin = sides.determinant().abs() / sides.x_axis.length().max(sides.y_axis.length()) < MIN_TRACED_FRAME_PIXELS; + + // Wrapping also reads across the seam where its source lies within a pixel's extent of the left or right side, which happens less than 2π extents from the seam. + let seam_reach = DVec2::X * std::f64::consts::TAU * frame.pixel_extent().x; + let [min, max] = local_bounds(within, to_local); + if thin || self.tears_within([min - seam_reach, max + seam_reach]) { + frame.pixel_bounds() + } else { + let read = traced_bounds(within, |point, include| include(to_pixels.transform_point2(self.source(to_local.transform_point2(point), frame.size)))); + match self { + Self::Polar { .. } => intersection(read, frame.pixel_bounds()), + _ => read, + } + } + } + }; + + // A read that misses the frame adds nothing + match read[0].cmple(read[1]).all() { + true => union(output, read), + false => output, + } + } + + /// The part of its input, in pixels, that a radial warp (Pinch, or Spherize as a sphere) reads to produce `output` (in pixels) within its ellipse, or `None` where the output misses the ellipse. + /// Each point reads its offset from the center scaled, so the reads lie both along the output's directions (or the opposite ones) as far as its distances read from, and within its corners scaled alike. + fn radial_source_region(&self, output: [DVec2; 2], frame: &EffectFrame) -> Option<[DVec2; 2]> { + // The output's corners, and where they lie where the ellipse is the unit circle + let half = frame.size / 2.; + let to_circle = DAffine2::from_scale(half.recip()) * frame.pixels_to_local(); + let [min, max] = output; + let pixel_corners = [min, DVec2::new(max.x, min.y), max, DVec2::new(min.x, max.y)]; + let corners = pixel_corners.map(|corner| to_circle.transform_point2(corner)); + + // How far from the center the output spans within the ellipse, past which the content stays as it is + let nearest = distance_outside(DVec2::ZERO, corners); + let farthest = corners.into_iter().map(DVec2::length).fold(0., f64::max).min(1.); + if nearest >= 1. { + return None; + } + + // The output's corners scaled about the center as much as the nearest and farthest points scale theirs, which bound how much those between do + let center = frame.local_to_pixels().transform_point2(DVec2::ZERO); + let scales = [nearest, farthest].map(|distance| self.radial_scale(distance)); + let scaled = pixel_corners.into_iter().flat_map(|corner| scales.map(|scale| center + (corner - center) * scale)); + let within_scaled_corners = scaled.fold([DVec2::INFINITY, DVec2::NEG_INFINITY], |[low, high], point| [low.min(point), high.max(point)]); + + // The least and most distances those read from, negative across the center, at the ends or where the warp turns back between them + let turning_points = self.radial_turning_points().into_iter().filter(|distance| (nearest..=farthest).contains(distance)); + let reads = [nearest, farthest].into_iter().chain(turning_points).map(|distance| self.radial_read(distance)); + let (least, most) = reads.fold((f64::INFINITY, f64::NEG_INFINITY), |(least, most), read| (least.min(read), most.max(read))); + + // The directions the output spans from the center: all of them around a center within it, or else those between its corners, less than half a turn apart + let (start, span) = match nearest > 0. { + true => { + let middle = corners.into_iter().sum::() / 4.; + let angles = corners.map(|corner| middle.perp_dot(corner).atan2(middle.dot(corner))); + let first = angles.into_iter().fold(f64::INFINITY, f64::min); + let last = angles.into_iter().fold(f64::NEG_INFINITY, f64::max); + (middle.to_angle() + first, last - first) + } + false => (0., std::f64::consts::TAU), + }; + + // Points at the least and most distances along those directions, also pushed out so the polygon through them holds the arcs between + let steps = (span / std::f64::consts::TAU * ELLIPSE_BOUND_SIDES as f64).ceil().max(1.); + let outward = 1. / (span / steps / 2.).cos(); + let to_pixels = frame.local_to_pixels() * DAffine2::from_scale(half); + let mut along_directions = [DVec2::INFINITY, DVec2::NEG_INFINITY]; + for step in 0..=steps as usize { + let direction = DVec2::from_angle(start + span * step as f64 / steps); + for distance in [least, least * outward, most, most * outward] { + let point = to_pixels.transform_point2(direction * distance); + along_directions = [along_directions[0].min(point), along_directions[1].max(point)]; + } + } + + // Where both bounds hold, plus a pixel that interpolating reads past them + let [low, high] = intersection(along_directions, within_scaled_corners); + Some([low - 1., high + 1.]) + } + + /// How many times its offset from the center a radial warp (Pinch, or Spherize as a sphere) reads a point `distance` from the center at, which only rises or only falls out from the center. + fn radial_scale(&self, distance: f64) -> f64 { + match *self { + Self::Pinch { amount } => 1. + amount * PINCH_STRENGTH * (1. - distance * distance).powi(2), + // At the center, where it can't divide, its limit there (the bend's slope) + Self::Spherize { amount, .. } if distance == 0. => match amount >= 0. { + true => 1. + amount * (std::f64::consts::FRAC_2_PI - 1.), + false => 1. - amount * (std::f64::consts::FRAC_PI_2 - 1.), + }, + Self::Spherize { amount, .. } => spherize_bend(distance, amount) / distance, + _ => 1., + } + } + + /// How far from the center a radial warp (Pinch, or Spherize as a sphere) reads a point `distance` from it, both as shares of the way to the ellipse's rim, which is negative across the center. + fn radial_read(&self, distance: f64) -> f64 { + match *self { + Self::Pinch { amount } => distance * (1. + amount * PINCH_STRENGTH * (1. - distance * distance).powi(2)), + Self::Spherize { amount, .. } => spherize_bend(distance, amount), + _ => distance, + } + } + + /// The distances from the center where a radial warp's read distance (see [`Self::radial_read`]) turns back, which it does only past an amount of 1 or -1. + fn radial_turning_points(&self) -> Vec { + match *self { + // Where the slope 1 + s(1 - u)(1 - 5u) is zero, for its strength s and the squared distance u + Self::Pinch { amount } => { + let strength = amount * PINCH_STRENGTH; + let discriminant = 16. * strength * strength - 20. * strength; + if strength == 0. || discriminant < 0. { + return Vec::new(); + } + + let squared_distances = [-1., 1.].map(|sign| (6. * strength + sign * discriminant.sqrt()) / (10. * strength)); + squared_distances.into_iter().filter(|squared| (0. ..=1.).contains(squared)).map(f64::sqrt).collect() + } + // Where the bend's slope is zero, at √(1 - d²) = (2/π)a/(a - 1) for an amount a above 1, or cos(πd/2) = (2/π)(1 + 1/a) below -1 + Self::Spherize { amount, .. } if amount > 1. => { + let root = std::f64::consts::FRAC_2_PI * amount / (amount - 1.); + if root <= 1. { vec![(1. - root * root).sqrt()] } else { Vec::new() } + } + Self::Spherize { amount, .. } if amount < -1. => vec![std::f64::consts::FRAC_2_PI * (std::f64::consts::FRAC_2_PI * (1. + 1. / amount)).acos()], + _ => Vec::new(), + } + } + + /// Whether the warp tears within a region of the frame's local space (between `min` and `max`), so the region's boundary doesn't bound where its points read from. + /// Only wrapping around the center tears, at the center and along the seam straight up from it, where the frame's left and right edges meet. + pub fn tears_within(&self, [min, max]: [DVec2; 2]) -> bool { + let Self::Polar { inverse: false } = self else { return false }; + min.x <= 0. && max.x >= 0. && min.y <= 0. + } + + /// A number identifying the warp to the shaders, followed by its two settings. + pub fn shader_parameters(&self) -> [f32; 3] { + match *self { + Self::Twirl { angle } => [0., angle as f32, 0.], + Self::Pinch { amount } => [1., (amount * PINCH_STRENGTH) as f32, 0.], + Self::Spherize { amount, cylindrical } => [2., amount as f32, cylindrical as u32 as f32], + Self::Polar { inverse } => [3., inverse as u32 as f32, 0.], + } + } + + /// Where the point at `local` (in the local space of a frame `size` across) reads the content from, in the same space. + pub fn source(&self, local: DVec2, size: DVec2) -> DVec2 { + let half = size / 2.; + let normalized = local / half; + + match *self { + Self::Twirl { angle } => { + // For PSD interop, the turn falls off with the square of the distance from the center + let distance = normalized.length(); + if distance >= 1. { + return local; + } + DVec2::from_angle(-angle * (1. - distance).powi(2)).rotate(normalized) * half + } + Self::Pinch { amount } => { + let distance_squared = normalized.length_squared(); + if distance_squared >= 1. { + return local; + } + local * (1. + amount * PINCH_STRENGTH * (1. - distance_squared).powi(2)) + } + Self::Spherize { amount, cylindrical } => { + let bend = |distance: f64| spherize_bend(distance, amount); + match cylindrical { + false => { + let distance = normalized.length(); + if distance >= 1. || distance <= 0. { + return local; + } + local * (bend(distance) / distance) + } + // It bends each row within a band as wide as the frame, running endlessly past its top and bottom + true => { + if normalized.x.abs() >= 1. { + return local; + } + DVec2::new(normalized.x.signum() * bend(normalized.x.abs()) * half.x, local.y) + } + } + } + // The angle counterclockwise from straight down runs across, and the distance from the center runs down + Self::Polar { inverse: false } => { + let angle = normalized.x.atan2(normalized.y); + DVec2::new(angle / std::f64::consts::PI, normalized.length() * 2. - 1.) * half + } + Self::Polar { inverse: true } => { + let angle = normalized.x * std::f64::consts::PI; + let distance = (normalized.y + 1.) / 2.; + DVec2::new(angle.sin(), angle.cos()) * distance * half + } + } + } +} + /// How many samples per side of a region its boundary is traced with to find what an effect reading from beyond its reach reads. const TRACED_SAMPLES_PER_SIDE: usize = 64; @@ -199,16 +589,24 @@ fn union([a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]) -> [DVec2; 2] { [a_min.min(b_min), a_max.max(b_max)] } +/// Where two boxes overlap, which is empty (its minimum past its maximum) where they don't. +fn intersection([a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]) -> [DVec2; 2] { + [a_min.max(b_min), a_max.min(b_max)] +} + +/// The bounding box of a box carried through `transform`, like one in pixels carried into a frame's local space. +fn local_bounds([min, max]: [DVec2; 2], transform: DAffine2) -> [DVec2; 2] { + let corners = [min, DVec2::new(max.x, min.y), max, DVec2::new(min.x, max.y)].map(|corner| transform.transform_point2(corner)); + [corners.into_iter().reduce(DVec2::min).unwrap_or_default(), corners.into_iter().reduce(DVec2::max).unwrap_or_default()] +} + impl EffectOperation { /// How far past the content this operation can paint, in its effect space, given the `corners` of the content's bounds there and how far the effects before it have `painted` past them. - /// Most reach a fixed distance, but a radial blur reaches farther from content lying farther from its center. + /// Most reach a fixed distance, but a radial blur reaches farther from content lying farther from its center, and a warp as far as its ellipse or square lies past the content. fn reach_around(&self, corners: [DVec2; 4], painted: f64) -> f64 { match self { - // Nothing painted lies farther from the center than the bounds' farthest corner and what's painted past them - Self::RadialBlur { method, amount, center, .. } => { - let farthest = corners.into_iter().map(|corner| corner.distance(*center)).fold(0., f64::max) + painted; - RadialBlur::new(*method, *amount, *center).reach(farthest) - } + Self::RadialBlur { method, amount, transform, .. } => RadialBlur::new(*method, *amount, *transform).reach_around(corners, painted), + _ if let Some((warp, transform)) = FrameWarp::of(self) => warp.reach_around(transform, corners, painted), _ => self.painted_reach(), } } @@ -216,7 +614,11 @@ impl EffectOperation { /// Whether this operation takes the content's frame, which effects relative to its extent measure from, unless it changes nothing. pub fn takes_frame(&self) -> bool { match self { - Self::MotionBlur { .. } + Self::Twirl { .. } + | Self::Pinch { .. } + | Self::Spherize { .. } + | Self::PolarCoordinates { .. } + | Self::MotionBlur { .. } | Self::RadialBlur { .. } | Self::DropShadow { .. } | Self::InnerShadow { .. } @@ -248,6 +650,36 @@ fn stretch_bound(linear_map: DMat2) -> f64 { (spans.x * spans.x + spans.y * spans.y).sqrt() } +/// The least and the most a linear map stretches a unit length in any direction (its singular values). +fn stretches(linear_map: DMat2) -> (f64, f64) { + let sum_of_squares = linear_map.x_axis.length_squared() + linear_map.y_axis.length_squared(); + let determinant = linear_map.determinant(); + let spread = (sum_of_squares * sum_of_squares - 4. * determinant * determinant).max(0.).sqrt(); + let most = ((sum_of_squares + spread) / 2.).sqrt(); + + // The least is the area scale over the most, since subtracting nearly equal values could round it to zero + let least = if most > 0. { determinant.abs() / most } else { 0. }; + (least, most) +} + +/// How far a `point` lies outside the parallelogram with these `corners` in order around it, or 0 within it. +fn distance_outside(point: DVec2, corners: [DVec2; 4]) -> f64 { + let edges = || (0..4).map(|index| (corners[index], corners[(index + 1) % 4])); + + // Within a parallelogram that doesn't collapse, the point lies on the same side of each edge + let sides: Vec = edges().map(|(start, end)| (end - start).perp_dot(point - start)).collect(); + if sides.iter().all(|&side| side > 0.) || sides.iter().all(|&side| side < 0.) { + return 0.; + } + + let to_edge = |(start, end): (DVec2, DVec2)| { + let along = (end - start).length_squared(); + let share = if along > 0. { ((point - start).dot(end - start) / along).clamp(0., 1.) } else { 0. }; + point.distance(start + (end - start) * share) + }; + edges().map(to_edge).fold(f64::INFINITY, f64::min) +} + /// The corners of the content's `bounds` and its `overhang` past them, in a space that `space` maps an effect space into, carried into that effect space. /// The overhang there is as far as it can stretch, so content isn't cut short. fn measured_in_effect_space(space: DAffine2, [min, max]: [DVec2; 2], overhang: f64) -> ([DVec2; 4], f64) { @@ -318,18 +750,21 @@ impl Effects { self.operations().any(|operation| operation.takes_frame()) } - /// Whether how far the effects reach depends on the content's bounds, as a radial blur's does on how far they lie from its center. + /// Whether how far the effects reach depends on the content's bounds, as a radial blur's does on how far they lie from its center and a warp's on how far its ellipse or square lies past them. pub fn reach_depends_on_size(&self) -> bool { - self.operations() - .any(|operation| matches!(operation, EffectOperation::RadialBlur { .. }) && !operation.changes_nothing()) + self.operations().any(|operation| { + let measures_from_bounds = matches!(operation, EffectOperation::RadialBlur { .. }) || FrameWarp::of(&operation).is_some(); + measures_from_bounds && !operation.changes_nothing() + }) } - /// The region, in pixels, that the content has to be rendered over so the effects can produce the `visible` part of their result (in pixels), - /// if any of them reads from beyond its reach, as a radial blur reads along its arcs and lines. `effect_to_pixels` maps the effect space into the pixels. + /// The region, in pixels, that the content has to be rendered over so the effects can produce the `visible` part of their result (in pixels), if any of them reads from beyond its reach, + /// as a radial blur reads along its arcs and lines and a warp within its own frame. `effect_to_pixels` maps the effect space into the pixels. /// The stages before each effect may need different regions, all of which the result covers, since the effects' passes share one image. pub fn source_region(&self, visible: [DVec2; 2], effect_to_pixels: DAffine2) -> Option<[DVec2; 2]> { let operations: Vec = self.operations().filter(|operation| !operation.changes_nothing()).collect(); - if !operations.iter().any(|operation| matches!(operation, EffectOperation::RadialBlur { .. })) { + let reads_beyond_reach = |operation: &EffectOperation| matches!(operation, EffectOperation::RadialBlur { .. }) || FrameWarp::of(operation).is_some(); + if !operations.iter().any(reads_beyond_reach) { return None; } @@ -341,7 +776,11 @@ impl Effects { let mut covered = visible; for operation in operations.iter().rev() { region = match operation { - EffectOperation::RadialBlur { method, amount, center, .. } => RadialBlur::new(*method, *amount, *center).source(region, effect_to_pixels, pixels_per_length), + EffectOperation::RadialBlur { method, amount, transform, .. } => RadialBlur::new(*method, *amount, *transform).source(region, effect_to_pixels, pixels_per_length), + _ if let Some((warp, transform)) = FrameWarp::of(operation) => match warp_frame(transform, effect_to_pixels) { + Some(square) => warp.source_region(region, &square), + None => region, + }, _ => { let reach = operation.reach() * spans; [region[0] - reach, region[1] + reach] @@ -381,7 +820,7 @@ mod tests { #[test] fn spins_sample_along_arcs_centered_on_each_point() { - let blur = RadialBlur::new(RadialBlurMethod::Spin, 90. / SPIN_DEGREES_PER_AMOUNT, DVec2::ZERO); + let blur = RadialBlur::new(RadialBlurMethod::Spin, 90. / SPIN_DEGREES_PER_AMOUNT, DAffine2::IDENTITY); let point = DVec2::new(10., 0.); let count = blur.sample_count(point, 1.); @@ -395,7 +834,7 @@ mod tests { assert!((blur.sample(point, 0, count) - first).length() < 1e-9); // The samples of a whole turn spread evenly around the circle, so no two land together and they balance about the center - let turn = RadialBlur::new(RadialBlurMethod::Spin, 360. / SPIN_DEGREES_PER_AMOUNT, DVec2::ZERO); + let turn = RadialBlur::new(RadialBlurMethod::Spin, 360. / SPIN_DEGREES_PER_AMOUNT, DAffine2::IDENTITY); let count = turn.sample_count(point, 1.); let mean = (0..count).map(|index| turn.sample(point, index, count)).sum::() / count as f64; assert!(mean.length() < 1e-9, "the samples of a whole turn average to {mean}"); @@ -403,7 +842,7 @@ mod tests { #[test] fn zooms_sample_along_lines_through_each_point_toward_the_center() { - let blur = RadialBlur::new(RadialBlurMethod::Zoom, 0.5 / ZOOM_FRACTION_PER_AMOUNT, DVec2::new(100., 0.)); + let blur = RadialBlur::new(RadialBlurMethod::Zoom, 0.5 / ZOOM_FRACTION_PER_AMOUNT, DAffine2::from_translation(DVec2::new(100., 0.))); // For PSD interop, the line spans from three quarters to five quarters of the point's distance from the center let point = DVec2::new(100., 40.); @@ -423,7 +862,7 @@ mod tests { let effects = Effects::from_operations([EffectOperation::RadialBlur { method: RadialBlurMethod::Spin, amount: 60., - center: DVec2::new(200., 150.), + transform: DAffine2::from_translation(DVec2::new(200., 150.)), gamma: false, }]); @@ -449,7 +888,7 @@ mod tests { use core_types::ATTR_TRANSFORM; use core_types::list::{ATTR_EFFECTS, Item}; - // A sharp shadow cast 50 units down, then a half turn about a center off to the side + // A sharp shadow cast 50 units down, then a half turn about a center off to the side, along circles or along ellipses that are oblong, turned, and slanted let (angle, distance, amount) = (90., 50., 180.); let shadow = EffectOperation::DropShadow { color: core_types::Color::BLACK, @@ -461,18 +900,24 @@ mod tests { contour: Default::default(), knockout: true, }; - let center = DVec2::new(150., -40.); - let spin = EffectOperation::RadialBlur { - method: RadialBlurMethod::Spin, - amount, + let center = DAffine2::from_translation(DVec2::new(150., -40.)); + let ellipses = [ center, - gamma: false, - }; + center * DAffine2::from_scale(DVec2::new(3., 1.)), + center * DAffine2::from_angle(0.6) * DAffine2::from_scale(DVec2::new(1., 4.)), + center * DAffine2::from_cols_array(&[2., 0., 1.5, 1., 0., 0.]), + ]; // A square 100 across turned 45 degrees and squashed to a tenth of its height, with the effects stamped after the squash, or before it so the squash carries their spin let turn = DAffine2::from_angle(std::f64::consts::FRAC_PI_4); let squashed = DAffine2::from_scale(DVec2::new(1., 0.1)) * turn; - for stamped in [squashed, turn] { + for (stamped, transform) in [squashed, turn].into_iter().flat_map(|stamped| ellipses.map(|transform| (stamped, transform))) { + let spin = EffectOperation::RadialBlur { + method: RadialBlurMethod::Spin, + amount, + transform, + gamma: false, + }; let mut item = Item::new_from_element(()).with_attribute(ATTR_TRANSFORM, stamped); stamp_effect(&mut item, Effect::new(&shadow)); stamp_effect(&mut item, Effect::new(&spin)); @@ -492,7 +937,7 @@ mod tests { ]; // Where the renderers' spin, turning in the effect space, carries the corners of the content and its shadow - let blur = RadialBlur::new(RadialBlurMethod::Spin, amount, center); + let blur = RadialBlur::new(RadialBlurMethod::Spin, amount, transform); for corner in corners { for cast in [DVec2::ZERO, shadow_offset(angle, distance)] { let point = space.inverse().transform_point2(corner) + cast; @@ -500,8 +945,8 @@ mod tests { let spun = space.transform_point2(blur.point_along(point, step as f64 / 200. - 0.5)); for reach in reaches { assert!( - spun.cmpge(bounds[0] - reach).all() && spun.cmple(bounds[1] + reach).all(), - "stamped at {stamped}, the spin carries the corner {corner} cast {cast} away to {spun}, past the reach of {reach} around {bounds:?}" + spun.cmpge(bounds[0] - reach - 1e-9).all() && spun.cmple(bounds[1] + reach + 1e-9).all(), + "stamped at {stamped} about {transform}, the spin carries the corner {corner} cast {cast} away to {spun}, past the reach of {reach} around {bounds:?}" ); } } @@ -516,7 +961,7 @@ mod tests { Effects::from_operations([EffectOperation::RadialBlur { method, amount: 360., - center, + transform: DAffine2::from_translation(center), gamma: false, }]) }; @@ -549,4 +994,431 @@ mod tests { let zoom = radial(RadialBlurMethod::Zoom, DVec2::splat(50.)); assert!((reach(&zoom, DAffine2::IDENTITY, 100.).x - 9. * half_diagonal).abs() < 1e-6); } + + #[test] + fn spins_follow_the_ellipses_of_their_transform_whatever_its_size() { + let center = DVec2::new(20., -10.); + let oblong = DAffine2::from_translation(center) * DAffine2::from_angle(0.5) * DAffine2::from_scale(DVec2::new(4., 1.)); + let spin = |transform| RadialBlur::new(RadialBlurMethod::Spin, 90., transform); + let point = DVec2::new(35., 4.); + + // Each point's arc keeps to the ellipse through it, the circle through it in the transform's space + let on_ellipse = |point: DVec2| oblong.inverse().transform_point2(point).length(); + for along in [-0.5, -0.2, 0.3, 0.5] { + let moved = spin(oblong).point_along(point, along); + assert!((on_ellipse(moved) - on_ellipse(point)).abs() < 1e-9, "{point} moves off its ellipse to {moved}"); + } + + // Scaling the transform evenly changes nothing, and a round transform spins as a center alone did + let scaled = oblong * DAffine2::from_scale(DVec2::splat(7.5)); + let round = DAffine2::from_translation(center) * DAffine2::from_angle(1.) * DAffine2::from_scale(DVec2::splat(30.)); + for along in [-0.5, 0.25] { + assert!((spin(scaled).point_along(point, along) - spin(oblong).point_along(point, along)).length() < 1e-9); + let turned = center + DVec2::from_angle(std::f64::consts::FRAC_PI_2 * along).rotate(point - center); + assert!((spin(round).point_along(point, along) - turned).length() < 1e-9); + } + assert_eq!(spin(scaled).sample_count(point, 2.), spin(oblong).sample_count(point, 2.)); + + // Lines through the center stay lines through it in any linear space, so a zoom takes only the center + let zoom = |transform| RadialBlur::new(RadialBlurMethod::Zoom, 100., transform); + assert_eq!(zoom(oblong).point_along(point, 0.4), zoom(DAffine2::from_translation(center)).point_along(point, 0.4)); + } + + #[test] + fn warps_reach_as_far_as_their_ellipse_or_square_lies_past_the_content() { + let reach = |operation: EffectOperation| Effects::from_operations([operation]).reach_around(DAffine2::IDENTITY, [DVec2::ZERO, DVec2::splat(100.)], 0.).x; + let twirl = |transform| EffectOperation::Twirl { angle: 90., transform }; + let unwrap = |transform| EffectOperation::PolarCoordinates { inverse: true, transform }; + + // On the frame of content 100 across, nothing is painted past it + let on_frame = DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_scale(DVec2::splat(100.)); + assert!(reach(twirl(on_frame)) < 1e-9 && reach(unwrap(on_frame)) < 1e-9); + + // Twice as large, the ellipse reaches 50 past the content's sides, as a polygon around it bounds it, and the square reaches as far as its corners + let twice = DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_scale(DVec2::splat(200.)); + let twirled = reach(twirl(twice)); + assert!((50. - 1e-9..50.5).contains(&twirled), "the twirl reaches {twirled}"); + assert!((reach(unwrap(twice)) - 50. * std::f64::consts::SQRT_2).abs() < 1e-9); + + // The identity places a circle 1 across at the content's corner, and a transform collapsing it onto a line paints nothing, which changes nothing unless it clears what's outside + assert!(reach(twirl(DAffine2::IDENTITY)) < 0.51); + let collapsed = DAffine2::from_scale(DVec2::new(100., 0.)); + assert!(twirl(collapsed).changes_nothing() && reach(twirl(collapsed)) == 0.); + assert!(!unwrap(collapsed).changes_nothing() && reach(unwrap(collapsed)) == 0.); + + // A band bends only across its rows, so upright or turned a quarter, one as wide as the content paints nothing past it however short its square, and one twice as wide reaches 50 past its sides + let band = |width: f64, angle: f64| EffectOperation::Spherize { + amount: 100., + cylindrical: true, + transform: DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_angle(angle) * DAffine2::from_scale(DVec2::new(width, 20.)), + }; + for angle in [0., std::f64::consts::FRAC_PI_2] { + assert!(reach(band(100., angle)) < 1e-9); + assert!((reach(band(200., angle)) - 50.).abs() < 1e-9); + } + } + + #[test] + fn squares_collapsed_onto_a_line_stay_collapsed_in_a_turned_space() { + // A square of no area, which turning leaves a rounding residue of area in + let singular = DAffine2::from_cols_array(&[100., 200., 300., 600., 0., 0.]); + let turned = DAffine2::from_angle(0.1); + assert!(warp_frame(singular, turned).is_none()); + + // Polar Coordinates clears everything there, reading nothing past the view and painting nothing past the content + let visible = [DVec2::ZERO, DVec2::splat(100.)]; + for inverse in [false, true] { + let polar = Effects::from_operations([EffectOperation::PolarCoordinates { inverse, transform: singular }]); + assert_eq!(polar.source_region(visible, turned), Some(visible)); + assert_eq!(polar.reach_around(turned, visible, 0.), DVec2::ZERO); + } + } + + #[test] + fn warps_read_nothing_more_for_a_view_missing_their_frame() { + // A view 100 across, with each warp's square 100 across lying far to its left + let visible = [DVec2::ZERO, DVec2::splat(100.)]; + let far_left = DAffine2::from_translation(DVec2::new(-9950., 50.)) * DAffine2::from_scale(DVec2::splat(100.)); + let warps = [ + EffectOperation::Twirl { angle: 90., transform: far_left }, + EffectOperation::Pinch { amount: 1000., transform: far_left }, + EffectOperation::Spherize { + amount: -300., + cylindrical: false, + transform: far_left, + }, + EffectOperation::Spherize { + amount: 100., + cylindrical: true, + transform: far_left, + }, + EffectOperation::PolarCoordinates { inverse: false, transform: far_left }, + EffectOperation::PolarCoordinates { inverse: true, transform: far_left }, + ]; + for warp in warps { + let region = Effects::from_operations([warp.clone()]).source_region(visible, DAffine2::IDENTITY); + assert_eq!(region, Some(visible), "{warp:?} reads beyond the view"); + } + } + + /// Whether the region a warp's `operation` needs for the `visible` part of its result (with the effect space on the pixels) holds where each of many points across that part reads from. + fn source_region_holds_every_read(operation: &EffectOperation, visible: [DVec2; 2]) -> Result<(), String> { + let Some([min, max]) = Effects::from_operations([operation.clone()]).source_region(visible, DAffine2::IDENTITY) else { + return Err("no region".to_string()); + }; + let Some((warp, transform)) = FrameWarp::of(operation) else { + return Err(format!("{operation:?} is no warp")); + }; + let Some(frame) = warp_frame(transform, DAffine2::IDENTITY) else { + return Err(format!("{operation:?} collapses")); + }; + + for (x, y) in (0..=200).flat_map(|y| (0..=200).map(move |x| (x, y))) { + let point = visible[0] + (visible[1] - visible[0]) * DVec2::new(x as f64, y as f64) / 200.; + let local = frame.pixels_to_local().transform_point2(point); + let source = warp.source(local, frame.size); + // Neither Polar Coordinates past its frame, which clears, nor a point reading itself reads anything + if (matches!(warp, FrameWarp::Polar { .. }) && !frame.contains(local)) || source == local { + continue; + } + let read = frame.local_to_pixels().transform_point2(source); + if read.cmplt(min).any() || read.cmpgt(max).any() { + return Err(format!("{point} reads {read}, past the region from {min} to {max}")); + } + } + Ok(()) + } + + #[test] + fn bands_read_along_their_rows_however_far_they_run_past_the_frame() { + let visible = [DVec2::ZERO, DVec2::new(100., 1000.)]; + let band = |amount, transform| EffectOperation::Spherize { amount, cylindrical: true, transform }; + + // A band 1000 wide with its square far below the view, and one 2000 wide turned an eighth, crossing the view far from its square's middle, each bent at any strength + let upright = DAffine2::from_translation(DVec2::new(500., 2000.)) * DAffine2::from_scale(DVec2::new(1000., 10.)); + let turned = DAffine2::from_translation(DVec2::new(500., 900.)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_4) * DAffine2::from_scale(DVec2::new(2000., 4.)); + for (amount, transform) in [100., -100., -300., 400., 1000.].into_iter().flat_map(|amount| [upright, turned].map(|transform| (amount, transform))) { + if let Err(error) = source_region_holds_every_read(&band(amount, transform), visible) { + panic!("{amount} {transform}: {error}"); + } + } + } + + #[test] + fn wrapping_within_a_frame_too_thin_to_trace_reads_across_it() { + // A square a thirtieth of a pixel wide and 1000 tall, which successive traced samples across the view would cross a whole revolution apart + let unwrap = EffectOperation::PolarCoordinates { + inverse: true, + transform: DAffine2::from_translation(DVec2::new(31.5 - (2. / 63.) / 4., -400.)) * DAffine2::from_scale(DVec2::new(2. / 63., 1000.)), + }; + let visible = [DVec2::ZERO, DVec2::splat(100.)]; + if let Err(error) = source_region_holds_every_read(&unwrap, visible) { + panic!("{error}"); + } + + // The view's middle column reads from as far up as the square's middle + let Some([min, _]) = Effects::from_operations([unwrap]).source_region(visible, DAffine2::IDENTITY) else { + panic!("the wrap should read beyond the view"); + }; + assert!(min.y <= -400., "the region starts at {min}"); + + // Slanted so both its sides are long, it's as thin between its slanted sides + let slanted = EffectOperation::PolarCoordinates { + inverse: true, + transform: DAffine2::from_cols_array(&[2. / 63., 4., 0., 1000., 31.5 - (2. / 63.) / 4., -400.]), + }; + if let Err(error) = source_region_holds_every_read(&slanted, visible) { + panic!("slanted: {error}"); + } + } + + #[test] + fn wrapping_reads_across_the_seam_for_views_just_beside_it() { + // A square from 0 to 100 with its seam running straight up from its middle, and views ending just left of the seam and starting just right of it + let wrap = Effects::from_operations([EffectOperation::PolarCoordinates { + inverse: false, + transform: DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_scale(DVec2::splat(100.)), + }]); + let left = [DVec2::ZERO, DVec2::new(49.5, 100.)]; + let right = [DVec2::new(50.5, 0.), DVec2::splat(100.)]; + + // Beside the seam, each mixes in reads just inside the square's opposite side + let (Some([_, left_max]), Some([right_min, _])) = (wrap.source_region(left, DAffine2::IDENTITY), wrap.source_region(right, DAffine2::IDENTITY)) else { + panic!("the wrap should read beyond the views"); + }; + assert!(left_max.x >= 100., "the view left of the seam reads only up to {left_max}"); + assert!(right_min.x <= 0., "the view right of the seam reads only from {right_min}"); + } + + #[test] + fn wide_bands_read_only_as_far_as_they_move_the_rows_in_view() { + // A band 100,000 wide about the view's middle, which near there moves rows under a fifth of the view's width, though a fifth of its half width farther out + let band = EffectOperation::Spherize { + amount: 100., + cylindrical: true, + transform: DAffine2::from_cols_array(&[100_000., 0., 0., 100., 50., 50.]), + }; + let visible = [DVec2::ZERO, DVec2::splat(100.)]; + if let Err(error) = source_region_holds_every_read(&band, visible) { + panic!("{error}"); + } + + let Some([min, max]) = Effects::from_operations([band]).source_region(visible, DAffine2::IDENTITY) else { + panic!("the band should read beyond the view"); + }; + assert!( + min.cmpge(DVec2::splat(-25.)).all() && max.cmple(DVec2::splat(125.)).all(), + "the region from {min} to {max} reaches far past where the rows move" + ); + } + + #[test] + fn slanted_bands_read_only_as_far_as_they_move_their_rows() { + // A band 100 wide slanted almost along the view's rows, with its square far left of the view, which moves each row at most 0.21 of its half width + let band = EffectOperation::Spherize { + amount: 100., + cylindrical: true, + transform: DAffine2::from_cols_array(&[100., 0., 10_000., 100., -100_000., -1000.]), + }; + let visible = [DVec2::ZERO, DVec2::splat(100.)]; + if let Err(error) = source_region_holds_every_read(&band, visible) { + panic!("{error}"); + } + + let Some([min, max]) = Effects::from_operations([band]).source_region(visible, DAffine2::IDENTITY) else { + panic!("the band should read beyond the view"); + }; + assert!( + min.cmpge(DVec2::splat(-15.)).all() && max.cmple(DVec2::splat(115.)).all(), + "the region from {min} to {max} reaches far past where the rows move" + ); + } + + /// Pinches and spheres past full strength, which fold the content over, reading from past the ellipse or across its center, within the circle that `transform` places. + fn folding_warps(transform: DAffine2) -> [EffectOperation; 7] { + let pinch = |amount| EffectOperation::Pinch { amount, transform }; + let sphere = |amount| EffectOperation::Spherize { + amount, + cylindrical: false, + transform, + }; + [pinch(1000.), pinch(300.), pinch(-500.), pinch(-1000.), sphere(-300.), sphere(600.), sphere(1000.)] + } + + #[test] + fn warps_past_full_strength_read_from_past_their_ellipse_within_their_source_region() { + // Circles 40 across about the middle of a view 100 across, upright or turned and slanted, seen whole, across the rim's right side, off the center, or about it + let upright = DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_scale(DVec2::splat(40.)); + let slanted = DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_angle(0.7) * DAffine2::from_cols_array(&[40., 0., 15., 25., 0., 0.]); + let views = [ + [DVec2::ZERO, DVec2::splat(100.)], + [DVec2::new(62., 40.), DVec2::new(75., 60.)], + [DVec2::new(55., 55.), DVec2::new(65., 62.)], + [DVec2::new(45., 44.), DVec2::new(52., 58.)], + ]; + let full_strength = |transform| { + let sphere = EffectOperation::Spherize { + amount: -100., + cylindrical: false, + transform, + }; + [EffectOperation::Pinch { amount: 100., transform }, sphere] + }; + + for transform in [upright, slanted] { + for warp in folding_warps(transform).into_iter().chain(full_strength(transform)) { + for visible in views { + if let Err(error) = source_region_holds_every_read(&warp, visible) { + panic!("{warp:?} seen from {} to {}: {error}", visible[0], visible[1]); + } + } + } + } + + // Each reads from past the rim or across the center, along the line through it + for operation in folding_warps(upright) { + let Some((warp, _)) = FrameWarp::of(&operation) else { continue }; + let reads = (0..=1000).map(|step| warp.source(DVec2::new(step as f64 / 1000., 0.), DVec2::splat(2.)).x); + let (least, most) = reads.fold((f64::INFINITY, f64::NEG_INFINITY), |(least, most), read| (least.min(read), most.max(read))); + assert!(least < -0.1 || most > 1.1, "{operation:?} reads only from {least} to {most} of the way to the rim"); + } + } + + #[test] + fn warps_past_full_strength_read_only_as_far_as_they_move_what_is_in_view() { + // A view 100 across about the middle of a circle 100,000 across, read from no more than 10 times as far from its middle as it reaches, rather than from across the circle + let visible = [DVec2::ZERO, DVec2::splat(100.)]; + let reach = 10. * 50. * std::f64::consts::SQRT_2; + for warp in folding_warps(DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_scale(DVec2::splat(100_000.))) { + if let Err(error) = source_region_holds_every_read(&warp, visible) { + panic!("{warp:?}: {error}"); + } + + let Some([min, max]) = Effects::from_operations([warp.clone()]).source_region(visible, DAffine2::IDENTITY) else { + panic!("{warp:?} should read beyond the view"); + }; + assert!( + min.cmpge(DVec2::splat(50. - reach)).all() && max.cmple(DVec2::splat(50. + reach)).all(), + "{warp:?} reads from {min} to {max}, far past where it moves what's in view" + ); + } + } + + #[test] + fn warps_within_oblong_ellipses_read_only_as_far_as_they_move_what_is_in_view() { + // A view 100 across about the middle of an ellipse 100,000 wide and 100 tall, spanning every direction and distance from its center, where each point reads its offset from the center scaled at most as much as the center's + let visible = [DVec2::ZERO, DVec2::splat(100.)]; + let transform = DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_scale(DVec2::new(100_000., 100.)); + let sphere = |amount| EffectOperation::Spherize { + amount, + cylindrical: false, + transform, + }; + let warps_and_center_scales = [ + (EffectOperation::Pinch { amount: 1., transform }, 1. + 0.01 * PINCH_STRENGTH), + (EffectOperation::Pinch { amount: 1000., transform }, 1. + 10. * PINCH_STRENGTH), + (sphere(-50.), 1. + 0.5 * (std::f64::consts::FRAC_PI_2 - 1.)), + (sphere(600.), 1. + 6. * (std::f64::consts::FRAC_2_PI - 1.)), + ]; + + for (warp, center_scale) in warps_and_center_scales { + if let Err(error) = source_region_holds_every_read(&warp, visible) { + panic!("{warp:?}: {error}"); + } + + let Some([min, max]) = Effects::from_operations([warp.clone()]).source_region(visible, DAffine2::IDENTITY) else { + panic!("{warp:?} should read beyond the view"); + }; + let reach = 50. * f64::max(center_scale.abs(), 1.) + 1.5; + assert!( + min.cmpge(DVec2::splat(50. - reach)).all() && max.cmple(DVec2::splat(50. + reach)).all(), + "{warp:?} reads from {min} to {max}, far past where it moves what's in view" + ); + } + } + + #[test] + fn cylinders_turned_a_quarter_bend_columns_within_a_band_as_tall_as_the_frame() { + let transform = DAffine2::from_translation(DVec2::new(30., -20.)) * DAffine2::from_angle(0.4) * DAffine2::from_scale(DVec2::new(80., 50.)); + let quarter_turned = transform * DAffine2::from_angle(std::f64::consts::FRAC_PI_2); + let (Some(frame), Some(turned_frame)) = (warp_frame(transform, DAffine2::IDENTITY), warp_frame(quarter_turned, DAffine2::IDENTITY)) else { + panic!("neither frame collapses"); + }; + + for amount in [1., -0.6] { + let cylinder = FrameWarp::Spherize { amount, cylindrical: true }; + + // Each column within a band as tall as the unturned frame, running endlessly across, bends along itself + let bent_column = |point: DVec2| { + let local = frame.pixels_to_local().transform_point2(point); + let half = frame.size / 2.; + let normalized = local.y / half.y; + let source = match normalized.abs() < 1. { + true => DVec2::new(local.x, spherize_bend(normalized.abs(), amount).copysign(normalized) * half.y), + false => local, + }; + frame.local_to_pixels().transform_point2(source) + }; + + for (x, y) in (-20..=20).flat_map(|y| (-20..=20).map(move |x| (x, y))) { + let point = DVec2::new(x as f64, y as f64) * 7.3; + let local = turned_frame.pixels_to_local().transform_point2(point); + let read = turned_frame.local_to_pixels().transform_point2(cylinder.source(local, turned_frame.size)); + let expected = bent_column(point); + assert!((read - expected).length() < 1e-6, "{amount}: {point} reads {read} rather than {expected}"); + } + } + } + + #[test] + fn radial_blurs_reach_a_finite_distance_about_extremely_oblong_ellipses() { + let corners = [DVec2::ZERO, DVec2::new(100., 0.), DVec2::splat(100.), DVec2::new(0., 100.)]; + let blur = RadialBlur::new(RadialBlurMethod::Spin, 90., DAffine2::from_scale(DVec2::new(2e8, 1.))); + for painted in [0., 5.] { + let reach = blur.reach_around(corners, painted); + assert!(reach.is_finite(), "reaches {reach} past what's painted {painted} past the content"); + } + } + + #[test] + fn twirls_turn_the_ellipse_in_the_frame_as_if_it_were_a_circle() { + let warp = FrameWarp::Twirl { angle: std::f64::consts::FRAC_PI_2 }; + let size = DVec2::new(200., 100.); + + // Past the ellipse inscribed in the frame nothing turns, and halfway out the turn is a quarter of the full angle, squashed with the ellipse + assert_eq!(warp.source(DVec2::new(70., 40.), size), DVec2::new(70., 40.)); + let source = warp.source(DVec2::new(50., 0.), size); + let turned = DVec2::from_angle(-std::f64::consts::FRAC_PI_8) * 0.5 * size / 2.; + assert!((source - turned).length() < 1e-9, "{source}"); + + // For PSD interop, a radian turns 57 degrees + assert!((twirl_angle_from_psd(57) - 1_f64.to_degrees()).abs() < 1e-9); + } + + #[test] + fn pinches_read_farthest_out_at_the_center() { + let warp = FrameWarp::Pinch { amount: 1. }; + let size = DVec2::splat(200.); + + let near_center = DVec2::new(1., 0.); + let source = warp.source(near_center, size); + assert!((source.x - (1. + PINCH_STRENGTH * (1. - 1e-4_f64).powi(2))).abs() < 1e-9, "{source}"); + assert_eq!(warp.source(DVec2::new(80., 70.), size), DVec2::new(80., 70.)); + } + + #[test] + fn polar_coordinates_wrap_and_unwrap_as_inverses() { + let size = DVec2::new(100., 80.); + let wrap = FrameWarp::Polar { inverse: false }; + let unwrap = FrameWarp::Polar { inverse: true }; + + // The center shows the top edge, straight down from it the middle, and to its right three quarters across + assert!((wrap.source(DVec2::ZERO, size).y + 40.).abs() < 1e-9); + assert!(wrap.source(DVec2::new(0., 20.), size).x.abs() < 1e-9); + assert!((wrap.source(DVec2::new(25., 0.), size).x - 25.).abs() < 1e-9); + for point in [DVec2::new(10., -20.), DVec2::new(-30., 15.), DVec2::new(45., 39.)] { + let round_trip = wrap.source(unwrap.source(point, size), size); + assert!((round_trip - point).length() < 1e-9, "{point} comes back as {round_trip}"); + } + } } diff --git a/node-graph/libraries/raster-kernels/src/filter_kernels.rs b/node-graph/libraries/raster-kernels/src/filter_kernels.rs index 5e64604d9f..fa7003c2bf 100644 --- a/node-graph/libraries/raster-kernels/src/filter_kernels.rs +++ b/node-graph/libraries/raster-kernels/src/filter_kernels.rs @@ -1,13 +1,13 @@ //! 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::generators::pcg3d; use glam::{DAffine2, DMat2, DVec2, IVec2}; use graphic_types::effects::spans_along_axes; use graphic_types::filters::{ Convolution, FieldSampling, GAUSSIAN_NOISE_LIMIT, HIGH_PASS_GRAY, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, average_weight, edge_gain, fill_shifts, neighborhood_radii, noise_extent, unsharp, unsharp_change, }; +use graphic_types::generator::pcg3d; use graphic_types::{EffectOperation, MinimumMaximumMode}; use raster_types::parallel_rows::fill_rows; diff --git a/node-graph/libraries/raster-kernels/src/generators.rs b/node-graph/libraries/raster-kernels/src/generators.rs index f4bdbddc36..44c85763f6 100644 --- a/node-graph/libraries/raster-kernels/src/generators.rs +++ b/node-graph/libraries/raster-kernels/src/generators.rs @@ -3,7 +3,7 @@ use crate::mandelbrot::{MandelbrotSetup, resolves_in_32_bits}; use core_types::Color; use glam::{DVec2, IVec2}; -use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType}; +use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType, hash_fraction, pcg3d}; use raster_types::parallel_rows::fill_rows; use raster_types::{Image, ImageError}; @@ -170,22 +170,7 @@ impl NoiseSampler { /// A random value from 0 to 1 for each cell of a grid, the same for the same seed and cell. In 32-bit math, which a GPU can match. fn white_noise(seed: i32, cell: IVec2) -> f32 { let [hash, _, _] = pcg3d([cell.x as u32, cell.y as u32, seed as u32]); - - // The top 24 bits, which an f32 holds exactly - (hash >> 8) as f32 / (1_u32 << 24) as f32 -} - -/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result. -pub(crate) fn pcg3d(input: [u32; 3]) -> [u32; 3] { - let mix = |[x, y, z]: [u32; 3]| { - let x = x.wrapping_add(y.wrapping_mul(z)); - let y = y.wrapping_add(z.wrapping_mul(x)); - let z = z.wrapping_add(x.wrapping_mul(y)); - [x, y, z] - }; - - let v = mix(input.map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223))); - mix(v.map(|value| value ^ (value >> 16))) + hash_fraction(hash) } #[cfg(test)] diff --git a/node-graph/libraries/raster-kernels/src/raster_effects.rs b/node-graph/libraries/raster-kernels/src/raster_effects.rs index c3948afba2..44a112051d 100644 --- a/node-graph/libraries/raster-kernels/src/raster_effects.rs +++ b/node-graph/libraries/raster-kernels/src/raster_effects.rs @@ -7,7 +7,7 @@ use crate::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH use crate::generators::pattern_sampler; use crate::layer_blending::blend_layer; use crate::masks::{feather_strength, mask_strength, masked, masked_box_blur_luminances, masked_radius_blur, masked_radius_blur_codes, variable_box_blur}; -use crate::resample_kernels::{MotionBlurShear, motion_blurred, radial_blurred}; +use crate::resample_kernels::{MotionBlurShear, frame_warped, motion_blurred, radial_blurred}; use crate::value_effects::{adjustments, evaluate_gradient_effects, filled_color}; use core_types::FallibleVec2Operations; use core_types::blending::BlendMode; @@ -26,7 +26,7 @@ use graphic_types::effects::{ use graphic_types::filters::sharpens_coverage; use graphic_types::generator::GeneratorPattern; use graphic_types::masks::masked_radius_blur_levels; -use graphic_types::resampling::RadialBlur; +use graphic_types::resampling::{FrameWarp, RadialBlur, warp_frame}; use raster_types::parallel_rows::fill_rows; use raster_types::{CPU, Image, Raster}; use std::collections::HashMap; @@ -170,6 +170,9 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: // Delete this baking once its callers read back the GPU's renders, which are exact. let pixels_per_length = spans_along_axes(effect_to_pixels); + // The effect space placed on the plane, past its margin + let effect_to_plane = DAffine2::from_translation(DVec2::new(margin_x as f64, margin_y as f64)) * DAffine2::from_mat2(effect_to_pixels); + // A layered effect's coverages become pieces, which the content knocks out once its layer is drawn, and a flattened one is knocked out by the faded content now let layered = index >= layers.flattened; let piece = |plane: usize| layered.then_some(EffectCapture { index, plane }); @@ -516,20 +519,38 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: full = in_light(full, !gamma, |plane| motion_blurred(&plane, &shear)); filled = filled.map(|filled| in_light(filled, !gamma, |plane| motion_blurred(&plane, &shear))); } - EffectOperation::RadialBlur { method, amount, center, gamma } => { + EffectOperation::RadialBlur { method, amount, transform, gamma } => { if !effect_to_pixels.determinant().is_normal() { continue; } // The effect space's origin is the content's, at the image's corner past the margin - let effect_to_plane = DAffine2::from_translation(DVec2::new(margin_x as f64, margin_y as f64)) * DAffine2::from_mat2(effect_to_pixels); - let blur = RadialBlur::new(method, amount, center); + let blur = RadialBlur::new(method, amount, transform); let pixels_per_length = effect_to_pixels.determinant().abs().sqrt(); merge_beneath(&mut full, &mut filled, &mut beneath); full = in_light(full, !gamma, |plane| radial_blurred(&plane, &blur, effect_to_plane, pixels_per_length)); filled = filled.map(|filled| in_light(filled, !gamma, |plane| radial_blurred(&plane, &blur, effect_to_plane, pixels_per_length))); } + EffectOperation::Twirl { .. } | EffectOperation::Pinch { .. } | EffectOperation::Spherize { .. } | EffectOperation::PolarCoordinates { .. } => { + // The frame the warp's transform places from the content's origin, at the image's corner past the margin + let Some((warp, transform)) = FrameWarp::of(operation) else { continue }; + let square = warp_frame(transform, effect_to_plane); + let clears = matches!(warp, FrameWarp::Polar { .. }); + if square.is_none() && !clears { + continue; + } + + merge_beneath(&mut full, &mut filled, &mut beneath); + + // Where its square collapses, Polar Coordinates clears everything + let warped = |plane: &Plane<[f32; 4]>| match &square { + Some(square) => frame_warped(plane, &warp, square), + None => Plane::new(plane.width, plane.height), + }; + full = warped(&full); + filled = filled.map(|filled| warped(&filled)); + } EffectOperation::Adjustment(ref adjustment) => { merge_beneath(&mut full, &mut filled, &mut beneath); full = adjust(&full, adjustment); @@ -1332,12 +1353,18 @@ mod tests { distance: 7., gamma: false, }; - let spin = EffectOperation::RadialBlur { + let spin = |transform| EffectOperation::RadialBlur { method: graphic_types::RadialBlurMethod::Spin, amount: 20., - center: DVec2::new(14.4, 10.8), + transform, gamma: false, }; + let center = DAffine2::from_translation(DVec2::new(14.4, 10.8)); + let oblong = center * DAffine2::from_angle(0.4) * DAffine2::from_scale(DVec2::new(3., 1.)); + let twirl = EffectOperation::Twirl { + angle: 90., + transform: DAffine2::from_translation(DVec2::splat(12.)) * DAffine2::from_scale(DVec2::new(16., 10.)), + }; // A white square in the middle of a black image, with the blur stamped before a later transform places it let placement = DAffine2::from_translation(DVec2::new(3.3, -7.6)) * DAffine2::from_scale(DVec2::splat(24.)); @@ -1351,7 +1378,7 @@ mod tests { }; // Each of the image's pixels blurs alike however the later transform scales and turns it - for operation in [motion, spin] { + for operation in [motion, spin(center), spin(oblong), twirl] { let still = evaluated(&operation, DAffine2::IDENTITY); for later in [DAffine2::from_scale(DVec2::splat(3.)), DAffine2::from_angle(0.7)] { let placed = evaluated(&operation, later); @@ -1370,7 +1397,7 @@ mod tests { let spin = EffectOperation::RadialBlur { method: graphic_types::RadialBlurMethod::Spin, amount: 90., - center: DVec2::splat(5.5), + transform: DAffine2::from_translation(DVec2::splat(5.5)), gamma: false, }; let evaluated = |stamped_at: DAffine2, placed_at: DAffine2| { @@ -1637,6 +1664,46 @@ mod tests { assert_eq!(adjusted(&[emptied, Adjustment::MakeOpaque]), [[0.; 4]; 3]); } + #[test] + fn rows_that_change_nothing_leave_the_effects_around_them_as_they_are() { + use graphic_types::EffectKind; + + let evaluate = |operations: Vec| { + let item = Item::new_from_element(Raster::new_cpu(Image::new(16, 16, Color::WHITE))) + .with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(16.))) + .with_attribute(ATTR_EFFECTS, Effects::from_operations(operations)); + evaluate_raster_effects(item).element().data.clone() + }; + let shadow = EffectOperation::default_for(EffectKind::DropShadow); + let inner_shadow = EffectOperation::default_for(EffectKind::InnerShadow); + let blur = EffectOperation::Blur { + radius_mask: Default::default(), + radius: 2., + box_blur: false, + gamma: false, + }; + + // The shadow stays beneath the content until the blur, so the inner shadow casts from the content alone + let expected = evaluate(vec![shadow.clone(), inner_shadow.clone(), blur.clone()]); + let minimum = EffectOperation::MinimumMaximum { + radius: 0., + mode: graphic_types::MinimumMaximumMode::Minimum, + }; + // A twirl through no angle, or within a circle collapsed onto a line + let still_twirl = EffectOperation::Twirl { + angle: 0., + transform: DAffine2::from_scale(DVec2::splat(10.)), + }; + let flat_twirl = EffectOperation::Twirl { + angle: 90., + transform: DAffine2::from_scale(DVec2::new(10., 0.)), + }; + for nothing in [minimum, still_twirl, flat_twirl] { + let actual = evaluate(vec![shadow.clone(), nothing.clone(), inner_shadow.clone(), blur.clone()]); + assert!(actual == expected, "{nothing:?} changed the result"); + } + } + #[test] fn interior_pieces_stack_within_the_contents_share_over_nothing() { use crate::layer_blending::blend_pixel; @@ -1673,4 +1740,26 @@ mod tests { assert!(close, "{blend_mode:?} at fill {fill}: {:?} against {expected:?} at {expected_alpha}", [red, green, blue, actual_alpha]); } } + + #[test] + fn wrapping_holds_up_on_rasters_one_pixel_across() { + // Wrapping within the square of the raster's own frame + let wrap = EffectOperation::PolarCoordinates { + inverse: false, + transform: DAffine2::from_translation(DVec2::splat(0.5)), + }; + + // Strips at scales and turns where roundoff can put half a pixel past half the frame + for (width, height) in [(1, 7), (7, 1)] { + for index in 0..40 { + let size = DVec2::new(width as f64, height as f64) * (0.3 + index as f64 * 0.71); + let transform = DAffine2::from_scale_angle_translation(size, index as f64 * 0.37, DVec2::new(index as f64 * 1.3, -2.1)); + let item = Item::new_from_element(Raster::new_cpu(Image::new(width, height, Color::WHITE))) + .with_attribute(ATTR_TRANSFORM, transform) + .with_attribute(ATTR_EFFECTS, Effects::from_operations([wrap.clone()])); + let evaluated = evaluate_raster_effects(item); + assert!(evaluated.element().data.iter().all(|color| color.a().is_finite()), "{width} by {height} at {index}"); + } + } + } } diff --git a/node-graph/libraries/raster-kernels/src/resample_kernels.rs b/node-graph/libraries/raster-kernels/src/resample_kernels.rs index 9c9dea7da2..9cd7d39ff1 100644 --- a/node-graph/libraries/raster-kernels/src/resample_kernels.rs +++ b/node-graph/libraries/raster-kernels/src/resample_kernels.rs @@ -1,11 +1,193 @@ -//! The effects that resample the content from elsewhere than nearby, on the CPU: blurs along lines and arcs. +//! The effects that resample the content from elsewhere than nearby, on the CPU: blurs along lines and arcs, and warps. //! They mirror the renderer's GPU passes, sampling between pixels the same way. use crate::effect_kernels::Plane; use glam::{DAffine2, DMat2, DVec2}; -use graphic_types::resampling::RadialBlur; +use graphic_types::resampling::{EffectFrame, FrameWarp, RadialBlur}; use raster_types::parallel_rows::fill_rows; +/// Frame coverage below this is roundoff at a side that a pixel only touches. +const NEGLIGIBLE_COVERAGE: f64 = 1. / 65_536.; + +/// Frame coverage below this, which no content shows through and single-precision placements can round to, counts as none for the reads leaving out what the frame touches. +const UNTOUCHED_COVERAGE: f64 = 1. / 256.; + +/// How much of a pixel centered at `local` the frame (`half` its size) covers along each of its axes, ramping from 1 at `half_pixel` within a side to 0 at `half_pixel` past it. +fn frame_coverage(local: DVec2, half: DVec2, half_pixel: DVec2) -> DVec2 { + (0.5 + (half - local.abs()) / (2. * half_pixel)).clamp(DVec2::ZERO, DVec2::ONE) +} + +/// A plane the size of `plane` with each pixel within the `frame` set to `inside` at its position in the frame's local space (clamped into it), and each other pixel cleared. +/// A pixel the frame's edge cuts through fades by how much of it the frame covers. +fn across_frame(plane: &Plane<[f32; 4]>, frame: &EffectFrame, inside: impl Fn(DVec2) -> [f32; 4] + Sync) -> Plane<[f32; 4]> { + let (half, half_pixel) = (frame.size / 2., frame.half_pixel()); + in_local_space(plane, frame, |local, _| { + let coverage = frame_coverage(local, half, half_pixel).element_product(); + if coverage < NEGLIGIBLE_COVERAGE { + return [0.; 4]; + } + inside(local.clamp(-half, half)).map(|channel| channel * coverage as f32) + }) +} + +/// The premultiplied pixel at a `point` in pixels interpolated as [`sample_bilinear`] does, but only between the pixels on the `frame`'s side of its edge, which it covers wholly. +/// The pixels its edge cuts through hold the content's own edge, so the reads leave them out. Where all four are, as at a corner, the nearest pixel on that side stands in. +/// Content too thin to cover any pixel wholly is instead unmixed from the transparency beside it in the pixels the frame touches, which may need [`held_at_opaque`] afterward. +fn sample_bilinear_on_side(plane: &Plane<[f32; 4]>, point: DVec2, frame: &EffectFrame) -> [f32; 4] { + let (to_local, half, extent) = (frame.pixels_to_local(), frame.size / 2., frame.pixel_extent()); + let on_side = |pixel: DVec2| frame_coverage(to_local.transform_point2(pixel + 0.5), half, extent).element_product() > 1. - UNTOUCHED_COVERAGE; + let color_at = |pixel: DVec2| pixel_or_transparent(plane, pixel); + let position = point - 0.5; + let base = position.floor(); + let fraction = (position - base).as_vec2(); + let corners = [DVec2::ZERO, DVec2::X, DVec2::Y, DVec2::ONE].map(|offset| { + let weights = (1. - fraction) + (2. * fraction - 1.) * offset.as_vec2(); + (base + offset, weights.x * weights.y) + }); + + let (mut sum, mut total) = ([0.; 4], 0.); + for (pixel, weight) in corners { + if weight <= 0. || !on_side(pixel) { + continue; + } + + let color = color_at(pixel); + sum = std::array::from_fn(|channel| sum[channel] + color[channel] * weight); + total += weight; + } + if total > 0. { + return sum.map(|channel| channel / total); + } + + if let Some(pixel) = nearest_around(point, on_side) { + return color_at(pixel); + } + + // The frame touches a pixel unless an axis of either separates them: the frame's, along which the pixel reaches its extent, or the pixel's, along which the frame spans its bounding box + let to_pixels = frame.local_to_pixels(); + let box_reach = to_pixels.matrix2.x_axis.abs() * half.x + to_pixels.matrix2.y_axis.abs() * half.y; + let touches = |pixel: DVec2| { + let along_frame = frame_coverage(to_local.transform_point2(pixel + 0.5), half, extent); + let along_pixels = frame_coverage(pixel + 0.5 - to_pixels.translation, box_reach, DVec2::splat(0.5)); + along_frame.min(along_pixels).min_element() >= UNTOUCHED_COVERAGE + }; + + // Each pixel the frame touches mixes the content with the transparency beside it by its coverage, so that mix is undone + let half_pixel = frame.half_pixel(); + let (mut sum, mut covered) = ([0.; 4], 0.); + for (pixel, weight) in corners { + if !touches(pixel) { + continue; + } + + let color = color_at(pixel); + sum = std::array::from_fn(|channel| sum[channel] + color[channel] * weight); + covered += frame_coverage(to_local.transform_point2(pixel + 0.5), half, half_pixel).element_product() as f32 * weight; + } + if covered <= 0. { + return [0.; 4]; + } + + sum.map(|channel| channel / covered) +} + +/// The premultiplied pixel of `plane` with its corner at `pixel`, or transparency past its edges. +fn pixel_or_transparent(plane: &Plane<[f32; 4]>, pixel: DVec2) -> [f32; 4] { + let (x, y) = (pixel.x as i64, pixel.y as i64); + let in_plane = x >= 0 && y >= 0 && (x as usize) < plane.width && (y as usize) < plane.height; + if in_plane { plane.data[y as usize * plane.width + x as usize] } else { [0.; 4] } +} + +/// The corner of the pixel nearest a `point` in pixels that `accepts` takes, among the 16 around the point, the first of those equally near. +fn nearest_around(point: DVec2, accepts: impl Fn(DVec2) -> bool) -> Option { + let base = (point - 0.5).floor(); + let around = (-1..=2).flat_map(|y| (-1..=2).map(move |x| base + DVec2::new(x as f64, y as f64))); + around + .filter(|&pixel| accepts(pixel)) + .min_by(|a, b| (*a + 0.5).distance_squared(point).total_cmp(&(*b + 0.5).distance_squared(point))) +} + +/// Premultiplied channels kept from going negative, scaled down to opaque past it, and with the color held within the alpha, as undoing a mix with what lies beside the content can overshoot. +fn held_at_opaque(color: [f32; 4]) -> [f32; 4] { + let kept = color.map(|channel| channel.max(0.)); + let scaled = kept.map(|channel| channel / kept[3].max(1.)); + scaled.map(|channel| channel.min(scaled[3])) +} + +/// A plane the size of `plane` with each pixel set to `value` at its position in the `frame`'s local space and its index. +fn in_local_space(plane: &Plane<[f32; 4]>, frame: &EffectFrame, value: impl Fn(DVec2, usize) -> [f32; 4] + Sync) -> Plane<[f32; 4]> { + let to_local = frame.pixels_to_local(); + + 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() { + *pixel = value(to_local.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)), y * plane.width + x); + } + }); + result +} + +/// The plane warped by a warp relative to the `frame`, which bends what earlier effects painted along with the content. O(width × height). +/// Polar Coordinates swaps the frame and its inscribed disc, so it reads only the pixels the frame covers wholly and clears what lies outside it. +pub fn frame_warped(plane: &Plane<[f32; 4]>, warp: &FrameWarp, frame: &EffectFrame) -> Plane<[f32; 4]> { + let (to_pixels, half_pixel) = (frame.local_to_pixels(), frame.half_pixel()); + let half = frame.size / 2.; + + let FrameWarp::Polar { inverse } = *warp else { + return in_local_space(plane, frame, |local, index| match warp.source(local, frame.size) { + source if source == local => plane.data[index], + source => sample_bilinear(plane, to_pixels.transform_point2(source)), + }); + }; + + // The reads lie a pixel's extent in from the frame's sides, which a turned pixel reaches farther along than half a pixel + let inset = frame.pixel_extent().min(half); + let sample_within = |local: DVec2| sample_bilinear_on_side(plane, to_pixels.transform_point2(local), frame); + let converted = |local: DVec2| { + let source = warp.source(local, frame.size); + + // Wrapping meets the frame's left and right sides at the seam straight up from the center, so it reads across them + let read = match inverse { + true => sample_within(source.clamp(-half + inset, half - inset)), + false => { + let [near, far, toward_far] = wrapped_across_sides(source, half, inset); + let near_read = sample_within(near); + if toward_far.x > 0. { + mix(near_read, sample_within(DVec2::new(far.x, near.y)), toward_far.x) + } else { + near_read + } + } + }; + + // Only wrapping's rim fades, where its source passes the bottom side, since unwrapping reads within the inscribed disc and wrapping gathers the top side at the center + let fade = match inverse { + true => 1., + false => (0.5 + (half.y - source.y) / (2. * half_pixel.y)).clamp(0., 1.), + }; + held_at_opaque(read).map(|channel| channel * fade as f32) + }; + across_frame(plane, frame, converted) +} + +/// For a source `wrapped` into a frame (`half` its size), the point just inside the side it's nearest and just inside the opposite side (`inset` in from them), along each axis, +/// and how far toward the opposite one to mix them: 0 past `inset` from the sides, rising to an even mix at a side. +fn wrapped_across_sides(wrapped: DVec2, half: DVec2, inset: DVec2) -> [DVec2; 3] { + let (low, high) = (-half + inset, half - inset); + let above = wrapped.cmpgt(high); + let below = wrapped.cmplt(low); + + let near = DVec2::select(above, high, DVec2::select(below, low, wrapped)); + let far = DVec2::select(above, low, DVec2::select(below, high, wrapped)); + let toward_far = DVec2::select(above, (wrapped - high) / (2. * inset), DVec2::select(below, (low - wrapped) / (2. * inset), DVec2::ZERO)); + [near, far, toward_far] +} + +/// Premultiplied channels from `a` to `b` by `t`. +fn mix(a: [f32; 4], b: [f32; 4], t: f64) -> [f32; 4] { + std::array::from_fn(|channel| a[channel] + (b[channel] - a[channel]) * t as f32) +} + /// The most samples a motion blur's box averages along its line at each pixel, past which its samples spread out evenly to cover it. pub const MAX_MOTION_BLUR_SAMPLES: f64 = 1024.; @@ -26,10 +208,10 @@ pub struct MotionBlurShear { } impl MotionBlurShear { - /// The shears of a line `distance` long at `angle` (in degrees counterclockwise from the right), both in the effect space, given the map from its lengths into pixels, measured from `anchor` (in pixels). + /// The shears of a line `distance` long (ignoring its sign) at `angle` (in degrees counterclockwise from the right), both in the effect space, given the map from its lengths into pixels, measured from `anchor` (in pixels). pub fn new(angle: f64, distance: f64, lengths_to_pixels: DMat2, anchor: DVec2) -> Option { let angle = angle.to_radians(); - let line = DVec2::new(angle.cos(), -angle.sin()) * distance.max(0.); + let line = DVec2::new(angle.cos(), -angle.sin()) * distance.abs(); let end = lengths_to_pixels * line; // For PSD interop, a diagonal runs along the effect space's x axis, and in the pixels, along whichever axis that one lies nearer, so opposite and turned lines agree @@ -226,6 +408,13 @@ mod tests { move |x, y| blurred.data[y * 41 + x][3] } + #[test] + fn overshot_unmixing_is_held_to_valid_premultiplied_channels() { + assert_eq!(held_at_opaque([0.3, -0.1, 0.2, -0.2]), [0.; 4]); + assert_eq!(held_at_opaque([0.6, 0.2, 0.1, 0.4]), [0.4, 0.2, 0.1, 0.4]); + assert_eq!(held_at_opaque([1.5, 0.5, 1., 2.]), [0.75, 0.25, 0.5, 1.]); + } + #[test] fn boxes_span_one_pixel_more_than_the_line_leaning_forward_at_odd_lengths() { assert_eq!(shear(0., 10.).box_span(), [-5.5, 5.5]); @@ -364,6 +553,179 @@ mod tests { assert!((total - 5001.).abs() < 0.01); } + #[test] + fn negative_distances_smear_as_positive_ones_do() { + use graphic_types::EffectOperation; + + // Through turned and unevenly scaled pixels, measured from an anchor off their corner + let lengths_to_pixels = DMat2::from_angle(0.3) * DMat2::from_diagonal(DVec2::new(1.5, 0.8)); + let anchor = DVec2::new(3.2, -1.); + let blur = |angle, distance| EffectOperation::MotionBlur { angle, distance, gamma: false }; + for (angle, distance) in [(0., 12.), (30., 7.5), (-70., 90.)] { + let shears = [distance, -distance].map(|distance| MotionBlurShear::new(angle, distance, lengths_to_pixels, anchor)); + assert_eq!(shears[0], shears[1], "lines {distance} long at {angle} degrees shear differently"); + + assert!(!blur(angle, -distance).changes_nothing()); + assert_eq!(blur(angle, -distance).reach(), blur(angle, distance).reach()); + } + assert!(blur(0., 0.).changes_nothing()); + } + + /// The warp an operation carries out, in the frame its transform places in a plane with a pixel to each unit of the effect space. + fn warp_in_plane(operation: &graphic_types::EffectOperation) -> (FrameWarp, EffectFrame) { + let (warp, transform) = FrameWarp::of(operation).unwrap(); + (warp, graphic_types::resampling::warp_frame(transform, glam::DAffine2::IDENTITY).unwrap()) + } + + #[test] + fn warps_read_transparency_past_their_frame() { + use glam::DAffine2; + use graphic_types::EffectOperation; + + // Opaque paint fills a plane wider than the square from 5 to 25, below which wrapping reads for the corners past its inscribed ellipse + let mut plane = Plane::<[f32; 4]>::new(30, 30); + plane.data = vec![[1.; 4]; 30 * 30]; + let wrap = EffectOperation::PolarCoordinates { + inverse: false, + transform: DAffine2::from_translation(DVec2::splat(15.)) * DAffine2::from_scale(DVec2::splat(20.)), + }; + let (warp, frame) = warp_in_plane(&wrap); + let wrapped = frame_warped(&plane, &warp, &frame); + + assert_eq!(wrapped.data[5 * 30 + 5][3], 0., "the frame's corner reads past it"); + assert!(wrapped.data[15 * 30 + 15][3] > 0.99, "the center reads the frame's top row"); + assert_eq!(wrapped.data[0], [0.; 4], "what lies outside the frame is cleared"); + + // Unwrapping across a square from 5.5 to 24.5 fills it, half covering the pixels its sides cut through and clearing those beyond + let unwrap = EffectOperation::PolarCoordinates { + inverse: true, + transform: DAffine2::from_translation(DVec2::splat(15.)) * DAffine2::from_scale(DVec2::splat(19.)), + }; + let (warp, frame) = warp_in_plane(&unwrap); + let unwrapped = frame_warped(&plane, &warp, &frame); + let [beyond, edge, within] = [4, 5, 6].map(|x| unwrapped.data[15 * 30 + x][3]); + assert!((within - 1.).abs() < 1e-6 && (edge - 0.5).abs() < 1e-6 && beyond == 0., "{beyond}, {edge}, {within}"); + } + + #[test] + fn warps_bend_what_lies_past_their_frame_along_with_the_content() { + use glam::DAffine2; + use graphic_types::EffectOperation; + + // Paint varying only across fills a plane taller than the frame from (5, 5) to (25, 35) + let mut plane = Plane::<[f32; 4]>::new(30, 40); + plane.data = (0..30 * 40).map(|index| [(index % 30) as f32 / 30., 0., 0., 1.]).collect(); + let transform = DAffine2::from_translation(DVec2::new(15., 20.)) * DAffine2::from_scale(DVec2::new(20., 30.)); + + // A cylinder bends every row of its band across the same way, above and below the frame too, with no seam, and leaves what lies beside the band as it is + let spherize = EffectOperation::Spherize { + amount: 80., + cylindrical: true, + transform, + }; + let (warp, frame) = warp_in_plane(&spherize); + let bent = frame_warped(&plane, &warp, &frame); + for x in 0..30 { + assert_eq!(bent.data[2 * 30 + x], bent.data[20 * 30 + x], "column {x} bends above the frame as within it"); + assert_eq!(bent.data[38 * 30 + x], bent.data[20 * 30 + x], "column {x} bends below the frame as within it"); + } + assert_ne!(bent.data[20 * 30 + 9], plane.data[20 * 30 + 9], "the band bends"); + assert_eq!(bent.data[20 * 30 + 27], plane.data[20 * 30 + 27], "beside the band, the paint stays as it is"); + + // A twirl leaves what lies past its ellipse as it is + let (warp, frame) = warp_in_plane(&EffectOperation::Twirl { angle: 120., transform }); + let twirled = frame_warped(&plane, &warp, &frame); + assert_eq!(twirled.data[2 * 30 + 10], plane.data[2 * 30 + 10]); + assert_ne!(twirled.data[20 * 30 + 12], plane.data[20 * 30 + 12], "the ellipse twirls"); + } + + /// The transforms of warps' squares in a plane 180 pixels square, cutting through pixels at every offset along their sides: + /// one 80 across with its sides meeting at 16 degrees, one 100 across turned 30 degrees, and an oblong turned and slanted. + fn slanted_and_turned_squares() -> [glam::DAffine2; 3] { + use glam::DAffine2; + + [ + DAffine2::from_cols_array(&[80., 0., 76.8, 22.4, 80.2, 80.3]), + DAffine2::from_translation(DVec2::new(90.3, 89.6)) * DAffine2::from_angle(30_f64.to_radians()) * DAffine2::from_scale(DVec2::splat(100.)), + DAffine2::from_translation(DVec2::new(88.7, 91.2)) * DAffine2::from_angle(0.6) * DAffine2::from_cols_array(&[110., 0., 30., 60., 0., 0.]), + ] + } + + #[test] + fn polar_coordinates_read_nothing_wholly_past_a_slanted_square() { + use graphic_types::EffectOperation; + + // Clear content but for opaque red at the pixel wholly past the slanted square's left side, a fifth of which plain interpolation reads where (45, 70) wraps from + let mut plane = Plane::<[f32; 4]>::new(180, 180); + plane.data[89 * 180 + 69] = [1., 0., 0., 1.]; + assert!(sample_bilinear(&plane, DVec2::new(69.533, 88.71))[3] > 0.2); + + for inverse in [false, true] { + let transform = slanted_and_turned_squares()[0]; + let (warp, frame) = warp_in_plane(&EffectOperation::PolarCoordinates { inverse, transform }); + let warped = frame_warped(&plane, &warp, &frame); + for (index, pixel) in warped.data.iter().enumerate() { + let (x, y) = (index % 180, index / 180); + assert_eq!(*pixel, [0.; 4], "({x}, {y}) shows {pixel:?} with inverse {inverse}"); + } + } + } + + #[test] + fn polar_coordinates_read_nothing_past_a_square_too_small_to_cover_a_pixel() { + use glam::DAffine2; + use graphic_types::EffectOperation; + + // A square 0.4 across turned 45 degrees, ending about 0.017 above the pixel from (10, 11), which only red fills, though the pixel's extent along the square's axes reaches it + let transform = DAffine2::from_translation(DVec2::new(10.5, 10.7)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_4) * DAffine2::from_scale(DVec2::splat(0.4)); + let mut plane = Plane::<[f32; 4]>::new(20, 20); + plane.data[11 * 20 + 10] = [1., 0., 0., 1.]; + + for inverse in [false, true] { + let (warp, frame) = warp_in_plane(&EffectOperation::PolarCoordinates { inverse, transform }); + let warped = frame_warped(&plane, &warp, &frame); + for (index, pixel) in warped.data.iter().enumerate() { + let (x, y) = (index % 20, index / 20); + assert_eq!(*pixel, [0.; 4], "({x}, {y}) shows {pixel:?} with inverse {inverse}"); + } + } + } + + #[test] + fn polar_coordinates_read_opaque_content_straddling_a_slanted_squares_sides_as_opaque() { + use graphic_types::EffectOperation; + + // Opaque white paint straddling the slanted square's sides, but for red at the pixel wholly past its left side + let mut plane = Plane::<[f32; 4]>::new(180, 180); + plane.data = vec![[1.; 4]; 180 * 180]; + plane.data[89 * 180 + 69] = [1., 0., 0., 1.]; + + for inverse in [false, true] { + let transform = slanted_and_turned_squares()[0]; + let (warp, frame) = warp_in_plane(&EffectOperation::PolarCoordinates { inverse, transform }); + let warped = frame_warped(&plane, &warp, &frame); + let (to_local, half, half_pixel, extent) = (frame.pixels_to_local(), frame.size / 2., frame.half_pixel(), frame.pixel_extent()); + + // Each pixel wholly within the square shows only the white, faded only around wrapping's rim, where its source nears or passes the square's bottom side + for (index, pixel) in warped.data.iter().enumerate() { + let (x, y) = (index % 180, index / 180); + let local = to_local.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)); + if (local.abs() + extent).cmpgt(half).any() { + continue; + } + + let expected = match inverse { + true => 1., + false => (0.5 + (half.y - warp.source(local, frame.size).y) / (2. * half_pixel.y)).clamp(0., 1.) as f32, + }; + assert!( + pixel.iter().all(|channel| (channel - expected).abs() < 1e-6), + "({x}, {y}) shows {pixel:?} rather than {expected} with inverse {inverse}" + ); + } + } + } + #[test] fn bilinear_samples_fade_to_transparency_past_the_edges() { let mut plane = Plane::<[f32; 4]>::new(2, 1); diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index c099a654d4..08cff8dc99 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -30,7 +30,7 @@ use graphic_types::filters::is_random_field_filter; use graphic_types::generator::GeneratorPattern; use graphic_types::masks::{MaskMode, masked_radius_blur_levels}; use graphic_types::raster_types::{CPU, GPU, Raster}; -use graphic_types::resampling::frame_of_bounds; +use graphic_types::resampling::{FrameWarp, frame_of_bounds}; use graphic_types::vector_types::gradient::{Gradient, GradientForm}; use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint, TargetPath}; use graphic_types::vector_types::vector::misc::dvec2_to_point; @@ -1109,8 +1109,13 @@ fn finish_deferred_markup( fn svg_expresses(operation: &EffectOperation) -> bool { match operation { EffectOperation::Adjustment(adjustment) => svg_expresses_adjustment(adjustment), - // No primitive blurs along a line or arc - EffectOperation::MotionBlur { .. } | EffectOperation::RadialBlur { .. } => false, + // Browsers displace with nearest-neighbor sampling, which can't match the GPU's interpolation, and no primitive blurs along a line or arc + EffectOperation::MotionBlur { .. } + | EffectOperation::RadialBlur { .. } + | EffectOperation::Twirl { .. } + | EffectOperation::Pinch { .. } + | EffectOperation::Spherize { .. } + | EffectOperation::PolarCoordinates { .. } => false, _ => true, } } @@ -1850,7 +1855,12 @@ fn write_svg_effects_filter_on_lattice( continue; } // The whole item becomes an image the GPU renders, which replaces this filter - EffectOperation::MotionBlur { .. } | EffectOperation::RadialBlur { .. } => continue, + EffectOperation::MotionBlur { .. } + | EffectOperation::RadialBlur { .. } + | EffectOperation::Twirl { .. } + | EffectOperation::Pinch { .. } + | EffectOperation::Spherize { .. } + | EffectOperation::PolarCoordinates { .. } => continue, }; for (plane, within, color, blend_mode) in planes { @@ -2840,10 +2850,20 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st bounds => bounds, }; + // Warps change even content without edges within their frames, so its effects, masks included, are carried out over the area in view, as for an endless color or gradient + let endless_area = match effects { + Some(effects) if warps_change_endless_content(effects) && matches!(bounds(), RenderBoundingBox::Infinite) => filtered_endless_area(effects, &compositing, render, render_params), + _ => None, + }; + let effects_bounds = || match (bounds(), endless_area) { + (RenderBoundingBox::Infinite, Some(area)) => RenderBoundingBox::Rectangle(area), + (bounds, _) => bounds, + }; + // Masks that leave it without edges wrap it in a group of their own, which takes the blend mode so it blends with what lies beneath let has_mask = effects.is_some_and(|effects| effects.operations().any(|operation| matches!(operation, EffectOperation::Mask { .. }))); let endless_mask = match effects { - Some(effects) if has_mask && matches!(bounds(), RenderBoundingBox::Infinite) => masks::write_endless_content_mask(render, effects, transform, render_params), + Some(effects) if has_mask && matches!(effects_bounds(), RenderBoundingBox::Infinite) => masks::write_endless_content_mask(render, effects, transform, render_params), _ => None, }; let endless_masked = endless_mask.is_some(); @@ -2854,8 +2874,8 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st Some(effects) if effects.any_takes_frame() => nested_effects_reach(element, transform, |_| true), _ => DVec2::ZERO, }; - let deferred = start_deferred_markup(render, render_params, &compositing, bounds, nested_reach.max_element()); - let filters = compositing.svg_filters(render, render_params, bounds, |keeps| Graphic::Graphic(Box::new(effects_content(item, element.clone(), keeps)))); + let deferred = start_deferred_markup(render, render_params, &compositing, effects_bounds, nested_reach.max_element()); + let filters = compositing.svg_filters(render, render_params, effects_bounds, |keeps| Graphic::Graphic(Box::new(effects_content(item, element.clone(), keeps)))); let filtered = filters.is_some(); render_svg_through_filters(render, filters, compositing.opacity, render_params.to_canvas(), |render| { @@ -5107,7 +5127,7 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende let Some(&color) = item.element() else { return }; let compositing = item.compositing(render_params, item.attribute_cloned_or_default(ATTR_TRANSFORM)); - // Leading masks that give the color edges let its effects be carried out within them like any other content's, and filters, which change even a flat color, carry them out over the area in view + // Leading masks that give the color edges let its effects be carried out within them like any other content's, and filters and warps, which change even a flat color, carry them out over the area in view let extent = compositing .effects .and_then(|(effects, _)| masks::masked_extent(effects, compositing.placement).or_else(|| filtered_endless_area(effects, &compositing, render, render_params))); @@ -5132,9 +5152,19 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende render_edgeless_color_svg(item, render, &compositing, color, render_params); } -/// The area in view in the current user space, grown past it by how far the `effects` and the groups around them read, for endless content whose filters read it there, if it has any. +/// Whether the effects change endless content (like a color or gradient filling everything) over the area in view, as filters reading its details do, and warps within their frames. +fn changes_endless_content_in_view(effects: &Effects) -> bool { + graphic_types::filters::has_filters(effects) || warps_change_endless_content(effects) +} + +/// Whether any of the effects is a warp that changes something, which it does within its frame even to endless content. +fn warps_change_endless_content(effects: &Effects) -> bool { + effects.operations().any(|operation| FrameWarp::of(&operation).is_some() && !operation.changes_nothing()) +} + +/// The area in view in the current user space, grown past it by how far the `effects` and the groups around them read, for endless content that its filters or warps change there, if it has any. fn filtered_endless_area(effects: &Effects, compositing: &ItemCompositing, render: &SvgRender, render_params: &RenderParams) -> Option<[DVec2; 2]> { - if !graphic_types::filters::has_filters(effects) { + if !changes_endless_content_in_view(effects) { return None; } let own_reach = effects @@ -5347,8 +5377,8 @@ fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBu let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - // Leading masks that give the color edges let its effects be carried out within them like any other content's, and filters, which change even a flat color, carry them out over the area in view, as in SVG - let carried_out = |effects: &Effects| masks::masked_extent(effects, compositing.placement).is_some() || graphic_types::filters::has_filters(effects); + // Leading masks that give the color edges let its effects be carried out within them like any other content's, and filters and warps, which change even a flat color, carry them out over the area in view, as in SVG + let carried_out = |effects: &Effects| masks::masked_extent(effects, compositing.placement).is_some() || changes_endless_content_in_view(effects); if compositing.effects.is_some_and(|(effects, _)| carried_out(effects)) { let vello_color = SRGBA8::from(color).to_peniko_color(); return draw_endless_item_with_effects(scene, &compositing, blend_mode, parent_transform, render_params, |scene| scene.fill_viewport(vello_color, None)); @@ -5461,7 +5491,7 @@ fn render_gradient_item_svg_with_thumbnail_rect(item: ItemRef<'_, Gradient>, thu let compositing = item.compositing(render_params, item.attribute_cloned_or_default(ATTR_TRANSFORM)); let settings = gradient_settings_from_item(item); - // Leading masks that give the gradient edges let its effects be carried out within them like any other content's, and filters reading its details carry them out over the area in view + // Leading masks that give the gradient edges let its effects be carried out within them like any other content's, and filters reading its details and warps carry them out over the area in view let extent = compositing .effects .and_then(|(effects, _)| masks::masked_extent(effects, compositing.placement).or_else(|| filtered_endless_area(effects, &compositing, render, render_params))); @@ -5629,8 +5659,8 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - // Leading masks that give the gradient edges let its effects be carried out within them like any other content's, and filters reading its details carry them out over the area in view, as in SVG - let carried_out = |effects: &Effects| masks::masked_extent(effects, compositing.placement).is_some() || graphic_types::filters::has_filters(effects); + // Leading masks that give the gradient edges let its effects be carried out within them like any other content's, and filters reading its details and warps carry them out over the area in view, as in SVG + let carried_out = |effects: &Effects| masks::masked_extent(effects, compositing.placement).is_some() || changes_endless_content_in_view(effects); if compositing.effects.is_some_and(|(effects, _)| carried_out(effects)) { let (brush, brush_transform) = gradient_brush(item, source_gradient, settings, parent_transform); return draw_endless_item_with_effects(scene, &compositing, blend_mode, parent_transform, render_params, |scene| { @@ -6961,7 +6991,7 @@ mod tests { let zoom = graphic_types::EffectOperation::RadialBlur { method: graphic_types::RadialBlurMethod::Zoom, amount: 100., - center: DVec2::splat(5.), + transform: DAffine2::from_translation(DVec2::splat(5.)), gamma: false, }; let group = Item::new_from_element(Graphic::VectorList(orange_square(std::slice::from_ref(&zoom), 1., 1.))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(2.))); @@ -6994,7 +7024,7 @@ mod tests { let zoom = graphic_types::EffectOperation::RadialBlur { method: graphic_types::RadialBlurMethod::Zoom, amount: 200., - center: DVec2::ZERO, + transform: DAffine2::IDENTITY, gamma: false, }; let effects = Effects::from_operations([zoom]); @@ -7056,15 +7086,21 @@ mod tests { let radial_blur = graphic_types::EffectOperation::RadialBlur { method: graphic_types::RadialBlurMethod::Spin, amount: 30., - center: DVec2::splat(5.), + transform: DAffine2::from_translation(DVec2::splat(5.)), gamma: false, }; + // Nor does a warp, which acts within the frame its own transform places + let twirl = graphic_types::EffectOperation::Twirl { + angle: 90., + transform: DAffine2::from_scale(DVec2::splat(10.)), + }; let shadow = drop_shadow(180., 3., 2.); let cases = [ (vec![shadow.clone()], false), (vec![shadow.clone(), motion_blur(4.)], false), (vec![shadow.clone(), motion_blur(0.)], false), - (vec![shadow, radial_blur], false), + (vec![shadow.clone(), radial_blur], false), + (vec![shadow, twirl], false), ]; for (effects, takes_frame) in cases { @@ -7147,6 +7183,47 @@ mod tests { ); } + #[test] + fn thumbnails_and_exports_hold_the_corners_of_a_turned_square_that_warps_paint_in() { + use graphic_types::EffectOperation; + use kurbo::Shape; + + // A disc 30 in radius in a group turned an eighth and unwrapped across the square around it, which reaches 30√2 from the middle along each axis, past the disc's 30 + let mut disc = Vector::item_from_bezpath(&kurbo::Circle::new((0., 0.), 30.).to_path(0.1)); + disc.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::RED)))); + let unwrap = EffectOperation::PolarCoordinates { + inverse: true, + transform: DAffine2::from_scale(DVec2::splat(60.)), + }; + let group = Item::new_from_element(Graphic::Vector(Box::new(disc))) + .with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(64.)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_4)) + .with_attribute(ATTR_EFFECTS, Effects::from_operations([unwrap])) + .with_attribute(ATTR_EDITOR_LAYER_PATH, NodeIdPath::from(vec![NodeId(1)])); + + // The group's layer inside another one, which the square reaches past too + let outer = Item::new_from_element(Graphic::GraphicList(List::new_from_item(group))).with_attribute(ATTR_EDITOR_LAYER_PATH, NodeIdPath::from(vec![NodeId(2)])); + let document = List::new_from_item(outer); + + let spans = |distance: f64, [min, max]: [DVec2; 2]| (min - DVec2::splat(64. - distance)).abs().max_element() < 0.05 && (max - DVec2::splat(64. + distance)).abs().max_element() < 0.05; + let corner = 30. * std::f64::consts::SQRT_2; + + // The thumbnail frames the corners, unless SVG draws it without the GPU's renders, which leave the warp out + let thumbnail = |maps_resolved: bool| match graphic_list_painted_bounds(&document, maps_resolved) { + RenderBoundingBox::Rectangle(bounds) => bounds, + bounds => panic!("the disc is bounded by {bounds:?}"), + }; + assert!(spans(corner, thumbnail(true)), "the thumbnail frames {:?}", thumbnail(true)); + assert!(spans(30., thumbnail(false)), "the thumbnail without the GPU frames {:?}", thumbnail(false)); + + // Exports hold the corners for both layers by how far the square reaches past the disc + let mut metadata = RenderMetadata::default(); + document.collect_metadata(&mut metadata, Footprint::default(), None, None); + for layer in [NodeId(1), NodeId(2)] { + let reach = metadata.effects_reach.get(&layer).copied(); + assert!(reach.is_some_and(|reach| (reach - (corner - 30.)).abs() < 0.05), "the layer {layer:?} reaches {reach:?}"); + } + } + #[test] fn svg_maps_cover_past_the_view_as_far_as_the_filters_reading_them_reach() { let blur = graphic_types::EffectOperation::Blur { @@ -7721,10 +7798,11 @@ mod tests { // A spin about the middle of an image 10 units square inside a group scaled 5 times, so the image spans 50 units of the document let mut image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(10.))); + let center = DAffine2::from_translation(DVec2::splat(5.)); let spin = EffectOperation::RadialBlur { method: RadialBlurMethod::Spin, amount: 90., - center: DVec2::splat(5.), + transform: center, gamma: false, }; stamp_effect(&mut image, Effect::new(&spin)); @@ -7739,11 +7817,12 @@ mod tests { }, ); - // The spin carries the corners as far as its size in the document says, a fifth of that in the group's units + // The spin carries the corners as far as it does in its effect space, which the group scales into the document and back into its own units let [deferred] = &render.deferred_images[..] else { panic!("expected one deferred image, got {}", render.deferred_images.len()) }; - let reach = RadialBlur::new(RadialBlurMethod::Spin, 90., DVec2::splat(5.)).reach(25. * std::f64::consts::SQRT_2) / 5.; + let corners = [DVec2::ZERO, DVec2::new(10., 0.), DVec2::splat(10.), DVec2::new(0., 10.)]; + let reach = RadialBlur::new(RadialBlurMethod::Spin, 90., center).reach_around(corners, 0.); let expected = [DVec2::splat(-reach), DVec2::splat(10. + reach)]; assert!( (deferred.bounds[0] - expected[0]).length() < 1e-9 && (deferred.bounds[1] - expected[1]).length() < 1e-9, @@ -7752,6 +7831,32 @@ mod tests { ); } + #[test] + fn effects_svg_cannot_express_that_change_nothing_leave_the_content_live() { + use graphic_types::raster_types::Image; + use graphic_types::{Effect, EffectKind, EffectOperation, stamp_effect}; + + let mut item = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(10.))); + stamp_effect(&mut item, Effect::new(&EffectOperation::default_for(EffectKind::DropShadow))); + stamp_effect( + &mut item, + Effect::new(&EffectOperation::Twirl { + angle: 0., + transform: DAffine2::from_scale(DVec2::splat(10.)), + }), + ); + + let mut render = SvgRender::new(); + List::new_from_item(item).render_svg( + &mut render, + &RenderParams { + for_export: true, + ..Default::default() + }, + ); + assert!(render.deferred_images.is_empty(), "{}", render.svg.to_svg_string()); + } + #[test] fn svg_paint_overlays_blend_with_the_content_in_gamma() { let mut primitives = SvgFilterPrimitives::default(); @@ -8393,4 +8498,67 @@ mod tests { assert!(region.iter().zip(expected).all(|(actual, expected)| (actual - expected).abs() < 1e-9), "{region:?} in {defs}"); assert!(!defs_of(Vec::new()).contains(" { - let blur = RadialBlur::new(method, amount, center); + EffectOperation::RadialBlur { method, amount, transform, gamma } => { + let blur = RadialBlur::new(method, amount, transform); recorder.merge_beneath(content, &mut full, &mut filled, beneath.take()); let unblurred = full.take().unwrap_or_else(|| recorder.scale(content, 1.)); full = Some(recorder.radial_blur(unblurred, &blur, effect_to_pixels, !gamma)); filled = filled.map(|filled| recorder.radial_blur(filled, &blur, effect_to_pixels, !gamma)); } + EffectOperation::Twirl { .. } | EffectOperation::Pinch { .. } | EffectOperation::Spherize { .. } | EffectOperation::PolarCoordinates { .. } => { + // The frame the warp's transform places in the effect space, measured from its origin (the content's) + let Some((warp, transform)) = FrameWarp::of(operation) else { continue }; + let square = warp_frame(transform, effect_to_pixels); + let clears = matches!(warp, FrameWarp::Polar { .. }); + if square.is_none() && !clears { + continue; + } + + recorder.merge_beneath(content, &mut full, &mut filled, beneath.take()); + let unwarped = full.take().unwrap_or_else(|| recorder.scale(content, 1.)); + + // Where its square collapses, Polar Coordinates clears everything + let warped = |recorder: &mut PassRecorder, texture: wgpu::Texture| match &square { + Some(square) => recorder.frame_warp(texture, &warp, square), + None => { + let cleared = recorder.scale(&texture, 0.); + recorder.textures.release(texture); + cleared + } + }; + full = Some(warped(&mut recorder, unwarped)); + filled = filled.map(|filled| warped(&mut recorder, filled)); + } EffectOperation::Adjustment(_) => { // A run of adjustments is carried out from its first row, in a pass for each standalone step and one for the steps between them let is_adjustment = |position: usize| is_pixel_filter(&operations[position].1) && matches!(operations[position].1, EffectOperation::Adjustment(_)); diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects/filters.wgsl b/node-graph/libraries/wgpu-executor/src/vello_effects/filters.wgsl index 87305ee3cf..5c6dc0a13c 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_effects/filters.wgsl +++ b/node-graph/libraries/wgpu-executor/src/vello_effects/filters.wgsl @@ -362,19 +362,6 @@ fn faded_by_shares(@builtin(position) position: vec4) -> @location(0) vec4< // For PSD interop, how many standard deviations Gaussian noise reaches, matching the CPU's const GAUSSIAN_NOISE_LIMIT: f32 = 3.5; -// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", matching the CPU's -fn pcg3d(input: vec3) -> vec3 { - var v = input * 1664525u + 1013904223u; - v.x += v.y * v.z; - v.y += v.z * v.x; - v.z += v.x * v.y; - v ^= v >> vec3(16u); - v.x += v.y * v.z; - v.y += v.z * v.x; - v.z += v.x * v.y; - return v; -} - // Values strictly between 0 and 1 from the top 23 bits of each hash, which an f32 holds exactly with the half added, matching the CPU's `unit_interval` fn unit_interval(hash: vec3) -> vec3 { return (vec3(hash >> vec3(9u)) + 0.5) / 8388608.; diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects/resample.rs b/node-graph/libraries/wgpu-executor/src/vello_effects/resample.rs index 311c24736e..66401de422 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_effects/resample.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_effects/resample.rs @@ -2,9 +2,23 @@ use super::{PARAMETER_TAPS, Parameters, PassRecorder}; use glam::DAffine2; -use graphic_types::resampling::{RadialBlur, RadialBlurMethod}; +use graphic_types::resampling::{EffectFrame, FrameWarp, RadialBlur, RadialBlurMethod}; use raster_kernels::resample_kernels::MotionBlurShear; +/// The tap array holding the frame's maps between the texture and its local space, and half its size, where the resampling shaders read them. +fn frame_taps(frame: &EffectFrame) -> [[f32; 4]; PARAMETER_TAPS] { + let to_local = frame.pixels_to_local().to_cols_array().map(|value| value as f32); + let to_pixels = frame.local_to_pixels().to_cols_array().map(|value| value as f32); + let half = (frame.size / 2.).as_vec2(); + + let mut taps = [[0.; 4]; PARAMETER_TAPS]; + taps[0] = [to_local[0], to_local[1], to_local[2], to_local[3]]; + taps[1] = [to_local[4], to_local[5], to_pixels[0], to_pixels[1]]; + taps[2] = [to_pixels[2], to_pixels[3], to_pixels[4], to_pixels[5]]; + taps[3] = [half.x, half.y, 0., 0.]; + taps +} + impl PassRecorder<'_> { /// `texture` smeared along the motion blur's line by its two shears around a box, in linear light if `linear`, matching the CPU's `motion_blurred`. pub(super) fn motion_blur(&mut self, texture: wgpu::Texture, shear: &MotionBlurShear, linear: bool) -> wgpu::Texture { @@ -28,16 +42,18 @@ impl PassRecorder<'_> { /// `texture` blurred along the radial blur's arcs or lines, in the effect space that `effect_to_pixels` places on the texture's pixels, in linear light if `linear`, matching the CPU's `radial_blurred`. pub(super) fn radial_blur(&mut self, texture: wgpu::Texture, blur: &RadialBlur, effect_to_pixels: DAffine2, linear: bool) -> wgpu::Texture { - // The shader measures offsets from the center, placed here in double precision, since positions can lie far from the effect space's origin - let center_to_pixels = effect_to_pixels * DAffine2::from_translation(blur.center); - let to_center = center_to_pixels.inverse().to_cols_array().map(|value| value as f32); - let from_center = center_to_pixels.to_cols_array().map(|value| value as f32); + // The shader measures offsets from the center in the circle's space, placed here in double precision, since positions can lie far from the effect space's origin + let circle_to_pixels = effect_to_pixels * blur.transform; + let to_circle = circle_to_pixels.inverse().to_cols_array().map(|value| value as f32); + let from_circle = circle_to_pixels.to_cols_array().map(|value| value as f32); let mut taps = [[0.; 4]; PARAMETER_TAPS]; - taps[0] = [to_center[0], to_center[1], to_center[2], to_center[3]]; - taps[1] = [to_center[4], to_center[5], from_center[0], from_center[1]]; - taps[2] = [from_center[2], from_center[3], from_center[4], from_center[5]]; - let pixels_per_length = effect_to_pixels.matrix2.determinant().abs().sqrt(); + taps[0] = [to_circle[0], to_circle[1], to_circle[2], to_circle[3]]; + taps[1] = [to_circle[4], to_circle[5], from_circle[0], from_circle[1]]; + taps[2] = [from_circle[2], from_circle[3], from_circle[4], from_circle[5]]; + + // An arc in the circle's space spans at most this many pixels for each of its units, as the CPU's `RadialBlur::sample_count` measures it + let pixels_per_length = effect_to_pixels.matrix2.determinant().abs().sqrt() * blur.longest_stretch(); let parameters = Parameters { values: [blur.extent as f32, if blur.method == RadialBlurMethod::Zoom { 1. } else { 0. }, pixels_per_length as f32, 0.], taps, @@ -50,4 +66,21 @@ impl PassRecorder<'_> { texture }) } + + /// `texture` warped relative to the `frame`, matching the CPU's `frame_warped`. + pub(super) fn frame_warp(&mut self, texture: wgpu::Texture, warp: &FrameWarp, frame: &EffectFrame) -> wgpu::Texture { + let [kind, setting, extra] = warp.shader_parameters(); + let mut taps = frame_taps(frame); + let (half_pixel, pixel_extent) = (frame.half_pixel().as_vec2(), frame.pixel_extent().as_vec2()); + taps[4] = [half_pixel.x, half_pixel.y, pixel_extent.x, pixel_extent.y]; + let parameters = Parameters { + values: [kind, setting, extra, 0.], + taps, + ..Default::default() + }; + + let warped = self.run("frame_warp", texture.format(), self.size, &texture, None, None, parameters); + self.textures.release(texture); + warped + } } diff --git a/node-graph/libraries/wgpu-executor/src/vello_generators.rs b/node-graph/libraries/wgpu-executor/src/vello_generators.rs index 376eb50603..22db4d81cb 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_generators.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_generators.rs @@ -33,7 +33,7 @@ impl Shader { let common = include_str!("vello_generators.wgsl"); match self { Self::Noise => [fastnoise_lite::WGSL_SOURCE, common, include_str!("vello_generators_noise.wgsl")].concat(), - Self::WhiteNoise => [common, include_str!("vello_generators_white_noise.wgsl")].concat(), + Self::WhiteNoise => [common, include_str!("vello_hash.wgsl"), include_str!("vello_generators_white_noise.wgsl")].concat(), Self::Mandelbrot => [common, include_str!("vello_generators_mandelbrot.wgsl")].concat(), } } diff --git a/node-graph/libraries/wgpu-executor/src/vello_generators_white_noise.wgsl b/node-graph/libraries/wgpu-executor/src/vello_generators_white_noise.wgsl index 52fb06dfce..5cab2b2b9b 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_generators_white_noise.wgsl +++ b/node-graph/libraries/wgpu-executor/src/vello_generators_white_noise.wgsl @@ -18,23 +18,7 @@ fn generate(@builtin(position) position: vec4) -> @location(0) vec4 { let point = parameters.corner + position.xy * parameters.texel; let cell = vec2(floor(point)); - let hash = pcg3d(vec3(bitcast>(cell), bitcast(parameters.noise.seed))); - - // The top 24 bits, which an f32 holds exactly - let value = f32(hash.x >> 8u) / 16777216.; + let value = hash_fraction(pcg3d(vec3(bitcast>(cell), bitcast(parameters.noise.seed))).x); return vec4(vec3(gray_level(value)), 1.); } - -// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result -fn pcg3d(input: vec3) -> vec3 { - var v = input * 1664525u + 1013904223u; - v.x += v.y * v.z; - v.y += v.z * v.x; - v.z += v.x * v.y; - v ^= v >> vec3(16u); - v.x += v.y * v.z; - v.y += v.z * v.x; - v.z += v.x * v.y; - return v; -} diff --git a/node-graph/libraries/wgpu-executor/src/vello_hash.wgsl b/node-graph/libraries/wgpu-executor/src/vello_hash.wgsl new file mode 100644 index 0000000000..ae7fb03b12 --- /dev/null +++ b/node-graph/libraries/wgpu-executor/src/vello_hash.wgsl @@ -0,0 +1,17 @@ +// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result, matching the CPU's `pcg3d` +fn pcg3d(input: vec3) -> vec3 { + var v = input * 1664525u + 1013904223u; + v.x += v.y * v.z; + v.y += v.z * v.x; + v.z += v.x * v.y; + v ^= v >> vec3(16u); + v.x += v.y * v.z; + v.y += v.z * v.x; + v.z += v.x * v.y; + return v; +} + +// A hash's top 24 bits as a fraction from 0 to 1, which an f32 holds exactly, matching the CPU's `hash_fraction` +fn hash_fraction(hash: u32) -> f32 { + return f32(hash >> 8u) / 16777216.; +} diff --git a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs index 0a5f8bca32..3a7c382fff 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs @@ -4985,16 +4985,21 @@ fn patterned_raster(offset: f64, effects: &[graphic_types::EffectOperation], fil /// The most that the GPU's render of `item` and its CPU evaluation differ by at any of the render's pixels, in levels of their premultiplied channels, or `None` without a GPU. fn gpu_and_cpu_difference(item: core_types::list::Item>, size: UVec2) -> Option { + gpu_and_cpu_difference_in_view(item, size, DAffine2::IDENTITY) +} + +/// Like [`gpu_and_cpu_difference`], with the GPU rendering through a `view` (a zoom, say), which should keep the evaluated raster's pixels on the render's. +fn gpu_and_cpu_difference_in_view(item: core_types::list::Item>, size: UVec2, view: DAffine2) -> Option { use core_types::ATTR_TRANSFORM; use rendering::{Render, RenderParams}; let graphic = graphic_types::Graphic::RasterCPU(Box::new(item.clone())); - let gpu = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?; + let gpu = render_in_view(size, view, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?; let evaluated = raster_kernels::evaluate_raster_effects(item); let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM); let raster = evaluated.element(); - let document_to_pixels = DAffine2::from_scale(glam::DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse(); + let document_to_pixels = DAffine2::from_scale(glam::DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse() * view.inverse(); let mut worst = 0; for y in 0..size.y { @@ -5223,7 +5228,7 @@ fn radial_blurs_reach_as_far_inside_faded_groups_and_from_out_of_view() { let spin = EffectOperation::RadialBlur { method: RadialBlurMethod::Spin, amount: 120., - center: DVec2::new(80., 16.), + transform: DAffine2::from_translation(DVec2::new(80., 16.)), gamma: false, }; let size = UVec2::new(160, 160); @@ -5269,9 +5274,17 @@ fn resampling_effects_match_on_the_cpu_and_gpu() { use graphic_types::{EffectOperation, RadialBlurMethod}; let motion = |angle, distance, gamma| EffectOperation::MotionBlur { angle, distance, gamma }; - let radial = |method, amount, center, gamma| EffectOperation::RadialBlur { method, amount, center, gamma }; + let radial = |method, amount, center, gamma| EffectOperation::RadialBlur { + method, + amount, + transform: DAffine2::from_translation(center), + gamma, + }; let shadow = drop_shadow(core_types::Color::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75), DVec2::new(4., 5.), 3., 0.); + // The warps act within the image 50 pixels across, measured from its corner + let on_image = DAffine2::from_translation(DVec2::splat(25.)) * DAffine2::from_scale(DVec2::splat(50.)); + let cases = [ vec![motion(0., 12., false)], vec![motion(30., 7.5, true)], @@ -5287,6 +5300,27 @@ fn resampling_effects_match_on_the_cpu_and_gpu() { vec![radial(RadialBlurMethod::Spin, 15., DVec2::new(-40., 90.), false)], vec![radial(RadialBlurMethod::Zoom, 30., DVec2::new(120., -30.), false)], vec![shadow, radial(RadialBlurMethod::Spin, 45., DVec2::new(10., 45.), false)], + vec![EffectOperation::Twirl { angle: 140., transform: on_image }], + vec![EffectOperation::Pinch { amount: 70., transform: on_image }], + vec![EffectOperation::Pinch { amount: -60., transform: on_image }], + vec![EffectOperation::Spherize { + amount: 100., + cylindrical: false, + transform: on_image, + }], + vec![EffectOperation::Spherize { + amount: -80., + cylindrical: true, + transform: on_image, + }], + // Turned a quarter, a cylinder bends the columns + vec![EffectOperation::Spherize { + amount: 50., + cylindrical: true, + transform: on_image * DAffine2::from_angle(std::f64::consts::FRAC_PI_2), + }], + vec![EffectOperation::PolarCoordinates { inverse: false, transform: on_image }], + vec![EffectOperation::PolarCoordinates { inverse: true, transform: on_image }], ]; for effects in cases { @@ -5299,30 +5333,748 @@ fn resampling_effects_match_on_the_cpu_and_gpu() { } } +#[test] +fn resampling_effects_match_on_turned_zoomed_and_oblong_content() { + use core_types::list::Item; + use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, EffectOperation, RadialBlurMethod, stamp_effect}; + + // An oblong raster of 60 by 36 pixels, two to each document unit, upright or turned a quarter and viewed at twice the size, so its pixels land on the render's + let level = |channel: f32| (channel * 255.).round() / 255.; + let data = (0..60 * 36) + .map(|index| { + let (x, y) = ((index % 60) as f32 + 0.5, (index / 60) as f32 + 0.5); + let alpha = if (x - 40.).hypot(y - 14.) < 6. { 0. } else { 1. }; + GraphicColor::from_gamma_srgb_channels(level(x / 60.), level(y / 36.), level((x * 0.3).sin() * 0.5 + 0.5), alpha) + }) + .collect::>(); + let upright = DAffine2::from_translation(DVec2::new(25., 25.)) * DAffine2::from_scale(DVec2::new(30., 18.)); + let turned = DAffine2::from_translation(DVec2::new(58., 25.)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_2) * DAffine2::from_scale(DVec2::new(30., 18.)); + let content = |placement: DAffine2, effects: &[EffectOperation]| { + let mut item = Item::new_from_element(Raster::new_cpu(Image { + width: 60, + height: 36, + data: data.clone(), + })) + .with_attribute(ATTR_TRANSFORM, placement); + effects.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation))); + item + }; + + // The warps act within each raster's own rectangle, measured from its origin in the effect space, which turns with the turned one + let warps = |placement: DAffine2| { + let transform = DAffine2::from_mat2(placement.matrix2) * DAffine2::from_translation(DVec2::splat(0.5)); + [ + EffectOperation::Twirl { angle: 150., transform }, + EffectOperation::Pinch { amount: 60., transform }, + EffectOperation::Spherize { + amount: -70., + cylindrical: true, + transform, + }, + EffectOperation::PolarCoordinates { inverse: false, transform }, + EffectOperation::PolarCoordinates { inverse: true, transform }, + ] + }; + + let cases = [ + EffectOperation::MotionBlur { + angle: 30., + distance: 6., + gamma: false, + }, + // About a point within the upright raster and beside the turned one, measured from each one's origin + EffectOperation::RadialBlur { + method: RadialBlurMethod::Spin, + amount: 25., + transform: DAffine2::from_translation(DVec2::new(18., 5.4)), + gamma: false, + }, + ]; + for placement in [upright, turned] { + for effect in warps(placement).iter().chain(&cases) { + let Some(worst) = gpu_and_cpu_difference_in_view(content(placement, std::slice::from_ref(effect)), UVec2::new(160, 160), DAffine2::from_scale(DVec2::splat(2.))) else { + return; + }; + assert!(worst <= 3, "{effect:?} differs from the GPU by up to {worst} levels"); + } + } +} + +/// Each warp, acting within the frame the `transform` places. +fn warps_within(transform: DAffine2) -> [graphic_types::EffectOperation; 7] { + use graphic_types::EffectOperation; + + [ + EffectOperation::Twirl { angle: 200., transform }, + EffectOperation::Pinch { amount: 80., transform }, + EffectOperation::Pinch { amount: -100., transform }, + EffectOperation::Spherize { + amount: 100., + cylindrical: false, + transform, + }, + EffectOperation::Spherize { + amount: 100., + cylindrical: true, + transform, + }, + EffectOperation::PolarCoordinates { inverse: false, transform }, + EffectOperation::PolarCoordinates { inverse: true, transform }, + ] +} + +#[test] +fn warps_match_on_the_cpu_and_gpu_within_small_offset_and_turned_slanted_frames() { + use glam::DVec2; + + // Within the image 50 pixels across, measured from its corner: a circle about a third its size toward its bottom right, and an oblong one turned and slanted about its middle + let small = DAffine2::from_translation(DVec2::new(32., 30.)) * DAffine2::from_scale(DVec2::splat(18.)); + let slanted = DAffine2::from_translation(DVec2::new(24., 26.)) * DAffine2::from_angle(0.6) * DAffine2::from_cols_array(&[40., 0., 12., 24., 0., 0.]); + for warp in [small, slanted].into_iter().flat_map(warps_within) { + for fill in [1., 0.5] { + let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&warp), fill), UVec2::new(160, 160)) else { + return; + }; + assert!(worst <= 3, "{warp:?} at fill {fill} differs from the GPU by up to {worst} levels"); + } + } +} + +#[test] +fn warps_paint_as_far_as_their_ellipse_or_square_reaches_past_the_content() { + use glam::DVec2; + use rendering::{Render, RenderParams}; + + // A circle three times as large as the image 50 pixels across, about its middle, reaching 50 past each of its sides + let transform = DAffine2::from_translation(DVec2::splat(25.)) * DAffine2::from_scale(DVec2::splat(150.)); + let size = UVec2::new(160, 160); + for warp in warps_within(transform) { + let item = patterned_raster(55., std::slice::from_ref(&warp), 1.); + let Some(worst) = gpu_and_cpu_difference(item.clone(), size) else { return }; + assert!(worst <= 3, "{warp:?} differs from the GPU by up to {worst} levels"); + + // All but pinching inward and wrapping, which gather the content toward the middle, paint more than 5 past the content from (55, 55) to (105, 105) rather than being cut off at its bounds + let graphic = graphic_types::Graphic::RasterCPU(Box::new(item)); + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + let gathers = match &warp { + graphic_types::EffectOperation::Pinch { amount, .. } => *amount > 0., + graphic_types::EffectOperation::PolarCoordinates { inverse, .. } => !inverse, + _ => false, + }; + let past_content = |x: u32, y: u32| !(50..110).contains(&x) || !(50..110).contains(&y); + let painted_past = (0..size.y) + .flat_map(|y| (0..size.x).map(move |x| (x, y))) + .any(|(x, y)| past_content(x, y) && pixel(&pixels, size, x, y)[3] > 0); + assert!(gathers || painted_past, "{warp:?} paints nothing far past the content"); + + // Unwrapping fills the square's top row with the content's middle, 50 above the content + if matches!(warp, graphic_types::EffectOperation::PolarCoordinates { inverse: true, .. }) { + assert_eq!(pixel(&pixels, size, 80, 5)[3], 255, "the unwrapped square's top row is cut off"); + } + } +} + +#[test] +fn warps_within_the_identity_or_a_collapsed_transform_change_nothing_else_unless_they_clear_it() { + use glam::DVec2; + use rendering::{Render, RenderParams}; + + let size = UVec2::new(160, 160); + let draw = |effects: &[graphic_types::EffectOperation], view: DAffine2| { + let graphic = graphic_types::Graphic::RasterCPU(Box::new(patterned_raster(55., effects, 1.))); + render_in_view(size, view, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) + }; + + // The identity is a circle 1 across at the image's corner (55, 55), changing nothing past a pixel or two, and a frame collapsed onto a line, even in a turned view, changes nothing at all. + // Polar Coordinates instead clears everything there, all outside its square. + let collapsed = DAffine2::from_scale(DVec2::new(50., 0.)); + let singular = DAffine2::from_cols_array(&[100., 200., 300., 600., 0., 0.]); + let turned = DAffine2::from_translation(DVec2::splat(80.)) * DAffine2::from_angle(0.1) * DAffine2::from_translation(DVec2::splat(-80.)); + for (transform, view, reach) in [(DAffine2::IDENTITY, DAffine2::IDENTITY, 2.), (collapsed, DAffine2::IDENTITY, 0.), (singular, turned, 0.)] { + let Some(plain) = draw(&[], view) else { return }; + for warp in warps_within(transform) { + let clears = matches!(warp, graphic_types::EffectOperation::PolarCoordinates { .. }); + let Some(warped) = draw(std::slice::from_ref(&warp), view) else { return }; + for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { + if (DVec2::new(x as f64 + 0.5, y as f64 + 0.5) - 55.).abs().max_element() <= reach { + continue; + } + let expected = if clears { [0.; 4] } else { premultiplied_levels(pixel(&plain, size, x, y)) }; + let actual = premultiplied_levels(pixel(&warped, size, x, y)); + let difference = (0..4).map(|channel| (expected[channel] - actual[channel]).abs()).fold(0., f32::max); + assert!(difference <= 2., "{warp:?} shows {actual:?} at ({x}, {y}) rather than {expected:?}"); + } + + let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&warp), 1.), size) else { + return; + }; + assert!(worst <= 3, "{warp:?} differs from the GPU by up to {worst} levels"); + } + } +} + +#[test] +fn warps_past_full_strength_fold_alike_on_the_cpu_and_gpu_reading_from_past_their_ellipse_and_the_view() { + use glam::DVec2; + use graphic_types::EffectOperation; + + // A circle 16 across within the image 50 pixels across, viewed whole or with the view's left edge 10 left of the circle's center, past which the strongest read the image + let transform = DAffine2::from_translation(DVec2::new(35., 25.)) * DAffine2::from_scale(DVec2::splat(16.)); + let cropped = DAffine2::from_translation(DVec2::new(-80., -40.)); + let sphere = |amount, cylindrical| EffectOperation::Spherize { amount, cylindrical, transform }; + let warps = [ + EffectOperation::Pinch { amount: 1000., transform }, + EffectOperation::Pinch { amount: -500., transform }, + EffectOperation::Pinch { amount: -1000., transform }, + sphere(-300., false), + sphere(600., false), + sphere(1000., false), + sphere(-300., true), + sphere(400., true), + ]; + + for warp in warps { + for (view, fill) in [(DAffine2::IDENTITY, 1.), (DAffine2::IDENTITY, 0.5), (cropped, 1.)] { + let Some(worst) = gpu_and_cpu_difference_in_view(patterned_raster(55., std::slice::from_ref(&warp), fill), UVec2::new(160, 160), view) else { + return; + }; + // Folds this strong magnify where they read, so the GPU's 32-bit rounding of each read shows as a level or two more + assert!(worst <= 5, "{warp:?} at fill {fill} in the view {view} differs from the GPU by up to {worst} levels"); + } + } +} + +/// The transforms of warps' squares in a texture 180 texels square, cutting through texels at every offset along their sides: +/// one 80 across with its sides meeting at 16 degrees, one 100 across turned 30 degrees, and an oblong turned and slanted. +fn slanted_and_turned_squares() -> [DAffine2; 3] { + use glam::DVec2; + + [ + DAffine2::from_cols_array(&[80., 0., 76.8, 22.4, 80.2, 80.3]), + DAffine2::from_translation(DVec2::new(90.3, 89.6)) * DAffine2::from_angle(30_f64.to_radians()) * DAffine2::from_scale(DVec2::splat(100.)), + DAffine2::from_translation(DVec2::new(88.7, 91.2)) * DAffine2::from_angle(0.6) * DAffine2::from_cols_array(&[110., 0., 30., 60., 0., 0.]), + ] +} + +#[test] +fn polar_coordinates_read_nothing_wholly_past_a_slanted_square_on_the_gpu() { + use graphic_types::{EffectOperation, Effects}; + use half::f16; + + // Clear content but for opaque red at the texel wholly past the slanted square's left side, which reads within the square beside that side have among the four around them + let size = 180; + let mut texels = vec![[f16::ZERO; 4]; size * size]; + texels[89 * size + 69] = [f16::ONE, f16::ZERO, f16::ZERO, f16::ONE]; + + for inverse in [false, true] { + let transform = slanted_and_turned_squares()[0]; + let effects = Effects::from_operations([EffectOperation::PolarCoordinates { inverse, transform }]); + let Some(gpu) = gpu_effect_texels(&effects, &texels, size, &[]) else { return }; + for (index, texel) in gpu.iter().enumerate() { + let (x, y) = (index % size, index / size); + assert_eq!(*texel, [0.; 4], "({x}, {y}) shows {texel:?} with inverse {inverse}"); + } + } +} + +#[test] +fn polar_coordinates_read_nothing_past_a_square_too_small_to_cover_a_texel_on_the_gpu() { + use glam::DVec2; + use graphic_types::{EffectOperation, Effects}; + use half::f16; + + // A square 0.4 across turned 45 degrees, ending about 0.017 above the texel from (10, 11), which only red fills, though the texel's extent along the square's axes reaches it + let transform = DAffine2::from_translation(DVec2::new(10.5, 10.7)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_4) * DAffine2::from_scale(DVec2::splat(0.4)); + let size = 20; + let mut texels = vec![[f16::ZERO; 4]; size * size]; + texels[11 * size + 10] = [f16::ONE, f16::ZERO, f16::ZERO, f16::ONE]; + + for inverse in [false, true] { + let effects = Effects::from_operations([EffectOperation::PolarCoordinates { inverse, transform }]); + let Some(gpu) = gpu_effect_texels(&effects, &texels, size, &[]) else { return }; + for (index, texel) in gpu.iter().enumerate() { + let (x, y) = (index % size, index / size); + assert_eq!(*texel, [0.; 4], "({x}, {y}) shows {texel:?} with inverse {inverse}"); + } + } +} + +#[test] +fn polar_coordinates_match_the_cpu_within_slanted_and_turned_squares() { + use graphic_types::resampling::{FrameWarp, warp_frame}; + use graphic_types::{EffectOperation, Effects}; + use half::f16; + use raster_kernels::resample_kernels::frame_warped; + + // Colors varying across a texture 180 texels square, around a hole and through a translucent band, so the squares' sides cut through edges and translucency + let size = 180; + let texels: Vec<[f16; 4]> = (0..size * size) + .map(|index| { + let (x, y) = ((index % size) as f32 + 0.5, (index / size) as f32 + 0.5); + let alpha = if (x - 70.).hypot(y - 95.) < 12. { + 0. + } else if (60. ..72.).contains(&y) { + 0.5 + } else { + 1. + }; + let straight = [x / size as f32, y / size as f32, (x * 0.3).sin() * 0.5 + 0.5]; + let [red, green, blue] = straight.map(|channel| channel * alpha); + [red, green, blue, alpha].map(f16::from_f32) + }) + .collect(); + let plane = raster_kernels::effect_kernels::Plane { + width: size, + height: size, + data: texels.iter().map(|texel| texel.map(f16::to_f32)).collect(), + }; + + for transform in slanted_and_turned_squares() { + for inverse in [false, true] { + let operation = EffectOperation::PolarCoordinates { inverse, transform }; + let Some(gpu) = gpu_effect_texels(&Effects::from_operations([operation.clone()]), &texels, size, &[]) else { + return; + }; + let (Some((warp, _)), Some(square)) = (FrameWarp::of(&operation), warp_frame(transform, DAffine2::IDENTITY)) else { + panic!("{operation:?} has no square") + }; + let cpu = frame_warped(&plane, &warp, &square); + + let levels = (gpu.iter().zip(&cpu.data)) + .flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs() * 255.)) + .fold(0_f32, f32::max); + assert!(levels <= 1., "{operation:?} strays from the CPU's kernel by {levels} levels"); + } + } +} + +/// The transforms of squares in a texture 160 texels square, all but the last with their left and right sides, which wrapping joins at its seam, cutting through texels: +/// one 120.5 wide, one 120 across turned 10 degrees, that one mirrored across, and one 121 across centered on a texel. +fn polar_seam_squares() -> [DAffine2; 4] { + use glam::DVec2; + + let center = DAffine2::from_translation(DVec2::splat(80.)); + let turned = center * DAffine2::from_angle(10_f64.to_radians()) * DAffine2::from_scale(DVec2::splat(120.)); + [ + center * DAffine2::from_scale(DVec2::new(120.5, 120.)), + turned, + turned * DAffine2::from_scale(DVec2::new(-1., 1.)), + DAffine2::from_translation(DVec2::splat(80.5)) * DAffine2::from_scale(DVec2::splat(121.)), + ] +} + +/// A texture 160 texels square of opaque blue, as half floats and as the CPU's plane. +fn opaque_polar_content() -> (Vec<[half::f16; 4]>, raster_kernels::effect_kernels::Plane<[f32; 4]>) { + let texels = vec![[0.2, 0.6, 0.9, 1.].map(half::f16::from_f32); 160 * 160]; + let plane = raster_kernels::effect_kernels::Plane { + width: 160, + height: 160, + data: texels.iter().map(|texel| texel.map(half::f16::to_f32)).collect(), + }; + (texels, plane) +} + +/// The `plane` unwrapped within the square the `transform` places, then wrapped back within it, on the CPU. +fn polar_round_trip_on_the_cpu(plane: &raster_kernels::effect_kernels::Plane<[f32; 4]>, transform: DAffine2) -> raster_kernels::effect_kernels::Plane<[f32; 4]> { + use graphic_types::resampling::{FrameWarp, warp_frame}; + use raster_kernels::resample_kernels::frame_warped; + + let Some(square) = warp_frame(transform, DAffine2::IDENTITY) else { + panic!("{transform} has no square") + }; + let unwrapped = frame_warped(plane, &FrameWarp::Polar { inverse: true }, &square); + frame_warped(&unwrapped, &FrameWarp::Polar { inverse: false }, &square) +} + +#[test] +fn polar_coordinates_round_trip_opaque_content_without_a_seam() { + use glam::DVec2; + use graphic_types::resampling::warp_frame; + + let (_, plane) = opaque_polar_content(); + for transform in polar_seam_squares() { + let round_trip = polar_round_trip_on_the_cpu(&plane, transform); + let Some(square) = warp_frame(transform, DAffine2::IDENTITY) else { + panic!("{transform} has no square") + }; + let (to_local, half) = (square.pixels_to_local(), square.size / 2.); + + // Around the center and along the seam straight up from it, away from the rim, each texel shows the opaque content as those beside it do + for (index, texel) in round_trip.data.iter().enumerate() { + let (x, y) = (index % 160, index / 160); + let local = to_local.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)); + if local.x.abs() > 1.5 || !(-half.y + 2. ..1.5).contains(&local.y) { + continue; + } + + let difference = texel.iter().zip(&plane.data[index]).map(|(actual, expected)| (actual - expected).abs()).fold(0., f32::max); + assert!(difference < 0.01, "({x}, {y}) on the seam within {transform} shows {texel:?}"); + } + } +} + +#[test] +fn polar_coordinates_round_trip_without_a_seam_on_the_gpu_as_on_the_cpu() { + use graphic_types::{EffectOperation, Effects}; + + let (texels, plane) = opaque_polar_content(); + for transform in polar_seam_squares() { + let [unwrap, wrap] = [true, false].map(|inverse| EffectOperation::PolarCoordinates { inverse, transform }); + let Some(gpu) = gpu_effect_texels(&Effects::from_operations([unwrap, wrap]), &texels, 160, &[]) else { + return; + }; + let cpu = polar_round_trip_on_the_cpu(&plane, transform); + + let levels = (gpu.iter().zip(&cpu.data)) + .flat_map(|(gpu, cpu)| (0..4).map(|channel| (gpu[channel] - cpu[channel]).abs() * 255.)) + .fold(0_f32, f32::max); + assert!(levels <= 1., "the round trip within {transform} strays from the CPU's kernel by {levels} levels"); + } +} + +#[test] +fn motion_blurs_of_negative_distances_smear_as_positive_ones_do_on_the_cpu_and_gpu() { + use graphic_types::EffectOperation; + use rendering::{Render, RenderParams}; + + let size = UVec2::new(160, 160); + for (angle, distance) in [(0., 12.), (30., 7.5), (-70., 90.)] { + let [positive, negative] = [distance, -distance].map(|distance| patterned_raster(55., &[EffectOperation::MotionBlur { angle, distance, gamma: false }], 1.)); + let Some(worst) = gpu_and_cpu_difference(negative.clone(), size) else { return }; + assert!(worst <= 3, "a line {distance} long backward at {angle} degrees differs from the GPU by up to {worst} levels"); + + let draw = |item: &core_types::list::Item<_>| { + let graphic = graphic_types::Graphic::RasterCPU(Box::new(item.clone())); + render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) + }; + let (Some(forward), Some(backward)) = (draw(&positive), draw(&negative)) else { return }; + assert!(forward == backward, "a line {distance} long at {angle} degrees smears differently backward on the GPU"); + } +} + +#[test] +fn elliptical_radial_blurs_match_on_the_cpu_and_gpu_whatever_their_transforms_size() { + use glam::DVec2; + use graphic_types::{EffectOperation, RadialBlurMethod}; + use rendering::{Render, RenderParams}; + + let size = UVec2::new(160, 160); + let radial = |method, transform| EffectOperation::RadialBlur { + method, + amount: 40., + transform, + gamma: false, + }; + let draw = |operation: &EffectOperation| { + let graphic = graphic_types::Graphic::RasterCPU(Box::new(patterned_raster(55., std::slice::from_ref(operation), 1.))); + render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) + }; + // The most two renders differ by in levels of their premultiplied channels + let same = |first: &[[u8; 4]], second: &[[u8; 4]]| { + let difference = |(first, second): (&[u8; 4], &[u8; 4])| { + let (first, second) = (premultiplied_levels(*first), premultiplied_levels(*second)); + (0..4).map(|channel| (first[channel] - second[channel]).abs()).fold(0., f32::max) + }; + first.iter().zip(second).map(difference).fold(0., f32::max) + }; + + // About the image's middle and a point beyond its corner, along circles stretched across, turned, and slanted + let centers = [DAffine2::from_translation(DVec2::new(25., 27.)), DAffine2::from_translation(DVec2::new(-10., 60.))]; + let shapes = [ + DAffine2::from_scale(DVec2::new(3., 1.)), + DAffine2::from_angle(0.7) * DAffine2::from_scale(DVec2::new(1., 2.5)), + DAffine2::from_cols_array(&[1., 0., 0.8, 1., 0., 0.]), + ]; + for method in [RadialBlurMethod::Spin, RadialBlurMethod::Zoom] { + for (center, shape) in centers.into_iter().flat_map(|center| shapes.map(|shape| (center, shape))) { + let blur = radial(method, center * shape); + let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., std::slice::from_ref(&blur), 1.), size) else { + return; + }; + assert!(worst <= 3, "{blur:?} differs from the GPU by up to {worst} levels"); + + // Scaling the transform evenly changes nothing but rounding + let (Some(blurred), Some(scaled)) = (draw(&blur), draw(&radial(method, center * shape * DAffine2::from_scale(DVec2::splat(6.))))) else { + return; + }; + assert!(same(&blurred, &scaled) <= 2., "{blur:?} changes as its transform scales evenly"); + } + + // A round transform, however large and turned, blurs as its center alone does + for center in centers { + let (Some(alone), Some(round)) = ( + draw(&radial(method, center)), + draw(&radial(method, center * DAffine2::from_angle(1.) * DAffine2::from_scale(DVec2::splat(30.)))), + ) else { + return; + }; + assert!(same(&alone, &round) <= 2., "{method:?} about {center} changes along circles"); + } + } +} + +#[test] +fn bands_read_from_past_the_view_along_their_rows() { + use core_types::list::Item; + use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; + use rendering::{Render, RenderParams}; + + // A white square 1000 across bent across within a band as wide, with the band's square far below a view of the left tenth, whose rows read from twice as far right as the view reaches + let spherize = EffectOperation::Spherize { + amount: 100., + cylindrical: true, + transform: DAffine2::from_translation(DVec2::new(500., 2000.)) * DAffine2::from_scale(DVec2::new(1000., 10.)), + }; + let mut square = Item::new_from_element(Raster::new_cpu(Image::new(1, 1, GraphicColor::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(1000.))); + stamp_effect(&mut square, Effect::new(&spherize)); + let graphic = Graphic::RasterCPU(Box::new(square)); + + // Each bent row reads the square from right of the view, so it stays white + let size = UVec2::new(100, 1000); + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + for (x, y) in [0, 510, 999].into_iter().flat_map(|y| (0..size.x).map(move |x| (x, y))) { + assert_eq!(pixel(&pixels, size, x, y), [255; 4], "the bent row reads nothing at ({x}, {y})"); + } +} + +#[test] +fn svgs_draw_warps_on_groups_of_endless_content_as_the_gpu_does_masking_them_once() { + use core_types::list::{ATTR_EFFECTS, Item, List}; + use core_types::transform::Footprint; + use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::vector_types::gradient::Gradient; + use graphic_types::{EffectOperation, Effects, Graphic, MaskMode}; + use rendering::deferred_image::MAX_DEFERRED_IMAGE_PIXELS; + use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender}; + + // A group holding a gradient across the view, warped within a circle 40 across about its middle: twirled (also after an inverted endless mask hides it by half), wrapped within the square around it, or pinched to read from past the view + let size = UVec2::splat(64); + let circle = DAffine2::from_translation(DVec2::splat(32.)) * DAffine2::from_scale(DVec2::splat(40.)); + let twirl = EffectOperation::Twirl { angle: 180., transform: circle }; + let wrap = EffectOperation::PolarCoordinates { inverse: false, transform: circle }; + let pinch = EffectOperation::Pinch { amount: 1000., transform: circle }; + let half_hidden = EffectOperation::Mask { + mask: Graphic::from(GraphicColor::WHITE), + mode: MaskMode::default(), + density: 50., + feather: 0., + invert: true, + }; + let gradient = Item::new_from_element(Gradient::from(vec![GraphicColor::BLACK, GraphicColor::WHITE])).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.))); + + for effects in [vec![twirl.clone()], vec![half_hidden, twirl], vec![wrap], vec![pinch]] { + let group = Item::new_from_element(Graphic::Gradient(gradient.clone())).with_attribute(ATTR_EFFECTS, Effects::from_operations(effects.clone())); + let graphic = Graphic::Graphic(Box::new(group)); + let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + // Wrapping clears the gradient outside its square, from 12 to 52 + if matches!(effects[..], [EffectOperation::PolarCoordinates { .. }]) { + assert_eq!(pixel(&gpu, size, 5, 30)[3], 0, "the wrap leaves the gradient outside its square"); + } + + // SVG draws the group as the GPU's image of the area in view + let footprint = Footprint { + transform: DAffine2::IDENTITY, + resolution: size, + ..Default::default() + }; + let mut render = SvgRender::new(); + List::new_from_element(graphic).render_svg( + &mut render, + &RenderParams { + view: Some(footprint), + for_export: true, + ..Default::default() + }, + ); + let [deferred] = &render.deferred_images[..] else { + panic!("{effects:?} draws {} images", render.deferred_images.len()) + }; + let Some(executor) = executor() else { return }; + let _turn = take_turn(); + let layout = deferred.layout(footprint.transform, size.as_dvec2(), MAX_DEFERRED_IMAGE_PIXELS).expect("the image is in view"); + let rendered = executor.render_deferred_svg_images(&render.deferred_images, footprint); + let [(_, texture)] = &rendered[..] else { panic!("expected one image, got {}", rendered.len()) }; + let image = executor.read_texture_pixels(texture).expect("the image reads back"); + + // The image matches the GPU's render of the view + for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { + let texel = layout.document_to_pixels.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor().as_uvec2(); + let index = ((texel.y * layout.size.x + texel.x) * 4) as usize; + let (expected, actual) = (premultiplied_levels(pixel(&gpu, size, x, y)), premultiplied_levels(image[index..index + 4].try_into().unwrap())); + let difference = (0..4).map(|channel| (expected[channel] - actual[channel]).abs()).fold(0., f32::max); + assert!(difference <= 2., "{effects:?} draws {actual:?} at ({x}, {y}) rather than the GPU's {expected:?}"); + } + + // Nothing in the SVG masks the image again + let mut svg = render.svg.to_svg_string(); + futures::executor::block_on(executor.resolve_deferred_svg_images(&mut svg, &mut Vec::new(), rendered)); + assert!(svg.contains("data:image/png;base64,") && !svg.contains("mask="), "{effects:?} draws {svg}"); + } +} + +#[test] +fn warps_bend_endless_gradients_within_their_circle() { + use core_types::list::Item; + use core_types::{ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::vector_types::gradient::{Gradient, GradientStop}; + use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; + use rendering::{Render, RenderParams}; + + // A gradient from black to white across the render, twirled within a circle 40 across about its middle + let stops = [(0., 0.), (1., 1.)].map(|(position, gray)| GradientStop { + position, + midpoint: 0.5, + color: GraphicColor::from_gamma_srgb_channels(gray, gray, gray, 1.), + }); + let size = UVec2::splat(64); + let gradient = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.))); + let mut twirled = gradient.clone(); + let twirl = EffectOperation::Twirl { + angle: 180., + transform: DAffine2::from_translation(DVec2::splat(32.)) * DAffine2::from_scale(DVec2::splat(40.)), + }; + stamp_effect(&mut twirled, Effect::new(&twirl)); + + let draw = |graphic: Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())); + let (Some(plain), Some(twirled)) = (draw(Graphic::Gradient(gradient)), draw(Graphic::Gradient(twirled))) else { + return; + }; + + // Past the circle the gradient stays as it is, and within it the twirl turns the gradient's levels + let mut turned = false; + for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { + let distance = DVec2::new(x as f64 + 0.5, y as f64 + 0.5).distance(DVec2::splat(32.)); + let difference = pixel(&plain, size, x, y) + .iter() + .zip(pixel(&twirled, size, x, y)) + .map(|(plain, twirled)| plain.abs_diff(twirled)) + .max() + .unwrap_or_default(); + assert!(distance < 21. || difference <= 2, "the twirl changes ({x}, {y}) past its circle"); + turned |= difference > 20; + } + assert!(turned, "the twirl leaves the gradient as it is within its circle"); +} + +#[test] +fn warps_carry_what_earlier_effects_paint_past_the_frame_on_the_cpu_and_gpu() { + use glam::DVec2; + use graphic_types::{EffectKind, EffectOperation}; + + // A shadow cast down and right and a glow all around, each painting well past the content's frame + let shadow = drop_shadow(core_types::Color::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.9), DVec2::new(6., 8.), 4., 0.); + let mut glow = EffectOperation::default_for(EffectKind::OuterGlow); + if let EffectOperation::OuterGlow { size, spread, .. } = &mut glow { + (*size, *spread) = (9., 40.); + } + + // The warps act within the image 50 pixels across, measured from its corner + let transform = DAffine2::from_translation(DVec2::splat(25.)) * DAffine2::from_scale(DVec2::splat(50.)); + let effects = [ + EffectOperation::Twirl { angle: 140., transform }, + EffectOperation::Spherize { + amount: -80., + cylindrical: true, + transform, + }, + EffectOperation::Spherize { + amount: 60., + cylindrical: true, + transform: transform * DAffine2::from_angle(std::f64::consts::FRAC_PI_2), + }, + EffectOperation::PolarCoordinates { inverse: false, transform }, + ]; + for (earlier, effect) in [&shadow, &glow].into_iter().flat_map(|earlier| effects.iter().map(move |effect| (earlier, effect))) { + for fill in [1., 0.5] { + let chain = [earlier.clone(), effect.clone()]; + let Some(worst) = gpu_and_cpu_difference(patterned_raster(55., &chain, fill), UVec2::new(160, 160)) else { + return; + }; + assert!(worst <= 3, "{chain:?} at fill {fill} differs from the GPU by up to {worst} levels"); + } + } +} + #[test] fn resampling_effects_read_what_lies_beyond_the_view() { use glam::DVec2; use graphic_types::{EffectOperation, Graphic, RadialBlurMethod}; use rendering::{Render, RenderParams}; - // Only the right part of the content is in view, yet the arcs around its middle sweep through the part left of the view + // Only the right part of the content is in view, yet the arcs around its middle, twists, and wraps read from the part left of the view + let on_image = DAffine2::from_translation(DVec2::splat(25.)) * DAffine2::from_scale(DVec2::splat(50.)); let spin = EffectOperation::RadialBlur { method: RadialBlurMethod::Spin, amount: 90., - center: DVec2::splat(25.), + transform: DAffine2::from_translation(DVec2::splat(25.)), gamma: false, }; - let graphic = Graphic::RasterCPU(Box::new(patterned_raster(20., &[spin], 1.))); - let graphic = &graphic; - let draw = |offset: f64| move |scene: &mut VelloSceneBuilder| graphic.render_to_vello(scene, DAffine2::from_translation(DVec2::new(-offset, 0.)), &RenderParams::default()); + let twirl = EffectOperation::Twirl { angle: 200., transform: on_image }; + let polar = EffectOperation::PolarCoordinates { inverse: false, transform: on_image }; - let Some(whole) = render(UVec2::new(96, 96), draw(0.)) else { return }; - let Some(part) = render(UVec2::new(32, 96), draw(56.)) else { return }; - for y in 0..96 { - for x in 0..32 { - let (expected, actual) = (pixel(&whole, UVec2::new(96, 96), x + 56, y), pixel(&part, UVec2::new(32, 96), x, y)); - let difference = expected.iter().zip(actual).map(|(&expected, actual)| expected.abs_diff(actual)).max().unwrap_or_default(); - assert!(difference <= 1, "at ({x}, {y}) the view shows {actual:?} rather than {expected:?}"); + for effect in [spin, twirl, polar] { + let graphic = Graphic::RasterCPU(Box::new(patterned_raster(20., std::slice::from_ref(&effect), 1.))); + let graphic = &graphic; + let draw = |offset: f64| move |scene: &mut VelloSceneBuilder| graphic.render_to_vello(scene, DAffine2::from_translation(DVec2::new(-offset, 0.)), &RenderParams::default()); + + let Some(whole) = render(UVec2::new(96, 96), draw(0.)) else { return }; + let Some(part) = render(UVec2::new(32, 96), draw(56.)) else { return }; + for y in 0..96 { + for x in 0..32 { + let (expected, actual) = (pixel(&whole, UVec2::new(96, 96), x + 56, y), pixel(&part, UVec2::new(32, 96), x, y)); + let difference = expected.iter().zip(actual).map(|(&expected, actual)| expected.abs_diff(actual)).max().unwrap_or_default(); + assert!(difference <= 1, "{effect:?} at ({x}, {y}) shows {actual:?} rather than {expected:?}"); + } } } } + +#[test] +fn warps_fill_the_corners_of_their_square_in_a_clipped_turned_group() { + use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List}; + use core_types::{ATTR_CLIPPING_MASK, ATTR_TRANSFORM, Color as GraphicColor}; + use glam::DVec2; + use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector}; + use rendering::{Render, RenderParams}; + use vello_gpu::kurbo::Shape; + + let filled = |path: &BezPath, color: GraphicColor| { + let mut item = Vector::item_from_bezpath(path); + item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(color)))); + item + }; + + // A red disc in a group turned an eighth and clipped to a white base, unwrapped across the whole square around it, with corners past the disc's own bounds + let base = Item::new_from_element(Graphic::Vector(Box::new(filled(&Rect::new(0., 0., 128., 128.).to_path(0.1), GraphicColor::WHITE)))); + let disc = filled(&vello_gpu::kurbo::Circle::new((0., 0.), 30.).to_path(0.1), GraphicColor::RED).with_attribute(ATTR_CLIPPING_MASK, true); + let unwrap = EffectOperation::PolarCoordinates { + inverse: true, + transform: DAffine2::from_scale(DVec2::splat(60.)), + }; + let group = Item::new_from_element(Graphic::Vector(Box::new(disc))) + .with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(64.)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_4)) + .with_attribute(ATTR_EFFECTS, Effects::from_operations([unwrap])); + let graphic = Graphic::GraphicList([base, group].into_iter().collect()); + + let size = UVec2::splat(128); + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + assert_eq!(pixel(&pixels, size, 64, 64), [255, 0, 0, 255], "the unwrapped disc shows over the base"); + assert_eq!(pixel(&pixels, size, 101, 64), [255, 0, 0, 255], "the square's corner past the disc's bounds is filled"); +} diff --git a/node-graph/libraries/wgpu-executor/src/vello_resample.wgsl b/node-graph/libraries/wgpu-executor/src/vello_resample.wgsl index cc1f39ef49..df2912cdb7 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_resample.wgsl +++ b/node-graph/libraries/wgpu-executor/src/vello_resample.wgsl @@ -1,5 +1,5 @@ // The passes that resample an item's content from elsewhere than nearby, like blurs along lines and arcs. -// They join the effect passes' module, sharing its parameters and inputs. +// They join the effect passes' module, sharing its parameters and inputs, and read their frame from the start of the tap array (see `frame_parameters`). // The source's texel, or transparency past its edges fn texel_or_transparent(texel: vec2) -> vec4 { @@ -115,13 +115,32 @@ fn motion_unshear(@builtin(position) position: vec4) -> @location(0) vec4, + // The map from the frame's local space into texels + local_to_texels: mat3x2, + // Half the lengths of the frame's sides, in the effect space + half_size: vec2, +} + +fn frame_parameters() -> Frame { + let taps = parameters.taps; + return Frame( + mat3x2(taps[0].xy, taps[0].zw, taps[1].xy), + mat3x2(taps[1].zw, taps[2].xy, taps[2].zw), + taps[3].xy, + ); +} + fn transform_point(transform: mat3x2, point: vec2) -> vec2 { return transform * vec3(point, 1.); } // A radial blur around or through its center, spanning `values.x` (a spin's angle, or a zoom's share of the distance to the center), -// spinning with `values.y` 0 or zooming with 1, at `values.z` texels per unit of the effect space, matching the CPU's `radial_blurred`. -// `taps[0..3]` hold the maps from texels into the effect space measured from the center, and back. +// spinning with `values.y` 0 or zooming with 1, at up to `values.z` texels per unit of its circle's space along an arc, matching the CPU's `radial_blurred`. +// `taps[0..3]` hold the maps from texels into its circle's space, measured from the center, and back. @fragment fn radial_blur(@builtin(position) position: vec4) -> @location(0) vec4 { let taps = parameters.taps; @@ -151,3 +170,212 @@ fn radial_blur(@builtin(position) position: vec4) -> @location(0) vec4 // Matching `RADIAL_SAMPLES_PER_PIXEL` and `MAX_RADIAL_SAMPLES` const RADIAL_SAMPLES_PER_TEXEL: f32 = 2.; const MAX_RADIAL_SAMPLES: u32 = 512u; + +const PI: f32 = 3.14159265358979; + +fn rotated(point: vec2, angle: f32) -> vec2 { + let turn = vec2(cos(angle), sin(angle)); + return vec2(turn.x * point.x - turn.y * point.y, turn.y * point.x + turn.x * point.y); +} + +// Spherize's bend of a distance from 0 to 1 by its `amount`, matching the CPU's `spherize_bend` +fn spherize_bend(distance: f32, amount: f32) -> f32 { + if amount >= 0. { + return distance + amount * ((2. / PI) * asin(distance) - distance); + } + return distance - amount * (sin(PI / 2. * distance) - distance); +} + +// Where a warp within the frame reads the point at `local` from (`values.x` 0 for Twirl, 1 Pinch, 2 Spherize, 3 Polar Coordinates, with its settings in `values.yz`), matching the CPU's `FrameWarp::source` +fn frame_warp_source(local: vec2, half: vec2) -> vec2 { + let kind = u32(parameters.values.x); + let setting = parameters.values.y; + let normalized = local / half; + + switch kind { + case 0u: { + let distance = length(normalized); + if distance >= 1. { + return local; + } + let falloff = 1. - distance; + return rotated(normalized, -setting * falloff * falloff) * half; + } + case 1u: { + let distance_squared = dot(normalized, normalized); + if distance_squared >= 1. { + return local; + } + let falloff = 1. - distance_squared; + return local * (1. + setting * falloff * falloff); + } + case 2u: { + // Its mode in `values.z` is 0 for a sphere and 1 for a cylinder + if u32(parameters.values.z) == 0u { + let distance = length(normalized); + if distance >= 1. || distance <= 0. { + return local; + } + return local * (spherize_bend(distance, setting) / distance); + } + if abs(normalized.x) >= 1. { + return local; + } + return vec2(sign(normalized.x) * spherize_bend(abs(normalized.x), setting) * half.x, local.y); + } + default: { + if setting < 0.5 { + let angle = select(atan2(normalized.x, normalized.y), 0., all(normalized == vec2(0.))); + return vec2(angle / PI, length(normalized) * 2. - 1.) * half; + } + let angle = normalized.x * PI; + let distance = (normalized.y + 1.) / 2.; + return vec2(sin(angle), cos(angle)) * distance * half; + } + } +} + +// Matching `NEGLIGIBLE_COVERAGE` and `UNTOUCHED_COVERAGE` +const NEGLIGIBLE_COVERAGE: f32 = 1. / 65536.; +const UNTOUCHED_COVERAGE: f32 = 1. / 256.; + +// How much of a texel centered at `local` the frame covers along each axis, ramping from 1 at `half_texel` within a side to 0 at `half_texel` past it, matching the CPU's `frame_coverage` +fn frame_coverage(local: vec2, half: vec2, half_texel: vec2) -> vec2 { + return clamp(0.5 + (half - abs(local)) / (2. * half_texel), vec2(0.), vec2(1.)); +} + +// A warp relative to the frame, matching the CPU's `frame_warped`. Twirl, Pinch, and Spherize carry every texel, leaving what lies past their ellipse or band as it is. +// Polar Coordinates reads only the texels the frame covers wholly (see `sample_bilinear_on_side`, a texel reaching `taps[4].zw` along its sides and half of one `taps[4].xy`) and clears what lies outside it, fading those its edge cuts through by how much it covers. +@fragment +fn frame_warp(@builtin(position) position: vec4) -> @location(0) vec4 { + let frame = frame_parameters(); + let original = textureLoad(source, vec2(position.xy), 0); + let local = transform_point(frame.texels_to_local, position.xy); + let half = frame.half_size; + if u32(parameters.values.x) != 3u { + let point = frame_warp_source(local, half); + if all(point == local) { + return original; + } + return sample_bilinear(transform_point(frame.local_to_texels, point)); + } + + let half_texel = parameters.taps[4].xy; + let covered = frame_coverage(local, half, half_texel); + let coverage = covered.x * covered.y; + if coverage < NEGLIGIBLE_COVERAGE { + return vec4(0.); + } + + // The reads lie a texel's extent in from the frame's sides, which a turned texel reaches farther along than half a texel + let point = frame_warp_source(clamp(local, -half, half), half); + let texel_extent = parameters.taps[4].zw; + let inset = min(texel_extent, half); + let low = -half + inset; + let high = half - inset; + let near = clamp(point, low, high); + var far = near; + var toward_far = 0.; + + // Wrapping meets the frame's left and right sides at the seam straight up from the center, so it reads across them, matching the CPU's `wrapped_across_sides` + let wrap = parameters.values.y < 0.5; + if wrap && point.x > high.x { + far.x = low.x; + toward_far = (point.x - high.x) / (2. * inset.x); + } else if wrap && point.x < low.x { + far.x = high.x; + toward_far = (low.x - point.x) / (2. * inset.x); + } + + // The reads on either side of the seam, taking turns through one call so the shader compiles quickly + var read = vec4(0.); + for (var side = 0; side < 2; side++) { + let weight = select(1. - toward_far, toward_far, side == 1); + if weight > 0. { + read += sample_bilinear_on_side(frame, transform_point(frame.local_to_texels, select(near, far, side == 1)), texel_extent, half_texel) * weight; + } + } + + // Only wrapping's rim fades, where its source passes the bottom side, matching the CPU + let fade = select(1., clamp(0.5 + (half.y - point.y) / (2. * half_texel.y), 0., 1.), wrap); + return held_at_opaque(read) * fade * coverage; +} + +// Whether the texel at `texel`, which reaches `texel_extent` along the frame's sides, lies on the frame's side of its edge, which covers it wholly +fn texel_on_side(frame: Frame, texel: vec2, texel_extent: vec2) -> bool { + let covered = frame_coverage(transform_point(frame.texels_to_local, texel + 0.5), frame.half_size, texel_extent); + return covered.x * covered.y > 1. - UNTOUCHED_COVERAGE; +} + +// Whether the frame touches the texel at `texel` (its corner), which it does unless an axis of either separates them: the frame's, along which the texel reaches `texel_extent`, or the texel's, along which the frame spans its bounding box +fn frame_touches_texel(frame: Frame, texel: vec2, texel_extent: vec2) -> bool { + let along_frame = frame_coverage(transform_point(frame.texels_to_local, texel + 0.5), frame.half_size, texel_extent); + let box_reach = abs(frame.local_to_texels[0]) * frame.half_size.x + abs(frame.local_to_texels[1]) * frame.half_size.y; + let along_texels = frame_coverage(texel + 0.5 - frame.local_to_texels[2], box_reach, vec2(0.5)); + return all(min(along_frame, along_texels) >= vec2(UNTOUCHED_COVERAGE)); +} + +// The source at a point in texels interpolated as `sample_bilinear` does, but only between the texels on the frame's side of its edge (see `texel_on_side`), matching the CPU's `sample_bilinear_on_side`. +// The texels the edge cuts through hold the content's own edge, so they're left out. Where all four are, as at a corner, the nearest texel on that side stands in. +// Content too thin to cover any texel wholly is instead unmixed from the transparency beside it in the texels the frame touches. +fn sample_bilinear_on_side(frame: Frame, point: vec2, texel_extent: vec2, half_texel: vec2) -> vec4 { + let position = point - 0.5; + let base = floor(position); + let fraction = position - base; + + var sum = vec4(0.); + var total = 0.; + // The texels the frame touches, with its coverage of each (`half_texel` half of one along its sides), for content too thin to cover any wholly + var bilinear_sum = vec4(0.); + var covered = 0.; + for (var corner = 0; corner < 4; corner++) { + let offset = vec2(f32(corner % 2), f32(corner / 2)); + let weights = mix(1. - fraction, fraction, offset); + let weight = weights.x * weights.y; + let texel = base + offset; + let color = texel_or_transparent(vec2(texel)); + if weight > 0. && texel_on_side(frame, texel, texel_extent) { + sum += color * weight; + total += weight; + } + + if frame_touches_texel(frame, texel, texel_extent) { + let coverage = frame_coverage(transform_point(frame.texels_to_local, texel + 0.5), frame.half_size, half_texel); + bilinear_sum += color * weight; + covered += coverage.x * coverage.y * weight; + } + } + if total > 0. { + return sum / total; + } + + // The nearest texel on the side among the 16 around the point, the first of those equally near + var nearest = vec4(0.); + var nearest_distance = -1.; + for (var y = -1; y <= 2; y++) { + for (var x = -1; x <= 2; x++) { + let texel = base + vec2(f32(x), f32(y)); + let distance_squared = dot(texel + 0.5 - point, texel + 0.5 - point); + if texel_on_side(frame, texel, texel_extent) && (nearest_distance < 0. || distance_squared < nearest_distance) { + nearest = texel_or_transparent(vec2(texel)); + nearest_distance = distance_squared; + } + } + } + if nearest_distance >= 0. { + return nearest; + } + if covered <= 0. { + return vec4(0.); + } + + // Each texel the frame touches mixes the content with the transparency beside it by its coverage, so that mix is undone + return bilinear_sum / covered; +} + +// Premultiplied channels kept from going negative, scaled down to opaque past it, and with the color held within the alpha, matching the CPU's `held_at_opaque` +fn held_at_opaque(color: vec4) -> vec4 { + let kept = max(color, vec4(0.)); + let scaled = kept / max(kept.a, 1.); + return min(scaled, vec4(scaled.a)); +} diff --git a/node-graph/nodes/blending/src/distortions.rs b/node-graph/nodes/blending/src/distortions.rs index a6b4f39974..4c8a30be75 100644 --- a/node-graph/nodes/blending/src/distortions.rs +++ b/node-graph/nodes/blending/src/distortions.rs @@ -1,6 +1,6 @@ use core_types::list::Item; use core_types::{Color, Ctx}; -use glam::DVec2; +use glam::DAffine2; use graphic_types::raster_types::{CPU, GPU, Raster}; use graphic_types::{Effect, EffectOperation, Generator, Graphic, RadialBlurMethod, Vector, stamp_effect}; use vector_types::Gradient; @@ -17,11 +17,10 @@ fn motion_blur( #[range] #[soft(-90..90)] angle: Item, - /// How long the line each point is smeared along is. + /// How long the line each point is smeared along is. Negative distances smear like positive ones. #[unit(" px")] #[range] - #[hard(0..)] - #[soft(..250)] + #[soft(0..250)] #[default(10.)] distance: Item, /// Opt to incorrectly blend the colors in gamma space for compatibility with the results from other software. @@ -40,7 +39,7 @@ fn motion_blur( } /// Smears the input graphics along circles around a center, or along lines through it. -#[node_macro::node(category("Raster: Filter"))] +#[node_macro::node(category("Raster: Filter"), version(2))] fn radial_blur( _: impl Ctx, /// The content to smear. @@ -54,9 +53,12 @@ fn radial_blur( #[soft(..100)] #[default(10.)] amount: Item, - /// The point the content spins around or zooms toward, as an offset from the origin of the content's local coordinate space. + /// Places the circle the content spins along, with the center it spins around or zooms toward, measured from the origin of the content's local coordinate space. By default, it's a circle 500 px across centered at (250, 250). + /// + /// Stretching, turning, or slanting the circle makes a spin follow ellipses rather than circles. Its size changes nothing, and a zoom only uses its center. #[unit(" px")] - center: Item, + #[default(250., 250., 500., 500.)] + transform: Item, /// Opt to incorrectly blend the colors in gamma space for compatibility with the results from other software. gamma: Item, ) -> Item { @@ -66,9 +68,126 @@ fn radial_blur( Effect::new(&EffectOperation::RadialBlur { method: *method.element(), amount: *amount.element(), - center: *center.element(), + transform: *transform.element(), gamma: *gamma.element(), }), ); content } + +/// Turns the input graphics around the center of a circle, the most at the center and none at its edge. +#[node_macro::node(category("Raster: Filter"))] +fn twirl( + _: impl Ctx, + /// The content to turn. + #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String, Generator)] + content: Item, + /// How far the center turns, clockwise for a positive angle. + #[unit("°")] + #[range] + #[soft(-999..999)] + #[default(50.)] + angle: Item, + /// Places the circle the content turns within, measured from the origin of the content's local coordinate space, which stretching, turning, or slanting makes an ellipse. By default, it's a circle 500 px across centered at (250, 250). + #[unit(" px")] + #[default(250., 250., 500., 500.)] + transform: Item, +) -> Item { + let mut content = content; + stamp_effect( + &mut content, + Effect::new(&EffectOperation::Twirl { + angle: *angle.element(), + transform: *transform.element(), + }), + ); + content +} + +/// Squeezes the input graphics toward the center of a circle, or pushes them out from it. +#[node_macro::node(category("Raster: Filter"))] +fn pinch( + _: impl Ctx, + /// The content to squeeze. + #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String, Generator)] + content: Item, + /// How strongly the content squeezes toward the center, or pushes out from it when negative. Past 100% either way, it grows stronger until the content folds over. + #[unit("%")] + #[range] + #[soft(-100..100)] + #[default(50.)] + amount: Item, + /// Places the circle the content squeezes within, measured from the origin of the content's local coordinate space, which stretching, turning, or slanting makes an ellipse. By default, it's a circle 500 px across centered at (250, 250). + #[unit(" px")] + #[default(250., 250., 500., 500.)] + transform: Item, +) -> Item { + let mut content = content; + stamp_effect( + &mut content, + Effect::new(&EffectOperation::Pinch { + amount: *amount.element(), + transform: *transform.element(), + }), + ); + content +} + +/// Bulges the input graphics out from the center of a circle, as if wrapped around a ball or an upright cylinder, or sinks them. +#[node_macro::node(category("Raster: Filter"))] +fn spherize( + _: impl Ctx, + /// The content to bulge. + #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String, Generator)] + content: Item, + /// How strongly the content bulges out, or sinks in when negative. Past 100% either way, it grows stronger until the content folds over. + #[unit("%")] + #[range] + #[soft(-100..100)] + #[default(100.)] + amount: Item, + /// Bulges the content only across, as if wrapped around an upright cylinder, rather than both ways around a ball. + cylindrical: Item, + /// Places the circle the content bulges within, measured from the origin of the content's local coordinate space, which stretching, turning, or slanting makes an ellipse. By default, it's a circle 500 px across centered at (250, 250). + /// + /// When cylindrical, the content bends as if wrapped around a cylinder as wide as the circle, within a band that runs on endlessly along it. Turning the transform turns the cylinder. + #[unit(" px")] + #[default(250., 250., 500., 500.)] + transform: Item, +) -> Item { + let mut content = content; + stamp_effect( + &mut content, + Effect::new(&EffectOperation::Spherize { + amount: *amount.element(), + cylindrical: *cylindrical.element(), + transform: *transform.element(), + }), + ); + content +} + +/// Wraps the input graphics within a square around its center, or unwraps them, clearing everything outside the square. +#[node_macro::node(category("Raster: Filter"))] +fn polar_coordinates( + _: impl Ctx, + /// The content to wrap. + #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String, Generator)] + content: Item, + /// Unwraps the content from around the square's center. Unchecked, the content wraps around the center, the square's top edge gathering there and its bottom edge running around the circle within it. + inverse: Item, + /// Places the square the content wraps within, measured from the origin of the content's local coordinate space. The seam where its left and right edges meet runs straight up from its center. By default, it's a square 500 px across centered at (250, 250). + #[unit(" px")] + #[default(250., 250., 500., 500.)] + transform: Item, +) -> Item { + let mut content = content; + stamp_effect( + &mut content, + Effect::new(&EffectOperation::PolarCoordinates { + inverse: *inverse.element(), + transform: *transform.element(), + }), + ); + content +}