From 19df13ad1d2d691382fc2c8cdc9901e403a72f81 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Tue, 1 Dec 2026 22:52:49 -0800 Subject: [PATCH] New node: 'Warp' (#5056) Add a Warp effect bending any graphic into 15 preset shapes --- .../data_panel/data_panel_message_handler.rs | 3 + .../document/node_graph/node_inspector.rs | 2 + node-graph/graph-craft/src/document/value.rs | 1 + .../interpreted-executor/src/node_registry.rs | 2 + .../graphic-types/src/effect_layers.rs | 2 + .../libraries/graphic-types/src/effects.rs | 84 +- node-graph/libraries/graphic-types/src/lib.rs | 2 + .../libraries/graphic-types/src/resampling.rs | 795 ++++++++++++- .../libraries/graphic-types/src/warp.rs | 583 ++++++++++ .../libraries/raster-kernels/src/lib.rs | 1 + .../raster-kernels/src/raster_effects.rs | 77 +- .../raster-kernels/src/resample_kernels.rs | 148 +++ .../raster-kernels/src/warp_kernels.rs | 684 +++++++++++ .../libraries/rendering/src/renderer.rs | 342 +++++- .../wgpu-executor/src/vello_adjustments.rs | 4 +- .../wgpu-executor/src/vello_effects.rs | 122 +- .../src/vello_effects/resample.rs | 2 +- .../wgpu-executor/src/vello_effects/warp.rs | 54 + .../wgpu-executor/src/vello_render/tests.rs | 1027 ++++++++++++++++- .../wgpu-executor/src/vello_resample.wgsl | 106 ++ .../wgpu-executor/src/vello_warp.wgsl | 452 ++++++++ node-graph/nodes/blending/src/distortions.rs | 50 +- node-graph/nodes/gstd/src/lib.rs | 2 +- 23 files changed, 4468 insertions(+), 77 deletions(-) create mode 100644 node-graph/libraries/graphic-types/src/warp.rs create mode 100644 node-graph/libraries/raster-kernels/src/warp_kernels.rs create mode 100644 node-graph/libraries/wgpu-executor/src/vello_effects/warp.rs create mode 100644 node-graph/libraries/wgpu-executor/src/vello_warp.wgsl diff --git a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs index a69626f95e..4b2bbc9f2c 100644 --- a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs +++ b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs @@ -7,6 +7,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*; use crate::node_graph_executor::InspectedContext; use glam::{Affine2, DAffine2, Vec2}; use graph_craft::document::NodeId; +use graphene_std::WarpStyle; use graphene_std::animation::RealTimeMode; use graphene_std::blending::BlendMode; use graphene_std::color::SRGBA8; @@ -1273,6 +1274,7 @@ impl_table_item_layout_for_choice_enum!( BevelTechnique, BevelStyle, RadialBlurMethod, + WarpStyle, WaveType, DisplaceMode, EffectKind, @@ -1467,6 +1469,7 @@ macro_rules! known_item_types { BevelDirection, BevelTechnique, RadialBlurMethod, + WarpStyle, WaveType, DisplaceMode, DashPattern, 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 6fc2013b7f..6da5751d47 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -20,6 +20,7 @@ use graph_craft::application_io::resource::{DataSource, Resource, ResourceId}; use graph_craft::document::value::TaggedValue; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput}; use graph_craft::{Type, concrete, item}; +use graphene_std::WarpStyle; use graphene_std::animation::RealTimeMode; use graphene_std::color::SRGBA8; use graphene_std::raster::{ @@ -457,6 +458,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), + Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index a540067995..fbc887bc01 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -548,6 +548,7 @@ tagged_value! { BevelTechnique(graphic_types::BevelTechnique), NoiseDistribution(graphic_types::NoiseDistribution), RadialBlurMethod(graphic_types::RadialBlurMethod), + WarpStyle(graphic_types::WarpStyle), WaveType(graphic_types::WaveType), DisplaceMode(graphic_types::DisplaceMode), GridType(vector::misc::GridType), diff --git a/node-graph/interpreted-executor/src/node_registry.rs b/node-graph/interpreted-executor/src/node_registry.rs index bf6aada7f9..c970915cab 100644 --- a/node-graph/interpreted-executor/src/node_registry.rs +++ b/node-graph/interpreted-executor/src/node_registry.rs @@ -5,6 +5,7 @@ use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::document::value::RenderOutput; use graph_craft::proto::{NodeConstructor, TypeErasedBox}; use graphene_animation::AnimationCurve; +use graphene_std::WarpStyle; use graphene_std::animation::RealTimeMode; use graphene_std::any::DynAnyNode; use graphene_std::brush::Stroke; @@ -299,6 +300,7 @@ fn node_registry() -> HashMap bool { | EffectOperation::Pinch { .. } | EffectOperation::Spherize { .. } | EffectOperation::PolarCoordinates { .. } + | EffectOperation::Warp { .. } | EffectOperation::Ripple { .. } | EffectOperation::Wave { .. } | EffectOperation::Displace { .. } @@ -397,6 +398,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM | EffectOperation::Pinch { .. } | EffectOperation::Spherize { .. } | EffectOperation::PolarCoordinates { .. } + | EffectOperation::Warp { .. } | EffectOperation::Ripple { .. } | EffectOperation::Wave { .. } | EffectOperation::Displace { .. } diff --git a/node-graph/libraries/graphic-types/src/effects.rs b/node-graph/libraries/graphic-types/src/effects.rs index 62513a7b60..c44ffc0e3f 100644 --- a/node-graph/libraries/graphic-types/src/effects.rs +++ b/node-graph/libraries/graphic-types/src/effects.rs @@ -8,6 +8,7 @@ use crate::filters::{Convolution, NoiseDistribution}; use crate::masks::{MaskMode, mask_feather_sigma}; use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters}; use crate::resampling::{DisplaceMode, RadialBlurMethod, WaveType, confines_to_frame}; +use crate::warp::WarpStyle; use core_types::ATTR_TRANSFORM; use core_types::Color; use core_types::blending::BlendMode; @@ -78,6 +79,8 @@ pub enum EffectKind { Spherize, /// Wraps the content within a square around its center, or unwraps it. PolarCoordinates, + /// Bends the content within a box into a preset shape, like an arc, a flag, or a fish. + Warp, /// Moves the content by crossing ripples, like the surface of a pond. Ripple, /// Moves the content by undulations of random lengths across and down. @@ -135,6 +138,7 @@ impl std::fmt::Display for EffectKind { Self::Pinch => "Pinch", Self::Spherize => "Spherize", Self::PolarCoordinates => "Polar Coordinates", + Self::Warp => "Warp", Self::Ripple => "Ripple", Self::Wave => "Wave", Self::Displace => "Displace", @@ -516,7 +520,7 @@ impl Effects { if let Some(effect) = self.0.element_mut(index) && matches!( effect.kind(), - EffectKind::RadialBlur | EffectKind::Twirl | EffectKind::Pinch | EffectKind::Spherize | EffectKind::PolarCoordinates + EffectKind::RadialBlur | EffectKind::Twirl | EffectKind::Pinch | EffectKind::Spherize | EffectKind::PolarCoordinates | EffectKind::Warp ) { let transform = effect.0.attribute_mut_or_insert_default::("transform"); transform.translation += stamped_transform.matrix2 * baked.translation; @@ -1038,6 +1042,19 @@ pub enum EffectOperation { inverse: bool, transform: DAffine2, }, + /// Carries the content within the square from -0.5 to 0.5 that its `transform` places in the effect space through the warp's patch, clearing all else. + Warp { + style: WarpStyle, + /// Percent, from -100 to 100. + bend: f64, + /// Percent, from -100 to 100. + horizontal_distortion: f64, + /// Percent, from -100 to 100. + vertical_distortion: f64, + /// Whether the style bends the square's left and right edges instead of the top and bottom. + vertical: bool, + transform: DAffine2, + }, /// Moves the content by crossing ripples measured from the frame's corner. Ripple { /// Percent, of how far the size moves the content at most. @@ -1132,6 +1149,7 @@ impl EffectOperation { Self::Pinch { .. } => EffectKind::Pinch, Self::Spherize { .. } => EffectKind::Spherize, Self::PolarCoordinates { .. } => EffectKind::PolarCoordinates, + Self::Warp { .. } => EffectKind::Warp, Self::Ripple { .. } => EffectKind::Ripple, Self::Wave { .. } => EffectKind::Wave, Self::Displace { .. } => EffectKind::Displace, @@ -1183,8 +1201,8 @@ impl EffectOperation { 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, + // They clear what lies outside their square, which is everything where the square collapses + Self::PolarCoordinates { .. } | Self::Warp { .. } => false, Self::Ripple { amount, size, .. } => *amount == 0. || *size == 0., Self::Wave { total_generators, @@ -1226,7 +1244,9 @@ impl EffectOperation { pub fn reads_pixels_around(&self) -> bool { match self { Self::Blur { .. } | Self::MotionBlur { .. } | Self::RadialBlur { .. } => true, - Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => true, + Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => { + true + } Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true, // Cast from the content's shape, reading a mask's own image or a feather's map, or changing each pixel alone Self::DropShadow { .. } @@ -1298,7 +1318,7 @@ impl EffectOperation { // The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3., // They reach as far as `Effects::reach_around` measures from where the content lies - Self::RadialBlur { .. } | Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } => 0., + Self::RadialBlur { .. } | Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } => 0., // Interpolating reads a pixel past the farthest a displacement moves the content, unless it keeps the result within the frame Self::Ripple { edge_mode, .. } | Self::Wave { edge_mode, .. } | Self::Displace { edge_mode, .. } if confines_to_frame(*edge_mode) => 0., Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => self.displacement_reach() + 1., @@ -1399,6 +1419,16 @@ impl EffectOperation { finite_transform(transform); } Self::PolarCoordinates { transform, .. } => finite_transform(transform), + Self::Warp { + bend, + horizontal_distortion, + vertical_distortion, + transform, + .. + } => { + [bend, horizontal_distortion, vertical_distortion].into_iter().for_each(finite); + finite_transform(transform); + } Self::Ripple { amount, size, .. } => [amount, size].into_iter().for_each(finite), Self::Wave { wavelength_min, @@ -1569,6 +1599,14 @@ impl EffectOperation { inverse: false, transform: DAffine2::IDENTITY, }, + EffectKind::Warp => Self::Warp { + style: WarpStyle::default(), + bend: 0., + horizontal_distortion: 0., + vertical_distortion: 0., + vertical: false, + transform: DAffine2::IDENTITY, + }, EffectKind::Ripple => Self::Ripple { amount: 0., size: 16., @@ -1883,6 +1921,22 @@ impl EffectOperation { visitor.parameter("inverse", inverse, false); visitor.parameter("transform", transform, DAffine2::IDENTITY); } + Self::Warp { + style, + bend, + horizontal_distortion, + vertical_distortion, + vertical, + transform, + } => { + visitor.parameter("style", style, WarpStyle::default()); + visitor.parameter("vertical", vertical, false); + // For PSD interop, the bend its warp dialog starts at + visitor.parameter("bend", bend, 50.); + visitor.parameter("horizontal_distortion", horizontal_distortion, 0.); + visitor.parameter("vertical_distortion", vertical_distortion, 0.); + visitor.parameter("transform", transform, DAffine2::IDENTITY); + } Self::Ripple { amount, size, edge_mode } => { visitor.parameter("amount", amount, 100.); visitor.parameter("size", size, 16.); @@ -2120,6 +2174,14 @@ mod tests { inverse: true, transform: DAffine2::from_cols_array(&[30., 0., 10., 20., 15., 10.]), }, + EffectOperation::Warp { + style: WarpStyle::Fish, + bend: -35., + horizontal_distortion: 20., + vertical_distortion: -10., + vertical: true, + transform: DAffine2::from_scale_angle_translation(DVec2::new(120., 60.), -0.2, DVec2::new(8., -4.)), + }, EffectOperation::Ripple { amount: -250., size: 32., @@ -2616,7 +2678,14 @@ mod tests { cylindrical: false, transform, }, - EffectOperation::PolarCoordinates { inverse: false, transform }, + EffectOperation::Warp { + style: WarpStyle::Arc, + bend: 50., + horizontal_distortion: 0., + vertical_distortion: 0., + vertical: false, + transform, + }, ]; for operation in operations { let mut effects = Effects::from_operations([operation.clone()]); @@ -2630,7 +2699,8 @@ mod tests { | EffectOperation::Twirl { transform, .. } | EffectOperation::Pinch { transform, .. } | EffectOperation::Spherize { transform, .. } - | EffectOperation::PolarCoordinates { transform, .. }, + | EffectOperation::PolarCoordinates { transform, .. } + | EffectOperation::Warp { transform, .. }, ) => transform, _ => panic!("the row should stay the same effect"), }; diff --git a/node-graph/libraries/graphic-types/src/lib.rs b/node-graph/libraries/graphic-types/src/lib.rs index a10460eba3..f2313bc9a6 100644 --- a/node-graph/libraries/graphic-types/src/lib.rs +++ b/node-graph/libraries/graphic-types/src/lib.rs @@ -9,6 +9,7 @@ pub mod graphic; pub mod masks; pub(crate) mod parameters; pub mod resampling; +pub mod warp; // Re-export all transitive dependencies so downstream crates only need to depend on graphic-types pub use core_types; @@ -28,6 +29,7 @@ pub use generator::Generator; pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector}; pub use masks::MaskMode; pub use resampling::{DisplaceMode, RadialBlurMethod, WaveType}; +pub use warp::WarpStyle; pub mod migrations { use crate::Vector; diff --git a/node-graph/libraries/graphic-types/src/resampling.rs b/node-graph/libraries/graphic-types/src/resampling.rs index 16814354a7..e6247ec2f8 100644 --- a/node-graph/libraries/graphic-types/src/resampling.rs +++ b/node-graph/libraries/graphic-types/src/resampling.rs @@ -5,6 +5,7 @@ use crate::Graphic; use crate::effects::{EffectOperation, Effects, collapses, effect_space, spans_along_axes}; use crate::generator::{hash_fraction, pcg3d}; use crate::masks::{MaskMode, mask_coverage}; +use crate::warp::{Warp, WarpMesh}; use core_types::graphene_hash::CacheHash; use dyn_any::DynAny; use glam::{DAffine2, DMat2, DVec2}; @@ -584,6 +585,480 @@ impl FrameWarp { } } +/// The [`Warp`] that `operation`, if a Warp, bends its square by, from its percentages, with the transform placing its square (see [`warp_frame`]). +pub fn warp_of(operation: &EffectOperation) -> Option<(Warp, DAffine2)> { + let EffectOperation::Warp { + style, + bend, + horizontal_distortion, + vertical_distortion, + vertical, + transform, + } = *operation + else { + return None; + }; + + let warp = Warp { + style, + bend: bend / 100., + horizontal_distortion: horizontal_distortion / 100., + vertical_distortion: vertical_distortion / 100., + vertical, + }; + Some((warp, transform)) +} + +/// About how many texels long a Warp's cells are, short enough that the source each texel interpolates lies where Newton's method polishes it from, unless the grid reaches its most cells. +pub const WARP_CELL_TEXELS: f64 = 8.; + +/// The most cells across or down a Warp's grid, which bounds how many triangles it draws. +pub const MAX_WARP_CELLS: u32 = 512; + +/// How many steps of Newton's method polish each texel's interpolated source onto the exact patch. +pub const WARP_POLISH_STEPS: u32 = 2; + +/// How far past each side of its `square`, as fractions of it, a Warp's patch runs, carrying the square's edge as it fades: +/// a pixel along each side, or where pixels are larger, the most its reach counts (see [`WARP_FADE`]). +fn warp_fade(square: &EffectFrame) -> DVec2 { + let pixel_lengths = DVec2::new(square.to_pixels.matrix2.x_axis.length(), square.to_pixels.matrix2.y_axis.length()); + pixel_lengths.recip().min(WARP_FADE / square.size) +} + +/// How far each way the edge of a Warp's `square` fades across its sides, in its local space: half its fade, which is half a pixel along each side where it fits. +/// A side the patch keeps in place fades by it as the square's own edge does. +pub fn warp_half_fade(square: &EffectFrame) -> DVec2 { + warp_fade(square) * square.size / 2. +} + +/// How many steps of Newton's method find the point of a side's curve nearest a texel. +pub const WARP_NEAREST_STEPS: u32 = 3; + +/// How many times sharper than the square's own a corner of a Warp's patch may be for its fringe to miter past the corner, which reaches as many times as far past it at most. +pub const WARP_MITER_LIMIT: f64 = 2.; + +/// What a fragment of a Warp's triangles draws: the patch within its square, or the fringe its edge fades across past one of the square's sides or corners. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WarpFragment { + Within, + /// Past the left, right, top, or bottom side (0 to 3). + PastSide(usize), + /// Past the top left, top right, bottom left, or bottom right corner (0 to 3), beside its left or right side and its top or bottom one. + PastCorner(usize), +} + +/// What a fragment of a Warp's triangles shows. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WarpShade { + /// How much of its texel the warped square covers. + pub coverage: f64, + /// The parameters (s, t) where it reads the content. + pub read: DVec2, +} + +/// The point at `t` of the cubic Bezier curve with these control `points`, and its first and second derivatives there. O(1). +fn cubic_at(points: [DVec2; 4], t: f64) -> [DVec2; 3] { + let rest = 1. - t; + let point = points[0] * (rest * rest * rest) + points[1] * (3. * t * rest * rest) + points[2] * (3. * t * t * rest) + points[3] * (t * t * t); + let first = (points[1] - points[0]) * (3. * rest * rest) + (points[2] - points[1]) * (6. * t * rest) + (points[3] - points[2]) * (3. * t * t); + let second = (points[2] - points[1] * 2. + points[0]) * (6. * rest) + (points[3] - points[2] * 2. + points[1]) * (6. * t); + [point, first, second] +} + +/// A Warp's patch over the part of its square a texture reads, in its texels, cut into a grid of cells that each split into two triangles, +/// and a fringe of quads past the square's sides and corners there, across which its edge fades. +/// Each triangle paints the content within the square that its texels interpolate the source of, polished onto the exact patch, with those where the patch turns over painted on top. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WarpTessellation { + /// The patch in texels, over parameters (s, t) with a unit square that's the part of the warp's square the texture reads. + pub patch: WarpMesh, + /// How many cells across and down the grid spans. + pub cells: [u32; 2], + /// Places the parameters (s, t) on the texels the content is read from. + pub source: DAffine2, + /// Maps the texels into the square's local space (see [`EffectFrame`]). + pub texels_to_local: DAffine2, + /// How far the square's edge fades each way across its sides, in its local space (see [`warp_half_fade`]). + pub half_fade: DVec2, + /// How far the edge fades each way across the left and right sides, and the top and bottom, in the texels square to them. + pub fringe: DVec2, + /// Whether the parameters' unit square reaches the warp's square's left, right, top, and bottom sides, which have fringes. + pub sides: [bool; 4], +} + +impl WarpTessellation { + /// The tessellation of the `mesh` (as fractions of the `square`) over the part of the square that a texture `size` texels across reads. + /// The patch keeps only that part, so its texels stay precise in 32-bit math however far the square reaches past the texture. `None` where there's nothing to draw or the square is degenerate. + pub fn new(mesh: &WarpMesh, square: &EffectFrame, size: DVec2) -> Option { + // The part of the square that the texture covers, with the texel past its edges that interpolating fades into + let [texture_low, texture_high] = local_bounds([-DVec2::ONE, size + 1.], square.to_pixels.inverse()); + let (low, high) = (texture_low.max(DVec2::ZERO), texture_high.min(DVec2::ONE)); + if !(low.cmplt(high).all() && low.is_finite() && high.is_finite()) { + return None; + } + + let source = square.to_pixels * DAffine2::from_translation(low) * DAffine2::from_scale(high - low); + let patch = mesh.transformed(square.to_pixels).over(low, high); + + // Cells short enough along each parameter for the longest its tangent grows over the patch + let lengths = patch.tangent_bounds(); + let count = |length: f64| (length / WARP_CELL_TEXELS).ceil().clamp(1., MAX_WARP_CELLS as f64) as u32; + let cells = [count(lengths.x), count(lengths.y)]; + + // The fade measured square to the sides in the texels, for which each local coordinate's gradient gives how fast it changes there + let texels_to_local = square.pixels_to_local(); + let half_fade = warp_half_fade(square); + let gradients = DVec2::new(texels_to_local.matrix2.row(0).length(), texels_to_local.matrix2.row(1).length()); + + let finite = patch.0.iter().flatten().all(|point| point.is_finite()) && source.is_finite(); + finite.then(|| Self { + patch, + cells, + source, + texels_to_local, + half_fade, + fringe: half_fade / gradients, + sides: [low.x <= 0., high.x >= 1., low.y <= 0., high.y >= 1.], + }) + } + + /// The parameters (s, t) of the grid's corner `index` (its column and row), and where the patch carries them in the texels. + pub fn vertex(&self, [column, row]: [u32; 2]) -> (DVec2, DVec2) { + let parameters = DVec2::new(column as f64 / self.cells[0] as f64, row as f64 / self.cells[1] as f64); + (parameters, self.patch.point(parameters)) + } + + /// The fringe's corner at the grid's index `along` the square's side `side` (see [`WarpFragment::PastSide`]): its parameters on the side, and where it lies in the texels, + /// on the side or at its `outer` edge, which lies twice the fade past the side, out of the square. + pub fn fringe_vertex(&self, side: usize, along: u32, outer: bool) -> (DVec2, DVec2) { + let axis = side / 2; + let mut index = [along; 2]; + index[axis] = if side % 2 == 0 { 0 } else { self.cells[axis] }; + + let (parameters, point) = self.vertex(index); + if !outer { + return (parameters, point); + } + + // At a corner where the other side's fringe meets it, it reaches as far as the corner's quad does + let last = self.cells[1 - axis]; + let end = (along == last) as usize; + let (other, corner) = if axis == 0 { (2 + end, side + 2 * end) } else { (end, end + 2 * (side % 2)) }; + if (along == 0 || along == last) && self.sides[other] { + return (parameters, point + self.corner_outward(corner)[axis]); + } + (parameters, point + self.outward(side, parameters[1 - axis])) + } + + /// The corner of the fringe past the square's corner `corner` (see [`WarpFragment::PastCorner`]): its parameters there, and where it lies in the texels, + /// past the corner by as far as the fringes of its sides reach where `outer` along each. + pub fn corner_vertex(&self, corner: usize, outer: [bool; 2]) -> (DVec2, DVec2) { + let (parameters, point) = self.vertex([(corner % 2) as u32 * self.cells[0], (corner / 2) as u32 * self.cells[1]]); + let reach = self.corner_outward(corner); + (parameters, point + (0..2).filter(|&index| outer[index]).map(|index| reach[index]).sum::()) + } + + /// How far the fringe past `side` reaches from its point at the parameter `along` it, in the texels: twice the fade there, out of the square. + fn outward(&self, side: usize, along: f64) -> DVec2 { + let [_, tangent, _] = cubic_at(self.side_curves(side).0, along); + -self.side_normal(side, tangent) * 2. * self.fringe[side / 2] + } + + /// How far the fringe reaches past the square's corner `corner`, past its left or right side and past its top or bottom one, in the texels: twice the fade past each side along the other's tangent, + /// mitering so the corner's quad meets the sides' fringes along their lines, or along each side's normal where the corner turns in or is sharper than [`WARP_MITER_LIMIT`] allows. + fn corner_outward(&self, corner: usize) -> [DVec2; 2] { + let sides = [corner % 2, 2 + corner / 2]; + let ends = [corner / 2, corner % 2]; + let reach = sides.map(|side| 2. * self.fringe[side / 2]); + + // Each side's normal at the corner, and its tangent heading from the corner along it + let [(normal_x, heading_x), (normal_y, heading_y)] = std::array::from_fn(|index| { + let [_, tangent, _] = cubic_at(self.side_curves(sides[index]).0, ends[index] as f64); + let heading = if ends[index] == 0 { tangent } else { -tangent }; + (self.side_normal(sides[index], tangent), heading.normalize_or_zero()) + }); + let sines = [normal_x.dot(heading_y), normal_y.dot(heading_x)]; + + // The square's own corners, as sharp as its axes are slanted in the texels + let axes = self.texels_to_local.matrix2; + let square_sine = axes.determinant().abs() / (axes.row(0).length() * axes.row(1).length()); + + if sines.iter().all(|&sine| sine * WARP_MITER_LIMIT >= square_sine) { + [-heading_y * (reach[0] / sines[0]), -heading_x * (reach[1] / sines[1])] + } else { + [-normal_x * reach[0], -normal_y * reach[1]] + } + } + + /// The curve the patch bends `side` into in the texels, over the parameter along it, and the cubic of the patch's tangent across it, heading into the square. + fn side_curves(&self, side: usize) -> ([DVec2; 4], [DVec2; 4]) { + let points = &self.patch.0; + match side { + 0 => (std::array::from_fn(|row| points[row][0]), std::array::from_fn(|row| (points[row][1] - points[row][0]) * 3.)), + 1 => (std::array::from_fn(|row| points[row][3]), std::array::from_fn(|row| (points[row][2] - points[row][3]) * 3.)), + 2 => (points[0], std::array::from_fn(|column| (points[1][column] - points[0][column]) * 3.)), + _ => (points[3], std::array::from_fn(|column| (points[2][column] - points[3][column]) * 3.)), + } + } + + /// The unit normal of `side`'s curve where its tangent is `tangent`, facing into the square as the patch carries it, the way the sheet runs from the side where it isn't turned over. + /// It turns with the curve alone, so it's smooth along it. + fn side_normal(&self, side: usize, tangent: DVec2) -> DVec2 { + let handedness = if side == 1 || side == 2 { 1. } else { -1. }; + tangent.perp().normalize_or_zero() * (handedness * self.source.matrix2.determinant().signum()) + } + + /// How much of the texel centered at `target` lies inside the curve the patch bends `side` into, along the side's axis, and the parameter along the side where it's nearest. + /// It fades by the texel's distance from the curve where it's nearest (from the `seed` along it), measured as the square's own sides measure it, so it matches their fade where the patch keeps the side in place. + fn side_coverage(&self, side: usize, seed: f64, target: DVec2) -> (f64, f64) { + let (curve, _) = self.side_curves(side); + let axis = side / 2; + + // Newton's method on where the offset from the curve meets its tangent squarely, keeping the nearest point it reaches, since it heads off past where the curve bends around the texel + let mut along = seed.clamp(0., 1.); + let mut nearest = (f64::INFINITY, along, DVec2::ZERO, DVec2::ZERO); + for step_index in 0..=WARP_NEAREST_STEPS { + let [point, first, second] = cubic_at(curve, along); + let offset = point - target; + if offset.length_squared() < nearest.0 { + nearest = (offset.length_squared(), along, point, first); + } + if step_index == WARP_NEAREST_STEPS { + break; + } + + let slope = offset.dot(first); + let curvature = first.length_squared() + offset.dot(second); + let step = if curvature > 0. { + slope / curvature + } else { + slope / first.length_squared().max(f64::MIN_POSITIVE) + }; + along = (along - step).clamp(0., 1.); + } + + // Farther from the nearest point found than the fringe reaches past it, the texel lies far within, or the search landed on a far part of the curve facing elsewhere, so it isn't faded + let (nearest_squared, along, point, tangent) = nearest; + if nearest_squared > WARP_FRINGE_PIXELS * WARP_FRINGE_PIXELS { + return (1., along); + } + let distance = self.side_normal(side, tangent).dot(target - point) * self.texels_to_local.matrix2.row(axis).length(); + ((0.5 + distance / (2. * self.half_fade[axis])).clamp(0., 1.), along) + } + + /// Whether the sheet heads into the square from `side` and runs out to the `parameters` across it without folding back, so the side's curve is its edge there. + /// Along the line of parameters level with them, the sheet's speed away from the curve is a quadratic, positive throughout exactly where its Bernstein coefficients show it. + fn unfolded_from_side(&self, side: usize, parameters: DVec2) -> bool { + let axis = side / 2; + let along = parameters[1 - axis].clamp(0., 1.); + let (curve, across) = self.side_curves(side); + let [_, tangent, _] = cubic_at(curve, along); + let [across, ..] = cubic_at(across, along); + let normal = self.side_normal(side, tangent); + if across.dot(normal) <= 0. { + return false; + } + + // The patch's line through the parameters, across the side + let rest = 1. - along; + let bases = [rest * rest * rest, 3. * along * rest * rest, 3. * along * along * rest, along * along * along]; + let points = &self.patch.0; + let line: [DVec2; 4] = match axis { + 0 => std::array::from_fn(|column| (0..4).map(|row| points[row][column] * bases[row]).sum()), + _ => std::array::from_fn(|row| (0..4).map(|column| points[row][column] * bases[column]).sum()), + }; + + // Its speed away from the side's curve from the side to the parameters, heading into the square + let (start, end) = (if side % 2 == 0 { 0. } else { 1. }, parameters[axis].clamp(0., 1.)); + let heading = if side % 2 == 0 { 1. } else { -1. }; + let [_, start_first, start_second] = cubic_at(line, start); + let [_, end_first, _] = cubic_at(line, end); + let (start_speed, end_speed) = (heading * normal.dot(start_first), heading * normal.dot(end_first)); + let middle = start_speed + (end - start) / 2. * heading * normal.dot(start_second); + start_speed > 0. && end_speed > 0. && (middle > 0. || start_speed * end_speed > middle * middle) + } + + /// What a `fragment` of the triangles shows at the texel centered at `target`, from the parameters (s, t) it interpolates there (polished onto the patch within the square). + /// Within the square, it's the content its parameters read, faded by its distance past the nearer side's curve along each axis where the sheet runs out to it from that side. + /// Past a side or corner, it's the content where the side's curve lies nearest, faded the same way. O(steps). + pub fn shade(&self, fragment: WarpFragment, parameters: DVec2, target: DVec2) -> WarpShade { + let local = |parameters: DVec2| (self.texels_to_local * self.source).transform_point2(parameters); + let nearer_side = |axis: usize, parameters: DVec2| 2 * axis + (local(parameters)[axis] > 0.) as usize; + let from_side = |side: usize, parameters: DVec2| if self.sides[side] { self.side_coverage(side, parameters[1 - side / 2], target).0 } else { 1. }; + + match fragment { + WarpFragment::Within => { + let coverage = (0..2).map(|axis| { + let side = nearer_side(axis, parameters); + if !self.sides[side] { + return 1.; + } + + // Far past the side's curve, the sheet covers the texel along its axis, as it does where it folds back over the side from deeper within the square + let (curve, _) = self.side_curves(side); + let [min, max] = curve.iter().fold([DVec2::INFINITY, DVec2::NEG_INFINITY], |[min, max], &point| [min.min(point), max.max(point)]); + let reach = self.fringe[axis]; + let far = target.cmplt(min - reach).any() || target.cmpgt(max + reach).any(); + if far || !self.unfolded_from_side(side, parameters) { + return 1.; + } + self.side_coverage(side, parameters[1 - axis], target).0 + }); + WarpShade { + coverage: coverage.product(), + read: parameters, + } + } + WarpFragment::PastSide(side) => { + let axis = side / 2; + let (coverage, along) = self.side_coverage(side, parameters[1 - axis], target); + let mut read = parameters; + read[axis] = (side % 2) as f64; + read[1 - axis] = along; + WarpShade { + coverage: coverage * from_side(nearer_side(1 - axis, read), read), + read, + } + } + WarpFragment::PastCorner(corner) => { + let read = DVec2::new((corner % 2) as f64, (corner / 2) as f64); + WarpShade { + coverage: from_side(corner % 2, read) * from_side(2 + corner / 2, read), + read, + } + } + } + } + + /// The parameters (s, t) that the patch carries onto the `target` texel, polished by Newton's method from the `seed` a triangle interpolates there. + /// Where the polish can't converge (near a fold's crease or a collapsed side) or lands farther than the seed, the seed stands. O(steps). + pub fn polished(&self, seed: DVec2, target: DVec2) -> DVec2 { + let cell = DVec2::ONE / DVec2::new(self.cells[0] as f64, self.cells[1] as f64); + + let mut parameters = seed; + let mut seed_distance = f64::INFINITY; + for step_index in 0..WARP_POLISH_STEPS { + let [point, along_s, along_t] = self.patch.point_and_tangents(parameters); + let residual = point - target; + if step_index == 0 { + seed_distance = residual.length(); + } + + let determinant = along_s.perp_dot(along_t); + if determinant.abs() <= 1e-6 * along_s.length() * along_t.length() { + break; + } + let step = DVec2::new(residual.perp_dot(along_t), along_s.perp_dot(residual)) / determinant; + if step.abs().cmpgt(cell.abs()).any() { + return seed; + } + parameters -= step; + } + + let distance = (self.patch.point(parameters) - target).length(); + if distance <= 0.5 && distance <= seed_distance { parameters } else { seed } + } +} + +/// The most cells the search for what a Warp reads looks at. +const WARP_SOURCE_CELLS: usize = 16_384; + +/// How far past where the patch carries a Warp's square its fringe reaches, in pixels, reading the content at the square's sides and corners: +/// past a corner, a pixel along each side, as many times as far as the miter limit allows, at most. +const WARP_FRINGE_PIXELS: f64 = 2. * WARP_MITER_LIMIT; + +/// The bounding box, in pixels, of where the Warp of the `mesh` (as fractions of the `square`) reads from to produce the `output` region (in pixels), unclamped and possibly empty. +/// Cells of the square are kept where the box around their part of the patch meets the output or its fringe, the largest split first until small beside it, so every layer of a fold counts and the budget ends on cells of one size. +/// O(cells in the output × log of them). +fn warp_source(mesh: &WarpMesh, square: &EffectFrame, output: [DVec2; 2]) -> [DVec2; 2] { + let in_pixels = mesh.transformed(square.to_pixels); + let output = [output[0] - WARP_FRINGE_PIXELS, output[1] + WARP_FRINGE_PIXELS]; + let leaf_size = ((output[1] - output[0]).max_element() / 8.).max(1.); + let source_of = |(start, end): (DVec2, DVec2)| local_bounds([start, end], square.to_pixels); + + // Cells queued by the size of their source, largest first, since the bits of a float that isn't negative order as it does + let mut cells: Vec<(DVec2, DVec2)> = Vec::new(); + let mut queue = std::collections::BinaryHeap::new(); + let enqueue = |cells: &mut Vec<(DVec2, DVec2)>, queue: &mut std::collections::BinaryHeap<(u64, usize)>, cell: (DVec2, DVec2)| { + let [min, max] = source_of(cell); + cells.push(cell); + queue.push(((max - min).max_element().max(0.).to_bits(), cells.len() - 1)); + }; + enqueue(&mut cells, &mut queue, (DVec2::ZERO, DVec2::ONE)); + + let mut read = [DVec2::INFINITY, DVec2::NEG_INFINITY]; + let mut looked = 0; + while let Some((_, index)) = queue.pop() { + let (start, end) = cells[index]; + looked += 1; + let [min, max] = in_pixels.over(start, end).hull_bounds(); + if !(min.cmple(output[1]).all() && max.cmpge(output[0]).all()) { + continue; + } + + let source = source_of((start, end)); + if (source[1] - source[0]).max_element() <= leaf_size || looked + queue.len() >= WARP_SOURCE_CELLS { + read = union(read, source); + continue; + } + + let middle = (start + end) / 2.; + for cell in [ + (start, middle), + (DVec2::new(middle.x, start.y), DVec2::new(end.x, middle.y)), + (DVec2::new(start.x, middle.y), DVec2::new(middle.x, end.y)), + (middle, end), + ] { + enqueue(&mut cells, &mut queue, cell); + } + } + + // Each texel interpolates the pixels around its source, or the nearest the square covers among the 16 around it, up to two past it + [read[0] - 2., read[1] + 2.] +} + +/// The part of its input, in pixels, that the Warp of the `mesh` (as fractions of the `square`) reads to produce `output` (in pixels): +/// what the patch carries there from within the square, which reads only the pixels the square covers, along with the output itself, as Polar Coordinates also counts it though it clears there. +pub fn warp_source_region(mesh: &WarpMesh, square: &EffectFrame, output: [DVec2; 2]) -> [DVec2; 2] { + let [square_min, square_max] = square.pixel_bounds(); + let read = intersection(warp_source(mesh, square, output), [square_min - 1., square_max + 1.]); + + // A read that misses the square adds nothing + match read[0].cmple(read[1]).all() { + true => union(output, read), + false => output, + } +} + +/// How many cells across and down a warp's patch splits into to bound it, so their control points hug it closely. +const WARP_REACH_CELLS: u32 = 8; + +/// How far past where its patch carries its square's sides, in the effect space, a Warp's edge fades at most, which its reach counts: the pixel it fades across, at a pixel per unit or more. +const WARP_FADE: f64 = 1.; + +/// How far past the parallelogram with these `corners` (the content's bounds in the effect space) the `warp` paints within the square its `transform` places there. +/// It paints within the patch over the square, so within the control points of the patch over each of many cells, and its edge fades past it by at most the fade, or past a corner, as many times as the miter limit allows. O(cells). +fn warp_reach_around(warp: &Warp, transform: DAffine2, corners: [DVec2; 4]) -> f64 { + let placement = transform * DAffine2::from_translation(DVec2::splat(-0.5)); + if collapses(&placement) { + return 0.; + } + + // The warp bends the shape its square has in the effect space, as the renderers' meshes do + let mesh = warp.mesh(DVec2::new(placement.matrix2.x_axis.length(), placement.matrix2.y_axis.length())).transformed(placement); + + // The signed distance past a convex shape is convex, so over the hull of each part's control points it's greatest at one of them + let cell = 1. / WARP_REACH_CELLS as f64; + let farthest = (0..WARP_REACH_CELLS * WARP_REACH_CELLS) + .flat_map(|index| { + let corner = cell * DVec2::new((index % WARP_REACH_CELLS) as f64, (index / WARP_REACH_CELLS) as f64); + mesh.over(corner, corner + cell).0.into_iter().flatten() + }) + .map(|point| signed_distance_outside(point, corners)) + .fold(f64::NEG_INFINITY, f64::max); + (farthest + WARP_FADE * WARP_MITER_LIMIT).max(0.) +} + /// Which maps move the content in a displacement, and which ways. #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -949,10 +1424,16 @@ impl EffectOperation { match self { 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), + _ if let Some((warp, transform)) = warp_of(self) => warp_reach_around(&warp, transform, corners), _ => self.reach_past(painted), } } + /// Whether this is a warp acting within the frame its own transform places (see [`warp_frame`]), like a twirl or a Warp. + pub fn is_warp(&self) -> bool { + FrameWarp::of(self).is_some() || warp_of(self).is_some() + } + /// Whether this operation takes the content's frame, which displacements measure from, unless it changes nothing. pub fn takes_frame(&self) -> bool { match self { @@ -961,6 +1442,7 @@ impl EffectOperation { | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } + | Self::Warp { .. } | Self::MotionBlur { .. } | Self::RadialBlur { .. } | Self::DropShadow { .. } @@ -1007,20 +1489,23 @@ fn stretches(linear_map: DMat2) -> (f64, f64) { /// 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])); + signed_distance_outside(point, corners).max(0.) +} - // 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)| { +/// How far a `point` lies outside the parallelogram with these `corners` in order around it, or less than 0 by how far it lies within it. +fn signed_distance_outside(point: DVec2, corners: [DVec2; 4]) -> f64 { + let to_edge = |index: usize| { + let (start, end) = (corners[index], corners[(index + 1) % 4]); 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) + let distance = (0..4).map(to_edge).fold(f64::INFINITY, f64::min); + + // Within a parallelogram that doesn't collapse, the point lies on the same side of each edge + let sides: [f64; 4] = std::array::from_fn(|index| (corners[(index + 1) % 4] - corners[index]).perp_dot(point - corners[index])); + let within = sides.iter().all(|&side| side > 0.) || sides.iter().all(|&side| side < 0.); + if within { -distance } else { distance } } /// 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. @@ -1096,7 +1581,7 @@ impl Effects { /// 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| { - let measures_from_bounds = matches!(operation, EffectOperation::RadialBlur { .. }) || FrameWarp::of(&operation).is_some(); + let measures_from_bounds = matches!(operation, EffectOperation::RadialBlur { .. }) || operation.is_warp(); measures_from_bounds && !operation.changes_nothing() }) } @@ -1111,8 +1596,7 @@ impl Effects { /// 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], frame: Option<&EffectFrame>, effect_to_pixels: DAffine2) -> Option<[DVec2; 2]> { let operations: Vec = self.operations().filter(|operation| !operation.changes_nothing()).collect(); - let reads_beyond_reach = - |operation: &EffectOperation| matches!(operation, EffectOperation::RadialBlur { .. }) || FrameWarp::of(operation).is_some() || (frame.is_some() && operation.reads_across_frame()); + let reads_beyond_reach = |operation: &EffectOperation| matches!(operation, EffectOperation::RadialBlur { .. }) || operation.is_warp() || (frame.is_some() && operation.reads_across_frame()); if !operations.iter().any(reads_beyond_reach) { return None; } @@ -1130,6 +1614,10 @@ impl Effects { Some(square) => warp.source_region(region, &square), None => region, }, + _ if let Some((warp, transform)) = warp_of(operation) => match warp_frame(transform, effect_to_pixels) { + Some(square) => warp_source_region(&warp.mesh(square.size), &square, region), + None => region, + }, (_, Some(frame)) if operation.reads_across_frame() => operation.source_across_frame(region, frame, pixels_per_length), _ => { let reach = operation.reach() * spans; @@ -1461,8 +1949,7 @@ mod tests { cylindrical: true, transform: far_left, }, - EffectOperation::PolarCoordinates { inverse: false, transform: far_left }, - EffectOperation::PolarCoordinates { inverse: true, transform: far_left }, + warp_effect(crate::warp::WarpStyle::Arc, 90., far_left), ]; for warp in warps { let region = Effects::from_operations([warp.clone()]).source_region(visible, None, DAffine2::IDENTITY); @@ -1749,6 +2236,286 @@ mod tests { } } + fn warp_effect(style: crate::warp::WarpStyle, bend: f64, transform: DAffine2) -> EffectOperation { + EffectOperation::Warp { + style, + bend, + horizontal_distortion: 0., + vertical_distortion: 0., + vertical: false, + transform, + } + } + + /// The transform placing a Warp's square on the unit square that `placement` places, as on the frame of content it places. + fn square_on(placement: DAffine2) -> DAffine2 { + placement * DAffine2::from_translation(DVec2::splat(0.5)) + } + + /// The Warp's mesh (as fractions of its square) and the transform placing its square's unit square, which spans 0 to 1. + fn warp_mesh_and_placement(operation: &EffectOperation) -> (WarpMesh, DAffine2) { + let (warp, transform) = warp_of(operation).unwrap(); + let placement = transform * DAffine2::from_translation(DVec2::splat(-0.5)); + (warp.mesh(DVec2::new(placement.matrix2.x_axis.length(), placement.matrix2.y_axis.length())), placement) + } + + #[test] + fn warp_effects_reach_as_far_as_their_bent_square_lies_past_the_content() { + use crate::warp::WarpStyle::*; + + // The farthest past the box's corners that the patch carries a point of its square, found from a dense grid of them, which the fade past it adds to + let farthest = |operation: &EffectOperation, corners: [DVec2; 4]| { + let (mesh, placement) = warp_mesh_and_placement(operation); + (0..201 * 201) + .map(|index| DVec2::new((index % 201) as f64, (index / 201) as f64) / 200.) + .map(|uv| distance_outside(placement.transform_point2(mesh.point(uv)), corners)) + .fold(0., f64::max) + }; + + // Banners upright and turned, bent either way within squares on their frames, reach past their bounds as far as the bend carries the square, and not much farther + let banner = DVec2::new(400., 100.); + let styles = [Arc, ArcLower, ArcUpper, Arch, Bulge, ShellLower, ShellUpper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist]; + let placements = [ + DAffine2::from_scale(banner), + DAffine2::from_angle(0.7) * DAffine2::from_scale(banner), + DAffine2::from_angle(-2.) * DAffine2::from_scale(DVec2::new(100., 400.)), + ]; + for (style, placement, bend) in styles + .into_iter() + .flat_map(|style| placements.into_iter().flat_map(move |placement| [50., -50.].map(|bend| (style, placement, bend)))) + { + let operation = warp_effect(style, bend, square_on(placement)); + let [min, max] = local_bounds([DVec2::ZERO, DVec2::ONE], placement); + let reach = Effects::from_operations([operation.clone()]).reach_around(DAffine2::IDENTITY, [min, max], 0.).x; + + let actual = farthest(&operation, [min, DVec2::new(max.x, min.y), max, DVec2::new(min.x, max.y)]); + assert!(actual <= reach + 1e-9, "{style:?} at {bend} reaches {actual}, past the reach of {reach}"); + assert!(reach <= 1.15 * actual + 3., "{style:?} at {bend} reaches {actual}, far short of the reach of {reach}"); + } + + // The identity places a square 1 across at the content's corner, and a transform collapsing it onto a line paints nothing, clearing everything + let reach = |operation: EffectOperation| Effects::from_operations([operation]).reach_around(DAffine2::IDENTITY, [DVec2::ZERO, DVec2::splat(100.)], 0.).x; + let identity = reach(warp_effect(Arc, 50., DAffine2::IDENTITY)); + assert!(identity < 8., "the square 1 across reaches {identity}"); + let collapsed = warp_effect(Arc, 50., DAffine2::from_scale(DVec2::new(100., 0.))); + assert!(!collapsed.changes_nothing() && reach(collapsed) == 0.); + } + + #[test] + fn warp_effects_in_a_row_reach_as_far_as_the_second_carries_what_the_first_bends() { + use crate::warp::WarpStyle::*; + + // A banner turned off the axes, which the first warp bends far past its square yet within its bounds, and the second bends what then lies within the square + let size = DVec2::new(400., 100.); + for angle in [0.3, std::f64::consts::FRAC_PI_4, 2.] { + let placement = DAffine2::from_angle(angle) * DAffine2::from_scale(size); + let bounds = local_bounds([DVec2::ZERO, DVec2::ONE], placement); + + for (first, second) in [Arch, ArcUpper, Squeeze, Rise] + .into_iter() + .flat_map(|first| [Twist, ShellLower, Flag, Arc].map(|second| (first, second))) + { + for (first_bend, second_bend) in [(80., -50.), (-50., 80.)] { + let (first_warp, second_warp) = (warp_effect(first, first_bend, square_on(placement)), warp_effect(second, second_bend, square_on(placement))); + let reach = Effects::from_operations([first_warp.clone(), second_warp.clone()]).reach_around(DAffine2::IDENTITY, bounds, 0.); + + // Where the second warp carries each point the first bends, or where it lies outside the square, which the reach counts though the warp clears it + let ((first_mesh, _), (second_mesh, _)) = (warp_mesh_and_placement(&first_warp), warp_mesh_and_placement(&second_warp)); + for index in 0..101 * 101 { + let uv = DVec2::new((index % 101) as f64, (index / 101) as f64) / 100.; + let bent = first_mesh.point(uv); + let within_square = bent.cmpge(DVec2::ZERO).all() && bent.cmple(DVec2::ONE).all(); + let point = placement.transform_point2(if within_square { second_mesh.point(bent) } else { bent }); + assert!( + point.cmpge(bounds[0] - reach - 1e-9).all() && point.cmple(bounds[1] + reach + 1e-9).all(), + "turned {angle}, {first:?} at {first_bend} then {second:?} at {second_bend} carries {uv} to {point}, past the reach of {reach} around {bounds:?}" + ); + } + } + } + } + } + + #[test] + fn warp_effects_stretched_after_they_bend_reach_as_far_as_their_bend_stretches() { + // A square 100 across bent into an arc within a square on it, then stretched four times as wide, which keeps the square's arcs, stretched with it + let arc = warp_effect(crate::warp::WarpStyle::Arc, 50., square_on(DAffine2::from_scale(DVec2::splat(100.)))); + let effects = Effects::from_operations([arc]); + let reach = |stretch: DVec2| effects.reach_around(DAffine2::from_scale(stretch), [DVec2::ZERO, DVec2::splat(100.) * stretch], 0.); + + let stretch = DVec2::new(4., 1.); + let (unstretched, stretched) = (reach(DVec2::ONE), reach(stretch)); + assert!( + (stretched - unstretched * stretch).abs().max_element() < 1e-9, + "stretched, it reaches {stretched} rather than {}", + unstretched * stretch + ); + assert!(stretched.x > 4. * 70., "the arc's ends reach {} past the stretched square's sides", stretched.x); + } + + #[test] + fn warp_effects_within_slanted_squares_reach_only_as_far_as_their_fade_past_the_patch() { + // A fisheye within a square 100 across and a tenth of a unit tall, slanted so its sides run nearly along each other, on content around it + let transform = DAffine2::from_cols_array(&[100., 0., 100., 0.1, 100., 50.]); + let fisheye = warp_effect(crate::warp::WarpStyle::Fisheye, 100., transform); + let bounds = [DVec2::ZERO, DVec2::new(200., 100.)]; + let reach = Effects::from_operations([fisheye.clone()]).reach_around(DAffine2::IDENTITY, bounds, 0.).x; + + // The farthest past the content that the patch carries a point of the square + let (mesh, placement) = warp_mesh_and_placement(&fisheye); + let corners = [bounds[0], DVec2::new(200., 0.), bounds[1], DVec2::new(0., 100.)]; + let drawn = (0..201 * 201) + .map(|index| DVec2::new((index % 201) as f64, (index / 201) as f64) / 200.) + .map(|uv| distance_outside(placement.transform_point2(mesh.point(uv)), corners)) + .fold(0., f64::max); + + // And the farthest its fringe paints past it at a pixel per unit, where each side's curve fades out and past each corner, where both sides' fades meet + let square = warp_frame(transform, DAffine2::IDENTITY).unwrap(); + let tessellation = WarpTessellation::new(&warp_of(&fisheye).unwrap().0.mesh(square.size), &square, bounds[1]).unwrap(); + let past_sides = (0..4).flat_map(|side| (0..=200).map(move |index| (side, index as f64 / 200.))).map(|(side, along)| { + let [point, tangent, _] = cubic_at(tessellation.side_curves(side).0, along); + point - tessellation.side_normal(side, tangent) * tessellation.fringe[side / 2] + }); + let past_corners = (0..4).map(|corner| { + let [across, down] = tessellation.corner_outward(corner); + tessellation.corner_vertex(corner, [false; 2]).1 + (across + down) / 2. + }); + let faded = past_sides.chain(past_corners).map(|point| distance_outside(point, corners)).fold(0., f64::max); + + let painted = drawn.max(faded); + assert!(faded > drawn, "its fringe fades only {faded} past the content, short of the patch's {drawn}"); + assert!( + painted <= reach + 1e-9 && reach <= 1.15 * painted + 3., + "it paints up to {painted} past the content, with a reach of {reach}" + ); + } + + #[test] + fn warp_effects_read_wherever_their_patch_carries_the_view_from() { + use crate::warp::WarpStyle; + + // Only the top of an arc bent far above its square from (100, 100) to (300, 200) is in view, which it carries from the square's top half + let transform = DAffine2::from_translation(DVec2::new(200., 150.)) * DAffine2::from_scale(DVec2::new(200., 100.)); + let arc = warp_effect(WarpStyle::Arc, 90., transform); + let visible = [DVec2::new(150., 0.), DVec2::new(250., 60.)]; + let [min, max] = Effects::from_operations([arc.clone()]).source_region(visible, None, DAffine2::IDENTITY).unwrap(); + + let square = warp_frame(transform, DAffine2::IDENTITY).unwrap(); + let mesh = warp_of(&arc).unwrap().0.mesh(square.size); + for index in 0..41 * 41 { + let uv = DVec2::new((index % 41) as f64, (index / 41) as f64) / 40.; + let landed = square.to_pixels.transform_point2(mesh.point(uv)); + if landed.cmpge(visible[0]).all() && landed.cmple(visible[1]).all() { + let source = square.to_pixels.transform_point2(uv); + assert!( + source.cmpge(min).all() && source.cmple(max).all(), + "{uv} lands in view at {landed} but reads from {source}, outside {min} to {max}" + ); + } + } + assert!(max.y < 175., "the region reads to {max}, past the square's bottom quarter"); + + // Below the square, a flag reads no farther down than the fade past its bottom side + let flag = warp_of(&warp_effect(WarpStyle::Flag, 30., transform)).unwrap().0.mesh(square.size); + let [_, read] = warp_source(&flag, &square, [DVec2::new(150., 200.), DVec2::new(250., 240.)]); + assert!(read.y < 204., "below the square, it reads down to {read}"); + } + + #[test] + fn warp_effects_read_the_pixels_around_each_source_they_interpolate() { + use crate::warp::WarpStyle; + + // A view beginning a quarter pixel right of where each warp carries its square's middle, along which the search splits its cells + let transform = DAffine2::from_translation(DVec2::new(100., 50.)) * DAffine2::from_scale(DVec2::new(200., 100.)); + let square = warp_frame(transform, DAffine2::IDENTITY).unwrap(); + let visible = [DVec2::new(100.25, 10.), DVec2::new(190., 90.)]; + for style in [WarpStyle::Flag, WarpStyle::Fisheye] { + let mesh = warp_of(&warp_effect(style, 50., transform)).unwrap().0.mesh(square.size); + let [min, max] = warp_source(&mesh, &square, visible); + + // Each point landing in view reads at most the 16 pixels around its source, the nearest the square covers among them standing in where it covers none of the four nearest + for index in 0..801 * 201 { + let uv = DVec2::new((index % 801) as f64 / 800., (index / 801) as f64 / 200.); + let landed = square.to_pixels.transform_point2(mesh.point(uv)); + if landed.cmpge(visible[0]).all() && landed.cmple(visible[1]).all() { + let source = square.to_pixels.transform_point2(uv); + let base = (source - 0.5).floor(); + let (first, last) = (base - 0.5, base + 2.5); + assert!( + first.cmpge(min).all() && last.cmple(max).all(), + "{style:?} carries {uv} into view at {landed}, reading the pixels centered from {first} to {last}, past {min} to {max}" + ); + } + } + } + } + + #[test] + fn warp_effects_zoomed_far_in_read_little_more_than_the_view_shows() { + use crate::warp::WarpStyle; + + // A view 200 pixels across of the arc's middle at a zoom of 1000, a fifth of a document unit across, which reads from about as small a part of the square lower down + let transform = DAffine2::from_translation(DVec2::new(200., 150.)) * DAffine2::from_scale(DVec2::new(200., 100.)); + let square = warp_frame(transform, DAffine2::from_scale(DVec2::splat(1000.)) * DAffine2::from_translation(-DVec2::new(190., 120.))).unwrap(); + let mesh = warp_of(&warp_effect(WarpStyle::Arc, 50., transform)).unwrap().0.mesh(square.size); + let visible = [DVec2::ZERO, DVec2::splat(200.)]; + let [min, max] = warp_source(&mesh, &square, visible); + assert!((max - min).max_element() < 600., "the region spans {min} to {max}"); + + // Each point of the square near the region that the patch carries into view reads from within it + let to_unit = square.to_pixels.inverse(); + let (near_min, near_max) = (to_unit.transform_point2(min - (max - min)), to_unit.transform_point2(max + (max - min))); + for index in 0..101 * 101 { + let uv = near_min + (near_max - near_min) * DVec2::new((index % 101) as f64, (index / 101) as f64) / 100.; + let landed = square.to_pixels.transform_point2(mesh.point(uv)); + let within_square = uv.cmpge(DVec2::ZERO).all() && uv.cmple(DVec2::ONE).all(); + if within_square && landed.cmpge(visible[0]).all() && landed.cmple(visible[1]).all() { + let source = square.to_pixels.transform_point2(uv); + assert!( + source.cmpge(min - 1e-6).all() && source.cmple(max + 1e-6).all(), + "{uv} lands in view at {landed} but reads from {source}, outside {min} to {max}" + ); + } + } + } + + #[test] + fn warp_tessellations_polish_their_sources_onto_the_exact_patch() { + use crate::warp::WarpStyle; + + let transform = DAffine2::from_translation(DVec2::new(200., 150.)) * DAffine2::from_scale(DVec2::new(200., 100.)); + let square = warp_frame(transform, DAffine2::IDENTITY).unwrap(); + let mesh = warp_of(&warp_effect(WarpStyle::Fish, 60., transform)).unwrap().0.mesh(square.size); + let tessellation = WarpTessellation::new(&mesh, &square, DVec2::new(400., 300.)).unwrap(); + assert!(tessellation.cells.iter().all(|&cells| (1..=MAX_WARP_CELLS).contains(&cells))); + + // A seed a few hundredths of a cell off lands back on the parameters the texel's point comes from + let cell = DVec2::ONE / DVec2::new(tessellation.cells[0] as f64, tessellation.cells[1] as f64); + for parameters in [DVec2::new(0.3, 0.4), DVec2::new(0.9, 0.1), DVec2::new(1.005, 0.5)] { + let texel = tessellation.patch.point(parameters); + let polished = tessellation.polished(parameters + cell * 0.03, texel); + assert!((polished - parameters).length() < 1e-6, "{parameters} polishes to {polished}"); + } + + // A seed more than a cell off, or one on a patch collapsed to a line that can't reach the texel, stands as it is + let far = DVec2::new(0.3, 0.4) + cell * 3.; + assert_eq!(tessellation.polished(far, tessellation.patch.point(DVec2::new(0.3, 0.4))), far); + let collapsed = WarpMesh([WarpMesh::identity().0[0]; 4]); + let flat = WarpTessellation::new(&collapsed, &square, DVec2::new(400., 300.)).unwrap(); + let seed = DVec2::new(0.5, 0.5); + assert_eq!(flat.polished(seed, flat.patch.point(seed) + DVec2::new(0., 5.)), seed); + + // Without a bend, the patch carries each point to where it reads the content from, a texture's view zoomed far in included + let zoomed = square.placed(DAffine2::from_scale(DVec2::splat(1000.)) * DAffine2::from_translation(-DVec2::new(180., 130.))); + for (square, size) in [(square, DVec2::new(400., 300.)), (zoomed, DVec2::new(400., 300.)), (zoomed, DVec2::new(3., 2.))] { + let tessellation = WarpTessellation::new(&WarpMesh::identity(), &square, size).unwrap(); + for parameters in [DVec2::ZERO, DVec2::ONE, DVec2::splat(0.3)] { + let (read, landed) = (tessellation.source.transform_point2(parameters), tessellation.patch.point(parameters)); + assert!((read - landed).length() < 1e-6, "{parameters} reads {read} but lands at {landed}"); + } + } + } + #[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 }; diff --git a/node-graph/libraries/graphic-types/src/warp.rs b/node-graph/libraries/graphic-types/src/warp.rs new file mode 100644 index 0000000000..747fe4f148 --- /dev/null +++ b/node-graph/libraries/graphic-types/src/warp.rs @@ -0,0 +1,583 @@ +//! A warp: a bicubic Bezier patch over a box, bent into one of the preset styles, which carries each point of the box's unit square to where it lands. +//! It's geometry alone, so warping the pixels of a graphic and warping vector geometry can share it. + +use core_types::graphene_hash::CacheHash; +use dyn_any::DynAny; +use glam::{DAffine2, DVec2, Vec2Swizzles}; + +/// The preset shape a warp bends its box into. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Dropdown)] +pub enum WarpStyle { + /// Bends the content into a band of concentric arcs, like a rainbow, its bottom edge spanning its width. + #[default] + Arc, + /// Bulges the bottom edge down into an arc, keeping the top edge straight. + ArcLower, + /// Bulges the top edge up into an arc, keeping the bottom edge straight. + ArcUpper, + #[menu_separator] + /// Bends the content up into an arch, its top and bottom edges following the same arc. + Arch, + /// Bulges the top edge up and the bottom edge down into arcs. + Bulge, + /// Bends the bottom edge down into an arc, fanning out from the straight top edge like a seashell. + ShellLower, + /// Bends the top edge up into an arc, fanning out from the straight bottom edge like a seashell. + ShellUpper, + #[menu_separator] + /// Waves the content like a flag, its top and bottom edges rising and falling together. + Flag, + /// Waves the content's middle up and down between its straight edges. + Wave, + /// Swells the content's left side and pinches its right, like a fish. + Fish, + /// Lowers the content's left side along a smooth curve, so it rises toward its right. + Rise, + #[menu_separator] + /// Magnifies the content's middle as if seen through a wide lens. + Fisheye, + /// Puffs the content's edges out, like a pillow. + Inflate, + /// Squeezes the content's sides in and stretches its top and bottom out. + Squeeze, + /// Twists the content's middle around, clockwise for a positive bend. + Twist, +} + +/// For PSD interop, a style's bend and distortions: what bends the box, from which the [`WarpMesh`] follows. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Warp { + pub style: WarpStyle, + /// How strongly the style bends the box, from -1 to 1, the other way when negative. + pub bend: f64, + /// How much taller the right side grows than the left (the left than the right when negative), as if turned away in perspective, from -1 to 1. + pub horizontal_distortion: f64, + /// How much wider the bottom grows than the top (the top than the bottom when negative), as if tipped away in perspective, from -1 to 1. + pub vertical_distortion: f64, + /// Whether the style is built mirrored across the diagonal, bending the left and right edges instead of the top and bottom. + pub vertical: bool, +} + +impl Warp { + /// For PSD interop, the control points that bend a box `size` across, as fractions of that size. + /// The arcs are true circles in the box's own units, so the mesh depends on its aspect ratio. A box without area is left as it is. + pub fn mesh(&self, size: DVec2) -> WarpMesh { + use WarpStyle::*; + if !(size.cmpgt(DVec2::ZERO).all() && size.is_finite()) { + return WarpMesh::identity(); + } + + let bend = self.bend.clamp(-1., 1.); + let (horizontal, vertical) = (self.horizontal_distortion.clamp(-1., 1.), self.vertical_distortion.clamp(-1., 1.)); + + // Some styles take their distortions in closed form + match self.style { + Inflate => return WarpMesh(centered_mesh(DVec2::splat(bend), horizontal, vertical)), + Squeeze if self.vertical => return WarpMesh(centered_mesh(DVec2::new(bend, -bend), horizontal, vertical)), + Squeeze => return WarpMesh(centered_mesh(DVec2::new(-bend, bend), horizontal, vertical)), + // Built vertically, a wave moves its columns' inner points across, each by its row's width + Wave if self.vertical => { + let mut mesh = centered_mesh(DVec2::ZERO, horizontal, vertical); + for (row, wave) in [(1, 1.), (2, -1.)] { + for column in [1, 2] { + mesh[row][column].x += 4. / 3. * bend * wave * (1. + vertical * lattice_position(row)); + } + } + return WarpMesh(mesh); + } + _ => {} + } + + // A vertical warp is the style built on the box with its axes swapped, then swapped back, except that a twist keeps its turn + let preset = match self.vertical && self.style != Twist { + true => transposed(preset_mesh(self.style, bend, size.yx())), + false => preset_mesh(self.style, bend, size), + }; + + // The distortions taper the rows, then the columns, in the box's own axes + let ruled = matches!(self.style, Arc | ArcLower | ArcUpper | Arch | Bulge | Flag | Wave | Fish | Rise); + let rows_tapered = tapered_rows(preset, vertical, ruled && !self.vertical); + WarpMesh(transposed(tapered_rows(transposed(rows_tapered), horizontal, ruled && self.vertical))) + } +} + +/// A bicubic Bezier patch as its 4x4 control points, in rows down its v direction, each row across its u direction. +/// Past the unit square, the patch continues each side along its tangent there, so it covers the whole plane smoothly. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WarpMesh(pub [[DVec2; 4]; 4]); + +impl WarpMesh { + /// The evenly spaced mesh leaving every point of the unit square where it is. + pub fn identity() -> Self { + Self(std::array::from_fn(|row| std::array::from_fn(|column| DVec2::new(column as f64, row as f64) / 3.))) + } + + /// Where the patch carries the point `uv`. + pub fn point(&self, uv: DVec2) -> DVec2 { + self.point_and_tangents(uv)[0] + } + + /// Where the patch carries the point `uv`, and how fast that moves along u and along v there. O(1). + pub fn point_and_tangents(&self, uv: DVec2) -> [DVec2; 3] { + let (across, across_slopes) = extended_bases(uv.x); + let (down, down_slopes) = extended_bases(uv.y); + + let mut result = [DVec2::ZERO; 3]; + for (row, points) in self.0.iter().enumerate() { + for (column, &point) in points.iter().enumerate() { + result[0] += point * (down[row] * across[column]); + result[1] += point * (down[row] * across_slopes[column]); + result[2] += point * (down_slopes[row] * across[column]); + } + } + result + } + + /// The control points of the patch over the rectangle from `start` to `end` in (u, v), which restricts the patch to it when inside the unit square. + /// The rectangle must lie within one of the nine regions the unit square's sides divide the plane into, past which the patch is a different polynomial. + pub fn over(&self, start: DVec2, end: DVec2) -> Self { + let (across, down) = (bezier_bases_over(start.x, end.x), bezier_bases_over(start.y, end.y)); + Self(std::array::from_fn(|row| { + std::array::from_fn(|column| { + let mut point = DVec2::ZERO; + for (mesh_row, points) in self.0.iter().enumerate() { + for (mesh_column, &mesh_point) in points.iter().enumerate() { + point += mesh_point * (down[mesh_row][row] * across[mesh_column][column]); + } + } + point + }) + })) + } + + /// The mesh with each control point carried through `transform`, which carries the patch along since Bezier patches keep their shape under affine maps. + pub fn transformed(&self, transform: DAffine2) -> Self { + Self(self.0.map(|row| row.map(|point| transform.transform_point2(point)))) + } + + /// The bounding box of the control points, which holds the whole patch over the unit square. + pub fn hull_bounds(&self) -> [DVec2; 2] { + let points = self.0.iter().flatten(); + [ + points.clone().fold(DVec2::INFINITY, |min, &point| min.min(point)), + points.fold(DVec2::NEG_INFINITY, |max, &point| max.max(point)), + ] + } + + /// The longest the patch's u and v tangents can be over the unit square, which bounds how far a step along each moves. + pub fn tangent_bounds(&self) -> DVec2 { + let mut longest = DVec2::ZERO; + for row in 0..4 { + for step in 0..3 { + longest.x = longest.x.max((self.0[row][step + 1] - self.0[row][step]).length()); + longest.y = longest.y.max((self.0[step + 1][row] - self.0[step][row]).length()); + } + } + longest * 3. + } +} + +/// The four cubic Bernstein polynomials at `t` and their slopes, continuing past 0 and 1 along their tangents there. +fn extended_bases(t: f64) -> ([f64; 4], [f64; 4]) { + if t < 0. { + return ([1. - 3. * t, 3. * t, 0., 0.], [-3., 3., 0., 0.]); + } + if t > 1. { + let past = t - 1.; + return ([0., 0., -3. * past, 1. + 3. * past], [0., 0., -3., 3.]); + } + + let rest = 1. - t; + ( + [rest * rest * rest, 3. * t * rest * rest, 3. * t * t * rest, t * t * t], + [-3. * rest * rest, 3. * rest * rest - 6. * t * rest, 6. * t * rest - 3. * t * t, 3. * t * t], + ) +} + +/// Each of the four extended Bernstein polynomials (see [`extended_bases`]) over the interval from `start` to `end` as the coefficients of the Bernstein polynomials of that interval. +/// Within one of the intervals that 0 and 1 divide the line into, each is a cubic, which its values and slopes at the interval's ends determine. +fn bezier_bases_over(start: f64, end: f64) -> [[f64; 4]; 4] { + let ((start_values, start_slopes), (end_values, end_slopes)) = (extended_bases(start), extended_bases(end)); + let third = (end - start) / 3.; + std::array::from_fn(|basis| { + [ + start_values[basis], + start_values[basis] + third * start_slopes[basis], + end_values[basis] - third * end_slopes[basis], + end_values[basis], + ] + }) +} + +/// The four control points, in the units of `width`, of a circular arc with its chord from (0, `y`) to (`width`, `y`), turning through `half_angle` (in radians) each side of its middle, +/// bulging up toward -y when `up`, and grown out from its center by `radius_offset`. Each end handle is 4/3 tan(half angle / 2) of the radius long, so the curve's middle lies on the circle. +fn arc_row(width: f64, y: f64, half_angle: f64, up: bool, radius_offset: f64) -> [DVec2; 4] { + // Measured from the chord's ends, without the radius itself, which grows without bound as the arc flattens + let away_from_center = if up { -1. } else { 1. }; + let (sin, cos) = half_angle.sin_cos(); + let handle = width / (3. * (half_angle / 2.).cos().powi(2)) + radius_offset * 4. / 3. * (half_angle / 2.).tan(); + + let start = DVec2::new(0., y) + DVec2::new(-sin, away_from_center * cos) * radius_offset; + let end = DVec2::new(width, y) + DVec2::new(sin, away_from_center * cos) * radius_offset; + [ + start, + start + DVec2::new(cos, away_from_center * sin) * handle, + end - DVec2::new(cos, -away_from_center * sin) * handle, + end, + ] +} + +/// A row of control points in the units of a box `size` across, as fractions of that size. +fn normalized(row: [DVec2; 4], size: DVec2) -> [DVec2; 4] { + row.map(|point| point / size) +} + +/// The rows from `top` to `bottom`, each control point a straight line between them. +fn rows_between(top: [DVec2; 4], bottom: [DVec2; 4]) -> [[DVec2; 4]; 4] { + std::array::from_fn(|row| std::array::from_fn(|column| top[column].lerp(bottom[column], row as f64 / 3.))) +} + +/// The mesh mirrored top to bottom. +fn flipped_vertically(mesh: [[DVec2; 4]; 4]) -> [[DVec2; 4]; 4] { + std::array::from_fn(|row| mesh[3 - row].map(|point| DVec2::new(point.x, 1. - point.y))) +} + +/// For PSD interop, the concentric arcs of an Arc of `bend` on a box `size` across: about a center below for a positive bend, the bottom row's chord spanning the width and each row above a third of the height farther out. +fn arc_mesh(bend: f64, size: DVec2) -> [[DVec2; 4]; 4] { + if bend < 0. { + return flipped_vertically(arc_mesh(-bend, size)); + } + let half_angle = bend * std::f64::consts::FRAC_PI_2; + std::array::from_fn(|row| normalized(arc_row(size.x, size.y, half_angle, true, size.y * (3 - row) as f64 / 3.), size)) +} + +/// For PSD interop, the top or bottom edge bent into an arc through its ends by `bend`, bulging out of the box for a positive bend. +fn edge_arc(bend: f64, size: DVec2, top: bool) -> [DVec2; 4] { + let half_angle = bend.abs() * std::f64::consts::FRAC_PI_2; + let up = if top { bend > 0. } else { bend < 0. }; + normalized(arc_row(size.x, if top { 0. } else { size.y }, half_angle, up, 0.), size) +} + +/// For PSD interop, the control points of a style's `bend` (from -1 to 1) on a box `size` across, as fractions of that size. +fn preset_mesh(style: WarpStyle, bend: f64, size: DVec2) -> [[DVec2; 4]; 4] { + let mut mesh = WarpMesh::identity().0; + let [identity_top, .., identity_bottom] = mesh; + + // Moves a control point by a fraction of the box + let mut nudge = |row: usize, column: usize, by: DVec2| mesh[row][column] += by; + + match style { + WarpStyle::Arc => arc_mesh(bend, size), + WarpStyle::ArcLower => rows_between(identity_top, edge_arc(bend, size, false)), + WarpStyle::ArcUpper => rows_between(edge_arc(bend, size, true), identity_bottom), + WarpStyle::Arch => { + let top = edge_arc(bend, size, true); + std::array::from_fn(|row| top.map(|point| point + DVec2::new(0., row as f64 / 3.))) + } + WarpStyle::Bulge => rows_between(edge_arc(bend, size, true), edge_arc(bend, size, false)), + // A shell takes the outer arc and its side points from the arc bent the other way, keeping the rest + WarpStyle::ShellLower => { + let arc = arc_mesh(-bend, size); + mesh[3] = arc[3]; + mesh[2][0] = arc[2][0]; + mesh[2][3] = arc[2][3]; + mesh + } + WarpStyle::ShellUpper => { + let arc = arc_mesh(bend, size); + mesh[0] = arc[0]; + mesh[1][0] = arc[1][0]; + mesh[1][3] = arc[1][3]; + mesh + } + WarpStyle::Flag => { + for row in 0..4 { + nudge(row, 1, DVec2::new(0., 2. * bend)); + nudge(row, 2, DVec2::new(0., -2. * bend)); + } + mesh + } + WarpStyle::Wave => { + for row in [1, 2] { + nudge(row, 1, DVec2::new(0., 4. / 3. * bend)); + nudge(row, 2, DVec2::new(0., -4. / 3. * bend)); + } + mesh + } + WarpStyle::Fish => { + for row in 0..4 { + let shift = 2. * bend * (2. * row as f64 / 3. - 1.); + nudge(row, 1, DVec2::new(0., shift)); + nudge(row, 2, DVec2::new(0., -shift)); + } + mesh + } + WarpStyle::Rise => { + for row in 0..4 { + nudge(row, 0, DVec2::new(0., 2. * bend)); + nudge(row, 1, DVec2::new(0., 2. * bend)); + } + mesh + } + // The inner points move out from the middle + WarpStyle::Fisheye => { + for (row, column) in [(1, 1), (1, 2), (2, 1), (2, 2)] { + let outward = DVec2::new(if column == 1 { -1. } else { 1. }, if row == 1 { -1. } else { 1. }); + nudge(row, column, outward * 2. * bend / 3.); + } + mesh + } + // The sides' middle points move out by a third of the bend (in for a squeeze's left and right) + WarpStyle::Inflate => centered_mesh(DVec2::splat(bend), 0., 0.), + WarpStyle::Squeeze => centered_mesh(DVec2::new(-bend, bend), 0., 0.), + // Each inner point moves the bend's size of the box toward the next inner point around, clockwise for a positive bend + WarpStyle::Twist => { + let amount = bend.abs(); + let moves = match bend >= 0. { + true => [(1, 1, DVec2::X), (1, 2, DVec2::Y), (2, 2, -DVec2::X), (2, 1, -DVec2::Y)], + false => [(1, 1, DVec2::Y), (2, 1, DVec2::X), (2, 2, -DVec2::Y), (1, 2, -DVec2::X)], + }; + for (row, column, direction) in moves { + nudge(row, column, direction * amount); + } + mesh + } + } +} + +/// Where the control points of row or column `index` lie in the evenly spaced mesh, from -1 at the first to 1 at the last. +fn lattice_position(index: usize) -> f64 { + 2. * index as f64 / 3. - 1. +} + +/// The mesh with its rows and columns swapped, and each point's coordinates too. +fn transposed(mesh: [[DVec2; 4]; 4]) -> [[DVec2; 4]; 4] { + std::array::from_fn(|row| std::array::from_fn(|column| mesh[column][row].yx())) +} + +/// For PSD interop, the mesh with each row scaled about the middle of its end points by `1 + distortion` times its [`lattice_position`], so the top shrinks and the bottom grows for a positive distortion. +/// A `ruled` style scales only its outer rows, each inner point moving as its column's end points do, in proportion to how near it lies to each. +fn tapered_rows(mesh: [[DVec2; 4]; 4], distortion: f64, ruled: bool) -> [[DVec2; 4]; 4] { + let scaled = |row: usize| { + let middle = (mesh[row][0] + mesh[row][3]) / 2.; + mesh[row].map(|point| middle + (point - middle) * (1. + distortion * lattice_position(row))) + }; + if !ruled { + return std::array::from_fn(scaled); + } + + let (top, bottom) = (scaled(0), scaled(3)); + std::array::from_fn(|row| { + let toward_bottom = row as f64 / 3.; + std::array::from_fn(|column| mesh[row][column] + (top[column] - mesh[0][column]) * (1. - toward_bottom) + (bottom[column] - mesh[3][column]) * toward_bottom) + }) +} + +/// For PSD interop, the mesh of an inflate or squeeze with `bends` across and down, in closed form with its `horizontal` and `vertical` distortions (each from -1 to 1). +/// Each point lies out from the middle of the box by its column's share of its row's width and its row's share of its column's height, which the bends widen at the middle rows and columns. +fn centered_mesh(bends: DVec2, horizontal: f64, vertical: f64) -> [[DVec2; 4]; 4] { + let side = |index: usize| if index < 2 { -1. } else { 1. }; + let middle = |index: usize| if index == 1 || index == 2 { 1. } else { 0. }; + + std::array::from_fn(|row| { + std::array::from_fn(|column| { + let width = 1. + (1. + horizontal * side(column)) * (vertical * lattice_position(row) + 2. * bends.x / 3. * middle(row)); + let height = 1. + horizontal * lattice_position(column) + 2. * bends.y / 3. * middle(column) * (1. + vertical * side(row)); + DVec2::splat(0.5) + DVec2::new(lattice_position(column) * width, lattice_position(row) * height) / 2. + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn every_style() -> impl Iterator { + use WarpStyle::*; + [Arc, ArcLower, ArcUpper, Arch, Bulge, ShellLower, ShellUpper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist].into_iter() + } + + fn warp(style: WarpStyle, bend: f64) -> Warp { + Warp { + style, + bend, + horizontal_distortion: 0., + vertical_distortion: 0., + vertical: false, + } + } + + #[test] + fn warps_without_bend_or_distortion_change_nothing() { + for style in every_style() { + for vertical in [false, true] { + let mesh = Warp { vertical, ..warp(style, 0.) }.mesh(DVec2::new(300., 120.)); + for (row, points) in mesh.0.iter().enumerate() { + for (column, point) in points.iter().enumerate() { + let expected = DVec2::new(column as f64, row as f64) / 3.; + assert!((*point - expected).length() < 1e-12, "{style:?} moves control point ({column}, {row}) to {point}"); + } + } + } + } + + // Nor does a box without area, however far bent + for size in [DVec2::new(0., 100.), DVec2::new(100., -5.), DVec2::new(f64::INFINITY, 100.)] { + assert_eq!(warp(WarpStyle::Arc, 0.5).mesh(size), WarpMesh::identity(), "{size}"); + } + } + + #[test] + fn arcs_bend_into_concentric_circles() { + // For PSD interop, an Arc of 50% on a box 200 by 100 turns its rows through 45 degrees each side about a center below, the bottom row spanning the width + let size = DVec2::new(200., 100.); + let mesh = warp(WarpStyle::Arc, 0.5).mesh(size); + let at = |u: f64, v: f64| mesh.point(DVec2::new(u, v)) * size; + + assert!((at(0., 1.) - DVec2::new(0., 100.)).length() < 1e-9); + assert!((at(0., 0.) - DVec2::new(-100. * 0.5_f64.sqrt(), 100. - 100. * 0.5_f64.sqrt())).length() < 1e-9); + let center = DVec2::new(100., 200.); + let inner_radius = 100. * 2_f64.sqrt(); + assert!((at(0.5, 1.) - DVec2::new(100., 200. - inner_radius)).length() < 1e-9, "{}", at(0.5, 1.)); + assert!((at(0.5, 0.) - DVec2::new(100., 200. - inner_radius - 100.)).length() < 1e-9); + + // Between the ends and the middle, the cubics stray from their circles by under a thousandth of the radius + for t in [0.1, 0.25, 0.4, 0.7] { + let distance = (at(t, 1.) - center).length(); + assert!((distance - inner_radius).abs() < 1e-3 * inner_radius, "{t} lies {distance} from the center"); + } + + // Bent the other way, the arc mirrors top to bottom + let flipped = warp(WarpStyle::Arc, -0.5).mesh(size); + let mirrored = flipped.point(DVec2::new(0.3, 0.)) * size; + assert!((mirrored - DVec2::new(at(0.3, 1.).x, 100. - at(0.3, 1.).y)).length() < 1e-9); + } + + #[test] + fn meshes_carry_points_where_psd_interop_measures_them() { + use WarpStyle::*; + + // For PSD interop, where these points (u, v) land from the box's corner, measured on boxes warped by each case's style, bend, distortions, and size + let points = [(0.125, 0.875), (0.5, 0.5), (0.875, 0.25)]; + let built_across = [ + (Arc, 46., -46., 63., (137., 291.), [(-18.2693, 273.7009), (68.5, 142.5221), (147.3426, 129.4578)]), + (ArcLower, -10., 40., -17., (137., 291.), [(21.154, 220.248), (68.5, 143.2627), (125.9035, 50.4845)]), + (ArcUpper, 72., 83., -82., (137., 291.), [(21.7839, 179.6745), (68.5, 105.941), (164.3882, -0.2931)]), + (Arch, 60., -12., 21., (137., 291.), [(4.7147, 246.6993), (68.5, 110.5975), (117.7196, 65.5829)]), + (Bulge, -5., 92., -7., (137., 291.), [(17.4618, 178.7312), (68.5, 145.6884), (123.2537, 23.3591)]), + (ShellLower, -11., -32., 81., (250., 250.), [(-47.7217, 235.6717), (124.4881, 122.5727), (193.4388, 77.0996)]), + (ShellUpper, 28., 22., 79., (250., 250.), [(-15.6586, 205.5381), (125.4301, 129.278), (198.9814, 66.0233)]), + (Flag, -34., 96., -71., (400., 120.), [(57.455, 58.6496), (200., 60.), (451.53, 38.6517)]), + (Wave, -68., 64., -81., (400., 120.), [(86.045, 77.1135), (200., 73.056), (447.47, 34.9449)]), + (Fish, -74., 37., 83., (300., 200.), [(-8.0592, 48.0784), (150., 100.), (199.4978, 54.1741)]), + (Rise, 21., -41., 3., (400., 120.), [(45.3181, 167.7718), (200., 85.2), (348.6213, 41.6151)]), + (Fisheye, -41., 9., 9., (400., 120.), [(49.4018, 99.2699), (198.155, 59.4465), (327.1722, 30.8844)]), + (Inflate, -44., -1., -25., (137., 291.), [(31.8545, 247.6754), (68.5753, 149.5012), (117.8414, 82.486)]), + (Squeeze, -100., -23., -76., (300., 200.), [(86.4829, 184.5195), (141.375, 119.), (327.0879, 79.9531)]), + (Twist, -50., 24., 26., (300., 200.), [(32.6476, 161.1075), (150.2812, 95.3125), (227.5034, 37.7156)]), + ]; + let built_vertically = [ + (Arc, -62., 57., -4., (400., 120.), [(51.7769, 143.6624), (281.6909, 62.3381), (414.7634, -239.3584)]), + (ArcLower, -34., 27., 97., (250., 250.), [(-13.9043, 199.8505), (103.2855, 125.2042), (130.5268, 48.473)]), + (ArcUpper, 9., -83., -59., (200., 300.), [(88.0162, 332.7032), (90.2822, 149.9693), (170.7866, 121.653)]), + (Arch, -85., -53., 82., (137., 291.), [(33.3319, 318.7345), (183.2029, 145.5), (165.5277, 91.453)]), + (Bulge, 1., -29., 26., (200., 300.), [(4.1491, 286.9706), (99.6583, 150.), (169.4088, 91.3111)]), + (ShellLower, 59., 77., 23., (137., 291.), [(14.9208, 183.6004), (89.0674, 140.4151), (185.5401, -57.6605)]), + (ShellUpper, -48., -13., 69., (400., 120.), [(-40.7272, 140.8086), (200.408, 64.7486), (305.3843, 32.0372)]), + (Flag, 12., 57., -90., (200., 300.), [(30.3873, 214.4063), (100., 150.), (253.6712, 42.9375)]), + (Wave, 47., 80., 36., (200., 300.), [(9.8851, 195.), (91.54, 150.), (159.0405, 30.)]), + (Fish, -65., 80., 86., (137., 291.), [(22.3632, 189.15), (99.1332, 145.5), (41.0932, 29.1)]), + (Rise, 26., -84., 45., (400., 120.), [(-108.2769, 133.35), (304., 60.), (484.505, 48.9)]), + (Fisheye, -59., 85., 44., (300., 200.), [(36.7591, 121.2068), (131.1938, 93.51), (197.0264, 24.3454)]), + (Inflate, -25., -87., -38., (200., 300.), [(73.5647, 332.1892), (105.4375, 153.5625), (175.6768, 129.9873)]), + (Squeeze, 92., -36., 24., (200., 300.), [(-14.3164, 264.5742), (91.72, 141.72), (185.5469, 105.8156)]), + (Twist, -69., 35., 4., (300., 200.), [(50.1306, 154.89), (143.9841, 94.9544), (232.9504, 32.6515)]), + ]; + + for (vertical, cases) in [(false, built_across), (true, built_vertically)] { + for (style, bend, horizontal_distortion, vertical_distortion, (width, height), landings) in cases { + let warp = Warp { + style, + bend: bend / 100., + horizontal_distortion: horizontal_distortion / 100., + vertical_distortion: vertical_distortion / 100., + vertical, + }; + let size = DVec2::new(width, height); + let mesh = warp.mesh(size); + for ((u, v), (x, y)) in points.into_iter().zip(landings) { + let landed = mesh.point(DVec2::new(u, v)) * size; + assert!(landed.distance(DVec2::new(x, y)) < 1e-3, "{warp:?} carries ({u}, {v}) to {landed}, not ({x}, {y})"); + } + } + } + } + + #[test] + fn vertical_warps_bend_the_sides() { + // Built vertically, an Arch bends its columns across, leaving the top and bottom edges' heights alone at the corners + let mesh = Warp { + vertical: true, + ..warp(WarpStyle::Arch, 0.4) + } + .mesh(DVec2::new(100., 300.)); + assert!(mesh.point(DVec2::new(0., 0.5)).x < -0.05, "the left edge bulges left"); + assert!((mesh.point(DVec2::new(0., 0.)) - DVec2::ZERO).length() < 1e-9); + } + + #[test] + fn patches_continue_each_side_along_its_tangent() { + let mesh = warp(WarpStyle::Flag, 0.6).mesh(DVec2::new(200., 100.)); + + // Past the right side, each point moves on in a straight line, at the speed it moved there + let [edge, across, _] = mesh.point_and_tangents(DVec2::new(1., 0.3)); + for past in [0.1, 0.5, 2.] { + let point = mesh.point(DVec2::new(1. + past, 0.3)); + assert!((point - (edge + across * past)).length() < 1e-12); + } + + // The tangents agree at the side, from either way + let inside = mesh.point_and_tangents(DVec2::new(1. - 1e-9, 0.3)); + let outside = mesh.point_and_tangents(DVec2::new(1. + 1e-9, 0.3)); + for (inside, outside) in inside.iter().zip(outside) { + assert!((*inside - outside).length() < 1e-6); + } + } + + #[test] + fn meshes_over_part_of_the_plane_trace_the_same_patch() { + let mesh = warp(WarpStyle::Twist, 0.7).mesh(DVec2::new(150., 100.)); + + // Within the unit square, past its side, and past its corner + for (start, end) in [ + (DVec2::new(0.2, 0.1), DVec2::new(0.6, 0.9)), + (DVec2::new(1., 0.3), DVec2::new(1.8, 0.5)), + (DVec2::new(-0.7, -0.4), DVec2::new(0., -0.1)), + ] { + let part = mesh.over(start, end); + for st in [DVec2::new(0.3, 0.7), DVec2::new(0., 1.), DVec2::new(0.9, 0.2)] { + let expected = mesh.point(start + (end - start) * st); + assert!((part.point(st) - expected).length() < 1e-12, "over {start} to {end} at {st}"); + } + } + + // A part reaching the unit square's side continues past it as the whole patch does + let part = mesh.over(DVec2::new(0.5, 0.), DVec2::new(1., 1.)); + assert!((part.point(DVec2::new(1.4, 0.5)) - mesh.point(DVec2::new(1.2, 0.5))).length() < 1e-12); + } + + #[test] + fn the_control_points_hold_the_patch() { + for style in every_style() { + let mesh = warp(style, -0.8).mesh(DVec2::new(240., 90.)); + let [min, max] = mesh.hull_bounds(); + for index in 0..=100 { + let point = mesh.point(DVec2::new((index % 11) as f64 / 10., (index / 11) as f64 / 9.).min(DVec2::ONE)); + assert!(point.cmpge(min - 1e-12).all() && point.cmple(max + 1e-12).all(), "{style:?} reaches {point} past {min} to {max}"); + } + } + } +} diff --git a/node-graph/libraries/raster-kernels/src/lib.rs b/node-graph/libraries/raster-kernels/src/lib.rs index c81fbeaf6d..9d578eabf8 100644 --- a/node-graph/libraries/raster-kernels/src/lib.rs +++ b/node-graph/libraries/raster-kernels/src/lib.rs @@ -14,6 +14,7 @@ pub mod masks; pub mod raster_effects; pub mod resample_kernels; pub mod value_effects; +pub mod warp_kernels; pub use kernel::*; pub use raster_effects::evaluate_raster_effects; diff --git a/node-graph/libraries/raster-kernels/src/raster_effects.rs b/node-graph/libraries/raster-kernels/src/raster_effects.rs index 799733ed13..a66750cbb5 100644 --- a/node-graph/libraries/raster-kernels/src/raster_effects.rs +++ b/node-graph/libraries/raster-kernels/src/raster_effects.rs @@ -9,6 +9,7 @@ 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, displaced, frame_warped, motion_blurred, radial_blurred}; use crate::value_effects::{adjusted_gradient, adjustments, evaluate_gradient_effects, filled_color}; +use crate::warp_kernels::WarpRasterizer; use core_types::FallibleVec2Operations; use core_types::blending::BlendMode; use core_types::color::{linear_to_srgb, srgb_to_linear}; @@ -26,7 +27,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::{DisplacementField, EffectFrame, FrameWarp, RadialBlur, map_displacement, warp_frame}; +use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, RadialBlur, map_displacement, warp_frame, warp_of}; use raster_types::parallel_rows::fill_rows; use raster_types::{CPU, Image, Raster}; use std::collections::HashMap; @@ -581,6 +582,21 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: full = warped(&full); filled = filled.map(|filled| warped(&filled)); } + EffectOperation::Warp { .. } => { + // The square the warp's transform places from the content's origin, at the image's corner past the margin + let Some((warp, transform)) = warp_of(operation) else { continue }; + let rasterizer = warp_frame(transform, effect_to_plane).map(|square| WarpRasterizer::new(&warp.mesh(square.size), &square, full.width, full.height)); + + merge_beneath(&mut full, &mut filled, &mut beneath); + + // Where its square collapses, it clears everything + let warped = |plane: &Plane<[f32; 4]>| match &rasterizer { + Some(rasterizer) => rasterizer.warped(plane), + None => Plane::new(plane.width, plane.height), + }; + full = warped(&full); + filled = filled.map(|filled| warped(&filled)); + } EffectOperation::Ripple { .. } | EffectOperation::Wave { .. } => { let (Some(frame), Some((field, edge_mode))) = (&frame, DisplacementField::of(operation)) else { continue; @@ -1503,6 +1519,65 @@ mod tests { } } + fn warp_effect(style: graphic_types::WarpStyle, bend: f64, transform: DAffine2) -> EffectOperation { + EffectOperation::Warp { + style, + bend, + horizontal_distortion: 0., + vertical_distortion: 0., + vertical: false, + transform, + } + } + + #[test] + fn warp_effects_keep_the_edge_fade_their_patch_carries_past_their_square() { + use graphic_types::{Effect, WarpStyle, stamp_effect}; + + // Styles that keep the sides of a square on the image in place but stretch across them, so only the fade of its edge lands past the square + for (style, bend) in [(WarpStyle::Twist, 100.), (WarpStyle::Twist, -100.), (WarpStyle::Fisheye, -60.)] { + let mut item = Item::new_from_element(Raster::new_cpu(Image { + width: 40, + height: 20, + data: vec![Color::WHITE; 40 * 20], + })) + .with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(40., 20.))); + let on_image = DAffine2::from_translation(DVec2::new(20., 10.)) * DAffine2::from_scale(DVec2::new(40., 20.)); + stamp_effect(&mut item, Effect::new(&warp_effect(style, bend, on_image))); + + // The image's outermost pixels are clear, so none of the fade is cut at its edge + let evaluated = evaluate_raster_effects(item); + let raster = evaluated.element(); + let (width, height) = (raster.width as usize, raster.height as usize); + let outermost = (0..width * height).filter(|index| index % width == 0 || index % width == width - 1 || index / width == 0 || index / width == height - 1); + let worst = outermost.map(|index| raster.data[index].a()).fold(0., f32::max); + assert!(worst < 1e-3, "{style:?} at {bend} ends at a hard edge with alpha {worst} on a {width} by {height} image"); + } + } + + #[test] + fn warp_effects_clear_what_earlier_warps_bent_past_their_square() { + use graphic_types::{Effect, WarpStyle, stamp_effect}; + + // A square image bent into an arc within a square on it, its ends reaching 0.707 of its width past its sides, then stretched four times as wide + let mut item = Item::new_from_element(Raster::new_cpu(Image::new(40, 40, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(40.))); + let on_square = DAffine2::from_translation(DVec2::splat(20.)) * DAffine2::from_scale(DVec2::splat(40.)); + stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Arc, 50., on_square))); + let mut item = item.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(160., 40.))); + + // A flag stamped after the stretch, in a run of its own within a square on the stretched image, only raises and lowers what lies within it, clearing the arc's ends past its sides + let on_stretched = DAffine2::from_translation(DVec2::new(80., 20.)) * DAffine2::from_scale(DVec2::new(160., 40.)); + stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Flag, 30., on_stretched))); + let evaluated = evaluate_raster_effects(item); + let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM); + let raster = evaluated.element(); + + let across = |x: u32| placement.transform_point2(DVec2::new((x as f64 + 0.5) / raster.width as f64, 0.)).x; + let opaque_columns = (0..raster.width).filter(|&x| (0..raster.height).any(|y| raster.data[(y * raster.width + x) as usize].a() > 0.5)); + let (left, right) = opaque_columns.fold((f64::INFINITY, f64::NEG_INFINITY), |(left, right), x| (left.min(across(x)), right.max(across(x)))); + assert!((-1.0..10.).contains(&left) && (150.0..161.).contains(&right), "the arc spans {left} to {right}"); + } + #[test] fn a_blurs_radius_mask_image_blurs_everything_the_effects_before_it_paint() { // A hard shadow cast 30 pixels right of content 20 wide, far past the blur's own reach of 9 diff --git a/node-graph/libraries/raster-kernels/src/resample_kernels.rs b/node-graph/libraries/raster-kernels/src/resample_kernels.rs index ab8f5a954a..8849d259a0 100644 --- a/node-graph/libraries/raster-kernels/src/resample_kernels.rs +++ b/node-graph/libraries/raster-kernels/src/resample_kernels.rs @@ -116,6 +116,87 @@ fn sample_bilinear_on_side(plane: &Plane<[f32; 4]>, point: DVec2, frame: &Effect std::array::from_fn(|channel| sum[channel] / covered - beside[channel] * (touched - covered) / covered) } +/// The most corners a pixel clipped by the four sides of a frame can have. +const CLIPPED_CORNERS: usize = 8; + +/// How much of each pixel (given by its corner) the `frame` covers: the share of its area left after clipping it by each of the frame's sides, which is none for a pixel the frame misses or only touches. O(1) per pixel. +pub(crate) fn pixel_area_within(frame: &EffectFrame) -> impl Fn(DVec2) -> f64 { + let (to_local, half, extent) = (frame.pixels_to_local(), frame.size / 2., frame.pixel_extent()); + // How far along the frame's local x and y a step across and a step down the pixels move + let rows = [to_local.matrix2.row(0), to_local.matrix2.row(1)]; + + move |pixel| { + let center = to_local.transform_point2(pixel + 0.5); + + // Wholly within the frame, or wholly past one of its sides + if (center.abs() + extent).cmple(half).all() { + return 1.; + } + if (center.abs() - extent).cmpge(half).any() { + return 0.; + } + + // The pixel's corners relative to its center, clipped by one side after another, each replacing the corners past it with where the edges cross it + let mut corners = [DVec2::ZERO; CLIPPED_CORNERS]; + corners[..4].copy_from_slice(&[DVec2::new(-0.5, -0.5), DVec2::new(0.5, -0.5), DVec2::new(0.5, 0.5), DVec2::new(-0.5, 0.5)]); + let mut count = 4; + for side in 0..4 { + // How far past the side a corner lies, beyond the positive or negative end of the local axis it bounds (x for the first two sides, y for the others) + let (axis, sign) = (side / 2, if side % 2 == 0 { 1. } else { -1. }); + let (direction, offset) = (rows[axis] * sign, sign * center[axis] - half[axis]); + let past = |corner: DVec2| direction.dot(corner) + offset; + + let (mut clipped, mut clipped_count) = ([DVec2::ZERO; CLIPPED_CORNERS], 0); + let mut previous = corners[count - 1]; + for ¤t in &corners[..count] { + let (previous_past, current_past) = (past(previous), past(current)); + if (previous_past > 0.) != (current_past > 0.) && clipped_count < CLIPPED_CORNERS { + clipped[clipped_count] = previous.lerp(current, previous_past / (previous_past - current_past)); + clipped_count += 1; + } + if current_past <= 0. && clipped_count < CLIPPED_CORNERS { + clipped[clipped_count] = current; + clipped_count += 1; + } + previous = current; + } + + if clipped_count == 0 { + return 0.; + } + (corners, count) = (clipped, clipped_count); + } + + // The area of what's left, by the shoelace formula + let twice_area: f64 = (0..count).map(|index| corners[index].perp_dot(corners[(index + 1) % count])).sum(); + (twice_area.abs() / 2.).min(1.) + } +} + +/// The premultiplied pixel at a `point` in pixels interpolated as [`sample_bilinear`] does, with each of the four pixels weighted by the share of it within a frame (`area_within` by its corner, see [`pixel_area_within`]), so none the frame misses is read. +/// Where the frame covers none of them, the nearest it covers among the 16 around stands in, the first of those equally near. +pub(crate) fn sample_bilinear_within(plane: &Plane<[f32; 4]>, point: DVec2, area_within: impl Fn(DVec2) -> f64) -> [f32; 4] { + let position = point - 0.5; + let base = position.floor(); + let fraction = (position - base).as_vec2(); + + let (mut sum, mut total) = ([0.; 4], 0.); + for offset in [DVec2::ZERO, DVec2::X, DVec2::Y, DVec2::ONE] { + let weights = (1. - fraction) + (2. * fraction - 1.) * offset.as_vec2(); + let weight = weights.x * weights.y * area_within(base + offset) as f32; + if weight > 0. { + let color = pixel_or_transparent(plane, base + offset); + sum = std::array::from_fn(|channel| sum[channel] + color[channel] * weight); + total += weight; + } + } + if total > 0. { + return sum.map(|channel| channel / total); + } + + nearest_around(point, |pixel| area_within(pixel) > 0.).map_or([0.; 4], |pixel| pixel_or_transparent(plane, pixel)) +} + /// 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); @@ -719,6 +800,73 @@ mod tests { ] } + /// The share of the pixel with its corner at `pixel` within the `frame`, from the lengths of the frame's part of the rows across the pixel. + fn pixel_area_by_rows(frame: &EffectFrame, pixel: DVec2) -> f64 { + let (to_local, half) = (frame.pixels_to_local(), frame.size / 2.); + + // The length of the part of the row across the pixel where both of the frame's local axes lie within it, each moving by `slope` along the row + let row_length = |y: f64| { + let start = to_local.transform_point2(DVec2::new(pixel.x, y)); + let (mut first, mut last) = (0_f64, 1_f64); + for axis in 0..2 { + let slope = to_local.matrix2.row(axis).x; + if slope == 0. { + if start[axis].abs() > half[axis] { + return 0.; + } + continue; + } + + let [low, high] = [-half[axis], half[axis]].map(|bound| (bound - start[axis]) / slope); + first = first.max(low.min(high)); + last = last.min(low.max(high)); + } + (last - first).max(0.) + }; + + // The rows where that length changes its slope (or jumps, along a level side): through the frame's corners, and where its sides cross the pixel's left and right edges + let corners = [DVec2::new(-1., -1.), DVec2::new(1., -1.), DVec2::ONE, DVec2::new(-1., 1.)].map(|corner| frame.local_to_pixels().transform_point2(corner * half)); + let mut breaks = vec![pixel.y, pixel.y + 1.]; + for (index, &corner) in corners.iter().enumerate() { + let next = corners[(index + 1) % 4]; + breaks.push(corner.y); + if next.x != corner.x { + breaks.extend([pixel.x, pixel.x + 1.].map(|edge| corner.y + (next.y - corner.y) * (edge - corner.x) / (next.x - corner.x))); + } + } + breaks.retain(|y| (pixel.y..=pixel.y + 1.).contains(y)); + breaks.sort_by(f64::total_cmp); + + // Between them the length changes evenly, so its value midway through each span gives the span's area exactly + breaks.windows(2).map(|span| row_length((span[0] + span[1]) / 2.) * (span[1] - span[0])).sum() + } + + #[test] + fn the_share_of_each_pixel_within_slanted_and_turned_frames_is_its_area_within_them() { + use graphic_types::resampling::warp_frame; + + for transform in slanted_and_turned_squares() { + let frame = warp_frame(transform, glam::DAffine2::IDENTITY).unwrap(); + let (to_local, half, extent) = (frame.pixels_to_local(), frame.size / 2., frame.pixel_extent()); + let area_within = pixel_area_within(&frame); + + // The pixels near the frame's sides, among them all those its sides cut through + let pixels = (0..180).flat_map(|y| (0..180).map(move |x| DVec2::new(x as f64, y as f64))); + let near_sides = pixels.filter(|&pixel| { + let center = to_local.transform_point2(pixel + 0.5).abs(); + !(center + 2. * extent).cmple(half).all() && !(center - 2. * extent).cmpge(half).any() + }); + for pixel in near_sides { + let (area, expected) = (area_within(pixel), pixel_area_by_rows(&frame, pixel)); + assert!((area - expected).abs() < 1e-9, "{pixel} has {area} within {transform} rather than {expected}"); + } + } + + // The pixel just past the slanted square's left side, which its corner nearest the square misses by 0.03, has none within it + let frame = warp_frame(slanted_and_turned_squares()[0], glam::DAffine2::IDENTITY).unwrap(); + assert_eq!(pixel_area_within(&frame)(DVec2::new(69., 89.)), 0.); + } + #[test] fn polar_coordinates_read_nothing_wholly_past_a_slanted_square() { use graphic_types::EffectOperation; diff --git a/node-graph/libraries/raster-kernels/src/warp_kernels.rs b/node-graph/libraries/raster-kernels/src/warp_kernels.rs new file mode 100644 index 0000000000..0e2a48524c --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/warp_kernels.rs @@ -0,0 +1,684 @@ +//! The Warp on the CPU, drawing the triangles of its tessellated patch in the order the GPU's mesh pass does. + +use crate::effect_kernels::Plane; +use crate::resample_kernels::{pixel_area_within, sample_bilinear_within}; +use glam::DVec2; +use graphic_types::resampling::{EffectFrame, WarpFragment, WarpTessellation}; +use graphic_types::warp::WarpMesh; +use raster_types::parallel_rows::fill_rows; + +/// A triangle of the tessellation, as its corners in the texels and their parameters (s, t), wound clockwise on screen. +struct Triangle { + corners: [DVec2; 3], + parameters: [DVec2; 3], + /// Twice its area. + area: f64, + /// Whether the patch turns its sheet over here, as where it folds over itself. + reversed: bool, + /// The part of the warp it draws. + fragment: WarpFragment, +} + +impl Triangle { + /// The triangle drawing a `fragment` with these corners, wound clockwise on screen, or `None` if it covers no area. + /// It's reversed where its winding disagrees with the square's `orientation` (the sign of its placement's determinant), which is 0 for the fringe. + fn new(mut corners: [(DVec2, DVec2); 3], orientation: f64, fragment: WarpFragment) -> Option { + let area = |corners: &[(DVec2, DVec2); 3]| (corners[1].1 - corners[0].1).perp_dot(corners[2].1 - corners[0].1); + let reversed = area(&corners) * orientation < 0.; + if area(&corners) < 0. { + corners.swap(1, 2); + } + let area = area(&corners); + (area > 0. && area.is_finite()).then(|| Self { + corners: corners.map(|(_, texel)| texel), + parameters: corners.map(|(parameters, _)| parameters), + area, + reversed, + fragment, + }) + } + + /// The parameters (s, t) interpolated at a `point` in the texels, if the triangle covers it. + /// A point on an edge belongs to the triangle only along its top or left edges, so the triangles sharing it cover it once. + fn interpolated(&self, point: DVec2) -> Option { + let mut weights = [0.; 3]; + for edge in 0..3 { + let (start, end) = (self.corners[(edge + 1) % 3], self.corners[(edge + 2) % 3]); + + // Measured from the same end of the edge for both triangles sharing it, so roundoff can't leave a point on it outside both + let side = match (start.x, start.y) < (end.x, end.y) { + true => (end - start).perp_dot(point - start), + false => -(start - end).perp_dot(point - end), + }; + + // On screen, clockwise winding puts the top edge heading right and the left edges heading up + let top_or_left = (start.y == end.y && end.x > start.x) || end.y < start.y; + if side < 0. || (side == 0. && !top_or_left) { + return None; + } + weights[edge] = side / self.area; + } + Some(self.parameters[0] * weights[0] + self.parameters[1] * weights[1] + self.parameters[2] * weights[2]) + } +} + +/// A Warp of the `mesh` (as fractions of its square) prepared for planes of one size, matching the GPU's mesh pass, so several planes warp through it with the work shared. +/// The fringe past the square's sides and corners is drawn first, then each triangle of the tessellation paints over those before it the content within the square that its texels' polished sources read, +/// leaving clear all that the bent square doesn't cover. For PSD interop, where it folds, the sheet turned over shows on top, like a flap of paper folded toward the viewer, so its triangles are drawn after the rest. +pub struct WarpRasterizer { + square: EffectFrame, + tessellation: Option, + triangles: Vec>, + /// The triangles each row of pixel centers may cross, in the order they're drawn. + crossing: Vec>, + width: usize, +} + +impl WarpRasterizer { + /// The warp of the `mesh` within the `square` (see [`graphic_types::resampling::warp_frame`]) for planes `width` by `height`. O(triangles and the rows they cross). + pub fn new(mesh: &WarpMesh, square: &EffectFrame, width: usize, height: usize) -> Self { + let tessellation = WarpTessellation::new(mesh, square, DVec2::new(width as f64, height as f64)); + let mut triangles = Vec::new(); + let mut crossing: Vec> = vec![Vec::new(); height]; + + if let Some(tessellation) = &tessellation { + // The fringe's quads along the left, right, top, and bottom sides, then past the corners where both sides meet, each split into two triangles as the GPU draws them + let [columns, rows] = tessellation.cells; + let quad = |[first, second, third, fourth]: [(DVec2, DVec2); 4], fragment| [Triangle::new([first, second, third], 0., fragment), Triangle::new([first, third, fourth], 0., fragment)]; + for side in (0..4).filter(|&side| tessellation.sides[side]) { + let segments = if side < 2 { rows } else { columns }; + for along in 0..segments { + let corners = [(along, false), (along + 1, false), (along + 1, true), (along, true)].map(|(along, outer)| tessellation.fringe_vertex(side, along, outer)); + triangles.extend(quad(corners, WarpFragment::PastSide(side))); + } + } + for corner in (0..4).filter(|&corner| tessellation.sides[corner % 2] && tessellation.sides[2 + corner / 2]) { + let corners = [[false, false], [true, false], [true, true], [false, true]].map(|outer| tessellation.corner_vertex(corner, outer)); + triangles.extend(quad(corners, WarpFragment::PastCorner(corner))); + } + + // Each cell's two triangles, cell by cell across each row of cells and row by row down, as the GPU draws them + let vertices: Vec<(DVec2, DVec2)> = (0..=rows) + .flat_map(|row| (0..=columns).map(move |column| (column, row))) + .map(|index| tessellation.vertex(index.into())) + .collect(); + let corner = |column: u32, row: u32| vertices[(row * (columns + 1) + column) as usize]; + let orientation = tessellation.source.matrix2.determinant().signum(); + triangles.reserve(2 * (columns * rows) as usize); + for row in 0..rows { + for column in 0..columns { + let [top_left, top_right, bottom_left, bottom_right] = [corner(column, row), corner(column + 1, row), corner(column, row + 1), corner(column + 1, row + 1)]; + triangles.extend([ + Triangle::new([top_left, top_right, bottom_right], orientation, WarpFragment::Within), + Triangle::new([top_left, bottom_right, bottom_left], orientation, WarpFragment::Within), + ]); + } + } + + // Those turned over are drawn after the rest + let drawn = [false, true] + .into_iter() + .flat_map(|reversed| (triangles.iter().enumerate()).filter_map(move |(index, triangle)| Some((index, triangle.as_ref().filter(|triangle| triangle.reversed == reversed)?)))); + for (index, triangle) in drawn { + let (top, bottom) = triangle + .corners + .iter() + .fold((f64::INFINITY, f64::NEG_INFINITY), |(top, bottom), corner| (top.min(corner.y), bottom.max(corner.y))); + let first = (top - 0.5).ceil().max(0.); + let last = (bottom - 0.5).floor().min(height as f64 - 1.); + if first <= last { + (first as usize..=last as usize).for_each(|y| crossing[y].push(index as u32)); + } + } + } + + Self { + square: *square, + tessellation, + triangles, + crossing, + width, + } + } + + /// The `plane` (of the size the warp was prepared for) carried through the warp. O(width × height). + pub fn warped(&self, plane: &Plane<[f32; 4]>) -> Plane<[f32; 4]> { + if plane.width != self.width || plane.height != self.crossing.len() { + log::error!( + "A Warp prepared for {} by {} pixels was given a plane {} by {}", + self.width, + self.crossing.len(), + plane.width, + plane.height + ); + return plane.clone(); + } + + let mut result = Plane::<[f32; 4]>::new(plane.width, plane.height); + let Some(tessellation) = &self.tessellation else { return result }; + let area_within = pixel_area_within(&self.square); + + // The triangles paint over each other from clear + fill_rows(&mut result.data, plane.width, |y, row| { + let center_y = y as f64 + 0.5; + for triangle in self.crossing[y].iter().filter_map(|&index| self.triangles[index as usize].as_ref()) { + let (left, right) = triangle + .corners + .iter() + .fold((f64::INFINITY, f64::NEG_INFINITY), |(left, right), corner| (left.min(corner.x), right.max(corner.x))); + let first = (left - 0.5).ceil().max(0.); + let last = (right - 0.5).floor().min(plane.width as f64 - 1.); + if first > last { + continue; + } + + for (x, pixel) in row.iter_mut().enumerate().take(last as usize + 1).skip(first as usize) { + let target = DVec2::new(x as f64 + 0.5, center_y); + let Some(seed) = triangle.interpolated(target) else { continue }; + let parameters = match triangle.fragment { + WarpFragment::Within => tessellation.polished(seed, target), + _ => seed, + }; + + // The content within the square there, faded by how much of the pixel the warped square covers, painted over what earlier triangles left + let shade = tessellation.shade(triangle.fragment, parameters, target); + let coverage = shade.coverage as f32; + if coverage <= 0. { + continue; + } + let color = sample_bilinear_within(plane, tessellation.source.transform_point2(shade.read), &area_within); + let painted = color.map(|channel| channel * coverage); + *pixel = std::array::from_fn(|channel| painted[channel] + pixel[channel] * (1. - painted[3])); + } + } + }); + result + } +} + +#[cfg(test)] +mod tests { + use super::*; + use glam::{DAffine2, UVec2}; + use graphic_types::resampling::{warp_frame, warp_half_fade}; + use graphic_types::warp::{Warp, WarpStyle}; + + /// The plane carried through the Warp of the `mesh` (as fractions of the `square`). + fn warped_plane(plane: &Plane<[f32; 4]>, mesh: &WarpMesh, square: &EffectFrame) -> Plane<[f32; 4]> { + WarpRasterizer::new(mesh, square, plane.width, plane.height).warped(plane) + } + + /// A plane 60 by 40 of colors ramping across and down, with the warp's square its middle 40 by 20 pixels. + fn ramps() -> (Plane<[f32; 4]>, EffectFrame) { + let mut plane = Plane::<[f32; 4]>::new(60, 40); + plane.data = (0..60 * 40).map(|index| [(index % 60) as f32 / 60., (index / 60) as f32 / 40., 0.5, 1.]).collect(); + let square = warp_frame(DAffine2::from_translation(DVec2::new(30., 20.)) * DAffine2::from_scale(DVec2::new(40., 20.)), DAffine2::IDENTITY).unwrap(); + (plane, square) + } + + fn warp(style: WarpStyle, bend: f64) -> Warp { + Warp { + style, + bend, + horizontal_distortion: 0., + vertical_distortion: 0., + vertical: false, + } + } + + #[test] + fn a_warp_without_bend_leaves_every_pixel_within_its_square_as_it_is_and_clears_the_rest() { + let (plane, square) = ramps(); + let warped = warped_plane(&plane, &warp(WarpStyle::Twist, 0.).mesh(square.size), &square); + + // The square's sides run along the pixels' edges, so each pixel lies wholly within or past it + for (index, (warped, original)) in warped.data.iter().zip(&plane.data).enumerate() { + let within = (10..50).contains(&(index % 60)) && (10..30).contains(&(index / 60)); + let expected = if within { *original } else { [0.; 4] }; + let difference = warped.iter().zip(expected).map(|(a, b)| (a - b).abs()).fold(0., f32::max); + assert!(difference < 1e-4, "pixel {index} became {warped:?} rather than {expected:?}"); + } + } + + #[test] + fn each_pixel_shows_the_content_where_the_patch_carries_it_from() { + let (plane, square) = ramps(); + let mesh = warp(WarpStyle::Flag, 0.3).mesh(square.size); + let warped = warped_plane(&plane, &mesh, &square); + + // The ramps read back where each point of the square lands + for uv in [DVec2::new(0.2, 0.3), DVec2::new(0.5, 0.5), DVec2::new(0.85, 0.6)] { + let landed = square.to_pixels.transform_point2(mesh.point(uv)); + let pixel = landed.floor(); + let color = warped.data[pixel.y as usize * 60 + pixel.x as usize]; + + // The pixel's center reads from near the point, which the ramps show to within a pixel + let source = square.to_pixels.transform_point2(uv); + assert!((color[0] * 60. - source.x as f32).abs() < 1.5, "{uv} reads across from {}, not {}", color[0] * 60., source.x); + assert!((color[1] * 40. - source.y as f32).abs() < 1.5, "{uv} reads down from {}, not {}", color[1] * 40., source.y); + } + } + + #[test] + fn what_lies_outside_the_square_and_what_the_bend_leaves_of_it_clear() { + // A flag only raises and lowers the square's content, lowering its top edge on the left and raising it on the right + let (plane, square) = ramps(); + let mesh = warp(WarpStyle::Flag, 0.2).mesh(square.size); + let warped = warped_plane(&plane, &mesh, &square); + + // Beside the square, and above it where the flag lowers its top edge, all is clear + for (x, y) in [(55, 20), (3, 35), (20, 3)] { + assert_eq!(warped.data[y * 60 + x], [0.; 4], "({x}, {y}) isn't clear"); + } + + // Where it lowers the top edge, what it leaves of the square is clear, and where it raises it, the square's top row shows above the square + assert!(warped.data[10 * 60 + 20][3] < 1e-3, "the square's top left shows {:?}", warped.data[10 * 60 + 20]); + let raised = warped.data[8 * 60 + 40]; + assert!((raised[1] * 40. - 10.5).abs() < 1.5 && raised[3] > 0.99, "above the square's top right shows {raised:?}"); + } + + /// Whether the patch of the `mesh` turns over anywhere within its unit square, so parts of it overlap, by the sign of its Jacobian across a dense grid. + fn folds(mesh: &WarpMesh) -> bool { + (0..65 * 65).any(|index| { + let [_, along_u, along_v] = mesh.point_and_tangents(DVec2::new((index % 65) as f64, (index / 65) as f64) / 64.); + along_u.perp_dot(along_v) <= 1e-9 + }) + } + + /// How many points of the unit square the patch of `mesh` (in pixels) carries onto `point`, found by splitting the square until its parts are small, then polishing each part's middle onto it. + /// A part whose polish settles outside it, or nowhere, splits further, as beside a fold's crease, and the points found from several parts count once. + fn preimages(mesh: &WarpMesh, point: DVec2) -> usize { + let mut found: Vec = Vec::new(); + let mut parts = vec![(DVec2::ZERO, DVec2::ONE)]; + while let Some((start, end)) = parts.pop() { + let [min, max] = mesh.over(start, end).hull_bounds(); + if point.cmplt(min).any() || point.cmpgt(max).any() { + continue; + } + let middle = (start + end) / 2.; + let split = [ + (start, middle), + (DVec2::new(middle.x, start.y), DVec2::new(end.x, middle.y)), + (DVec2::new(start.x, middle.y), DVec2::new(middle.x, end.y)), + (middle, end), + ]; + let size = (end - start).max_element(); + if size > 1. / 64. { + parts.extend(split); + continue; + } + + let mut uv = middle; + for _ in 0..16 { + let [landed, along_u, along_v] = mesh.point_and_tangents(uv); + let (residual, determinant) = (landed - point, along_u.perp_dot(along_v)); + if determinant.abs() < 1e-12 { + break; + } + uv -= DVec2::new(residual.perp_dot(along_v), along_u.perp_dot(residual)) / determinant; + } + + let settled = (mesh.point(uv) - point).length() < 1e-6; + if settled && uv.cmpge(DVec2::ZERO).all() && uv.cmple(DVec2::ONE).all() && found.iter().all(|other| other.distance(uv) > 1e-7) { + found.push(uv); + } + let within_part = uv.cmpge(start - 1e-9).all() && uv.cmple(end + 1e-9).all(); + if !(settled && within_part) && size > 1. / 4096. { + parts.extend(split); + } + } + found.len() + } + + /// How many layers of content show at each of 8 by 8 samples across `pixel` (its corner) after the Warp of the `mesh` (as fractions of the `square`): + /// one for each point of the square the patch carries onto it. + fn supersampled_layers(mesh: &WarpMesh, square: &EffectFrame, pixel: DVec2) -> [usize; 64] { + let in_pixels = mesh.transformed(square.to_pixels); + std::array::from_fn(|index| preimages(&in_pixels, pixel + (DVec2::new((index % 8) as f64, (index / 8) as f64) + 0.5) / 8.)) + } + + /// How much of the pixel with its corner at `pixel` the `square` itself covers, fading across its sides as a side the warp keeps in place does. + fn square_coverage(square: &EffectFrame, pixel: DVec2) -> f32 { + let (local, half, half_fade) = (square.pixels_to_local().transform_point2(pixel + 0.5), square.size / 2., warp_half_fade(square)); + (0.5 + (half - local.abs()) / (2. * half_fade)).clamp(DVec2::ZERO, DVec2::ONE).element_product() as f32 + } + + #[test] + fn sides_a_bend_keeps_in_place_match_the_content_at_any_squeeze_and_offset() { + use WarpStyle::*; + + // Content of one color reaching past a square 39 by 19 at quarter-pixel offsets and scaled between pixels (its corners on the reference's samples), and past squares slanted and turned off the grid, + // which fisheyes, waves, and twists bend across their range while keeping all four sides in place + let bends = (-25..=25) + .map(|step| step as f64 * 0.04) + .chain([0.58, 0.59, 0.6, 0.61, 0.66, 0.67, 0.68, 0.75, 0.76, 0.77, -0.59, -0.6, -0.76]); + let placements = [ + DAffine2::from_cols_array(&[39., 0., 0., 19., 30., 20.]), + DAffine2::from_cols_array(&[39., 0., 0., 19., 30.25, 20.5]), + DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]), + DAffine2::from_cols_array(&[39., 0., 0., 19., 30.75, 20.75]), + DAffine2::from_cols_array(&[42.5, 0., 0., 20.75, 30.25, 20.375]), + DAffine2::from_cols_array(&[24., 0., 16., 14., 30.3, 20.6]), + DAffine2::from_translation(DVec2::new(30.4, 20.15)) * DAffine2::from_angle(0.5) * DAffine2::from_scale(DVec2::new(30., 14.)), + ]; + for (style, bend, placement) in [Fisheye, Wave, Twist] + .into_iter() + .flat_map(|style| bends.clone().flat_map(move |bend| placements.map(|placement| (style, bend, placement)))) + { + let square = warp_frame(placement, DAffine2::IDENTITY).unwrap(); + let mesh = warp(style, bend).mesh(square.size); + let folding = folds(&mesh); + let offset = placement.translation; + + // The 3 by 3 pixels around each corner of an upright square, where its coverage is its area, with the layers a supersampled reference counts across them. + // A slanted square's edge fades by its coverage along its axes instead, as the square's own edge does, which the check of every pixel below holds it to. + let upright = placement.matrix2.x_axis.y == 0. && placement.matrix2.y_axis.x == 0.; + let corners = [DVec2::splat(-0.5), DVec2::new(0.5, -0.5), DVec2::new(-0.5, 0.5), DVec2::splat(0.5)].map(|corner| placement.transform_point2(corner)); + let around_corners: Vec<(DVec2, [usize; 64])> = corners + .into_iter() + .filter(|_| upright) + .flat_map(|corner| (0..9).map(move |index| (corner - 1.5).floor() + DVec2::new((index % 3) as f64, (index / 3) as f64))) + .map(|pixel| (pixel, supersampled_layers(&mesh, &square, pixel))) + .collect(); + + for alpha in [1., 0.5] { + let plane = Plane { + data: vec![[alpha; 4]; 60 * 40], + ..Plane::<[f32; 4]>::new(60, 40) + }; + let warped = warped_plane(&plane, &mesh, &square); + + // Where the patch doesn't fold, it shows the content within the square, clear past it, and the content faded by the square's coverage across its sides. + // Where it folds, the layers of opaque content cover at least that much. + for (index, pixel) in warped.data.iter().enumerate() { + let expected = alpha * square_coverage(&square, DVec2::new((index % 60) as f64, (index / 60) as f64)); + let error = pixel.iter().map(|channel| (channel - expected).abs()).fold(0., f32::max); + let (x, y) = (index % 60, index / 60); + if !folding { + assert!( + error < 1e-4, + "{style:?} at {bend} placed at {offset}, alpha {alpha}, shows {pixel:?} rather than {expected} at ({x}, {y})" + ); + } else if alpha == 1. { + assert!(pixel[3] > expected - 1e-4, "{style:?} at {bend} placed at {offset} shows {pixel:?}, short of {expected} at ({x}, {y})"); + } + } + + // Around each corner, it matches the reference + for (pixel, layers) in &around_corners { + let reference = layers.iter().map(|&layers| 1. - (1. - alpha).powi(layers as i32)).sum::() / 64.; + let shown = warped.data[pixel.y as usize * 60 + pixel.x as usize][3]; + assert!( + (shown - reference).abs() < 1e-3, + "{style:?} at {bend} placed at {offset}, alpha {alpha}, shows {shown} at {pixel} rather than {reference}" + ); + } + } + } + } + + #[test] + fn strongly_bent_styles_keep_opaque_content_opaque_within_their_patch_at_any_scale() { + use WarpStyle::*; + + // Opaque content past squares 120 by 90 at non-integer scales, which fish (whose sides curve back near each other) and other styles bend far, both ways and turned, and fish within smaller squares + let styles = [Fish, Arch, Bulge, Flag, Wave, Fisheye, Squeeze, Twist]; + let cases = |styles: Vec, square: DVec2| { + styles.into_iter().flat_map(move |style| { + [-1., -0.6, 0.6, 1.].into_iter().flat_map(move |bend| { + [false, true] + .into_iter() + .flat_map(move |vertical| [0.91, 1.09, 1.37].map(move |scale| (style, bend, vertical, square * scale))) + }) + }) + }; + for (style, bend, vertical, size) in cases(styles.to_vec(), DVec2::new(120., 90.)).chain(cases(vec![Fish], DVec2::new(60., 40.))) { + let (width, height) = ((size.x * 3.) as usize, (size.y * 3.) as usize); + let plane = Plane { + data: vec![[1.; 4]; width * height], + ..Plane::<[f32; 4]>::new(width, height) + }; + let center = DVec2::new(width as f64, height as f64) / 2. + DVec2::new(0.3, 0.2); + let square = warp_frame(DAffine2::from_translation(center) * DAffine2::from_scale(size), DAffine2::IDENTITY).unwrap(); + let mesh = Warp { vertical, ..warp(style, bend) }.mesh(square.size); + let warped = warped_plane(&plane, &mesh, &square); + + // Each pixel the patch carries a point of the square onto, which lies at least a pixel within the patch and two from the curves its sides bend into, is opaque + let in_pixels = mesh.transformed(square.to_pixels); + let sides: Vec = (0..=400) + .flat_map(|index| { + let t = index as f64 / 400.; + [DVec2::new(0., t), DVec2::new(1., t), DVec2::new(t, 0.), DVec2::new(t, 1.)] + }) + .map(|uv| in_pixels.point(uv)) + .collect(); + for index in 0..101 * 101 { + let uv = DVec2::new((index % 101) as f64, (index / 101) as f64) / 100.; + let pixel = in_pixels.point(uv).floor(); + let within_plane = pixel.cmpge(DVec2::ZERO).all() && pixel.x < width as f64 && pixel.y < height as f64; + if !within_plane || sides.iter().any(|side| side.distance(pixel + 0.5) < 2.) { + continue; + } + + let alpha = warped.data[pixel.y as usize * width + pixel.x as usize][3]; + let within_patch = || { + [DVec2::ZERO, DVec2::X, -DVec2::X, DVec2::Y, -DVec2::Y] + .iter() + .all(|&offset| preimages(&in_pixels, pixel + 0.5 + offset) > 0) + }; + assert!( + alpha > 0.99 || !within_patch(), + "{style:?} at {bend}, vertical {vertical}, within a square {size}, shows {alpha} at {pixel} from {uv}" + ); + } + } + } + + #[test] + fn sides_curving_sharply_toward_a_pixel_fade_it() { + // Opaque content past a square 10 by 200 that a flag waves far, so its top side's crest curves tightly past the pixel (28, 87), a third of a pixel within it + let plane = Plane { + data: vec![[1.; 4]; 80 * 500], + ..Plane::<[f32; 4]>::new(80, 500) + }; + let square = warp_frame(DAffine2::from_cols_array(&[10., 0., 0., 200., 25.625, 300.75]), DAffine2::IDENTITY).unwrap(); + let warped = warped_plane(&plane, &warp(WarpStyle::Flag, 1.).mesh(square.size), &square); + + // It fades by the third of a pixel, as two thirds past the pixel's middle, though the curve's tangent where the pixel's source lies passes two pixels away + let alpha = warped.data[87 * 80 + 28][3]; + assert!((alpha - 0.83).abs() < 0.02, "the pixel shows alpha {alpha}"); + } + + #[test] + fn fisheyes_squeezing_the_content_nearly_flat_against_a_side_keep_it_seamless() { + // Opaque content past a square with its top side three quarters of the way down a row of pixels, against which fisheyes squeeze the content nearly flat + for bend in [0.59, 0.6] { + let plane = Plane { + data: vec![[1.; 4]; 60 * 40], + ..Plane::<[f32; 4]>::new(60, 40) + }; + let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]), DAffine2::IDENTITY).unwrap(); + let warped = warped_plane(&plane, &warp(WarpStyle::Fisheye, bend).mesh(square.size), &square); + for (index, pixel) in warped.data.iter().enumerate() { + let expected = square_coverage(&square, DVec2::new((index % 60) as f64, (index / 60) as f64)); + assert!( + (pixel[3] - expected).abs() < 1e-4, + "bent {bend}, ({}, {}) shows {pixel:?} rather than {expected}", + index % 60, + index / 60 + ); + } + } + } + + #[test] + fn slanted_squares_keep_the_content_as_it_is_past_corners_they_keep_in_place() { + // Opaque content past a square slanted to corners an eighth of a turn sharp, off the pixel grid, within which a fisheye keeps the sides in place + let plane = Plane { + data: vec![[1.; 4]; 120 * 80], + ..Plane::<[f32; 4]>::new(120, 80) + }; + let square = warp_frame(DAffine2::from_cols_array(&[40., 0., 40., 40., 61., 40.75]), DAffine2::IDENTITY).unwrap(); + let warped = warped_plane(&plane, &warp(WarpStyle::Fisheye, 0.4).mesh(square.size), &square); + for (index, pixel) in warped.data.iter().enumerate() { + let expected = square_coverage(&square, DVec2::new((index % 120) as f64, (index / 120) as f64)); + assert!((pixel[3] - expected).abs() < 1e-4, "({}, {}) shows {pixel:?} rather than {expected}", index % 120, index / 120); + } + } + + #[test] + fn folds_returning_over_a_side_change_smoothly_as_the_side_moves() { + // Clear rows down through the one a square's top side runs through the middle of, and opaque rows below, which a fisheye folds out over the clear rows and back + let alpha_at = |down: f64| { + let mut plane = Plane::<[f32; 4]>::new(60, 40); + plane.data[11 * 60..].fill([1.; 4]); + let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, down]), DAffine2::IDENTITY).unwrap(); + warped_plane(&plane, &warp(WarpStyle::Fisheye, 1.).mesh(square.size), &square).data[10 * 60 + 30][3] + }; + + // Moving the side a fiftieth of a pixel across the pixel's center moves its fade only as far + let (above, below) = (alpha_at(19.99), alpha_at(20.01)); + assert!((above - below).abs() < 0.03, "the pixel's alpha jumps from {above} to {below}"); + } + + #[test] + fn folds_out_past_a_side_clear_what_lies_outside_the_square_beneath_them() { + // Opaque rows down to just above a square's top side, and clear rows below, which a fisheye folds out over the rows above + let mut plane = Plane::<[f32; 4]>::new(60, 40); + plane.data[..10 * 60].fill([1.; 4]); + let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.]), DAffine2::IDENTITY).unwrap(); + let warped = warped_plane(&plane, &warp(WarpStyle::Fisheye, 1.).mesh(square.size), &square); + + // The fold carries only the square's clear content, and the rows above clear + for (index, pixel) in warped.data.iter().enumerate() { + assert!(pixel[3] < 1e-4, "({}, {}) shows {pixel:?}", index % 60, index / 60); + } + } + + #[test] + fn content_well_outside_the_bent_square_clears() { + // Opaque content 80 by 60 pixels, within which a flag bends a square 30 by 20 at its middle + let plane = Plane { + data: vec![[1.; 4]; 80 * 60], + ..Plane::<[f32; 4]>::new(80, 60) + }; + let square = warp_frame(DAffine2::from_cols_array(&[30., 0., 0., 20., 40., 30.]), DAffine2::IDENTITY).unwrap(); + let mesh = warp(WarpStyle::Flag, 0.4).mesh(square.size); + let warped = warped_plane(&plane, &mesh, &square); + + // The pixels within two and a half of where the patch carries the square, past which its edge's fade and its fringe's miters reach nothing + let in_pixels = mesh.transformed(square.to_pixels); + let mut near = vec![false; 80 * 60]; + for index in 0..201 * 201 { + let point = in_pixels.point(DVec2::new((index % 201) as f64, (index / 201) as f64) / 200.); + for (x, y) in (-3..=3).flat_map(|y| (-3..=3).map(move |x| (x, y))) { + let pixel = (point - 0.5).round() + DVec2::new(x as f64, y as f64); + if (pixel + 0.5).distance(point) <= 2.5 && pixel.cmpge(DVec2::ZERO).all() && pixel.x < 80. && pixel.y < 60. { + near[pixel.y as usize * 80 + pixel.x as usize] = true; + } + } + } + + // All else is clear, though the content was opaque there + let far: Vec = (0..80 * 60).filter(|&index| !near[index]).collect(); + assert!(far.len() > 2000, "only {} pixels lie far from the patch", far.len()); + for index in far { + assert_eq!(warped.data[index], [0.; 4], "({}, {}) shows {:?}", index % 80, index / 80, warped.data[index]); + } + } + + #[test] + fn nothing_wholly_outside_a_slanted_or_turned_square_is_carried_through_it() { + // Clear content but for an opaque pixel just above the top side of a slanted square, which an upper arc raises past where the pixel lies, + // or just above the top corner of a square turned an eighth, which an arc bends far around + let cases = [ + (UVec2::new(80, 40), UVec2::new(30, 9), WarpStyle::ArcUpper, 0.5, [40., 0., 40., 4., 50., 12.]), + (UVec2::new(80, 60), UVec2::new(40, 9), WarpStyle::Arc, 0.8, [20., 20., -20., 20., 40.5, 30.01]), + ]; + for (size, opaque, style, bend, transform) in cases { + let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize); + plane.data[(opaque.y * size.x + opaque.x) as usize] = [1.; 4]; + let square = warp_frame(DAffine2::from_cols_array(&transform), DAffine2::IDENTITY).unwrap(); + let warped = warped_plane(&plane, &warp(style, bend).mesh(square.size), &square); + + // The patch carries none of the pixel anywhere, and the pixel clears where it lies + for (index, pixel) in warped.data.iter().enumerate() { + assert!(pixel[3] < 1e-3, "{style:?} shows {pixel:?} at ({}, {})", index % plane.width, index / plane.width); + } + } + } + + #[test] + fn squares_far_smaller_than_a_pixel_paint_nothing_past_the_content() { + // Opaque content 25 pixels across at a hundredth of a pixel per unit, twisted within a square one unit across at its middle, which its reach keeps within the content + let mut plane = Plane::<[f32; 4]>::new(64, 64); + for y in 0..25 { + plane.data[y * 64..y * 64 + 25].fill([1.; 4]); + } + let square = warp_frame(DAffine2::from_translation(DVec2::splat(1275.)), DAffine2::from_scale(DVec2::splat(0.01))).unwrap(); + let warped = warped_plane(&plane, &warp(WarpStyle::Twist, 0.8).mesh(square.size), &square); + + for (index, pixel) in warped.data.iter().enumerate() { + let (x, y) = (index % 64, index / 64); + assert!((x < 25 && y < 25) || pixel[3] < 1e-3, "({x}, {y}) past the content shows {pixel:?}"); + } + } + + #[test] + fn folds_show_the_sheet_turned_over_on_top() { + // Columns that double back across the middle, so it's covered by the left and right of the content and by the sheet between them turned over + let (plane, square) = ramps(); + let mesh = WarpMesh(std::array::from_fn(|row| [0., 1.5, -0.5, 1.].map(|x| DVec2::new(x, row as f64 / 3.)))); + let warped = warped_plane(&plane, &mesh, &square); + + // For PSD interop, the middle shows the turned sheet, which reads near the content's middle rather than a quarter in from either side + let red = warped.data[20 * 60 + 30][0]; + assert!((red - 0.49).abs() < 0.03, "the middle shows red {red}"); + assert!(warped.data[20 * 60 + 30][3] > 0.999); + } + + #[test] + fn mirrored_squares_fold_as_the_mirror_of_upright_ones() { + // The fold above in the square and content mirrored left to right, where the turned sheet winds the other way on screen + let (plane, square) = ramps(); + let mesh = WarpMesh(std::array::from_fn(|row| [0., 1.5, -0.5, 1.].map(|x| DVec2::new(x, row as f64 / 3.)))); + let mirror = |index: usize| index - index % 60 + 59 - index % 60; + let mirrored_plane = Plane { + data: (0..60 * 40).map(|index| plane.data[mirror(index)]).collect(), + ..plane.clone() + }; + let mirrored_square = square.placed(DAffine2::from_translation(DVec2::new(60., 0.)) * DAffine2::from_scale(DVec2::new(-1., 1.))); + + let upright = warped_plane(&plane, &mesh, &square); + let mirrored = warped_plane(&mirrored_plane, &mesh, &mirrored_square); + for (index, color) in upright.data.iter().enumerate() { + let difference = color.iter().zip(mirrored.data[mirror(index)]).map(|(a, b)| (a - b).abs()).fold(0., f32::max); + assert!(difference < 1e-3, "pixel {index} shows {color:?} upright but {:?} mirrored", mirrored.data[mirror(index)]); + } + } + + #[test] + fn every_style_at_its_extremes_paints_colors_within_range() { + use WarpStyle::*; + let (plane, square) = ramps(); + + for style in [Arc, ArcLower, ArcUpper, Arch, Bulge, ShellLower, ShellUpper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist] { + for (bend, horizontal_distortion, vertical_distortion) in [(1., 0., 0.), (-1., 0., 0.), (1., 1., 1.), (-1., -1., 1.), (1., -1., -1.), (0., 1., -1.)] { + for vertical in [false, true] { + let warp = Warp { + style, + bend, + horizontal_distortion, + vertical_distortion, + vertical, + }; + let warped = warped_plane(&plane, &warp.mesh(square.size), &square); + + // Premultiplied, each color lies within its alpha, which lies within 0 to 1 + let within = |pixel: &[f32; 4]| pixel.iter().all(|channel| channel.is_finite() && (0.0..=pixel[3] + 1e-4).contains(channel)) && pixel[3] <= 1. + 1e-4; + assert!(warped.data.iter().all(within), "{warp:?} paints colors out of range"); + } + } + } + } +} diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index 2d8ff9c8b4..11d357c364 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::{EffectFrame, FrameWarp, frame_of_bounds}; +use graphic_types::resampling::{EffectFrame, 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; @@ -1127,6 +1127,7 @@ fn svg_expresses(operation: &EffectOperation) -> bool { | EffectOperation::Pinch { .. } | EffectOperation::Spherize { .. } | EffectOperation::PolarCoordinates { .. } + | EffectOperation::Warp { .. } | EffectOperation::Ripple { .. } | EffectOperation::Wave { .. } | EffectOperation::Displace { .. } => false, @@ -1874,6 +1875,7 @@ fn write_svg_effects_filter_on_lattice( | EffectOperation::Pinch { .. } | EffectOperation::Spherize { .. } | EffectOperation::PolarCoordinates { .. } + | EffectOperation::Warp { .. } | EffectOperation::Ripple { .. } | EffectOperation::Wave { .. } | EffectOperation::Displace { .. } => continue, @@ -5199,7 +5201,7 @@ fn changes_endless_content_in_view(effects: &Effects) -> bool { /// 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()) + effects.operations().any(|operation| operation.is_warp() && !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. @@ -7190,6 +7192,113 @@ mod tests { assert_eq!(region_sizes.0.len(), 1, "the line is culled"); } + /// Records where in the document each effects group's region a Vello scene renders begins, drawing nothing. + /// Its far corner isn't recorded, since a region's texture rounds its size up. + struct RegionOrigins(Vec); + + impl crate::vello_scene_builder::EffectsRenderer for RegionOrigins { + fn renders_effects(&self) -> bool { + true + } + + fn render_effects( + &mut self, + _: glam::UVec2, + view: kurbo::Affine, + _: &Effects, + _: &EffectLayers, + _: f32, + _: f32, + _: DAffine2, + _: Option, + _: Option, + _: &mut dyn FnMut(usize, &mut VelloSceneBuilder), + _: &mut dyn FnMut(&mut VelloSceneBuilder), + ) -> Vec<(wgpu::Texture, BlendMode)> { + let origin = view.inverse() * kurbo::Point::ZERO; + self.0.push(DVec2::new(origin.x, origin.y)); + Vec::new() + } + } + + #[test] + fn vello_regions_of_warped_groups_hold_what_their_children_paint_past_them() { + use graphic_types::WarpStyle; + use kurbo::Shape; + + // A group bent within a square on the rectangle it holds, whose shadow paints past the rectangle and outside the square, where it stays + let size = DVec2::new(400., 200.); + let shadow = drop_shadow(0., 0., 20.); + let mut rectangle = Vector::item_from_bezpath(&kurbo::Rect::new(0., 0., size.x, size.y).to_path(0.1)); + rectangle.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE)))); + rectangle.set_attribute(ATTR_EFFECTS, Effects::from_operations([shadow.clone()])); + let placement = DAffine2::from_translation(DVec2::splat(300.)); + + for style in [WarpStyle::Flag, WarpStyle::Arc, WarpStyle::Twist] { + let warp = warp_effect(style, 50., square_on(DAffine2::from_scale(size))); + let mut group = Item::new_from_element(Graphic::VectorList(List::new_from_item(rectangle.clone()))); + group.set_attribute(ATTR_TRANSFORM, placement); + group.set_attribute(ATTR_EFFECTS, Effects::from_operations([warp.clone()])); + + let mut region_origins = RegionOrigins(Vec::new()); + let mut scene = VelloSceneBuilder::new(1200, 1000, kurbo::Affine::IDENTITY, 4096).with_effects_renderer(&mut region_origins); + List::new_from_item(group).render_to_vello(&mut scene, DAffine2::IDENTITY, &RenderParams::default()); + drop(scene); + + let [origin] = region_origins.0[..] else { + panic!("expected the group's region, got {:?}", region_origins.0) + }; + let [patch_min, _] = warp_patch_box(&warp, placement, |_| true); + let shadow_min = placement.translation - shadow.reach(); + assert!( + origin.cmple(patch_min).all() && origin.cmple(shadow_min).all(), + "{style:?} bends to {patch_min} and the shadow reaches {shadow_min}, past the region from {origin}" + ); + } + } + + #[test] + fn vello_keeps_a_vector_with_a_warp_reaching_into_a_tilted_canvas() { + use graphic_types::WarpStyle; + use kurbo::Shape; + + // A rise with both distortions within a square on the rectangle, which reaches past a corner of the square on both sides there, which a tilted canvas turns off the view's axes + let size = DVec2::new(200., 100.); + let warp = graphic_types::EffectOperation::Warp { + style: WarpStyle::Rise, + bend: -50., + horizontal_distortion: 50., + vertical_distortion: 50., + vertical: false, + transform: square_on(DAffine2::from_scale(size)), + }; + let mut rectangle = Vector::item_from_bezpath(&kurbo::Rect::new(0., 0., size.x, size.y).to_path(0.1)); + rectangle.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE)))); + rectangle.set_attribute(ATTR_EFFECTS, Effects::from_operations([warp.clone()])); + + let extent = 1000.; + for degrees in [30_f64, -30., 45., 135.] { + let turn = DAffine2::from_angle(degrees.to_radians()); + let [min, max] = warp_patch_box(&warp, turn, |_| true); + let middle = (min + max) / 2.; + + // The bent square reaching 6 pixels into the view past each of its edges, so it's drawn through its effects group rather than culled + for shift in [ + DVec2::new(6. - max.x, extent / 2. - middle.y), + DVec2::new(extent / 2. - middle.x, 6. - max.y), + DVec2::new(extent - 6. - min.x, extent / 2. - middle.y), + DVec2::new(extent / 2. - middle.x, extent - 6. - min.y), + ] { + let view = kurbo::Affine::new((DAffine2::from_translation(shift) * turn).to_cols_array()); + let mut region_origins = RegionOrigins(Vec::new()); + let mut scene = VelloSceneBuilder::new(extent as u16, extent as u16, view, 4096).with_effects_renderer(&mut region_origins); + List::new_from_item(rectangle.clone()).render_to_vello(&mut scene, DAffine2::IDENTITY, &RenderParams::default()); + drop(scene); + assert_eq!(region_origins.0.len(), 1, "tilted {degrees} degrees and shifted by {shift}, the rectangle is culled"); + } + } + } + #[test] fn vello_finds_the_frame_of_content_only_for_effects_that_take_it() { /// Records whether each effects group a Vello scene renders comes with its content's frame, drawing nothing. @@ -7970,6 +8079,235 @@ mod tests { ); } + fn warp_effect(style: graphic_types::WarpStyle, bend: f64, transform: DAffine2) -> graphic_types::EffectOperation { + graphic_types::EffectOperation::Warp { + style, + bend, + horizontal_distortion: 0., + vertical_distortion: 0., + vertical: false, + transform, + } + } + + /// The transform placing a Warp's square on the unit square that `placement` places, as on the frame of content it places. + fn square_on(placement: DAffine2) -> DAffine2 { + placement * DAffine2::from_translation(DVec2::splat(0.5)) + } + + /// The box of where the Warp `effect` bends the points (u, v) of its square that `within` takes, sampled densely, in a space that `space` maps its effect space into. + fn warp_patch_box(effect: &graphic_types::EffectOperation, space: DAffine2, within: impl Fn(DVec2) -> bool) -> [DVec2; 2] { + let (warp, transform) = graphic_types::resampling::warp_of(effect).unwrap(); + let placement = transform * DAffine2::from_translation(DVec2::splat(-0.5)); + let mesh = warp.mesh(DVec2::new(placement.matrix2.x_axis.length(), placement.matrix2.y_axis.length())); + (0..201 * 201) + .map(|index| DVec2::new((index % 201) as f64, (index / 201) as f64) / 200.) + .filter(|&uv| within(uv)) + .map(|uv| (space * placement).transform_point2(mesh.point(uv))) + .fold([DVec2::INFINITY, DVec2::NEG_INFINITY], |[min, max], point| [min.min(point), max.max(point)]) + } + + /// The bounds of the images deferred to the GPU when `list` renders to SVG, in the user spaces their markup is drawn in. + fn deferred_image_bounds(list: List) -> Vec<[DVec2; 2]> { + let mut render = SvgRender::new(); + let render_params = RenderParams { + for_export: true, + ..Default::default() + }; + list.render_svg(&mut render, &render_params); + render.deferred_images.iter().map(|deferred| deferred.bounds).collect() + } + + #[test] + fn deferred_images_of_warped_groups_hold_what_their_children_paint_past_them() { + use graphic_types::raster_types::Image; + use graphic_types::{Effect, EffectOperation, WarpStyle, stamp_effect}; + + // A group bent within a square on the image it holds, which a blur spreads past its edges and the square, where it stays + let size = DVec2::new(400., 200.); + let blur = EffectOperation::Blur { + radius_mask: Default::default(), + radius: 5., + box_blur: false, + gamma: false, + }; + let nested = Effects::from_operations([blur.clone()]).reach_around(DAffine2::IDENTITY, [DVec2::ZERO, size], 0.).max_element(); + for style in [WarpStyle::Flag, WarpStyle::Arc, WarpStyle::Rise, WarpStyle::Twist] { + let warp = warp_effect(style, 50., square_on(DAffine2::from_scale(size))); + let mut image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size)); + stamp_effect(&mut image, Effect::new(&blur)); + let mut group = Item::new_from_element(Graphic::RasterCPU(Box::new(image))); + stamp_effect(&mut group, Effect::new(&warp)); + + let [bounds] = deferred_image_bounds(List::new_from_item(group))[..] else { + panic!("expected one deferred image") + }; + let [patch_min, patch_max] = warp_patch_box(&warp, DAffine2::IDENTITY, |_| true); + let [painted_min, painted_max] = [patch_min.min(DVec2::splat(-nested)), patch_max.max(size + nested)]; + assert!( + bounds[0].cmple(painted_min).all() && bounds[1].cmpge(painted_max).all(), + "{style:?} paints from {painted_min} to {painted_max}, past the image's {bounds:?}" + ); + } + } + + #[test] + fn deferred_images_of_warped_items_in_turned_groups_hold_their_whole_bend() { + use graphic_types::raster_types::Image; + use graphic_types::{Effect, WarpStyle, stamp_effect}; + + // An image bent within a square on it inside a group turned by the angle, with its markup drawn upright in the group's space + for (style, size) in [ + (WarpStyle::Arc, DVec2::new(400., 200.)), + (WarpStyle::ArcUpper, DVec2::new(400., 100.)), + (WarpStyle::Rise, DVec2::new(400., 200.)), + ] { + for degrees in [0_f64, 30., 45., 90.] { + let warp = warp_effect(style, 50., square_on(DAffine2::from_scale(size))); + let mut image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size)); + stamp_effect(&mut image, Effect::new(&warp)); + let group = Item::new_from_element(Graphic::RasterCPU(Box::new(image))).with_attribute(ATTR_TRANSFORM, DAffine2::from_angle(degrees.to_radians())); + + let [bounds] = deferred_image_bounds(List::new_from_item(group))[..] else { + panic!("expected one deferred image") + }; + let patch = warp_patch_box(&warp, DAffine2::IDENTITY, |_| true); + assert!( + bounds[0].cmple(patch[0]).all() && bounds[1].cmpge(patch[1]).all(), + "{style:?} turned {degrees} degrees bends to {patch:?}, past the image's {bounds:?}" + ); + } + } + } + + #[test] + fn layers_grow_by_how_far_their_turned_leaves_bend() { + use graphic_types::raster_types::Image; + use graphic_types::{Effect, WarpStyle, stamp_effect}; + + // A layer holding an image turned by the angle, bent within a square on it, which turns with it in the effect space + let cases = [ + (WarpStyle::Rise, DVec2::new(100., 400.)), + (WarpStyle::Arc, DVec2::new(100., 400.)), + (WarpStyle::Flag, DVec2::new(100., 400.)), + (WarpStyle::ArcUpper, DVec2::new(400., 100.)), + ]; + for (style, size) in cases { + for degrees in [0_f64, 30., 90., 180.] { + let placement = DAffine2::from_angle(degrees.to_radians()) * DAffine2::from_scale(size); + let warp = warp_effect(style, 50., square_on(placement)); + let mut image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, placement); + stamp_effect(&mut image, Effect::new(&warp)); + let layer = Item::new_from_element(Graphic::RasterCPU(Box::new(image))); + + let RenderBoundingBox::Rectangle(bounds) = graphic_list_painted_bounds(&List::new_from_item(layer), true) else { + panic!("expected bounds") + }; + let patch = warp_patch_box(&warp, DAffine2::IDENTITY, |_| true); + assert!( + bounds[0].cmple(patch[0]).all() && bounds[1].cmpge(patch[1]).all(), + "{style:?} turned {degrees} degrees bends to {patch:?}, past the layer's {bounds:?}" + ); + } + } + + // An ellipse doesn't fill its square, so turned off its axes, its bounds hold less than its square's + use kurbo::Shape; + let size = DVec2::new(400., 100.); + let ellipse = kurbo::Ellipse::new((size.x / 2., size.y / 2.), (size.x / 2., size.y / 2.), 0.).to_path(0.01); + for (style, bend) in [(WarpStyle::Inflate, 50.), (WarpStyle::Arch, 50.), (WarpStyle::ArcUpper, 50.), (WarpStyle::Squeeze, -50.)] { + for degrees in [30_f64, 45.] { + let placement = DAffine2::from_angle(degrees.to_radians()); + let warp = warp_effect(style, bend, square_on(placement * DAffine2::from_scale(size))); + let mut shape = Vector::item_from_bezpath(&ellipse); + shape.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE)))); + shape.set_attribute(ATTR_TRANSFORM, placement); + stamp_effect(&mut shape, Effect::new(&warp)); + let layer = Item::new_from_element(Graphic::Vector(Box::new(shape))); + + let RenderBoundingBox::Rectangle(bounds) = graphic_list_painted_bounds(&List::new_from_item(layer), true) else { + panic!("expected bounds") + }; + let patch = warp_patch_box(&warp, DAffine2::IDENTITY, |uv| (uv - 0.5).length() <= 0.5); + assert!( + bounds[0].cmple(patch[0]).all() && bounds[1].cmpge(patch[1]).all(), + "{style:?} on an ellipse turned {degrees} degrees bends to {patch:?}, past the layer's {bounds:?}" + ); + } + } + } + + #[test] + fn layers_grow_by_how_far_their_bent_leaves_stretch() { + use graphic_types::raster_types::Image; + use graphic_types::{Effect, WarpStyle, stamp_effect}; + + // An image bent within a square on it while square, then stretched four times as wide, as a transform after the warp does + let square = DVec2::splat(100.); + let warp = warp_effect(WarpStyle::Arc, 50., square_on(DAffine2::from_scale(square))); + let mut image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(square)); + stamp_effect(&mut image, Effect::new(&warp)); + image.set_attribute(ATTR_TRANSFORM, DAffine2::from_scale(square * DVec2::new(4., 1.))); + let layer = Item::new_from_element(Graphic::RasterCPU(Box::new(image))); + + let RenderBoundingBox::Rectangle(bounds) = graphic_list_painted_bounds(&List::new_from_item(layer), true) else { + panic!("expected bounds") + }; + + // The square's arcs, stretched with it + let patch = warp_patch_box(&warp, DAffine2::from_scale(DVec2::new(4., 1.)), |_| true); + assert!( + bounds[0].cmple(patch[0]).all() && bounds[1].cmpge(patch[1]).all(), + "the bend reaches {patch:?}, past the layer's {bounds:?}" + ); + } + + #[test] + fn svg_filter_regions_of_groups_in_turned_groups_hold_their_childrens_bend() { + use graphic_types::raster_types::Image; + use graphic_types::{Effect, EffectOperation, WarpStyle, stamp_effect}; + + // A group turned by the angle, holding a blurred group, holding an image bent within a square on it, upright in the turned group's space + let size = DVec2::new(400., 100.); + let warp = warp_effect(WarpStyle::ArcUpper, 50., square_on(DAffine2::from_scale(size))); + let blur = EffectOperation::Blur { + radius_mask: Default::default(), + radius: 5., + box_blur: false, + gamma: false, + }; + for degrees in [0_f64, 30., 45., 90.] { + let mut image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size)); + stamp_effect(&mut image, Effect::new(&warp)); + let mut blurred = Item::new_from_element(Graphic::RasterCPU(Box::new(image))); + stamp_effect(&mut blurred, Effect::new(&blur)); + let turned = Item::new_from_element(Graphic::Graphic(Box::new(blurred))).with_attribute(ATTR_TRANSFORM, DAffine2::from_angle(degrees.to_radians())); + + let mut render = SvgRender::new(); + let render_params = RenderParams { + for_export: true, + ..Default::default() + }; + List::new_from_item(turned).render_svg(&mut render, &render_params); + + // The blur's filter region, in the turned group's space, holds the bulge the image's markup draws + let filter = render.svg_defs.split(" f64 { + let value = filter.split(&format!(" {name}=\"")).nth(1).and_then(|rest| rest.split('"').next()); + value.and_then(|value| value.parse().ok()).unwrap_or_else(|| panic!("the filter has no {name}")) + }; + let region = [ + DVec2::new(attribute("x"), attribute("y")), + DVec2::new(attribute("x") + attribute("width"), attribute("y") + attribute("height")), + ]; + let patch = warp_patch_box(&warp, DAffine2::IDENTITY, |_| true); + assert!( + region[0].cmple(patch[0]).all() && region[1].cmpge(patch[1]).all(), + "turned {degrees} degrees, the bend reaches {patch:?}, past the filter's {region:?}" + ); + } + } + #[test] fn effects_svg_cannot_express_that_change_nothing_leave_the_content_live() { use graphic_types::raster_types::Image; diff --git a/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs b/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs index 2fb9b9d665..ba606470cc 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs @@ -2,7 +2,7 @@ //! from `vello_adjustments.wgsl`, while the kinds that compilers struggle to build inside its loop each get a shader and pass of their own. Steps read their //! settings from a texture, so changing those recompiles nothing. -use crate::vello_effects::{WORKING_FORMAT, full_target_pipeline}; +use crate::vello_effects::{WORKING_FORMAT, pass_pipeline}; use core_types::graphene_hash::CacheHash; use graphic_types::Adjustment; use raster_kernels::adjustment_steps::{AdjustmentSteps, StepKind, shader_constants}; @@ -314,7 +314,7 @@ impl AdjustmentShaders { label: Some("vello_adjustments"), source: wgpu::ShaderSource::Wgsl(shader.source().into()), }); - full_target_pipeline(device, &self.pipeline_layout, &module, "adjust", format) + pass_pipeline(device, &self.pipeline_layout, &module, "vertex", "adjust", format, None) })) .clone() } diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects.rs b/node-graph/libraries/wgpu-executor/src/vello_effects.rs index 5323153213..a2d4848171 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_effects.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_effects.rs @@ -9,7 +9,7 @@ use glam::{DAffine2, DVec2, UVec2}; use graphic_types::effect_layers::{EffectLayers, EffectPiece, LayerPart, PiecePlace, is_pixel_filter}; use graphic_types::effects::{EffectCapture, GRADIENT_GLOW_FADE, GRADIENT_TABLE_SIZE, GlowFill, OutlineFill, bevel_light, contour_gradient_span, grow_and_tent, outline_extents, shadow_offset}; use graphic_types::masks::{mask_feather_sigma, masked_radius_blur_levels}; -use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, RadialBlur, warp_frame}; +use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, RadialBlur, WarpTessellation, warp_frame, warp_of}; use graphic_types::{Adjustment, BevelDirection, BevelStyle, BevelTechnique, EffectOperation, Effects, GlowSource, GlowTechnique}; use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH, chamfer_passes}; use raster_kernels::resample_kernels::MotionBlurShear; @@ -21,6 +21,7 @@ mod filters; mod masks; mod resample; mod styles; +mod warp; use resample::Displacement; @@ -86,14 +87,22 @@ fn kernel_taps(kernel: BlurKernel, levels: u32) -> Vec<[f32; 4]> { taps } -/// A pipeline running the `entry_point` of `shader` over one triangle covering a target of `format`. -pub(crate) fn full_target_pipeline(device: &wgpu::Device, layout: &wgpu::PipelineLayout, shader: &wgpu::ShaderModule, entry_point: &'static str, format: wgpu::TextureFormat) -> wgpu::RenderPipeline { +/// A pipeline running the `vertex_entry_point` and then the fragment `entry_point` of `shader` into a target of `format`, blending by `blend` (or writing without it). +pub(crate) fn pass_pipeline( + device: &wgpu::Device, + layout: &wgpu::PipelineLayout, + shader: &wgpu::ShaderModule, + vertex_entry_point: &'static str, + entry_point: &'static str, + format: wgpu::TextureFormat, + blend: Option, +) -> wgpu::RenderPipeline { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some(entry_point), layout: Some(layout), vertex: wgpu::VertexState { module: shader, - entry_point: Some("vertex"), + entry_point: Some(vertex_entry_point), compilation_options: Default::default(), buffers: &[], }, @@ -103,7 +112,7 @@ pub(crate) fn full_target_pipeline(device: &wgpu::Device, layout: &wgpu::Pipelin compilation_options: Default::default(), targets: &[Some(wgpu::ColorTargetState { format, - blend: None, + blend, write_mask: wgpu::ColorWrites::ALL, })], }), @@ -148,6 +157,7 @@ impl EffectPasses { include_str!("vello_hash.wgsl"), include_str!("vello_effects/filters.wgsl"), include_str!("vello_resample.wgsl"), + include_str!("vello_warp.wgsl"), include_str!("vello_styles.wgsl"), include_str!("vello_masks.wgsl") ) @@ -178,9 +188,10 @@ impl EffectPasses { ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None, }, + // The Warp's vertices read the parameters too wgpu::BindGroupLayoutEntry { binding: 4, - visibility: wgpu::ShaderStages::FRAGMENT, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, @@ -218,11 +229,17 @@ impl EffectPasses { } fn pipeline(&self, device: &wgpu::Device, entry_point: &'static str, format: wgpu::TextureFormat) -> wgpu::RenderPipeline { + self.pipeline_with(device, "vertex", entry_point, format, None) + } + + /// The pipeline running the fragment shader's `entry_point` into `format` after the `vertex_entry_point`, blending by `blend` (or writing without it). + /// It's cached by the fragment shader's entry point, so each takes one vertex shader and blend. + fn pipeline_with(&self, device: &wgpu::Device, vertex_entry_point: &'static str, entry_point: &'static str, format: wgpu::TextureFormat, blend: Option) -> wgpu::RenderPipeline { let mut pipelines = self.pipelines.lock().unwrap_or_else(PoisonError::into_inner); pipelines .entry((entry_point, format)) - .or_insert_with(|| full_target_pipeline(device, &self.pipeline_layout, &self.shader, entry_point, format)) + .or_insert_with(|| pass_pipeline(device, &self.pipeline_layout, &self.shader, vertex_entry_point, entry_point, format, blend)) .clone() } @@ -763,6 +780,27 @@ impl EffectPasses { full = Some(warped(&mut recorder, unwarped)); filled = filled.map(|filled| warped(&mut recorder, filled)); } + EffectOperation::Warp { .. } => { + // The square the warp's transform places in the effect space, measured from its origin (the content's) + let Some((warp, transform)) = warp_of(operation) else { continue }; + let square = warp_frame(transform, effect_to_pixels); + let tessellation = square.as_ref().and_then(|square| WarpTessellation::new(&warp.mesh(square.size), square, recorder.size.as_dvec2())); + + 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, or the patch reaches none of the image, it clears everything + let warped = |recorder: &mut PassRecorder, texture: wgpu::Texture| match (&square, &tessellation) { + (Some(square), Some(tessellation)) => recorder.warp_effect(texture, square, tessellation), + _ => { + 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::Ripple { .. } | EffectOperation::Wave { .. } => { let (Some(frame), Some((field, edge_mode))) = (&frame, DisplacementField::of(operation)) else { continue; @@ -1092,6 +1130,21 @@ impl EffectPasses { content: Option<&wgpu::TextureView>, parameters: Parameters, ) { + let bind_group = self.bind_group(device, size, source, secondary, content, parameters); + let pipeline = self.pipeline(device, entry_point, format); + Self::draw(encoder, entry_point, target, &bind_group, &[(&pipeline, 3, 1)]); + } + + /// The bind group of a pass into a target `size` texels across, reading the `source` view and optionally the `secondary` and `content` views. + fn bind_group( + &self, + device: &wgpu::Device, + size: UVec2, + source: &wgpu::TextureView, + secondary: Option<&wgpu::TextureView>, + content: Option<&wgpu::TextureView>, + parameters: Parameters, + ) -> wgpu::BindGroup { let parameters = Parameters { target_to_uv: [1. / size.x as f32, 1. / size.y as f32], ..parameters @@ -1103,7 +1156,7 @@ impl EffectPasses { contents: bytemuck::bytes_of(¶meters), usage: wgpu::BufferUsages::UNIFORM, }); - let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("vello_effects_bind_group"), layout: &self.bind_group_layout, entries: &[ @@ -1128,34 +1181,33 @@ impl EffectPasses { resource: parameters_buffer.as_entire_binding(), }, ], - }); - - let pipeline = self.pipeline(device, entry_point, format); - draw_covering(encoder, entry_point, &pipeline, &bind_group, target); + }) } -} -/// Records a pass clearing `target` and drawing one triangle covering it with the `pipeline` reading the `bind_group`. -fn draw_covering(encoder: &mut wgpu::CommandEncoder, label: &str, pipeline: &wgpu::RenderPipeline, bind_group: &wgpu::BindGroup, target: &wgpu::TextureView) { - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some(label), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: target, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), - store: wgpu::StoreOp::Store, - }, - depth_slice: None, - })], - depth_stencil_attachment: None, - timestamp_writes: None, - occlusion_query_set: None, - multiview_mask: None, - }); - pass.set_pipeline(pipeline); - pass.set_bind_group(0, bind_group, &[]); - pass.draw(0..3, 0..1); + /// Records a render pass clearing `target` and then, for each of the `draws` in order, drawing its count of vertices through its pipeline its count of instances over. + fn draw(encoder: &mut wgpu::CommandEncoder, label: &str, target: &wgpu::TextureView, bind_group: &wgpu::BindGroup, draws: &[(&wgpu::RenderPipeline, u32, u32)]) { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(label), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + depth_slice: None, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_bind_group(0, bind_group, &[]); + for &(pipeline, vertices, instances) in draws { + pass.set_pipeline(pipeline); + pass.draw(0..vertices, 0..instances); + } + } } /// Whether an operation leaves the content as it is, by its settings alone or as a blur or bevel too slight to see at this scale. @@ -1685,7 +1737,7 @@ impl PassRecorder<'_> { }); let pipeline = shaders.pipeline(self.device, prepared.shader, format); - draw_covering(&mut self.encoder, "adjust", &pipeline, &bind_group, target); + EffectPasses::draw(&mut self.encoder, "adjust", target, &bind_group, &[(&pipeline, 3, 1)]); #[cfg(test)] self.textures.drawn_passes.push("adjust"); 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 706f576d51..c8258d7ff2 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_effects/resample.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_effects/resample.rs @@ -7,7 +7,7 @@ use graphic_types::vector_types::GradientSpread; 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] { +pub(super) 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(); diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects/warp.rs b/node-graph/libraries/wgpu-executor/src/vello_effects/warp.rs new file mode 100644 index 0000000000..a2954a1b9f --- /dev/null +++ b/node-graph/libraries/wgpu-executor/src/vello_effects/warp.rs @@ -0,0 +1,54 @@ +//! Records the Warp's pass, with its shaders in `vello_warp.wgsl`. + +use super::resample::frame_taps; +use super::{EffectPasses, PARAMETER_TAPS, Parameters, PassRecorder}; +use graphic_types::resampling::{EffectFrame, WarpTessellation}; + +/// The first tap holding the tessellation, after the square and how its edge fades. +const TESSELLATION_TAPS: usize = 5; + +/// The tap array holding the warp's square where the frame warps read it, with how far its edge fades each way and how far a texel reaches along its sides in `taps[4]`, then its tessellation +/// where the warp shaders read it: the patch's control points two to a tap, how far its edge fades across its sides in the texels and which sides it reaches, and where its parameters read the content. +fn warp_taps(square: &EffectFrame, tessellation: &WarpTessellation) -> [[f32; 4]; PARAMETER_TAPS] { + let mut taps = frame_taps(square); + let (half_fade, extent) = (tessellation.half_fade.as_vec2(), square.pixel_extent().as_vec2()); + taps[4] = [half_fade.x, half_fade.y, extent.x, extent.y]; + + for (tap, [first, second]) in taps[TESSELLATION_TAPS..].iter_mut().zip(tessellation.patch.0.as_flattened().as_chunks::<2>().0) { + *tap = [first.x, first.y, second.x, second.y].map(|value| value as f32); + } + + let sides = (0..4).filter(|&side| tessellation.sides[side]).map(|side| 1 << side).sum::(); + let [a, b, c, d, e, f] = tessellation.source.to_cols_array().map(|value| value as f32); + taps[TESSELLATION_TAPS + 8] = [tessellation.fringe.x as f32, tessellation.fringe.y as f32, sides as f32, 0.]; + taps[TESSELLATION_TAPS + 9] = [a, b, c, d]; + taps[TESSELLATION_TAPS + 10] = [e, f, tessellation.cells[0] as f32, tessellation.cells[1] as f32]; + taps +} + +impl PassRecorder<'_> { + /// `texture` with the content within its `square` carried through the warp's `tessellation` (made for this recorder's size), and all else cleared, matching the CPU's `WarpRasterizer`. + pub(super) fn warp_effect(&mut self, texture: wgpu::Texture, square: &EffectFrame, tessellation: &WarpTessellation) -> wgpu::Texture { + let parameters = Parameters { + values: [tessellation.source.matrix2.determinant().signum() as f32, 0., 0., 0.], + taps: warp_taps(square, tessellation), + ..Default::default() + }; + + // Six corners for each quad of the fringe along the sides and past the corners, and for each cell's two triangles + let [columns, rows] = tessellation.cells; + let vertices = 12 * (columns + rows) + 24 + 6 * columns * rows; + + let format = texture.format(); + let warped = self.textures.acquire(self.device, self.size, format); + let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default()); + let reading = self.passes.bind_group(self.device, self.size, &view(&texture), None, None, parameters); + let mesh = (self.passes).pipeline_with(self.device, "warp_vertex", "warp_effect", format, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING)); + + // The triangles painting over each other from clear, the second time over drawing those where the patch turns over on top of the rest + EffectPasses::draw(&mut self.encoder, "warp_effect", &view(&warped), &reading, &[(&mesh, vertices, 2)]); + + self.textures.release(texture); + warped + } +} 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 21c0a6b5f4..ce44824084 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs @@ -5023,21 +5023,31 @@ fn x_and_y_displacement( /// A 50 by 50 raster at (`offset`, `offset`), one pixel per document unit, of colors varying across it around a hole, carrying `effects` with `fill`. fn patterned_raster(offset: f64, effects: &[graphic_types::EffectOperation], fill: f64) -> core_types::list::Item> { + patterned_raster_sized(offset, UVec2::splat(50), effects, fill) +} + +/// Like [`patterned_raster`], `size` pixels across. +fn patterned_raster_sized( + offset: f64, + size: UVec2, + effects: &[graphic_types::EffectOperation], + fill: f64, +) -> core_types::list::Item> { use core_types::list::Item; use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM}; use graphic_types::raster_types::{Image, Raster}; use graphic_types::stamp_effect; - let data = (0..50 * 50) + let data = (0..size.x * size.y) .map(|index| { - let (x, y) = ((index % 50) as f32 + 0.5, (index / 50) as f32 + 0.5); + let (x, y) = ((index % size.x) as f32 + 0.5, (index / size.x) as f32 + 0.5); let alpha = if (x - 32.).hypot(y - 20.) < 7. { 0. } else { 1. }; core_types::Color::from_gamma_srgb_channels(x / 50., y / 50., ((x * 0.4).sin() * 0.5 + 0.5) * (1. - y / 100.), alpha) }) .collect(); - let placement = DAffine2::from_translation(glam::DVec2::splat(offset)) * DAffine2::from_scale(glam::DVec2::splat(50.)); + let placement = DAffine2::from_translation(glam::DVec2::splat(offset)) * DAffine2::from_scale(size.as_dvec2()); - let mut item = Item::new_from_element(Raster::new_cpu(Image { width: 50, height: 50, data })) + let mut item = Item::new_from_element(Raster::new_cpu(Image { width: size.x, height: size.y, data })) .with_attribute(ATTR_TRANSFORM, placement) .with_attribute(ATTR_OPACITY_FILL, fill); effects.iter().for_each(|operation| stamp_effect(&mut item, stamped_at(operation, placement))); @@ -5058,20 +5068,80 @@ fn gpu_and_cpu_difference(item: core_types::list::Item>, size: UVec2, view: DAffine2) -> Option { - use core_types::ATTR_TRANSFORM; + Some(gpu_and_cpu_differences_in_view(item, size, view)?.into_iter().max().unwrap_or_default()) +} + +/// How much the GPU's render of `item` through a `view` and its CPU evaluation differ by at each of the render's pixels, row by row, as [`gpu_and_cpu_difference_in_view`] measures it. +fn gpu_and_cpu_differences_in_view(item: core_types::list::Item>, size: UVec2, view: DAffine2) -> Option> { use rendering::{Render, RenderParams}; let graphic = graphic_types::Graphic::RasterCPU(Box::new(item.clone())); let gpu = render_in_view(size, view, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?; + Some(cpu_differences(&gpu, size, item, view, UVec2::ZERO, size)) +} + +/// The GPU's renders of the `items` (as if each were drawn alone in a render `tile` pixels across), drawn side by side in one render in rows of `columns`, each cut from it. `None` without a GPU. +fn gpu_tiles(items: &[core_types::list::Item>], tile: UVec2, columns: u32) -> Option>> { + use core_types::ATTR_TRANSFORM; + use core_types::list::{Item, List}; + use rendering::{Render, RenderParams}; + + // Each item moved into its tile, which its effects follow + let origin = |index: usize| UVec2::new(index as u32 % columns, index as u32 / columns) * tile; + let placed = items.iter().enumerate().map(|(index, item)| { + let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); + let item = item.clone().with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(origin(index).as_dvec2()) * transform); + Item::new_from_element(graphic_types::Graphic::from(item)) + }); + let graphic = graphic_types::Graphic::GraphicList(placed.collect::>()); + let size = UVec2::new(columns, (items.len() as u32).div_ceil(columns)) * tile; + let gpu = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?; + + let tiles = (0..items.len()).map(|index| { + let origin = origin(index); + (0..tile.y) + .flat_map(|y| (0..tile.x).map(move |x| (x, y))) + .map(|(x, y)| pixel(&gpu, size, origin.x + x, origin.y + y)) + .collect() + }); + Some(tiles.collect()) +} + +/// Like [`gpu_and_cpu_differences_in_view`] for each of the `items` (as if each were drawn alone in a render `tile` pixels across), drawn together as [`gpu_tiles`] draws them: +/// each one's tile, and how much its CPU evaluation differs from it at each pixel there, row by row. `None` without a GPU. +fn gpu_tiles_and_cpu_differences( + items: Vec>>, + tile: UVec2, + columns: u32, +) -> Option, Vec)>> { + let tiles = gpu_tiles(&items, tile, columns)?; + let differences = items + .into_iter() + .zip(&tiles) + .map(|(item, pixels)| cpu_differences(pixels, tile, item, DAffine2::IDENTITY, UVec2::ZERO, tile)); + Some(tiles.iter().cloned().zip(differences).collect()) +} + +/// How much the CPU evaluation of `item` through a `view` differs from the `gpu` render of it, `size` pixels across, at each pixel of the part `extent` across from `origin`, row by row, +/// in levels of their premultiplied channels. +fn cpu_differences( + gpu: &[[u8; 4]], + size: UVec2, + item: core_types::list::Item>, + view: DAffine2, + origin: UVec2, + extent: UVec2, +) -> Vec { + use core_types::ATTR_TRANSFORM; 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() * view.inverse(); - let mut worst = 0; - for y in 0..size.y { - for x in 0..size.x { + let mut differences = Vec::with_capacity((extent.x * extent.y) as usize); + for y in origin.y..origin.y + extent.y { + for x in origin.x..origin.x + extent.x { let point = document_to_pixels.transform_point2(glam::DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor(); let inside = point.x >= 0. && point.y >= 0. && point.x < raster.width as f64 && point.y < raster.height as f64; let cpu = if inside { @@ -5082,15 +5152,16 @@ fn gpu_and_cpu_difference_in_view(item: core_types::list::Item graphic_types::EffectOperation { + graphic_types::EffectOperation::Warp { + style, + bend, + horizontal_distortion: 0., + vertical_distortion: 0., + vertical: false, + transform, + } +} + +/// The transform placing a warp's square on the unit square that `placement` places, as on the frame of content it places. +fn square_on(placement: DAffine2) -> DAffine2 { + placement * DAffine2::from_translation(glam::DVec2::splat(0.5)) +} + +#[test] +fn warp_effects_on_a_tilted_canvas_keep_all_they_paint() { + use glam::DVec2; + use graphic_types::{EffectOperation, Graphic, WarpStyle}; + use rendering::{Render, RenderParams}; + + // Within a square on a raster 200 by 100 at the origin + let on_raster = square_on(DAffine2::from_scale(DVec2::new(200., 100.))); + let chains = [ + // A rise with both distortions reaches far past one corner of its square, past both sides there, on a canvas tilted off the document's axes + vec![EffectOperation::Warp { + style: WarpStyle::Rise, + bend: -50., + horizontal_distortion: 50., + vertical_distortion: 50., + vertical: false, + transform: on_raster, + }], + // An arch bends far above its square yet within its tilted bounds, where a twist after it clears it, bending what remains within the square + vec![warp_effect(WarpStyle::Arch, 80., on_raster), warp_effect(WarpStyle::Twist, -50., on_raster)], + ]; + let size = UVec2::splat(480); + + for effects in &chains { + let item = patterned_raster_sized(0., UVec2::new(200, 100), effects, 1.); + + for degrees in [30_f64, 45.] { + let view = DAffine2::from_translation(DVec2::splat(240.)) * DAffine2::from_angle(degrees.to_radians()) * DAffine2::from_translation(-DVec2::new(100., 50.)); + + // The GPU's warp, beside the CPU's warped image drawn plainly through the same view + let warped = Graphic::RasterCPU(Box::new(item.clone())); + let Some(gpu) = render_in_view(size, view, |scene| warped.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + let evaluated = Graphic::RasterCPU(Box::new(raster_kernels::evaluate_raster_effects(item.clone()))); + let Some(cpu) = render_in_view(size, view, |scene| evaluated.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + // Where the CPU's image shows the content, so does the GPU's + let missing = (0..size.x * size.y).filter(|index| pixel(&cpu, size, index % size.x, index / size.x)[3] > 192 && pixel(&gpu, size, index % size.x, index / size.x)[3] < 64); + let missing = missing.count(); + assert!(missing <= 2, "{effects:?} tilted {degrees} degrees, {missing} pixels of the content are missing on the GPU"); + } + } +} + +#[test] +fn warp_effects_match_on_the_cpu_and_gpu() { + use core_types::ATTR_TRANSFORM; + use glam::DVec2; + use graphic_types::{EffectOperation, WarpStyle}; + + let warp = |style, bend, horizontal_distortion, vertical_distortion, vertical, transform| EffectOperation::Warp { + style, + bend, + horizontal_distortion, + vertical_distortion, + vertical, + transform, + }; + let shadow = drop_shadow(core_types::Color::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75), DVec2::new(4., 5.), 3., 0.); + + // Within a square on the image 50 pixels across, measured from its corner + let on_image = square_on(DAffine2::from_scale(DVec2::splat(50.))); + + // Every style bent both ways short of folding over itself, where a crease's texels could fall to either side + use WarpStyle::*; + let styles = [Arc, ArcLower, ArcUpper, Arch, Bulge, ShellLower, ShellUpper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist]; + let mut cases: Vec> = styles.iter().flat_map(|&style| [40., -30.].map(|bend| vec![warp(style, bend, 0., 0., false, on_image)])).collect(); + cases.extend([ + vec![warp(Arc, 30., 25., -20., false, on_image)], + vec![warp(Flag, 35., 0., 0., true, on_image)], + vec![warp(Bulge, -25., -30., 15., true, on_image)], + // What a shadow paints past the square clears, as on the CPU + vec![shadow.clone(), warp(Arc, 45., 0., 0., false, on_image)], + vec![shadow.clone(), warp(Wave, 50., 0., 0., false, on_image)], + ]); + // All of them side by side in one render + let filled_cases: Vec<_> = cases.iter().flat_map(|effects| [1., 0.5].map(|fill| (effects, fill))).collect(); + let items = filled_cases.iter().map(|&(effects, fill)| patterned_raster(55., effects, fill)).collect(); + let Some(tiles) = gpu_tiles_and_cpu_differences(items, UVec2::new(160, 160), 10) else { + return; + }; + for (&(effects, fill), (_, differences)) in filled_cases.iter().zip(tiles) { + let worst = differences.into_iter().max().unwrap_or_default(); + assert!(worst <= 3, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels"); + } + + // A square wider than it's tall, bending into arcs that are circles in its own units + let on_oblong = square_on(DAffine2::from_scale(DVec2::new(50., 30.))); + for effect in [ + warp(Arc, 40., 0., 0., false, on_oblong), + warp(Bulge, 35., 0., 0., true, on_oblong), + warp(Twist, 40., 0., 0., false, on_oblong), + ] { + let Some(worst) = gpu_and_cpu_difference(patterned_raster_sized(55., UVec2::new(50, 30), std::slice::from_ref(&effect), 1.), UVec2::new(160, 160)) else { + return; + }; + assert!(worst <= 3, "{effect:?} on a raster 50 by 30 differs from the GPU by up to {worst} levels"); + } + + // Where the patch folds over itself, the GPU shows the sheet turned over on top as the CPU does, so only the texels along its creases differ. + // The wave's square is nudged off the texel grid, since the side its turned-over part ends at, which fades only outward, otherwise runs exactly through texel centers that roundoff splits between layers. + let nudged = DAffine2::from_translation(DVec2::new(0.3, 0.18)) * on_image; + for effect in [ + warp(Wave, 100., 100., 100., false, nudged), + warp(Fisheye, 100., 0., 0., false, on_image), + warp(ShellLower, -100., 0., 0., false, on_image), + ] { + let Some(differences) = gpu_and_cpu_differences_in_view(patterned_raster(55., std::slice::from_ref(&effect), 1.), UVec2::new(160, 160), DAffine2::IDENTITY) else { + return; + }; + let differing = differences.iter().filter(|&&difference| difference > 3).count(); + assert!(differing <= 8, "{effect:?} differs from the GPU by over 3 levels at {differing} texels"); + } + + // Only the right part of the warped content in view reads the part of the content left of the view, which the patch carries there. + // Premultiplied, so a faint pixel's colors don't magnify roundoff. + let partial_cases = [ + vec![warp(Arc, 60., 0., 0., false, on_image)], + vec![warp(Twist, 70., 0., 0., false, on_image)], + vec![shadow.clone(), warp(Flag, 40., 0., 0., false, on_image)], + ]; + for effects in partial_cases { + use rendering::{Render, RenderParams}; + + let graphic = graphic_types::Graphic::RasterCPU(Box::new(patterned_raster(20., &effects, 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 }; + let premultiplied = |[red, green, blue, alpha]: [u8; 4]| [red, green, blue].map(|channel| channel as f32 * alpha as f32 / 255.).into_iter().chain([alpha as f32]); + 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 = premultiplied(expected) + .zip(premultiplied(actual)) + .map(|(expected, actual)| (expected - actual).abs()) + .fold(0., f32::max); + assert!(difference <= 1.5, "{effects:?} at ({x}, {y}) shows {actual:?} rather than {expected:?}"); + } + } + } + + // Upright and turned a quarter, viewed at twice the size so the content's pixels land on the render's + let upright = DAffine2::from_translation(DVec2::splat(27.)) * DAffine2::from_scale(DVec2::splat(25.)); + let turned = DAffine2::from_translation(DVec2::new(52., 27.)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_2) * DAffine2::from_scale(DVec2::splat(25.)); + for placement in [upright, turned] { + for effect in [warp(Arc, 40., 0., 0., false, on_image), warp(Rise, -35., 10., 0., true, on_image)] { + let item = patterned_raster(0., std::slice::from_ref(&effect), 1.).with_attribute(ATTR_TRANSFORM, placement); + let Some(worst) = gpu_and_cpu_difference_in_view(item, 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"); + } + } +} + +#[test] +fn warp_effects_match_on_the_cpu_and_gpu_within_offset_turned_and_slanted_squares() { + use glam::DVec2; + use graphic_types::{EffectOperation, WarpStyle}; + + // Within the image 50 pixels across, measured from its corner: a square smaller than it toward its bottom right, an oblong one turned about its middle, and one slanted + let offset = DAffine2::from_translation(DVec2::new(32., 30.)) * DAffine2::from_scale(DVec2::new(24., 18.)); + let turned = DAffine2::from_translation(DVec2::new(25., 26.)) * DAffine2::from_angle(0.6) * DAffine2::from_scale(DVec2::new(40., 24.)); + let slanted = DAffine2::from_translation(DVec2::new(24., 26.)) * DAffine2::from_cols_array(&[40., 0., 12., 24., 0., 0.]); + let warps = |transform| { + [ + warp_effect(WarpStyle::Arc, 50., transform), + warp_effect(WarpStyle::Flag, -40., transform), + warp_effect(WarpStyle::Twist, 60., transform), + warp_effect(WarpStyle::Fisheye, 50., transform), + EffectOperation::Warp { + style: WarpStyle::Rise, + bend: -35., + horizontal_distortion: 20., + vertical_distortion: -15., + vertical: true, + transform, + }, + ] + }; + // All of them side by side in one render + let cases: Vec<_> = [offset, turned, slanted] + .into_iter() + .flat_map(warps) + .flat_map(|warp| [1., 0.5].map(|fill| (warp.clone(), fill))) + .collect(); + let items = cases.iter().map(|(warp, fill)| patterned_raster(55., std::slice::from_ref(warp), *fill)).collect(); + let Some(tiles) = gpu_tiles_and_cpu_differences(items, UVec2::new(160, 160), 6) else { + return; + }; + for ((warp, fill), (_, differences)) in cases.iter().zip(tiles) { + let worst = differences.into_iter().max().unwrap_or_default(); + assert!(worst <= 3, "{warp:?} at fill {fill} differs from the GPU by up to {worst} levels"); + } +} + +/// Content of one `color` 60 by 40 pixels, one to each document unit, bent by a Warp of the `style` and `bend` within the square its `transform` places, if any. +fn one_color_raster( + color: core_types::Color, + warp: Option<(graphic_types::WarpStyle, f64, DAffine2)>, +) -> core_types::list::Item> { + use core_types::ATTR_TRANSFORM; + use core_types::list::Item; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, stamp_effect}; + + let mut item = Item::new_from_element(Raster::new_cpu(Image::new(60, 40, color))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::new(60., 40.))); + if let Some((style, bend, transform)) = warp { + stamp_effect(&mut item, Effect::new(&warp_effect(style, bend, transform))); + } + item +} + +/// How much of the pixel with its corner at `pixel` a Warp's square that `placement` places (from -0.5 to 0.5, at a pixel per unit) covers, fading across its sides as a side the warp keeps in place does. +fn warp_square_coverage(placement: DAffine2, pixel: glam::DVec2) -> f64 { + use graphic_types::resampling::{warp_frame, warp_half_fade}; + + let Some(square) = warp_frame(placement, DAffine2::IDENTITY) else { return 0. }; + let (local, half, half_fade) = (square.pixels_to_local().transform_point2(pixel + 0.5), square.size / 2., warp_half_fade(&square)); + (0.5 + (half - local.abs()) / (2. * half_fade)).clamp(glam::DVec2::ZERO, glam::DVec2::ONE).element_product() +} + +#[test] +fn warp_effects_leave_the_content_as_it_is_along_sides_they_keep_in_place_at_any_squeeze_and_offset() { + use glam::DVec2; + use graphic_types::WarpStyle; + use graphic_types::warp::Warp; + + // Content of one color within a square 39 by 19 at two offsets and at a scale between pixels, and within squares slanted and turned off the pixel grid, which fisheyes, waves, and twists bend + // both ways, either side of where fisheyes squeeze the content nearly flat, past where they fold, and farther, keeping all four sides in place. The CPU's sweep covers their whole range. + let size = UVec2::new(64, 44); + let bends = [-60., 40., 59., 60., 67., 76., 100.]; + let placements = [ + DAffine2::from_cols_array(&[39., 0., 0., 19., 30., 20.]), + DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]), + DAffine2::from_cols_array(&[42.5, 0., 0., 20.75, 30.25, 20.375]), + DAffine2::from_cols_array(&[24., 0., 16., 14., 30.3, 20.6]), + DAffine2::from_translation(DVec2::new(30.4, 20.15)) * DAffine2::from_angle(0.5) * DAffine2::from_scale(DVec2::new(30., 14.)), + ]; + let cases: Vec<_> = [WarpStyle::Fisheye, WarpStyle::Wave, WarpStyle::Twist] + .into_iter() + .flat_map(|style| bends.into_iter().flat_map(move |bend| placements.map(|placement| (style, bend, placement)))) + .collect(); + + // All the cases side by side in one render for each color + for color in [core_types::Color::WHITE, core_types::Color::from_rgbaf32_unchecked(1., 1., 1., 0.5)] { + let items = cases.iter().map(|&(style, bend, placement)| one_color_raster(color, Some((style, bend, placement)))).collect(); + let Some(tiles) = gpu_tiles_and_cpu_differences(items, size, 15) else { return }; + + for (&(style, bend, placement), (warped, differences)) in cases.iter().zip(tiles) { + let offset = placement.translation; + + // Whether the patch turns over anywhere + let warp = Warp { + style, + bend: bend / 100., + horizontal_distortion: 0., + vertical_distortion: 0., + vertical: false, + }; + let mesh = warp.mesh(DVec2::new(placement.matrix2.x_axis.length(), placement.matrix2.y_axis.length())); + let folds = (0..65 * 65).any(|index| { + let [_, along_s, along_t] = mesh.point_and_tangents(DVec2::new((index % 65) as f64, (index / 65) as f64) / 64.); + along_s.perp_dot(along_t) <= 1e-9 + }); + + // Where the patch doesn't fold, it shows the content within the square, clear past it, and the content faded by the square's coverage across its sides. + // Where it folds, the layers of opaque content cover at least that much. + for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { + let expected = warp_square_coverage(placement, DVec2::new(x as f64, y as f64)) as f32 * color.a() * 255.; + let alpha = pixel(&warped, size, x, y)[3] as f32; + if !folds { + assert!( + (alpha - expected).abs() <= 1., + "{style:?} at {bend} placed at {offset}, {color:?}, shows alpha {alpha} rather than {expected} at ({x}, {y})" + ); + } else if color.a() == 1. { + assert!(alpha >= expected - 1., "{style:?} at {bend} placed at {offset} shows alpha {alpha}, short of {expected} at ({x}, {y})"); + } + } + + // Around each corner, it matches the CPU, which matches a supersampled reference there + let corners = [DVec2::splat(-0.5), DVec2::new(0.5, -0.5), DVec2::new(-0.5, 0.5), DVec2::splat(0.5)].map(|corner| placement.transform_point2(corner)); + for pixel in corners + .into_iter() + .flat_map(|corner| (0..9).map(move |index| (corner - 1.5).floor() + DVec2::new((index % 3) as f64, (index / 3) as f64))) + { + let difference = differences[(pixel.y as u32 * size.x + pixel.x as u32) as usize]; + assert!( + difference <= 2, + "{style:?} at {bend} placed at {offset}, {color:?}, differs from the CPU by {difference} levels at {pixel}" + ); + } + } + } +} + +#[test] +fn warp_effects_with_folds_out_past_a_side_clear_what_lies_outside_the_square_beneath_them() { + use core_types::ATTR_TRANSFORM; + use core_types::list::Item; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect}; + use rendering::{Render, RenderParams}; + + // Opaque rows 60 pixels wide down to just above a square's top side, and clear rows below, which a fisheye folds out over the rows above + let mut image = Image::new(60, 40, core_types::Color::TRANSPARENT); + image.data[..10 * 60].fill(core_types::Color::WHITE); + let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(60., 40.))); + stamp_effect( + &mut item, + Effect::new(&warp_effect(WarpStyle::Fisheye, 100., DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.]))), + ); + let graphic = Graphic::RasterCPU(Box::new(item)); + + let size = UVec2::new(60, 40); + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + // The fold carries only the square's clear content, and the rows above clear + for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { + let alpha = pixel(&pixels, size, x, y)[3]; + assert!(alpha <= 1, "({x}, {y}) shows alpha {alpha}"); + } +} + +#[test] +fn warp_effects_clear_content_well_outside_the_bent_square() { + use glam::DVec2; + use graphic_types::warp::Warp; + use graphic_types::{Graphic, WarpStyle}; + use rendering::{Render, RenderParams}; + + // Opaque content 60 by 40 pixels, within which a flag bends a square 30 by 20 at its middle + let size = UVec2::new(60, 40); + let placement = DAffine2::from_cols_array(&[30., 0., 0., 20., 30., 20.]); + let graphic = Graphic::RasterCPU(Box::new(one_color_raster(core_types::Color::WHITE, Some((WarpStyle::Flag, 40., placement))))); + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + // The pixels within two and a half of where the patch carries the square, past which its edge's fade and its fringe's miters reach nothing + let warp = Warp { + style: WarpStyle::Flag, + bend: 0.4, + horizontal_distortion: 0., + vertical_distortion: 0., + vertical: false, + }; + let (mesh, to_pixels) = (warp.mesh(DVec2::new(30., 20.)), placement * DAffine2::from_translation(DVec2::splat(-0.5))); + let mut near = vec![false; (size.x * size.y) as usize]; + for index in 0..201 * 201 { + let point = to_pixels.transform_point2(mesh.point(DVec2::new((index % 201) as f64, (index / 201) as f64) / 200.)); + for (x, y) in (-3..=3).flat_map(|y| (-3..=3).map(move |x| (x, y))) { + let pixel = (point - 0.5).round() + DVec2::new(x as f64, y as f64); + if (pixel + 0.5).distance(point) <= 2.5 && pixel.cmpge(DVec2::ZERO).all() && pixel.x < size.x as f64 && pixel.y < size.y as f64 { + near[(pixel.y as u32 * size.x + pixel.x as u32) as usize] = true; + } + } + } + + // All else is clear, though the content was opaque there + let far: Vec = (0..size.x * size.y).filter(|&index| !near[index as usize]).collect(); + assert!(far.len() > 1000, "only {} pixels lie far from the patch", far.len()); + for index in far { + let alpha = pixel(&pixels, size, index % size.x, index / size.x)[3]; + assert!(alpha == 0, "({}, {}) shows alpha {alpha}", index % size.x, index / size.x); + } +} + +/// For fish bent far within a square that `placement` places on opaque content `content` pixels across, both ways and turned, and placed at zooms between pixels, +/// the alphas the GPU renders at the pixels of each fish's body (the half of the square nearer the side it bends out from, where it doesn't fold) farther than `margin` from the curves its sides bend into. +fn warp_fish_body_alphas(content: UVec2, placement: DAffine2, margin: f64) -> Option> { + use core_types::ATTR_TRANSFORM; + use core_types::list::Item; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::warp::Warp; + use graphic_types::{Effect, EffectOperation, WarpStyle, stamp_effect}; + + // Each fish stamped on the content, which is then placed at its zoom, as a view between pixels would show it + let cases: Vec<(f64, bool, f64)> = [60., 80., 100.] + .into_iter() + .flat_map(|bend| [false, true].into_iter().flat_map(move |vertical| [0.91, 1.09, 1.37].map(move |zoom| (bend, vertical, zoom)))) + .collect(); + let view = |zoom: f64| DAffine2::from_translation(DVec2::new(40.3, 60.2)) * DAffine2::from_scale(DVec2::splat(zoom)); + let items: Vec<_> = (cases.iter()) + .map(|&(bend, vertical, zoom)| { + let unplaced = DAffine2::from_scale(content.as_dvec2()); + let mut item = Item::new_from_element(Raster::new_cpu(Image::new(content.x, content.y, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, unplaced); + let fish = EffectOperation::Warp { + style: WarpStyle::Fish, + bend, + horizontal_distortion: 0., + vertical_distortion: 0., + vertical, + transform: placement, + }; + stamp_effect(&mut item, Effect::new(&fish)); + item.with_attribute(ATTR_TRANSFORM, view(zoom) * unplaced) + }) + .collect(); + let tile = UVec2::new(240, 260); + let tiles = gpu_tiles(&items, tile, 6)?; + + let mut alphas = Vec::new(); + for (&(bend, vertical, zoom), pixels) in cases.iter().zip(&tiles) { + let warp = Warp { + style: WarpStyle::Fish, + bend: bend / 100., + horizontal_distortion: 0., + vertical_distortion: 0., + vertical, + }; + let mesh = warp.mesh(DVec2::new(placement.matrix2.x_axis.length(), placement.matrix2.y_axis.length())); + let to_pixels = view(zoom) * placement * DAffine2::from_translation(DVec2::splat(-0.5)); + let sides: Vec = (0..=400) + .flat_map(|index| { + let t = index as f64 / 400.; + [DVec2::new(0., t), DVec2::new(1., t), DVec2::new(t, 0.), DVec2::new(t, 1.)] + }) + .map(|uv| to_pixels.transform_point2(mesh.point(uv))) + .collect(); + + for index in 0..101 * 101 { + let across = DVec2::new((index % 101) as f64 / 200., (index / 101) as f64 / 100.); + let uv = if vertical { DVec2::new(across.y, across.x) } else { across }; + let texel = to_pixels.transform_point2(mesh.point(uv)).floor(); + let within_tile = texel.cmpge(DVec2::ZERO).all() && texel.x < tile.x as f64 && texel.y < tile.y as f64; + if within_tile && sides.iter().all(|side| side.distance(texel + 0.5) >= margin) { + alphas.push((bend, vertical, zoom, texel, pixel(pixels, tile, texel.x as u32, texel.y as u32)[3])); + } + } + } + Some(alphas) +} + +#[test] +fn warp_effects_bending_far_leave_no_holes_within_their_patch_at_any_zoom() { + // Opaque content just the size of the square, so its own edge fades where the zoom stretches it, yet nowhere within the body is anything like a hole + let Some(alphas) = warp_fish_body_alphas(UVec2::new(60, 40), DAffine2::from_cols_array(&[60., 0., 0., 40., 30., 20.]), 3.) else { + return; + }; + for (bend, vertical, zoom, texel, alpha) in alphas { + assert!(alpha >= 192, "the fish at {bend}, vertical {vertical}, at zoom {zoom}, shows alpha {alpha} at {texel}"); + } +} + +#[test] +fn warp_effects_bending_far_keep_opaque_content_opaque_within_their_patch_at_any_zoom() { + // Opaque content reaching 20 pixels past the square on each side, so each pixel within the body reads only opaque content + let Some(alphas) = warp_fish_body_alphas(UVec2::new(100, 80), DAffine2::from_cols_array(&[60., 0., 0., 40., 50., 40.]), 2.) else { + return; + }; + for (bend, vertical, zoom, texel, alpha) in alphas { + assert!(alpha >= 254, "the fish at {bend}, vertical {vertical}, at zoom {zoom}, shows alpha {alpha} at {texel}"); + } +} + +#[test] +fn warp_effects_with_sides_curving_sharply_toward_a_pixel_fade_it() { + use core_types::ATTR_TRANSFORM; + use core_types::list::Item; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect}; + use rendering::{Render, RenderParams}; + + // Opaque content past a square 10 by 200 that a flag waves far, so its top side's crest curves tightly past the pixel (28, 87), a third of a pixel within it, as on the CPU + let size = UVec2::new(80, 500); + let mut item = Item::new_from_element(Raster::new_cpu(Image::new(size.x, size.y, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2())); + stamp_effect( + &mut item, + Effect::new(&warp_effect(WarpStyle::Flag, 100., DAffine2::from_cols_array(&[10., 0., 0., 200., 25.625, 300.75]))), + ); + let graphic = Graphic::RasterCPU(Box::new(item)); + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + let alpha = pixel(&pixels, size, 28, 87)[3]; + assert!(alpha.abs_diff(212) <= 4, "the pixel shows alpha {alpha}"); +} + +#[test] +fn warp_effects_of_fisheyes_squeezing_the_content_nearly_flat_against_a_side_keep_it_seamless() { + use graphic_types::{Graphic, WarpStyle}; + use rendering::{Render, RenderParams}; + + // Opaque content past a square with its top side three quarters of the way down a row of pixels, against which fisheyes squeeze the content nearly flat + let size = UVec2::new(60, 40); + for bend in [59., 60.] { + let transform = DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]); + let graphic = Graphic::RasterCPU(Box::new(one_color_raster(core_types::Color::WHITE, Some((WarpStyle::Fisheye, bend, transform))))); + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { + let (alpha, expected) = (pixel(&pixels, size, x, y)[3] as f64, warp_square_coverage(transform, glam::DVec2::new(x as f64, y as f64)) * 255.); + assert!((alpha - expected).abs() <= 1., "bent {bend}, ({x}, {y}) shows alpha {alpha} rather than {expected}"); + } + } +} + +#[test] +fn warp_effects_within_slanted_squares_keep_the_content_as_it_is_past_corners_they_keep_in_place() { + use core_types::ATTR_TRANSFORM; + use core_types::list::Item; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect}; + use rendering::{Render, RenderParams}; + + // Opaque content past a square slanted to corners an eighth of a turn sharp, off the pixel grid, within which a fisheye keeps the sides in place + let size = UVec2::new(120, 80); + let transform = DAffine2::from_cols_array(&[40., 0., 40., 40., 61., 40.75]); + let mut item = Item::new_from_element(Raster::new_cpu(Image::new(size.x, size.y, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2())); + stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Fisheye, 40., transform))); + let graphic = Graphic::RasterCPU(Box::new(item)); + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { + let (alpha, expected) = (pixel(&pixels, size, x, y)[3] as f64, warp_square_coverage(transform, glam::DVec2::new(x as f64, y as f64)) * 255.); + assert!((alpha - expected).abs() <= 1., "({x}, {y}) shows alpha {alpha} rather than {expected}"); + } +} + +#[test] +fn warp_effects_of_folds_returning_over_a_side_change_smoothly_as_the_side_moves() { + use core_types::ATTR_TRANSFORM; + use core_types::list::Item; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect}; + use rendering::{Render, RenderParams}; + + // Clear rows down through the one a square's top side runs through the middle of, and opaque rows below, which a fisheye folds out over the clear rows and back + let size = UVec2::new(60, 40); + let alpha_at = |down: f64| { + let mut image = Image::new(size.x, size.y, core_types::Color::WHITE); + image.data[..11 * 60].fill(core_types::Color::TRANSPARENT); + let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(60., 40.))); + stamp_effect( + &mut item, + Effect::new(&warp_effect(WarpStyle::Fisheye, 100., DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, down]))), + ); + let graphic = Graphic::RasterCPU(Box::new(item)); + render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())).map(|pixels| pixel(&pixels, size, 30, 10)[3]) + }; + + // Moving the side a fiftieth of a pixel across the pixel's center moves its fade only as far + let (Some(above), Some(below)) = (alpha_at(19.99), alpha_at(20.01)) else { return }; + assert!(above.abs_diff(below) <= 8, "the pixel's alpha jumps from {above} to {below}"); +} + +#[test] +fn warp_effects_carry_nothing_wholly_outside_a_slanted_or_turned_square() { + use core_types::ATTR_TRANSFORM; + use core_types::list::Item; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect}; + use rendering::{Render, RenderParams}; + + // Clear content, one pixel to each document unit, but for an opaque pixel just above the top side of a slanted square, which an upper arc raises past where the pixel lies, + // or just above the top corner of a square turned an eighth, which an arc bends far around + let cases = [ + (UVec2::new(80, 40), UVec2::new(30, 9), WarpStyle::ArcUpper, 50., [40., 0., 40., 4., 50., 12.]), + (UVec2::new(80, 60), UVec2::new(40, 9), WarpStyle::Arc, 80., [20., 20., -20., 20., 40.5, 30.01]), + ]; + for (size, opaque, style, bend, transform) in cases { + let mut image = Image::new(size.x, size.y, core_types::Color::TRANSPARENT); + image.data[(opaque.y * size.x + opaque.x) as usize] = core_types::Color::WHITE; + let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2())); + stamp_effect(&mut item, Effect::new(&warp_effect(style, bend, DAffine2::from_cols_array(&transform)))); + let graphic = Graphic::RasterCPU(Box::new(item)); + + // The patch carries none of the pixel anywhere, and the pixel clears where it lies + let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + for (x, y) in (0..size.y).flat_map(|y| (0..size.x).map(move |x| (x, y))) { + let alpha = pixel(&pixels, size, x, y)[3]; + assert!(alpha <= 1, "{style:?} shows alpha {alpha} at ({x}, {y})"); + } + } +} + +#[test] +fn warp_effects_within_squares_far_smaller_than_a_pixel_match_on_the_cpu_and_gpu() { + use core_types::ATTR_TRANSFORM; + use core_types::list::Item; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, WarpStyle, stamp_effect}; + + // Opaque white 25 pixels across stretched to 2500 units and viewed at a hundredth of that, twisted within a square one unit across at its middle + let mut item = Item::new_from_element(Raster::new_cpu(Image::new(25, 25, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(2500.))); + stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Twist, 80., DAffine2::from_translation(DVec2::splat(1275.))))); + + let Some(worst) = gpu_and_cpu_difference_in_view(item, UVec2::splat(64), DAffine2::from_scale(DVec2::splat(0.01))) else { + return; + }; + assert!(worst <= 3, "the GPU differs from the CPU by up to {worst} levels"); +} + +#[test] +fn warp_effects_within_the_identity_or_a_collapsed_transform_clear_all_but_a_pixel_or_two() { + use glam::DVec2; + use graphic_types::WarpStyle; + use rendering::{Render, RenderParams}; + + let size = UVec2::new(160, 160); + let draw = |effects: &[graphic_types::EffectOperation]| { + let graphic = graphic_types::Graphic::RasterCPU(Box::new(patterned_raster(55., effects, 1.))); + render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) + }; + + // The identity is a square 1 across at the image's corner (55, 55), clearing all a pixel or two from it, and a square collapsed onto a line clears everything + let collapsed = DAffine2::from_scale(DVec2::new(50., 0.)); + for (transform, reach) in [(DAffine2::IDENTITY, 2.), (collapsed, 0.)] { + for warp in [WarpStyle::Arc, WarpStyle::Twist, WarpStyle::Squeeze].map(|style| warp_effect(style, 80., transform)) { + let Some(warped) = draw(std::slice::from_ref(&warp)) 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 alpha = pixel(&warped, size, x, y)[3]; + assert!(alpha == 0, "{warp:?} shows alpha {alpha} at ({x}, {y})"); + } + + 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 warp_effects_on_squares_turned_since_an_earlier_warp_match_on_the_cpu_and_gpu() { + use core_types::ATTR_TRANSFORM; + use core_types::list::Item; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, WarpStyle, stamp_effect}; + + // A banner of 160 by 40 pixels, one to each document unit, of colors varying across it + let banner = UVec2::new(160, 40); + let data: Vec<_> = (0..banner.x * banner.y) + .map(|index| { + let (x, y) = ((index % banner.x) as f32 + 0.5, (index / banner.x) as f32 + 0.5); + core_types::Color::from_gamma_srgb_channels(x / banner.x as f32, y / banner.y as f32, (x * 0.2).sin() * 0.5 + 0.5, 1.) + }) + .collect(); + let image = Image { + width: banner.x, + height: banner.y, + data, + }; + + // An arc within a square on the banner bends it far above its top side, then a transform turns it off the document's axes. + // A flag within a square on the turned banner, stamped after the turn, starts a run of its own. + for degrees in [45_f64, 30., -60.] { + let turn = DAffine2::from_angle(degrees.to_radians()); + let stamped = DAffine2::from_scale(banner.as_dvec2()); + let mut item = Item::new_from_element(Raster::new_cpu(image.clone())).with_attribute(ATTR_TRANSFORM, stamped); + stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Arc, 50., square_on(stamped)))); + let mut item = item.with_attribute(ATTR_TRANSFORM, turn * stamped); + stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Flag, 30., square_on(turn * stamped)))); + + // Viewed turned back, so the content's pixels land on the render's + let view = DAffine2::from_translation(DVec2::new(48., 64.)) * turn.inverse(); + let Some(worst) = gpu_and_cpu_difference_in_view(item, UVec2::new(256, 136), view) else { + return; + }; + assert!(worst <= 3, "turned {degrees} degrees, the flag differs from the GPU by up to {worst} levels"); + } +} + +#[test] +fn radial_blurs_spin_all_that_earlier_warps_bent_past_a_frame_turned_or_scaled_since() { + use core_types::ATTR_TRANSFORM; + use core_types::list::Item; + use glam::DVec2; + use graphic_types::raster_types::{Image, Raster}; + use graphic_types::{Effect, EffectOperation, Graphic, RadialBlurMethod, WarpStyle, stamp_effect}; + use rendering::{Render, RenderParams}; + + // A banner of 300 by 30 pixels, one to each document unit once placed, of colors varying across it + let banner = UVec2::new(300, 30); + let data: Vec<_> = (0..banner.x * banner.y) + .map(|index| { + let (x, y) = ((index % banner.x) as f32 + 0.5, (index / banner.x) as f32 + 0.5); + core_types::Color::from_gamma_srgb_channels(x / banner.x as f32, y / banner.y as f32, (x * 0.2).sin() * 0.5 + 0.5, 1.) + }) + .collect(); + + // An arc within a square on the banner bends it into a half ring where it spans `stamped_size`, then it's placed by `placement`, and a spin about a point past its end stamped after starts a run of its own + let bent_and_spun = |stamped_size: DVec2, placement: DAffine2| { + let image = Image { + width: banner.x, + height: banner.y, + data: data.clone(), + }; + let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(stamped_size)); + stamp_effect(&mut item, Effect::new(&warp_effect(WarpStyle::Arc, 100., square_on(DAffine2::from_scale(stamped_size))))); + let mut item = item.with_attribute(ATTR_TRANSFORM, placement); + stamp_effect( + &mut item, + Effect::new(&EffectOperation::RadialBlur { + method: RadialBlurMethod::Spin, + amount: 45., + transform: DAffine2::from_translation(placement.transform_point2(DVec2::new(1.5, 0.5))), + gamma: false, + }), + ); + item + }; + let size = banner.as_dvec2(); + + // Scaled twice as large and turned a half since, its pixels still land on the render's, so the CPU and GPU match throughout + let scaled = bent_and_spun(size / 2., DAffine2::from_angle(std::f64::consts::PI) * DAffine2::from_scale(size)); + let Some(worst) = gpu_and_cpu_difference_in_view(scaled, UVec2::new(440, 520), DAffine2::from_translation(DVec2::new(380., 240.))) else { + return; + }; + assert!(worst <= 3, "scaled and turned a half, the spin differs from the GPU by up to {worst} levels"); + + // Turned 60 degrees since, the GPU shows the smear wherever the CPU's image drawn plainly does + let turned = bent_and_spun(size, DAffine2::from_angle(60_f64.to_radians()) * DAffine2::from_scale(size)); + let (render_size, view) = (UVec2::new(560, 460), DAffine2::from_translation(DVec2::new(200., 100.))); + let warped = Graphic::RasterCPU(Box::new(turned.clone())); + let Some(gpu) = render_in_view(render_size, view, |scene| warped.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + let evaluated = Graphic::RasterCPU(Box::new(raster_kernels::evaluate_raster_effects(turned))); + let Some(cpu) = render_in_view(render_size, view, |scene| evaluated.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + let alpha = |pixels: &[[u8; 4]], index: u32| pixel(pixels, render_size, index % render_size.x, index / render_size.x)[3]; + let missing = (0..render_size.x * render_size.y).filter(|&index| alpha(&cpu, index) >= 8 && alpha(&gpu, index) == 0).count(); + assert!(missing <= 2, "turned 60 degrees, {missing} pixels of the smear are missing on the GPU"); +} + +#[test] +fn warp_effects_clear_what_earlier_effects_paint_past_a_slanted_square() { + use core_types::ATTR_TRANSFORM; + use glam::{DMat2, DVec2}; + use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect}; + use rendering::{Render, RenderParams}; + + // Content slanted 45 degrees within a square on it, casting a sharp shadow 20 units down, past the square's slanted bottom side + let slant = DMat2::from_cols(DVec2::new(100., 0.), DVec2::new(100., 100.)); + let skewed = DAffine2::from_translation(DVec2::new(20., 10.)) * DAffine2::from_mat2(slant); + let shadow = drop_shadow(core_types::Color::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 1.), DVec2::new(0., 20.), 0., 0.); + let flag = warp_effect(WarpStyle::Flag, 0.25, square_on(DAffine2::from_mat2(slant))); + + // The shadow alone, and with a flag too slight to move the content more than a pixel + let size = UVec2::new(240, 160); + let draw = |effects: &[graphic_types::EffectOperation]| { + let mut item = patterned_raster(0., &[], 1.).with_attribute(ATTR_TRANSFORM, skewed); + effects.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation))); + let graphic = Graphic::RasterCPU(Box::new(item)); + render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) + }; + let (Some(alone), Some(flagged)) = (draw(std::slice::from_ref(&shadow)), draw(&[shadow.clone(), flag])) else { + return; + }; + + // Wherever the shadow alone shows well within the slanted square, so does the flagged one, and wherever it shows well past the square, the flagged one is clear + let alpha = |pixels: &[[u8; 4]], index: u32| pixel(pixels, size, index % size.x, index / size.x)[3]; + let local = |index: u32| skewed.inverse().transform_point2(DVec2::new((index % size.x) as f64 + 0.5, (index / size.x) as f64 + 0.5)); + let shown: Vec = (0..size.x * size.y).filter(|&index| alpha(&alone, index) > 192).collect(); + let within: Vec = shown + .iter() + .copied() + .filter(|&index| local(index).cmpgt(DVec2::splat(0.03)).all() && local(index).cmplt(DVec2::splat(0.97)).all()) + .collect(); + let past: Vec = shown + .iter() + .copied() + .filter(|&index| local(index).cmplt(DVec2::splat(-0.03)).any() || local(index).cmpgt(DVec2::splat(1.03)).any()) + .collect(); + assert!(past.len() > 500, "only {} pixels of the shadow lie past the slanted square", past.len()); + + let missing = within.iter().filter(|&&index| alpha(&flagged, index) < 64).count(); + assert!(missing <= 2, "{missing} pixels of the content are missing within the slanted square"); + let kept = past.iter().filter(|&&index| alpha(&flagged, index) > 1).count(); + assert!(kept == 0, "{kept} pixels of the shadow show past the slanted square"); +} + +#[test] +fn warp_effects_clear_what_a_minimum_grows_past_a_turned_square() { + use core_types::ATTR_TRANSFORM; + use core_types::list::{ATTR_APPEARANCE, List}; + use glam::DVec2; + use graphic_types::{Appearance, Coverage, Effect, Graphic, Vector, WarpStyle, stamp_effect}; + use rendering::{Render, RenderParams}; + use vello_gpu::kurbo::Shape; + + // An opaque rectangle 200 by 100 turned 45 degrees when its effects were stamped, within a square on it, then left turned or turned back upright, + // so a minimum's square leans across the rectangle and grows it past each side by the square's half diagonal + let centered = |transform: DAffine2| DAffine2::from_translation(DVec2::splat(200.)) * transform * DAffine2::from_translation(-DVec2::new(100., 50.)); + let turned = centered(DAffine2::from_angle(std::f64::consts::FRAC_PI_4)); + let minimum = minimum_maximum(20., MinimumMaximumMode::Minimum); + let flag = warp_effect(WarpStyle::Flag, 0.25, DAffine2::from_mat2(turned.matrix2) * square_on(DAffine2::from_scale(DVec2::new(200., 100.)))); + let size = UVec2::splat(400); + + for placement in [turned, centered(DAffine2::IDENTITY)] { + // The grown rectangle alone, and with a flag too slight to move the content more than a pixel + let draw = |effects: &[graphic_types::EffectOperation]| { + let mut item = Vector::item_from_bezpath(&Rect::new(0., 0., 200., 100.).to_path(0.1)); + item.set_attribute( + ATTR_APPEARANCE, + Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(core_types::Color::WHITE))), + ); + item.set_attribute(ATTR_TRANSFORM, turned); + effects.iter().for_each(|operation| stamp_effect(&mut item, Effect::new(operation))); + item.set_attribute(ATTR_TRANSFORM, placement); + let graphic = Graphic::Vector(Box::new(item)); + render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) + }; + let (Some(alone), Some(flagged)) = (draw(std::slice::from_ref(&minimum)), draw(&[minimum.clone(), flag.clone()])) else { + return; + }; + + // Wherever the grown rectangle alone shows well within the square, so does the flagged one, and wherever it shows well past the square, the flagged one is clear + let alpha = |pixels: &[[u8; 4]], index: u32| pixel(pixels, size, index % size.x, index / size.x)[3]; + let local = |index: u32| placement.inverse().transform_point2(DVec2::new((index % size.x) as f64 + 0.5, (index / size.x) as f64 + 0.5)); + let shown: Vec = (0..size.x * size.y).filter(|&index| alpha(&alone, index) > 192).collect(); + let within: Vec = shown + .iter() + .copied() + .filter(|&index| local(index).cmpgt(DVec2::splat(3.)).all() && local(index).cmplt(DVec2::new(197., 97.)).all()) + .collect(); + let past: Vec = shown + .iter() + .copied() + .filter(|&index| local(index).cmplt(DVec2::splat(-3.)).any() || local(index).cmpgt(DVec2::new(203., 103.)).any()) + .collect(); + assert!(past.len() > 500, "placed at {placement}, only {} pixels of the grown rectangle lie past its square", past.len()); + + let missing = within.iter().filter(|&&index| alpha(&flagged, index) < 64).count(); + assert!(missing <= 2, "placed at {placement}, {missing} pixels of the rectangle are missing within its square"); + let kept = past.iter().filter(|&&index| alpha(&flagged, index) > 1).count(); + assert!(kept == 0, "placed at {placement}, {kept} pixels of the grown rectangle show past its square"); + } +} + +#[test] +fn warp_effects_leave_what_earlier_warps_bent_before_a_stretch_alike_on_the_cpu_and_gpu() { + use core_types::ATTR_TRANSFORM; + use glam::DVec2; + use graphic_types::{Effect, Graphic, WarpStyle, stamp_effect}; + use rendering::{Render, RenderParams}; + + let size = UVec2::new(560, 200); + + // A square bent into an arc within a square on it, then stretched four times as wide, its ends then far past its sides, past the square of a warp stamped after the stretch + let stretched = DAffine2::from_translation(DVec2::new(180., 70.)) * DAffine2::from_scale(DVec2::new(200., 50.)); + let arc = warp_effect(WarpStyle::Arc, 50., square_on(DAffine2::from_scale(DVec2::splat(50.)))); + for second in [WarpStyle::Flag, WarpStyle::Twist] { + let mut item = patterned_raster(0., std::slice::from_ref(&arc), 1.).with_attribute(ATTR_TRANSFORM, stretched); + stamp_effect(&mut item, Effect::new(&warp_effect(second, 30., square_on(DAffine2::from_mat2(stretched.matrix2))))); + + // The GPU's warps, beside the CPU's warped image drawn plainly, with pixels four times as wide as the render's + let warped = Graphic::RasterCPU(Box::new(item.clone())); + let Some(gpu) = render(size, |scene| warped.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + let evaluated = Graphic::RasterCPU(Box::new(raster_kernels::evaluate_raster_effects(item))); + let Some(cpu) = render(size, |scene| evaluated.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + // Each shows the content wherever the other does + let alpha = |pixels: &[[u8; 4]], index: u32| pixel(pixels, size, index % size.x, index / size.x)[3]; + let shown_by_one = |index: &u32| (alpha(&gpu, *index) > 192 && alpha(&cpu, *index) < 64) || (alpha(&cpu, *index) > 192 && alpha(&gpu, *index) < 64); + let differing = (0..size.x * size.y).filter(shown_by_one).count(); + assert!(differing <= 2, "after {second:?}, {differing} pixels of the content show on only one of the CPU and GPU"); + } +} + +#[test] +fn warp_effects_stretched_after_they_bend_keep_their_bend_stretched() { + use core_types::ATTR_TRANSFORM; + use glam::DVec2; + use graphic_types::{Graphic, WarpStyle}; + use rendering::{Render, RenderParams}; + + // A square 50 across bent into an arc within a square on it, then stretched four times as wide, as a transform after the warp does + let arc = warp_effect(WarpStyle::Arc, 50., square_on(DAffine2::from_scale(DVec2::splat(50.)))); + let stretched = DAffine2::from_translation(DVec2::new(160., 40.)) * DAffine2::from_scale(DVec2::new(200., 50.)); + let graphic = Graphic::RasterCPU(Box::new(patterned_raster(0., std::slice::from_ref(&arc), 1.).with_attribute(ATTR_TRANSFORM, stretched))); + let size = UVec2::new(520, 140); + let Some(image) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + // The square's arcs stretched with it, their ends 0.707 of its width past its sides and their top 0.207 of its height above it + let painted = (0..size.x * size.y).filter(|index| pixel(&image, size, index % size.x, index / size.x)[3] > 128); + let (left, right, top) = painted.fold((size.x, 0, size.y), |(left, right, top), index| { + (left.min(index % size.x), right.max(index % size.x), top.min(index / size.x)) + }); + let within = |edge: u32, expected: f64| (edge as f64 - expected).abs() < 3.; + assert!(within(left, 18.6) && within(right, 501.4) && within(top, 29.6), "the bend spans {left} to {right} from {top} down"); +} diff --git a/node-graph/libraries/wgpu-executor/src/vello_resample.wgsl b/node-graph/libraries/wgpu-executor/src/vello_resample.wgsl index ff630ad6c8..7b02412eae 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_resample.wgsl +++ b/node-graph/libraries/wgpu-executor/src/vello_resample.wgsl @@ -244,6 +244,112 @@ fn frame_coverage(local: vec2, half: vec2, half_texel: vec2) -> v return clamp(0.5 + (half - abs(local)) / (2. * half_texel), vec2(0.), vec2(1.)); } +// Matching `CLIPPED_CORNERS` +const CLIPPED_CORNERS: i32 = 8; + +// How much of the texel at `texel` (its corner) the frame covers, which reaches `texel_extent` along its sides: the share of its area left after clipping it by each of the frame's sides, matching the CPU's `pixel_area_within` +fn texel_area_within(frame: Frame, texel: vec2, texel_extent: vec2) -> f32 { + let center = transform_point(frame.texels_to_local, texel + 0.5); + let half = frame.half_size; + + // Wholly within the frame, or wholly past one of its sides + if all(abs(center) + texel_extent <= half) { + return 1.; + } + if any(abs(center) - texel_extent >= half) { + return 0.; + } + + // The texel's corners relative to its center, clipped by one side after another, each replacing the corners past it with where the edges cross it + var corners = array, CLIPPED_CORNERS>(vec2(-0.5, -0.5), vec2(0.5, -0.5), vec2(0.5, 0.5), vec2(-0.5, 0.5), vec2(0.), vec2(0.), vec2(0.), vec2(0.)); + var count = 4; + for (var side = 0; side < 4; side++) { + // How far past the side a corner lies, beyond the positive or negative end of the local axis it bounds (x for the first two sides, y for the others) + let sign = select(1., -1., side % 2 == 1); + let along_y = side >= 2; + let row = select(vec2(frame.texels_to_local[0].x, frame.texels_to_local[1].x), vec2(frame.texels_to_local[0].y, frame.texels_to_local[1].y), along_y); + let direction = row * sign; + let offset = select(sign * center.x - half.x, sign * center.y - half.y, along_y); + + var clipped = array, CLIPPED_CORNERS>(); + var clipped_count = 0; + var previous = corners[count - 1]; + for (var index = 0; index < count; index++) { + let current = corners[index]; + let previous_past = dot(direction, previous) + offset; + let current_past = dot(direction, current) + offset; + if (previous_past > 0.) != (current_past > 0.) && clipped_count < CLIPPED_CORNERS { + clipped[clipped_count] = mix(previous, current, previous_past / (previous_past - current_past)); + clipped_count++; + } + if current_past <= 0. && clipped_count < CLIPPED_CORNERS { + clipped[clipped_count] = current; + clipped_count++; + } + previous = current; + } + + if clipped_count == 0 { + return 0.; + } + corners = clipped; + count = clipped_count; + } + + // The area of what's left, by the shoelace formula + var twice_area = 0.; + for (var index = 0; index < count; index++) { + let next = corners[(index + 1) % count]; + twice_area += corners[index].x * next.y - corners[index].y * next.x; + } + return min(abs(twice_area) / 2., 1.); +} + +// The source at a point in texels interpolated as `sample_bilinear` does, with each of the four texels weighted by the share of it the frame covers (see `texel_area_within`), so none the frame misses is read, matching the CPU's `sample_bilinear_within`. +// Where the frame covers none of them, the nearest it covers among the 16 around stands in, the first of those equally near. +fn sample_bilinear_within(frame: Frame, point: vec2, texel_extent: vec2) -> vec4 { + let position = point - 0.5; + let base = floor(position); + let fraction = position - base; + + // The four texels around, then only if the frame covers none of them the 16 around, taking turns through one call so the shader compiles quickly + var sum = vec4(0.); + var total = 0.; + var nearest = vec4(0.); + var nearest_distance = -1.; + for (var index = 0; index < 20; index++) { + if index == 4 && total > 0. { + break; + } + + let bilinear = index < 4; + let around = index - 4; + let offset = select(vec2(f32(around % 4 - 1), f32(around / 4 - 1)), vec2(f32(index % 2), f32(index / 2)), bilinear); + let texel = base + offset; + let distance_squared = dot(texel + 0.5 - point, texel + 0.5 - point); + if !bilinear && nearest_distance >= 0. && distance_squared >= nearest_distance { + continue; + } + + let area = texel_area_within(frame, texel, texel_extent); + if bilinear { + let weights = mix(1. - fraction, fraction, offset); + let weight = weights.x * weights.y * area; + if weight > 0. { + sum += texel_or_transparent(vec2(texel)) * weight; + total += weight; + } + } else if area > 0. { + nearest = texel_or_transparent(vec2(texel)); + nearest_distance = distance_squared; + } + } + if total > 0. { + return sum / total; + } + return nearest; +} + // 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 diff --git a/node-graph/libraries/wgpu-executor/src/vello_warp.wgsl b/node-graph/libraries/wgpu-executor/src/vello_warp.wgsl new file mode 100644 index 0000000000..0fc444bbe2 --- /dev/null +++ b/node-graph/libraries/wgpu-executor/src/vello_warp.wgsl @@ -0,0 +1,452 @@ +// The Warp's pass, drawing the fringe past its square's sides and corners, then each cell of its tessellated patch as two triangles over those before, +// from clear, matching the CPU's `WarpRasterizer`. +// Its square lies in `taps[0..5]`, then from `WARP_TAPS` its patch's control points in texels, how far its edge fades across its sides and which sides it reaches, and where its parameters read the content (see `warp_taps`). + +// Matching `WARP_POLISH_STEPS` +const WARP_POLISH_STEPS: i32 = 2; + +// Matching `WARP_NEAREST_STEPS` +const WARP_NEAREST_STEPS: i32 = 3; + +// Matching `WARP_MITER_LIMIT` +const WARP_MITER_LIMIT: f32 = 2.; + +// Matching `WARP_FRINGE_PIXELS` +const WARP_FRINGE_TEXELS: f32 = 2. * WARP_MITER_LIMIT; + +// Matching `TESSELLATION_TAPS` +const WARP_TAPS: u32 = 5u; + +struct WarpVertex { + @builtin(position) position: vec4, + @location(0) st: vec2, + // What the triangle draws (see the CPU's `WarpFragment`): 0 within the square, 1 to 4 past its left, right, top, or bottom side, and 5 to 8 past its top left, top right, bottom left, or bottom right corner + @location(1) @interpolate(flat) fragment: u32, +} + +// The patch's control point in `row` and `column`, in the texels +fn warp_control(row: u32, column: u32) -> vec2 { + let index = row * 4u + column; + let tap = parameters.taps[WARP_TAPS + index / 2u]; + return select(tap.xy, tap.zw, index % 2u == 1u); +} + +// The four cubic Bernstein polynomials at `t` and their slopes, continuing past 0 and 1 along their tangents there, matching the CPU's `extended_bases` +struct WarpBases { + values: vec4, + slopes: vec4, +} + +fn warp_bases(t: f32) -> WarpBases { + if t < 0. { + return WarpBases(vec4(1. - 3. * t, 3. * t, 0., 0.), vec4(-3., 3., 0., 0.)); + } + if t > 1. { + let past = t - 1.; + return WarpBases(vec4(0., 0., -3. * past, 1. + 3. * past), vec4(0., 0., -3., 3.)); + } + let rest = 1. - t; + return WarpBases( + vec4(rest * rest * rest, 3. * t * rest * rest, 3. * t * t * rest, t * t * t), + vec4(-3. * rest * rest, 3. * rest * rest - 6. * t * rest, 6. * t * rest - 3. * t * t, 3. * t * t), + ); +} + +// Where the patch carries the parameters `st` in the texels, and how fast that moves along s and t, matching the CPU's `WarpMesh::point_and_tangents` +struct WarpPoint { + point: vec2, + along_s: vec2, + along_t: vec2, +} + +fn warp_point(st: vec2) -> WarpPoint { + let across = warp_bases(st.x); + let down = warp_bases(st.y); + + var result = WarpPoint(vec2(0.), vec2(0.), vec2(0.)); + for (var row = 0u; row < 4u; row++) { + for (var column = 0u; column < 4u; column++) { + let control = warp_control(row, column); + result.point += control * (down.values[row] * across.values[column]); + result.along_s += control * (down.values[row] * across.slopes[column]); + result.along_t += control * (down.slopes[row] * across.values[column]); + } + } + return result; +} + +// The point at `t` of the cubic Bezier curve with control points `a` to `d`, and its first and second derivatives there, matching the CPU's `cubic_at` +struct WarpCubic { + point: vec2, + first: vec2, + second: vec2, +} + +fn warp_cubic(a: vec2, b: vec2, c: vec2, d: vec2, t: f32) -> WarpCubic { + let rest = 1. - t; + return WarpCubic( + a * (rest * rest * rest) + b * (3. * t * rest * rest) + c * (3. * t * t * rest) + d * (t * t * t), + (b - a) * (3. * rest * rest) + (c - b) * (6. * t * rest) + (d - c) * (3. * t * t), + (c - b * 2. + a) * (6. * rest) + (d - c * 2. + b) * (6. * t), + ); +} + +// Control point `index` of the curve the patch bends `side` (0 to 3, left, right, top, and bottom) into, along it, matching the CPU's `WarpTessellation::side_curves` +fn warp_side_control(side: u32, index: u32) -> vec2 { + let row = select(index, select(0u, 3u, side == 3u), side >= 2u); + let column = select(select(0u, 3u, side == 1u), index, side >= 2u); + return warp_control(row, column); +} + +// Control point `index` of the cubic of the patch's tangent across `side`, heading into the square +fn warp_across_control(side: u32, index: u32) -> vec2 { + let row = select(index, select(1u, 2u, side == 3u), side >= 2u); + let column = select(select(1u, 2u, side == 1u), index, side >= 2u); + return 3. * (warp_control(row, column) - warp_side_control(side, index)); +} + +fn warp_side_curve(side: u32, t: f32) -> WarpCubic { + return warp_cubic(warp_side_control(side, 0u), warp_side_control(side, 1u), warp_side_control(side, 2u), warp_side_control(side, 3u), t); +} + +fn warp_side_across(side: u32, t: f32) -> vec2 { + return warp_cubic(warp_across_control(side, 0u), warp_across_control(side, 1u), warp_across_control(side, 2u), warp_across_control(side, 3u), t).point; +} + +// How fast the square's local coordinate measured across `side` changes in the texels +fn warp_side_gradient_length(side: u32) -> f32 { + let texels_to_local = frame_parameters().texels_to_local; + return length(select(vec2(texels_to_local[0].x, texels_to_local[1].x), vec2(texels_to_local[0].y, texels_to_local[1].y), side >= 2u)); +} + +// The unit normal of `side`'s curve where its tangent is `tangent`, facing into the square as the patch carries it, matching the CPU's `WarpTessellation::side_normal` +fn warp_side_normal(side: u32, tangent: vec2) -> vec2 { + let handedness = select(-1., 1., side == 1u || side == 2u); + return vec2(-tangent.y, tangent.x) / max(length(tangent), 1e-30) * (handedness * parameters.values.x); +} + +// Whether the fringe past `side` is drawn, where the patch reaches it +fn warp_has_side(side: u32) -> bool { + return ((u32(parameters.taps[WARP_TAPS + 8u].z) >> side) & 1u) == 1u; +} + +// How far the edge fades each way across `side`, in the texels square to it +fn warp_fringe(side: u32) -> f32 { + return select(parameters.taps[WARP_TAPS + 8u].x, parameters.taps[WARP_TAPS + 8u].y, side >= 2u); +} + +// How far the fringe past `side` reaches from its point at the parameter `along` it, in the texels, matching the CPU's `WarpTessellation::outward` +fn warp_outward(side: u32, along: f32) -> vec2 { + return -warp_side_normal(side, warp_side_curve(side, along).first) * 2. * warp_fringe(side); +} + +// How far the fringe reaches past the square's corner `corner`, past its left or right side (`xy`) and past its top or bottom one (`zw`), in the texels, +// matching the CPU's `WarpTessellation::corner_outward` +fn warp_corner_outward(corner: u32) -> vec4 { + let side_x = corner % 2u; + let side_y = 2u + corner / 2u; + let end_x = f32(corner / 2u); + let end_y = f32(corner % 2u); + let reach_x = 2. * warp_fringe(side_x); + let reach_y = 2. * warp_fringe(side_y); + + // Each side's normal at the corner, and its tangent heading from the corner along it + let tangent_x = warp_side_curve(side_x, end_x).first; + let tangent_y = warp_side_curve(side_y, end_y).first; + let normal_x = warp_side_normal(side_x, tangent_x); + let normal_y = warp_side_normal(side_y, tangent_y); + let heading_x = tangent_x * (1. - 2. * end_x) / max(length(tangent_x), 1e-30); + let heading_y = tangent_y * (1. - 2. * end_y) / max(length(tangent_y), 1e-30); + let sine_x = dot(normal_x, heading_y); + let sine_y = dot(normal_y, heading_x); + + // The square's own corners, as sharp as its axes are slanted in the texels + let texels_to_local = frame_parameters().texels_to_local; + let determinant = texels_to_local[0].x * texels_to_local[1].y - texels_to_local[1].x * texels_to_local[0].y; + let square_sine = abs(determinant) / (warp_side_gradient_length(0u) * warp_side_gradient_length(2u)); + + if sine_x * WARP_MITER_LIMIT >= square_sine && sine_y * WARP_MITER_LIMIT >= square_sine { + return vec4(-heading_y * (reach_x / sine_x), -heading_x * (reach_y / sine_y)); + } + return vec4(-normal_x * reach_x, -normal_y * reach_y); +} + +// How much of the texel at `texel_center` lies inside the curve the patch bends `side` into, along the side's axis, and the parameter along the side where it's nearest, +// matching the CPU's `WarpTessellation::side_coverage` +struct WarpSideCoverage { + coverage: f32, + along: f32, +} + +fn warp_side_coverage(side: u32, seed: f32, texel_center: vec2) -> WarpSideCoverage { + var along = clamp(seed, 0., 1.); + var nearest = WarpCubic(vec2(0.), vec2(0.), vec2(0.)); + var nearest_along = along; + var nearest_distance = 3.4e38; + for (var step = 0; step <= WARP_NEAREST_STEPS; step++) { + let curve = warp_side_curve(side, along); + let offset = curve.point - texel_center; + if dot(offset, offset) < nearest_distance { + nearest = curve; + nearest_along = along; + nearest_distance = dot(offset, offset); + } + if step == WARP_NEAREST_STEPS { + break; + } + + let slope = dot(offset, curve.first); + let curvature = dot(curve.first, curve.first) + dot(offset, curve.second); + let change = select(slope / max(dot(curve.first, curve.first), 1.17549435e-38), slope / curvature, curvature > 0.); + along = clamp(along - change, 0., 1.); + } + + // Farther from the nearest point found than the fringe reaches past it, the texel lies far within, or the search landed on a far part of the curve facing elsewhere, so it isn't faded + if nearest_distance > WARP_FRINGE_TEXELS * WARP_FRINGE_TEXELS { + return WarpSideCoverage(1., nearest_along); + } + let distance = dot(warp_side_normal(side, nearest.first), texel_center - nearest.point) * warp_side_gradient_length(side); + let half_fade = select(parameters.taps[4].x, parameters.taps[4].y, side >= 2u); + return WarpSideCoverage(clamp(0.5 + distance / (2. * half_fade), 0., 1.), nearest_along); +} + +// Control point `index` of the patch's line through the parameters level with `along` across a side on the square's `down` axis or across it, from its Bernstein `bases` there +fn warp_line_control(down: bool, index: u32, bases: vec4) -> vec2 { + var point = vec2(0.); + for (var other = 0u; other < 4u; other++) { + point += select(warp_control(other, index), warp_control(index, other), down) * bases[other]; + } + return point; +} + +// Whether the sheet heads into the square from `side` and runs out to the parameters `st` across it without folding back, matching the CPU's `WarpTessellation::unfolded_from_side` +fn warp_unfolded_from_side(side: u32, st: vec2) -> bool { + let down = side >= 2u; + let along = clamp(select(st.y, st.x, down), 0., 1.); + let curve = warp_side_curve(side, along); + let across = warp_side_across(side, along); + let normal = warp_side_normal(side, curve.first); + if dot(across, normal) <= 0. { + return false; + } + + // The patch's line through the parameters, across the side + let rest = 1. - along; + let bases = vec4(rest * rest * rest, 3. * along * rest * rest, 3. * along * along * rest, along * along * along); + let line = array, 4>(warp_line_control(down, 0u, bases), warp_line_control(down, 1u, bases), warp_line_control(down, 2u, bases), warp_line_control(down, 3u, bases)); + + // Its speed away from the side's curve from the side to the parameters, heading into the square + let start = select(0., 1., side % 2u == 1u); + let end = clamp(select(st.x, st.y, down), 0., 1.); + let heading = select(1., -1., side % 2u == 1u); + let at_start = warp_cubic(line[0], line[1], line[2], line[3], start); + let at_end = warp_cubic(line[0], line[1], line[2], line[3], end); + let start_speed = heading * dot(normal, at_start.first); + let end_speed = heading * dot(normal, at_end.first); + let middle = start_speed + (end - start) / 2. * heading * dot(normal, at_start.second); + return start_speed > 0. && end_speed > 0. && (middle > 0. || start_speed * end_speed > middle * middle); +} + +// Where the parameters (s, t) read the content, in the texels +fn warp_source_to_texels() -> mat3x2 { + return mat3x2(parameters.taps[WARP_TAPS + 9u].xy, parameters.taps[WARP_TAPS + 9u].zw, parameters.taps[WARP_TAPS + 10u].xy); +} + +// The nearer side to the parameters `st` on the square's `axis` (0 across, 1 down) +fn warp_nearer_side(axis: u32, st: vec2) -> u32 { + let local = transform_point(frame_parameters().texels_to_local, transform_point(warp_source_to_texels(), st)); + return 2u * axis + select(0u, 1u, select(local.x, local.y, axis == 1u) > 0.); +} + +// How much of the texel at `texel_center` the sheet beside `side` covers along its axis, where the fringe there is drawn, from the parameter `along` the side +fn warp_from_side(side: u32, along: f32, texel_center: vec2) -> f32 { + if !warp_has_side(side) { + return 1.; + } + return warp_side_coverage(side, along, texel_center).coverage; +} + +// How much of the texel at `texel_center` a fragment within the square covers along `axis`, from its polished parameters `st` +fn warp_within_coverage(axis: u32, st: vec2, texel_center: vec2) -> f32 { + let side = warp_nearer_side(axis, st); + if !warp_has_side(side) { + return 1.; + } + + // Far past the side's curve, the sheet covers the texel along its axis, as it does where it folds back over the side from deeper within the square + let a = warp_side_control(side, 0u); + let b = warp_side_control(side, 1u); + let c = warp_side_control(side, 2u); + let d = warp_side_control(side, 3u); + let reach = warp_fringe(side); + let far = any(texel_center < min(min(a, b), min(c, d)) - reach) || any(texel_center > max(max(a, b), max(c, d)) + reach); + if far || !warp_unfolded_from_side(side, st) { + return 1.; + } + return warp_side_coverage(side, select(st.y, st.x, axis == 1u), texel_center).coverage; +} + +// What a fragment of the triangles shows at the texel at `texel_center`, from the parameters `st` it interpolates there (polished within the square), matching the CPU's `WarpTessellation::shade` +struct WarpShade { + coverage: f32, + read: vec2, +} + +fn warp_shade(fragment: u32, st: vec2, texel_center: vec2) -> WarpShade { + if fragment == 0u { + return WarpShade(warp_within_coverage(0u, st, texel_center) * warp_within_coverage(1u, st, texel_center), st); + } + if fragment <= 4u { + let side = fragment - 1u; + let down = side >= 2u; + let nearest = warp_side_coverage(side, select(st.y, st.x, down), texel_center); + let position = f32(side % 2u); + let read = select(vec2(position, nearest.along), vec2(nearest.along, position), down); + let other_axis = select(1u, 0u, down); + return WarpShade(nearest.coverage * warp_from_side(warp_nearer_side(other_axis, read), position, texel_center), read); + } + let corner = fragment - 5u; + let read = vec2(f32(corner % 2u), f32(corner / 2u)); + return WarpShade(warp_from_side(corner % 2u, read.y, texel_center) * warp_from_side(2u + corner / 2u, read.x, texel_center), read); +} + +// The parameters of the grid's corner `index` (its column and row) +fn warp_grid_parameters(index: vec2) -> vec2 { + return vec2(index) / parameters.taps[WARP_TAPS + 10u].zw; +} + +// The corner (0 to 3) of a fringe's quad that the vertex `index` among its six takes, as its two triangles take its corners 0, 1, 2, then 0, 2, 3 +fn warp_quad_corner(index: u32) -> u32 { + return select(select(index, 0u, index == 3u), select(2u, 3u, index == 5u), index >= 4u); +} + +// The grid's index of corner `corner` (0 to 5) of the `cell`, as its two triangles take its top left, top right, and bottom right corners, then its top left, bottom right, and bottom left +fn warp_cell_corner(cell: vec2, corner: u32) -> vec2 { + return cell + vec2(select(0u, 1u, corner == 1u || corner == 2u || corner == 4u), select(0u, 1u, corner == 2u || corner == 4u || corner == 5u)); +} + +// The fringe's quads along the left, right, top, and bottom sides, then past the corners where both sides meet, then each cell's two triangles, cell by cell across each row and row by row down, +// matching the CPU's `WarpRasterizer`. The first instance draws the fringe and the triangles wound as the square is (`values.x` its orientation's sign), and the second draws those turned over, on top. +@vertex +fn warp_vertex(@builtin(vertex_index) index: u32, @builtin(instance_index) instance: u32) -> WarpVertex { + let cells = vec2(parameters.taps[WARP_TAPS + 10u].zw); + let fringe_vertices = 12u * (cells.x + cells.y); + let corner_vertices = 24u; + + var grid_index = vec2(0u); + var offset = vec2(0.); + var fragment = 0u; + var shown = true; + if index < fringe_vertices { + // A side's quad, with its inner edge on the side and its outer edge past it + let left_and_right = 6u * cells.y; + var side = 0u; + var within = index; + if within >= 2u * left_and_right { + within -= 2u * left_and_right; + side = 2u + within / (6u * cells.x); + within = within % (6u * cells.x); + } else { + side = within / left_and_right; + within = within % left_and_right; + } + let quad_corner = warp_quad_corner(within % 6u); + let along = within / 6u + select(0u, 1u, quad_corner == 1u || quad_corner == 2u); + let position = select(0u, select(cells.x, cells.y, side >= 2u), side % 2u == 1u); + grid_index = select(vec2(position, along), vec2(along, position), side >= 2u); + if quad_corner >= 2u { + // At a corner where the other side's fringe meets it, it reaches as far as the corner's quad does + let last = select(cells.y, cells.x, side >= 2u); + let end = select(0u, 1u, along == last); + let other = select(2u + end, end, side >= 2u); + if (along == 0u || along == last) && warp_has_side(other) { + let reach = warp_corner_outward(select(side + 2u * end, end + 2u * (side % 2u), side >= 2u)); + offset = select(reach.xy, reach.zw, side >= 2u); + } else { + let parameters_along = warp_grid_parameters(grid_index); + offset = warp_outward(side, select(parameters_along.y, parameters_along.x, side >= 2u)); + } + } + fragment = 1u + side; + shown = warp_has_side(side) && instance == 0u; + } else if index < fringe_vertices + corner_vertices { + // A corner's quad, reaching past it as far as the fringes of its sides + let within = index - fringe_vertices; + let corner = within / 6u; + let quad_corner = warp_quad_corner(within % 6u); + grid_index = vec2((corner % 2u) * cells.x, (corner / 2u) * cells.y); + let reach = warp_corner_outward(corner); + if quad_corner == 1u || quad_corner == 2u { + offset += reach.xy; + } + if quad_corner >= 2u { + offset += reach.zw; + } + fragment = 5u + corner; + shown = warp_has_side(corner % 2u) && warp_has_side(2u + corner / 2u) && instance == 0u; + } else { + // A cell's corner, drawn in the instance for its triangle's winding + let within = index - fringe_vertices - corner_vertices; + let cell = vec2((within / 6u) % cells.x, (within / 6u) / cells.x); + let corner = within % 6u; + let first = corner - corner % 3u; + let a = warp_point(warp_grid_parameters(warp_cell_corner(cell, first))).point; + let b = warp_point(warp_grid_parameters(warp_cell_corner(cell, first + 1u))).point; + let c = warp_point(warp_grid_parameters(warp_cell_corner(cell, first + 2u))).point; + let reversed = ((b - a).x * (c - a).y - (b - a).y * (c - a).x) * parameters.values.x < 0.; + grid_index = warp_cell_corner(cell, corner); + shown = reversed == (instance == 1u); + } + + let st = warp_grid_parameters(grid_index); + if !shown { + return WarpVertex(vec4(-2., -2., 0., 1.), st, fragment); + } + let texel = warp_point(st).point + offset; + return WarpVertex(vec4(texel * parameters.target_to_uv * vec2(2., -2.) + vec2(-1., 1.), 0., 1.), st, fragment); +} + +// The parameters the patch carries onto the texel center `goal`, polished by Newton's method from the `seed` its triangle interpolates, matching the CPU's `WarpTessellation::polished` +fn warp_polished(seed: vec2, goal: vec2) -> vec2 { + let cell = 1. / parameters.taps[WARP_TAPS + 10u].zw; + + var st = seed; + var seed_distance = 0.; + for (var polish = 0; polish < WARP_POLISH_STEPS; polish++) { + let at = warp_point(st); + let residual = at.point - goal; + if polish == 0 { + seed_distance = length(residual); + } + + let determinant = at.along_s.x * at.along_t.y - at.along_s.y * at.along_t.x; + if abs(determinant) <= 1e-6 * length(at.along_s) * length(at.along_t) { + break; + } + let step = vec2(residual.x * at.along_t.y - residual.y * at.along_t.x, at.along_s.x * residual.y - at.along_s.y * residual.x) / determinant; + if any(abs(step) > cell) { + return seed; + } + st -= step; + } + + let distance = length(warp_point(st).point - goal); + if distance <= 0.5 && distance <= seed_distance { + return st; + } + return seed; +} + +// Each texel of a triangle shows the content its fragment reads (polished onto the patch within the square), faded by how much of the texel the warped square covers, which blending paints over what's beneath +@fragment +fn warp_effect(vertex: WarpVertex) -> @location(0) vec4 { + var st = vertex.st; + if vertex.fragment == 0u { + st = warp_polished(vertex.st, vertex.position.xy); + } + let shade = warp_shade(vertex.fragment, st, vertex.position.xy); + if shade.coverage <= 0. { + return vec4(0.); + } + return sample_bilinear_within(frame_parameters(), transform_point(warp_source_to_texels(), shade.read), parameters.taps[4].zw) * shade.coverage; +} diff --git a/node-graph/nodes/blending/src/distortions.rs b/node-graph/nodes/blending/src/distortions.rs index be25b9f2f7..04b698fa67 100644 --- a/node-graph/nodes/blending/src/distortions.rs +++ b/node-graph/nodes/blending/src/distortions.rs @@ -3,7 +3,7 @@ use core_types::{ATTR_TRANSFORM, Color, Ctx}; use glam::{DAffine2, DVec2}; use graphic_types::raster_types::{CPU, GPU, Raster}; use graphic_types::resampling::MAX_WAVE_GENERATORS; -use graphic_types::{DisplaceMode, Effect, EffectOperation, Generator, Graphic, RadialBlurMethod, Vector, WaveType, linked_to_content, stamp_effect}; +use graphic_types::{DisplaceMode, Effect, EffectOperation, Generator, Graphic, RadialBlurMethod, Vector, WarpStyle, WaveType, linked_to_content, stamp_effect}; use vector_types::{Gradient, GradientSpread}; /// Smears the input graphics along a line, as if they moved while being captured. @@ -193,6 +193,54 @@ fn polar_coordinates( content } +/// Bends the input graphics within a box into a preset shape, like an arc, a flag, or a fish, clearing everything outside the bent box. +#[node_macro::node(category("Raster: Filter"))] +#[allow(clippy::too_many_arguments)] +fn warp( + _: impl Ctx, + /// The content to bend. + #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String, Generator)] + content: Item, + /// The shape the box bends into. + style: Item, + /// Bends the box's left and right edges instead of its top and bottom. + vertical: Item, + /// How strongly the shape bends the box, the other way when negative. + #[unit("%")] + #[range] + #[hard(-100..100)] + #[default(50.)] + bend: Item, + /// How much taller the box's right side grows than its left, or the left than the right when negative, as if turned away in perspective. + #[unit("%")] + #[range] + #[hard(-100..100)] + horizontal_distortion: Item, + /// How much wider the box's bottom grows than its top, or the top than the bottom when negative, as if tipped away in perspective. + #[unit("%")] + #[range] + #[hard(-100..100)] + vertical_distortion: Item, + /// Places the box the content bends within, measured from the origin of the content's local coordinate space. 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::Warp { + style: *style.element(), + bend: *bend.element(), + horizontal_distortion: *horizontal_distortion.element(), + vertical_distortion: *vertical_distortion.element(), + vertical: *vertical.element(), + transform: *transform.element(), + }), + ); + content +} + /// Moves the input graphics by crossing ripples, like the surface of a pond. #[node_macro::node(category("Raster: Filter"))] fn ripple( diff --git a/node-graph/nodes/gstd/src/lib.rs b/node-graph/nodes/gstd/src/lib.rs index 196e69a518..07a342bd95 100644 --- a/node-graph/nodes/gstd/src/lib.rs +++ b/node-graph/nodes/gstd/src/lib.rs @@ -17,7 +17,7 @@ pub use graphic_types::{ Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Cover, CoverPlacement, Coverage, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector, stamp_coverage, }; -pub use graphic_types::{DisplaceMode, RadialBlurMethod, WaveType}; +pub use graphic_types::{DisplaceMode, RadialBlurMethod, WarpStyle, WaveType}; pub use math_nodes; pub use path_bool_nodes; pub use raster_nodes;