mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-06 11:11:48 -10:00
New nodes: 'Twirl', 'Pinch', 'Spherize', and 'Polar Coordinates' (#5042)
Add Twirl, Pinch, Spherize, and Polar Coordinates effects
This commit is contained in:
1 parent
d6ee55b86a
commit
738ea6ac20
22 files changed
+3129
-216
No files matched your search
@@ -1,13 +1,13 @@
|
||||
//! The pixel filters on the CPU, which mirror the renderer's GPU passes on premultiplied gamma-encoded channels.
|
||||
|
||||
use crate::effect_kernels::{BlurKernel, Plane};
|
||||
use crate::generators::pcg3d;
|
||||
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use graphic_types::filters::{
|
||||
Convolution, FieldSampling, GAUSSIAN_NOISE_LIMIT, HIGH_PASS_GRAY, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, average_weight,
|
||||
edge_gain, fill_shifts, neighborhood_radii, noise_extent, unsharp, unsharp_change,
|
||||
};
|
||||
use graphic_types::generator::pcg3d;
|
||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::mandelbrot::{MandelbrotSetup, resolves_in_32_bits};
|
||||
use core_types::Color;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType, hash_fraction, pcg3d};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{Image, ImageError};
|
||||
|
||||
@@ -170,22 +170,7 @@ impl NoiseSampler {
|
||||
/// A random value from 0 to 1 for each cell of a grid, the same for the same seed and cell. In 32-bit math, which a GPU can match.
|
||||
fn white_noise(seed: i32, cell: IVec2) -> f32 {
|
||||
let [hash, _, _] = pcg3d([cell.x as u32, cell.y as u32, seed as u32]);
|
||||
|
||||
// The top 24 bits, which an f32 holds exactly
|
||||
(hash >> 8) as f32 / (1_u32 << 24) as f32
|
||||
}
|
||||
|
||||
/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result.
|
||||
pub(crate) fn pcg3d(input: [u32; 3]) -> [u32; 3] {
|
||||
let mix = |[x, y, z]: [u32; 3]| {
|
||||
let x = x.wrapping_add(y.wrapping_mul(z));
|
||||
let y = y.wrapping_add(z.wrapping_mul(x));
|
||||
let z = z.wrapping_add(x.wrapping_mul(y));
|
||||
[x, y, z]
|
||||
};
|
||||
|
||||
let v = mix(input.map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223)));
|
||||
mix(v.map(|value| value ^ (value >> 16)))
|
||||
hash_fraction(hash)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH
|
||||
use crate::generators::pattern_sampler;
|
||||
use crate::layer_blending::blend_layer;
|
||||
use crate::masks::{feather_strength, mask_strength, masked, masked_box_blur_luminances, masked_radius_blur, masked_radius_blur_codes, variable_box_blur};
|
||||
use crate::resample_kernels::{MotionBlurShear, motion_blurred, radial_blurred};
|
||||
use crate::resample_kernels::{MotionBlurShear, frame_warped, motion_blurred, radial_blurred};
|
||||
use crate::value_effects::{adjustments, evaluate_gradient_effects, filled_color};
|
||||
use core_types::FallibleVec2Operations;
|
||||
use core_types::blending::BlendMode;
|
||||
@@ -26,7 +26,7 @@ use graphic_types::effects::{
|
||||
use graphic_types::filters::sharpens_coverage;
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use graphic_types::masks::masked_radius_blur_levels;
|
||||
use graphic_types::resampling::RadialBlur;
|
||||
use graphic_types::resampling::{FrameWarp, RadialBlur, warp_frame};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{CPU, Image, Raster};
|
||||
use std::collections::HashMap;
|
||||
@@ -170,6 +170,9 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
// Delete this baking once its callers read back the GPU's renders, which are exact.
|
||||
let pixels_per_length = spans_along_axes(effect_to_pixels);
|
||||
|
||||
// The effect space placed on the plane, past its margin
|
||||
let effect_to_plane = DAffine2::from_translation(DVec2::new(margin_x as f64, margin_y as f64)) * DAffine2::from_mat2(effect_to_pixels);
|
||||
|
||||
// A layered effect's coverages become pieces, which the content knocks out once its layer is drawn, and a flattened one is knocked out by the faded content now
|
||||
let layered = index >= layers.flattened;
|
||||
let piece = |plane: usize| layered.then_some(EffectCapture { index, plane });
|
||||
@@ -516,20 +519,38 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
full = in_light(full, !gamma, |plane| motion_blurred(&plane, &shear));
|
||||
filled = filled.map(|filled| in_light(filled, !gamma, |plane| motion_blurred(&plane, &shear)));
|
||||
}
|
||||
EffectOperation::RadialBlur { method, amount, center, gamma } => {
|
||||
EffectOperation::RadialBlur { method, amount, transform, gamma } => {
|
||||
if !effect_to_pixels.determinant().is_normal() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The effect space's origin is the content's, at the image's corner past the margin
|
||||
let effect_to_plane = DAffine2::from_translation(DVec2::new(margin_x as f64, margin_y as f64)) * DAffine2::from_mat2(effect_to_pixels);
|
||||
let blur = RadialBlur::new(method, amount, center);
|
||||
let blur = RadialBlur::new(method, amount, transform);
|
||||
let pixels_per_length = effect_to_pixels.determinant().abs().sqrt();
|
||||
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
full = in_light(full, !gamma, |plane| radial_blurred(&plane, &blur, effect_to_plane, pixels_per_length));
|
||||
filled = filled.map(|filled| in_light(filled, !gamma, |plane| radial_blurred(&plane, &blur, effect_to_plane, pixels_per_length)));
|
||||
}
|
||||
EffectOperation::Twirl { .. } | EffectOperation::Pinch { .. } | EffectOperation::Spherize { .. } | EffectOperation::PolarCoordinates { .. } => {
|
||||
// The frame the warp's transform places from the content's origin, at the image's corner past the margin
|
||||
let Some((warp, transform)) = FrameWarp::of(operation) else { continue };
|
||||
let square = warp_frame(transform, effect_to_plane);
|
||||
let clears = matches!(warp, FrameWarp::Polar { .. });
|
||||
if square.is_none() && !clears {
|
||||
continue;
|
||||
}
|
||||
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
|
||||
// Where its square collapses, Polar Coordinates clears everything
|
||||
let warped = |plane: &Plane<[f32; 4]>| match &square {
|
||||
Some(square) => frame_warped(plane, &warp, square),
|
||||
None => Plane::new(plane.width, plane.height),
|
||||
};
|
||||
full = warped(&full);
|
||||
filled = filled.map(|filled| warped(&filled));
|
||||
}
|
||||
EffectOperation::Adjustment(ref adjustment) => {
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
full = adjust(&full, adjustment);
|
||||
@@ -1332,12 +1353,18 @@ mod tests {
|
||||
distance: 7.,
|
||||
gamma: false,
|
||||
};
|
||||
let spin = EffectOperation::RadialBlur {
|
||||
let spin = |transform| EffectOperation::RadialBlur {
|
||||
method: graphic_types::RadialBlurMethod::Spin,
|
||||
amount: 20.,
|
||||
center: DVec2::new(14.4, 10.8),
|
||||
transform,
|
||||
gamma: false,
|
||||
};
|
||||
let center = DAffine2::from_translation(DVec2::new(14.4, 10.8));
|
||||
let oblong = center * DAffine2::from_angle(0.4) * DAffine2::from_scale(DVec2::new(3., 1.));
|
||||
let twirl = EffectOperation::Twirl {
|
||||
angle: 90.,
|
||||
transform: DAffine2::from_translation(DVec2::splat(12.)) * DAffine2::from_scale(DVec2::new(16., 10.)),
|
||||
};
|
||||
|
||||
// A white square in the middle of a black image, with the blur stamped before a later transform places it
|
||||
let placement = DAffine2::from_translation(DVec2::new(3.3, -7.6)) * DAffine2::from_scale(DVec2::splat(24.));
|
||||
@@ -1351,7 +1378,7 @@ mod tests {
|
||||
};
|
||||
|
||||
// Each of the image's pixels blurs alike however the later transform scales and turns it
|
||||
for operation in [motion, spin] {
|
||||
for operation in [motion, spin(center), spin(oblong), twirl] {
|
||||
let still = evaluated(&operation, DAffine2::IDENTITY);
|
||||
for later in [DAffine2::from_scale(DVec2::splat(3.)), DAffine2::from_angle(0.7)] {
|
||||
let placed = evaluated(&operation, later);
|
||||
@@ -1370,7 +1397,7 @@ mod tests {
|
||||
let spin = EffectOperation::RadialBlur {
|
||||
method: graphic_types::RadialBlurMethod::Spin,
|
||||
amount: 90.,
|
||||
center: DVec2::splat(5.5),
|
||||
transform: DAffine2::from_translation(DVec2::splat(5.5)),
|
||||
gamma: false,
|
||||
};
|
||||
let evaluated = |stamped_at: DAffine2, placed_at: DAffine2| {
|
||||
@@ -1637,6 +1664,46 @@ mod tests {
|
||||
assert_eq!(adjusted(&[emptied, Adjustment::MakeOpaque]), [[0.; 4]; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_that_change_nothing_leave_the_effects_around_them_as_they_are() {
|
||||
use graphic_types::EffectKind;
|
||||
|
||||
let evaluate = |operations: Vec<EffectOperation>| {
|
||||
let item = Item::new_from_element(Raster::new_cpu(Image::new(16, 16, Color::WHITE)))
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(16.)))
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations(operations));
|
||||
evaluate_raster_effects(item).element().data.clone()
|
||||
};
|
||||
let shadow = EffectOperation::default_for(EffectKind::DropShadow);
|
||||
let inner_shadow = EffectOperation::default_for(EffectKind::InnerShadow);
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
// The shadow stays beneath the content until the blur, so the inner shadow casts from the content alone
|
||||
let expected = evaluate(vec![shadow.clone(), inner_shadow.clone(), blur.clone()]);
|
||||
let minimum = EffectOperation::MinimumMaximum {
|
||||
radius: 0.,
|
||||
mode: graphic_types::MinimumMaximumMode::Minimum,
|
||||
};
|
||||
// A twirl through no angle, or within a circle collapsed onto a line
|
||||
let still_twirl = EffectOperation::Twirl {
|
||||
angle: 0.,
|
||||
transform: DAffine2::from_scale(DVec2::splat(10.)),
|
||||
};
|
||||
let flat_twirl = EffectOperation::Twirl {
|
||||
angle: 90.,
|
||||
transform: DAffine2::from_scale(DVec2::new(10., 0.)),
|
||||
};
|
||||
for nothing in [minimum, still_twirl, flat_twirl] {
|
||||
let actual = evaluate(vec![shadow.clone(), nothing.clone(), inner_shadow.clone(), blur.clone()]);
|
||||
assert!(actual == expected, "{nothing:?} changed the result");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interior_pieces_stack_within_the_contents_share_over_nothing() {
|
||||
use crate::layer_blending::blend_pixel;
|
||||
@@ -1673,4 +1740,26 @@ mod tests {
|
||||
assert!(close, "{blend_mode:?} at fill {fill}: {:?} against {expected:?} at {expected_alpha}", [red, green, blue, actual_alpha]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapping_holds_up_on_rasters_one_pixel_across() {
|
||||
// Wrapping within the square of the raster's own frame
|
||||
let wrap = EffectOperation::PolarCoordinates {
|
||||
inverse: false,
|
||||
transform: DAffine2::from_translation(DVec2::splat(0.5)),
|
||||
};
|
||||
|
||||
// Strips at scales and turns where roundoff can put half a pixel past half the frame
|
||||
for (width, height) in [(1, 7), (7, 1)] {
|
||||
for index in 0..40 {
|
||||
let size = DVec2::new(width as f64, height as f64) * (0.3 + index as f64 * 0.71);
|
||||
let transform = DAffine2::from_scale_angle_translation(size, index as f64 * 0.37, DVec2::new(index as f64 * 1.3, -2.1));
|
||||
let item = Item::new_from_element(Raster::new_cpu(Image::new(width, height, Color::WHITE)))
|
||||
.with_attribute(ATTR_TRANSFORM, transform)
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([wrap.clone()]));
|
||||
let evaluated = evaluate_raster_effects(item);
|
||||
assert!(evaluated.element().data.iter().all(|color| color.a().is_finite()), "{width} by {height} at {index}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,193 @@
|
||||
//! The effects that resample the content from elsewhere than nearby, on the CPU: blurs along lines and arcs.
|
||||
//! The effects that resample the content from elsewhere than nearby, on the CPU: blurs along lines and arcs, and warps.
|
||||
//! They mirror the renderer's GPU passes, sampling between pixels the same way.
|
||||
|
||||
use crate::effect_kernels::Plane;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::resampling::RadialBlur;
|
||||
use graphic_types::resampling::{EffectFrame, FrameWarp, RadialBlur};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// Frame coverage below this is roundoff at a side that a pixel only touches.
|
||||
const NEGLIGIBLE_COVERAGE: f64 = 1. / 65_536.;
|
||||
|
||||
/// Frame coverage below this, which no content shows through and single-precision placements can round to, counts as none for the reads leaving out what the frame touches.
|
||||
const UNTOUCHED_COVERAGE: f64 = 1. / 256.;
|
||||
|
||||
/// How much of a pixel centered at `local` the frame (`half` its size) covers along each of its axes, ramping from 1 at `half_pixel` within a side to 0 at `half_pixel` past it.
|
||||
fn frame_coverage(local: DVec2, half: DVec2, half_pixel: DVec2) -> DVec2 {
|
||||
(0.5 + (half - local.abs()) / (2. * half_pixel)).clamp(DVec2::ZERO, DVec2::ONE)
|
||||
}
|
||||
|
||||
/// A plane the size of `plane` with each pixel within the `frame` set to `inside` at its position in the frame's local space (clamped into it), and each other pixel cleared.
|
||||
/// A pixel the frame's edge cuts through fades by how much of it the frame covers.
|
||||
fn across_frame(plane: &Plane<[f32; 4]>, frame: &EffectFrame, inside: impl Fn(DVec2) -> [f32; 4] + Sync) -> Plane<[f32; 4]> {
|
||||
let (half, half_pixel) = (frame.size / 2., frame.half_pixel());
|
||||
in_local_space(plane, frame, |local, _| {
|
||||
let coverage = frame_coverage(local, half, half_pixel).element_product();
|
||||
if coverage < NEGLIGIBLE_COVERAGE {
|
||||
return [0.; 4];
|
||||
}
|
||||
inside(local.clamp(-half, half)).map(|channel| channel * coverage as f32)
|
||||
})
|
||||
}
|
||||
|
||||
/// The premultiplied pixel at a `point` in pixels interpolated as [`sample_bilinear`] does, but only between the pixels on the `frame`'s side of its edge, which it covers wholly.
|
||||
/// The pixels its edge cuts through hold the content's own edge, so the reads leave them out. Where all four are, as at a corner, the nearest pixel on that side stands in.
|
||||
/// Content too thin to cover any pixel wholly is instead unmixed from the transparency beside it in the pixels the frame touches, which may need [`held_at_opaque`] afterward.
|
||||
fn sample_bilinear_on_side(plane: &Plane<[f32; 4]>, point: DVec2, frame: &EffectFrame) -> [f32; 4] {
|
||||
let (to_local, half, extent) = (frame.pixels_to_local(), frame.size / 2., frame.pixel_extent());
|
||||
let on_side = |pixel: DVec2| frame_coverage(to_local.transform_point2(pixel + 0.5), half, extent).element_product() > 1. - UNTOUCHED_COVERAGE;
|
||||
let color_at = |pixel: DVec2| pixel_or_transparent(plane, pixel);
|
||||
let position = point - 0.5;
|
||||
let base = position.floor();
|
||||
let fraction = (position - base).as_vec2();
|
||||
let corners = [DVec2::ZERO, DVec2::X, DVec2::Y, DVec2::ONE].map(|offset| {
|
||||
let weights = (1. - fraction) + (2. * fraction - 1.) * offset.as_vec2();
|
||||
(base + offset, weights.x * weights.y)
|
||||
});
|
||||
|
||||
let (mut sum, mut total) = ([0.; 4], 0.);
|
||||
for (pixel, weight) in corners {
|
||||
if weight <= 0. || !on_side(pixel) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let color = color_at(pixel);
|
||||
sum = std::array::from_fn(|channel| sum[channel] + color[channel] * weight);
|
||||
total += weight;
|
||||
}
|
||||
if total > 0. {
|
||||
return sum.map(|channel| channel / total);
|
||||
}
|
||||
|
||||
if let Some(pixel) = nearest_around(point, on_side) {
|
||||
return color_at(pixel);
|
||||
}
|
||||
|
||||
// The frame touches a pixel unless an axis of either separates them: the frame's, along which the pixel reaches its extent, or the pixel's, along which the frame spans its bounding box
|
||||
let to_pixels = frame.local_to_pixels();
|
||||
let box_reach = to_pixels.matrix2.x_axis.abs() * half.x + to_pixels.matrix2.y_axis.abs() * half.y;
|
||||
let touches = |pixel: DVec2| {
|
||||
let along_frame = frame_coverage(to_local.transform_point2(pixel + 0.5), half, extent);
|
||||
let along_pixels = frame_coverage(pixel + 0.5 - to_pixels.translation, box_reach, DVec2::splat(0.5));
|
||||
along_frame.min(along_pixels).min_element() >= UNTOUCHED_COVERAGE
|
||||
};
|
||||
|
||||
// Each pixel the frame touches mixes the content with the transparency beside it by its coverage, so that mix is undone
|
||||
let half_pixel = frame.half_pixel();
|
||||
let (mut sum, mut covered) = ([0.; 4], 0.);
|
||||
for (pixel, weight) in corners {
|
||||
if !touches(pixel) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let color = color_at(pixel);
|
||||
sum = std::array::from_fn(|channel| sum[channel] + color[channel] * weight);
|
||||
covered += frame_coverage(to_local.transform_point2(pixel + 0.5), half, half_pixel).element_product() as f32 * weight;
|
||||
}
|
||||
if covered <= 0. {
|
||||
return [0.; 4];
|
||||
}
|
||||
|
||||
sum.map(|channel| channel / covered)
|
||||
}
|
||||
|
||||
/// The premultiplied pixel of `plane` with its corner at `pixel`, or transparency past its edges.
|
||||
fn pixel_or_transparent(plane: &Plane<[f32; 4]>, pixel: DVec2) -> [f32; 4] {
|
||||
let (x, y) = (pixel.x as i64, pixel.y as i64);
|
||||
let in_plane = x >= 0 && y >= 0 && (x as usize) < plane.width && (y as usize) < plane.height;
|
||||
if in_plane { plane.data[y as usize * plane.width + x as usize] } else { [0.; 4] }
|
||||
}
|
||||
|
||||
/// The corner of the pixel nearest a `point` in pixels that `accepts` takes, among the 16 around the point, the first of those equally near.
|
||||
fn nearest_around(point: DVec2, accepts: impl Fn(DVec2) -> bool) -> Option<DVec2> {
|
||||
let base = (point - 0.5).floor();
|
||||
let around = (-1..=2).flat_map(|y| (-1..=2).map(move |x| base + DVec2::new(x as f64, y as f64)));
|
||||
around
|
||||
.filter(|&pixel| accepts(pixel))
|
||||
.min_by(|a, b| (*a + 0.5).distance_squared(point).total_cmp(&(*b + 0.5).distance_squared(point)))
|
||||
}
|
||||
|
||||
/// Premultiplied channels kept from going negative, scaled down to opaque past it, and with the color held within the alpha, as undoing a mix with what lies beside the content can overshoot.
|
||||
fn held_at_opaque(color: [f32; 4]) -> [f32; 4] {
|
||||
let kept = color.map(|channel| channel.max(0.));
|
||||
let scaled = kept.map(|channel| channel / kept[3].max(1.));
|
||||
scaled.map(|channel| channel.min(scaled[3]))
|
||||
}
|
||||
|
||||
/// A plane the size of `plane` with each pixel set to `value` at its position in the `frame`'s local space and its index.
|
||||
fn in_local_space(plane: &Plane<[f32; 4]>, frame: &EffectFrame, value: impl Fn(DVec2, usize) -> [f32; 4] + Sync) -> Plane<[f32; 4]> {
|
||||
let to_local = frame.pixels_to_local();
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
*pixel = value(to_local.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)), y * plane.width + x);
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// The plane warped by a warp relative to the `frame`, which bends what earlier effects painted along with the content. O(width × height).
|
||||
/// Polar Coordinates swaps the frame and its inscribed disc, so it reads only the pixels the frame covers wholly and clears what lies outside it.
|
||||
pub fn frame_warped(plane: &Plane<[f32; 4]>, warp: &FrameWarp, frame: &EffectFrame) -> Plane<[f32; 4]> {
|
||||
let (to_pixels, half_pixel) = (frame.local_to_pixels(), frame.half_pixel());
|
||||
let half = frame.size / 2.;
|
||||
|
||||
let FrameWarp::Polar { inverse } = *warp else {
|
||||
return in_local_space(plane, frame, |local, index| match warp.source(local, frame.size) {
|
||||
source if source == local => plane.data[index],
|
||||
source => sample_bilinear(plane, to_pixels.transform_point2(source)),
|
||||
});
|
||||
};
|
||||
|
||||
// The reads lie a pixel's extent in from the frame's sides, which a turned pixel reaches farther along than half a pixel
|
||||
let inset = frame.pixel_extent().min(half);
|
||||
let sample_within = |local: DVec2| sample_bilinear_on_side(plane, to_pixels.transform_point2(local), frame);
|
||||
let converted = |local: DVec2| {
|
||||
let source = warp.source(local, frame.size);
|
||||
|
||||
// Wrapping meets the frame's left and right sides at the seam straight up from the center, so it reads across them
|
||||
let read = match inverse {
|
||||
true => sample_within(source.clamp(-half + inset, half - inset)),
|
||||
false => {
|
||||
let [near, far, toward_far] = wrapped_across_sides(source, half, inset);
|
||||
let near_read = sample_within(near);
|
||||
if toward_far.x > 0. {
|
||||
mix(near_read, sample_within(DVec2::new(far.x, near.y)), toward_far.x)
|
||||
} else {
|
||||
near_read
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Only wrapping's rim fades, where its source passes the bottom side, since unwrapping reads within the inscribed disc and wrapping gathers the top side at the center
|
||||
let fade = match inverse {
|
||||
true => 1.,
|
||||
false => (0.5 + (half.y - source.y) / (2. * half_pixel.y)).clamp(0., 1.),
|
||||
};
|
||||
held_at_opaque(read).map(|channel| channel * fade as f32)
|
||||
};
|
||||
across_frame(plane, frame, converted)
|
||||
}
|
||||
|
||||
/// For a source `wrapped` into a frame (`half` its size), the point just inside the side it's nearest and just inside the opposite side (`inset` in from them), along each axis,
|
||||
/// and how far toward the opposite one to mix them: 0 past `inset` from the sides, rising to an even mix at a side.
|
||||
fn wrapped_across_sides(wrapped: DVec2, half: DVec2, inset: DVec2) -> [DVec2; 3] {
|
||||
let (low, high) = (-half + inset, half - inset);
|
||||
let above = wrapped.cmpgt(high);
|
||||
let below = wrapped.cmplt(low);
|
||||
|
||||
let near = DVec2::select(above, high, DVec2::select(below, low, wrapped));
|
||||
let far = DVec2::select(above, low, DVec2::select(below, high, wrapped));
|
||||
let toward_far = DVec2::select(above, (wrapped - high) / (2. * inset), DVec2::select(below, (low - wrapped) / (2. * inset), DVec2::ZERO));
|
||||
[near, far, toward_far]
|
||||
}
|
||||
|
||||
/// Premultiplied channels from `a` to `b` by `t`.
|
||||
fn mix(a: [f32; 4], b: [f32; 4], t: f64) -> [f32; 4] {
|
||||
std::array::from_fn(|channel| a[channel] + (b[channel] - a[channel]) * t as f32)
|
||||
}
|
||||
|
||||
/// The most samples a motion blur's box averages along its line at each pixel, past which its samples spread out evenly to cover it.
|
||||
pub const MAX_MOTION_BLUR_SAMPLES: f64 = 1024.;
|
||||
|
||||
@@ -26,10 +208,10 @@ pub struct MotionBlurShear {
|
||||
}
|
||||
|
||||
impl MotionBlurShear {
|
||||
/// The shears of a line `distance` long at `angle` (in degrees counterclockwise from the right), both in the effect space, given the map from its lengths into pixels, measured from `anchor` (in pixels).
|
||||
/// The shears of a line `distance` long (ignoring its sign) at `angle` (in degrees counterclockwise from the right), both in the effect space, given the map from its lengths into pixels, measured from `anchor` (in pixels).
|
||||
pub fn new(angle: f64, distance: f64, lengths_to_pixels: DMat2, anchor: DVec2) -> Option<Self> {
|
||||
let angle = angle.to_radians();
|
||||
let line = DVec2::new(angle.cos(), -angle.sin()) * distance.max(0.);
|
||||
let line = DVec2::new(angle.cos(), -angle.sin()) * distance.abs();
|
||||
let end = lengths_to_pixels * line;
|
||||
|
||||
// For PSD interop, a diagonal runs along the effect space's x axis, and in the pixels, along whichever axis that one lies nearer, so opposite and turned lines agree
|
||||
@@ -226,6 +408,13 @@ mod tests {
|
||||
move |x, y| blurred.data[y * 41 + x][3]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overshot_unmixing_is_held_to_valid_premultiplied_channels() {
|
||||
assert_eq!(held_at_opaque([0.3, -0.1, 0.2, -0.2]), [0.; 4]);
|
||||
assert_eq!(held_at_opaque([0.6, 0.2, 0.1, 0.4]), [0.4, 0.2, 0.1, 0.4]);
|
||||
assert_eq!(held_at_opaque([1.5, 0.5, 1., 2.]), [0.75, 0.25, 0.5, 1.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boxes_span_one_pixel_more_than_the_line_leaning_forward_at_odd_lengths() {
|
||||
assert_eq!(shear(0., 10.).box_span(), [-5.5, 5.5]);
|
||||
@@ -364,6 +553,179 @@ mod tests {
|
||||
assert!((total - 5001.).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_distances_smear_as_positive_ones_do() {
|
||||
use graphic_types::EffectOperation;
|
||||
|
||||
// Through turned and unevenly scaled pixels, measured from an anchor off their corner
|
||||
let lengths_to_pixels = DMat2::from_angle(0.3) * DMat2::from_diagonal(DVec2::new(1.5, 0.8));
|
||||
let anchor = DVec2::new(3.2, -1.);
|
||||
let blur = |angle, distance| EffectOperation::MotionBlur { angle, distance, gamma: false };
|
||||
for (angle, distance) in [(0., 12.), (30., 7.5), (-70., 90.)] {
|
||||
let shears = [distance, -distance].map(|distance| MotionBlurShear::new(angle, distance, lengths_to_pixels, anchor));
|
||||
assert_eq!(shears[0], shears[1], "lines {distance} long at {angle} degrees shear differently");
|
||||
|
||||
assert!(!blur(angle, -distance).changes_nothing());
|
||||
assert_eq!(blur(angle, -distance).reach(), blur(angle, distance).reach());
|
||||
}
|
||||
assert!(blur(0., 0.).changes_nothing());
|
||||
}
|
||||
|
||||
/// The warp an operation carries out, in the frame its transform places in a plane with a pixel to each unit of the effect space.
|
||||
fn warp_in_plane(operation: &graphic_types::EffectOperation) -> (FrameWarp, EffectFrame) {
|
||||
let (warp, transform) = FrameWarp::of(operation).unwrap();
|
||||
(warp, graphic_types::resampling::warp_frame(transform, glam::DAffine2::IDENTITY).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warps_read_transparency_past_their_frame() {
|
||||
use glam::DAffine2;
|
||||
use graphic_types::EffectOperation;
|
||||
|
||||
// Opaque paint fills a plane wider than the square from 5 to 25, below which wrapping reads for the corners past its inscribed ellipse
|
||||
let mut plane = Plane::<[f32; 4]>::new(30, 30);
|
||||
plane.data = vec![[1.; 4]; 30 * 30];
|
||||
let wrap = EffectOperation::PolarCoordinates {
|
||||
inverse: false,
|
||||
transform: DAffine2::from_translation(DVec2::splat(15.)) * DAffine2::from_scale(DVec2::splat(20.)),
|
||||
};
|
||||
let (warp, frame) = warp_in_plane(&wrap);
|
||||
let wrapped = frame_warped(&plane, &warp, &frame);
|
||||
|
||||
assert_eq!(wrapped.data[5 * 30 + 5][3], 0., "the frame's corner reads past it");
|
||||
assert!(wrapped.data[15 * 30 + 15][3] > 0.99, "the center reads the frame's top row");
|
||||
assert_eq!(wrapped.data[0], [0.; 4], "what lies outside the frame is cleared");
|
||||
|
||||
// Unwrapping across a square from 5.5 to 24.5 fills it, half covering the pixels its sides cut through and clearing those beyond
|
||||
let unwrap = EffectOperation::PolarCoordinates {
|
||||
inverse: true,
|
||||
transform: DAffine2::from_translation(DVec2::splat(15.)) * DAffine2::from_scale(DVec2::splat(19.)),
|
||||
};
|
||||
let (warp, frame) = warp_in_plane(&unwrap);
|
||||
let unwrapped = frame_warped(&plane, &warp, &frame);
|
||||
let [beyond, edge, within] = [4, 5, 6].map(|x| unwrapped.data[15 * 30 + x][3]);
|
||||
assert!((within - 1.).abs() < 1e-6 && (edge - 0.5).abs() < 1e-6 && beyond == 0., "{beyond}, {edge}, {within}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warps_bend_what_lies_past_their_frame_along_with_the_content() {
|
||||
use glam::DAffine2;
|
||||
use graphic_types::EffectOperation;
|
||||
|
||||
// Paint varying only across fills a plane taller than the frame from (5, 5) to (25, 35)
|
||||
let mut plane = Plane::<[f32; 4]>::new(30, 40);
|
||||
plane.data = (0..30 * 40).map(|index| [(index % 30) as f32 / 30., 0., 0., 1.]).collect();
|
||||
let transform = DAffine2::from_translation(DVec2::new(15., 20.)) * DAffine2::from_scale(DVec2::new(20., 30.));
|
||||
|
||||
// A cylinder bends every row of its band across the same way, above and below the frame too, with no seam, and leaves what lies beside the band as it is
|
||||
let spherize = EffectOperation::Spherize {
|
||||
amount: 80.,
|
||||
cylindrical: true,
|
||||
transform,
|
||||
};
|
||||
let (warp, frame) = warp_in_plane(&spherize);
|
||||
let bent = frame_warped(&plane, &warp, &frame);
|
||||
for x in 0..30 {
|
||||
assert_eq!(bent.data[2 * 30 + x], bent.data[20 * 30 + x], "column {x} bends above the frame as within it");
|
||||
assert_eq!(bent.data[38 * 30 + x], bent.data[20 * 30 + x], "column {x} bends below the frame as within it");
|
||||
}
|
||||
assert_ne!(bent.data[20 * 30 + 9], plane.data[20 * 30 + 9], "the band bends");
|
||||
assert_eq!(bent.data[20 * 30 + 27], plane.data[20 * 30 + 27], "beside the band, the paint stays as it is");
|
||||
|
||||
// A twirl leaves what lies past its ellipse as it is
|
||||
let (warp, frame) = warp_in_plane(&EffectOperation::Twirl { angle: 120., transform });
|
||||
let twirled = frame_warped(&plane, &warp, &frame);
|
||||
assert_eq!(twirled.data[2 * 30 + 10], plane.data[2 * 30 + 10]);
|
||||
assert_ne!(twirled.data[20 * 30 + 12], plane.data[20 * 30 + 12], "the ellipse twirls");
|
||||
}
|
||||
|
||||
/// The transforms of warps' squares in a plane 180 pixels square, cutting through pixels at every offset along their sides:
|
||||
/// one 80 across with its sides meeting at 16 degrees, one 100 across turned 30 degrees, and an oblong turned and slanted.
|
||||
fn slanted_and_turned_squares() -> [glam::DAffine2; 3] {
|
||||
use glam::DAffine2;
|
||||
|
||||
[
|
||||
DAffine2::from_cols_array(&[80., 0., 76.8, 22.4, 80.2, 80.3]),
|
||||
DAffine2::from_translation(DVec2::new(90.3, 89.6)) * DAffine2::from_angle(30_f64.to_radians()) * DAffine2::from_scale(DVec2::splat(100.)),
|
||||
DAffine2::from_translation(DVec2::new(88.7, 91.2)) * DAffine2::from_angle(0.6) * DAffine2::from_cols_array(&[110., 0., 30., 60., 0., 0.]),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polar_coordinates_read_nothing_wholly_past_a_slanted_square() {
|
||||
use graphic_types::EffectOperation;
|
||||
|
||||
// Clear content but for opaque red at the pixel wholly past the slanted square's left side, a fifth of which plain interpolation reads where (45, 70) wraps from
|
||||
let mut plane = Plane::<[f32; 4]>::new(180, 180);
|
||||
plane.data[89 * 180 + 69] = [1., 0., 0., 1.];
|
||||
assert!(sample_bilinear(&plane, DVec2::new(69.533, 88.71))[3] > 0.2);
|
||||
|
||||
for inverse in [false, true] {
|
||||
let transform = slanted_and_turned_squares()[0];
|
||||
let (warp, frame) = warp_in_plane(&EffectOperation::PolarCoordinates { inverse, transform });
|
||||
let warped = frame_warped(&plane, &warp, &frame);
|
||||
for (index, pixel) in warped.data.iter().enumerate() {
|
||||
let (x, y) = (index % 180, index / 180);
|
||||
assert_eq!(*pixel, [0.; 4], "({x}, {y}) shows {pixel:?} with inverse {inverse}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polar_coordinates_read_nothing_past_a_square_too_small_to_cover_a_pixel() {
|
||||
use glam::DAffine2;
|
||||
use graphic_types::EffectOperation;
|
||||
|
||||
// A square 0.4 across turned 45 degrees, ending about 0.017 above the pixel from (10, 11), which only red fills, though the pixel's extent along the square's axes reaches it
|
||||
let transform = DAffine2::from_translation(DVec2::new(10.5, 10.7)) * DAffine2::from_angle(std::f64::consts::FRAC_PI_4) * DAffine2::from_scale(DVec2::splat(0.4));
|
||||
let mut plane = Plane::<[f32; 4]>::new(20, 20);
|
||||
plane.data[11 * 20 + 10] = [1., 0., 0., 1.];
|
||||
|
||||
for inverse in [false, true] {
|
||||
let (warp, frame) = warp_in_plane(&EffectOperation::PolarCoordinates { inverse, transform });
|
||||
let warped = frame_warped(&plane, &warp, &frame);
|
||||
for (index, pixel) in warped.data.iter().enumerate() {
|
||||
let (x, y) = (index % 20, index / 20);
|
||||
assert_eq!(*pixel, [0.; 4], "({x}, {y}) shows {pixel:?} with inverse {inverse}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polar_coordinates_read_opaque_content_straddling_a_slanted_squares_sides_as_opaque() {
|
||||
use graphic_types::EffectOperation;
|
||||
|
||||
// Opaque white paint straddling the slanted square's sides, but for red at the pixel wholly past its left side
|
||||
let mut plane = Plane::<[f32; 4]>::new(180, 180);
|
||||
plane.data = vec![[1.; 4]; 180 * 180];
|
||||
plane.data[89 * 180 + 69] = [1., 0., 0., 1.];
|
||||
|
||||
for inverse in [false, true] {
|
||||
let transform = slanted_and_turned_squares()[0];
|
||||
let (warp, frame) = warp_in_plane(&EffectOperation::PolarCoordinates { inverse, transform });
|
||||
let warped = frame_warped(&plane, &warp, &frame);
|
||||
let (to_local, half, half_pixel, extent) = (frame.pixels_to_local(), frame.size / 2., frame.half_pixel(), frame.pixel_extent());
|
||||
|
||||
// Each pixel wholly within the square shows only the white, faded only around wrapping's rim, where its source nears or passes the square's bottom side
|
||||
for (index, pixel) in warped.data.iter().enumerate() {
|
||||
let (x, y) = (index % 180, index / 180);
|
||||
let local = to_local.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
|
||||
if (local.abs() + extent).cmpgt(half).any() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let expected = match inverse {
|
||||
true => 1.,
|
||||
false => (0.5 + (half.y - warp.source(local, frame.size).y) / (2. * half_pixel.y)).clamp(0., 1.) as f32,
|
||||
};
|
||||
assert!(
|
||||
pixel.iter().all(|channel| (channel - expected).abs() < 1e-6),
|
||||
"({x}, {y}) shows {pixel:?} rather than {expected} with inverse {inverse}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bilinear_samples_fade_to_transparency_past_the_edges() {
|
||||
let mut plane = Plane::<[f32; 4]>::new(2, 1);
|
||||
|
||||
Reference in new issue
Block a user