New node: 'Warp' (#5056)

Add a Warp effect bending any graphic into 15 preset shapes
This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-12-01 22:52:49 -08:00
1 parent a412979a7f
commit 19df13ad1d
23 files changed
+4468 -77

No files matched your search

@@ -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()
}
@@ -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::BlendState>,
) -> 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::BlendState>) -> 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(&parameters),
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");
@@ -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();
@@ -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::<u32>();
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
}
}
File diff suppressed because it is too large. Load diff
@@ -244,6 +244,112 @@ fn frame_coverage(local: vec2<f32>, half: vec2<f32>, half_texel: vec2<f32>) -> v
return clamp(0.5 + (half - abs(local)) / (2. * half_texel), vec2<f32>(0.), vec2<f32>(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<f32>, texel_extent: vec2<f32>) -> 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<vec2<f32>, CLIPPED_CORNERS>(vec2<f32>(-0.5, -0.5), vec2<f32>(0.5, -0.5), vec2<f32>(0.5, 0.5), vec2<f32>(-0.5, 0.5), vec2<f32>(0.), vec2<f32>(0.), vec2<f32>(0.), vec2<f32>(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<f32>(frame.texels_to_local[0].x, frame.texels_to_local[1].x), vec2<f32>(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<vec2<f32>, 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<f32>, texel_extent: vec2<f32>) -> vec4<f32> {
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<f32>(0.);
var total = 0.;
var nearest = vec4<f32>(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>(f32(around % 4 - 1), f32(around / 4 - 1)), vec2<f32>(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<i32>(texel)) * weight;
total += weight;
}
} else if area > 0. {
nearest = texel_or_transparent(vec2<i32>(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
@@ -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<f32>,
@location(0) st: vec2<f32>,
// 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<f32> {
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<f32>,
slopes: vec4<f32>,
}
fn warp_bases(t: f32) -> WarpBases {
if t < 0. {
return WarpBases(vec4<f32>(1. - 3. * t, 3. * t, 0., 0.), vec4<f32>(-3., 3., 0., 0.));
}
if t > 1. {
let past = t - 1.;
return WarpBases(vec4<f32>(0., 0., -3. * past, 1. + 3. * past), vec4<f32>(0., 0., -3., 3.));
}
let rest = 1. - t;
return WarpBases(
vec4<f32>(rest * rest * rest, 3. * t * rest * rest, 3. * t * t * rest, t * t * t),
vec4<f32>(-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<f32>,
along_s: vec2<f32>,
along_t: vec2<f32>,
}
fn warp_point(st: vec2<f32>) -> WarpPoint {
let across = warp_bases(st.x);
let down = warp_bases(st.y);
var result = WarpPoint(vec2<f32>(0.), vec2<f32>(0.), vec2<f32>(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<f32>,
first: vec2<f32>,
second: vec2<f32>,
}
fn warp_cubic(a: vec2<f32>, b: vec2<f32>, c: vec2<f32>, d: vec2<f32>, 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<f32> {
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<f32> {
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<f32> {
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<f32>(texels_to_local[0].x, texels_to_local[1].x), vec2<f32>(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<f32>) -> vec2<f32> {
let handedness = select(-1., 1., side == 1u || side == 2u);
return vec2<f32>(-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<f32> {
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<f32> {
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<f32>(-heading_y * (reach_x / sine_x), -heading_x * (reach_y / sine_y));
}
return vec4<f32>(-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<f32>) -> WarpSideCoverage {
var along = clamp(seed, 0., 1.);
var nearest = WarpCubic(vec2<f32>(0.), vec2<f32>(0.), vec2<f32>(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<f32>) -> vec2<f32> {
var point = vec2<f32>(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<f32>) -> 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<f32>(rest * rest * rest, 3. * along * rest * rest, 3. * along * along * rest, along * along * along);
let line = array<vec2<f32>, 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<f32> {
return mat3x2<f32>(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<f32>) -> 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>) -> 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<f32>, texel_center: vec2<f32>) -> 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<f32>,
}
fn warp_shade(fragment: u32, st: vec2<f32>, texel_center: vec2<f32>) -> 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<f32>(position, nearest.along), vec2<f32>(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>(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<u32>) -> vec2<f32> {
return vec2<f32>(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<u32>, corner: u32) -> vec2<u32> {
return cell + vec2<u32>(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<u32>(parameters.taps[WARP_TAPS + 10u].zw);
let fringe_vertices = 12u * (cells.x + cells.y);
let corner_vertices = 24u;
var grid_index = vec2<u32>(0u);
var offset = vec2<f32>(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<u32>(position, along), vec2<u32>(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<u32>((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<u32>((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<f32>(-2., -2., 0., 1.), st, fragment);
}
let texel = warp_point(st).point + offset;
return WarpVertex(vec4<f32>(texel * parameters.target_to_uv * vec2<f32>(2., -2.) + vec2<f32>(-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<f32>, goal: vec2<f32>) -> vec2<f32> {
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<f32>(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<f32> {
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<f32>(0.);
}
return sample_bilinear_within(frame_parameters(), transform_point(warp_source_to_texels(), shade.read), parameters.taps[4].zw) * shade.coverage;
}