use std::{collections::HashSet, ops::RangeInclusive, sync::Arc};
use image::imageops;
use image::{Pixel, Rgba, RgbaImage};
use rand::Rng;
use rand::seq::{IndexedRandom, SliceRandom};
use swash::scale::ScaleContext;
use swash::shape::{Direction, ShapeContext};
use swash::text::{BidiClass, Codepoint, Script};
use swash::zeno::{Mask, Origin, Placement, Vector};
use swash::{CacheKey, FontRef};
use thiserror::Error;
use crate::{CaptchaError, Challenge, Format, Image, Point, Rect, Size, render};
const DEFAULT_LABELS: [&str; 15] = [
"我", "是", "行", "为", "式", "验", "证", "码", "的", "随", "机", "文", "本", "种", "子",
];
const MAX_SYMBOLS: u32 = 64;
const MAX_LABEL_CHARS: usize = 32;
const CELL_MARGIN: u32 = 2;
#[derive(Clone)]
pub struct Font {
data: Arc<[u8]>,
offset: u32,
key: CacheKey,
}
impl std::fmt::Debug for Font {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Font").finish_non_exhaustive()
}
}
impl Font {
pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self, FontError> {
let bytes = bytes.as_ref();
let font = FontRef::from_index(bytes, 0).ok_or(FontError("invalid font header"))?;
let metrics = font.metrics(&[]);
if metrics.units_per_em < 16 || metrics.glyph_count == 0 {
return Err(FontError("invalid font metrics"));
}
if !ScaleContext::new().builder(font).build().has_outlines() {
return Err(FontError("no supported glyph outlines"));
}
Ok(Self {
data: Arc::from(bytes),
offset: font.offset,
key: font.key,
})
}
pub fn bundled() -> Result<Self, FontError> {
Self::from_bytes(include_bytes!("fonts/caprs-sans.otf"))
}
fn font_ref(&self) -> FontRef<'_> {
FontRef {
data: &self.data,
offset: self.offset,
key: self.key,
}
}
}
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("could not parse font: {0}")]
pub struct FontError(&'static str);
#[derive(Clone, Debug)]
pub struct Shape {
name: String,
pixels: RgbaImage,
}
impl Shape {
#[must_use]
pub fn new(name: impl Into<String>, pixels: RgbaImage) -> Self {
Self {
name: name.into(),
pixels,
}
}
pub fn from_region(
name: impl Into<String>,
source: &RgbaImage,
region: Rect,
) -> Result<Self, CaptchaError> {
render::check_size(region.size, "shape region")?;
let x = u32::try_from(region.origin.x).ok();
let y = u32::try_from(region.origin.y).ok();
let Some((x, y)) = x.zip(y).filter(|&(x, y)| {
u64::from(x) + u64::from(region.size.width) <= u64::from(source.width())
&& u64::from(y) + u64::from(region.size.height) <= u64::from(source.height())
}) else {
return Err(CaptchaError::invalid(
"shape region",
"must fit inside the source image",
));
};
let pixels =
imageops::crop_imm(source, x, y, region.size.width, region.size.height).to_image();
Ok(Self::new(name, pixels))
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Symbols {
Text {
labels: Vec<String>,
fonts: Vec<Font>,
},
Shapes(Vec<Shape>),
}
impl Symbols {
pub fn bundled_text() -> Result<Self, FontError> {
Ok(Self::Text {
labels: DEFAULT_LABELS.map(str::to_owned).to_vec(),
fonts: vec![Font::bundled()?],
})
}
}
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct Backgrounds {
pub master: Vec<RgbaImage>,
pub thumbnail: Vec<RgbaImage>,
}
impl Backgrounds {
#[must_use]
pub fn new(master: Vec<RgbaImage>, thumbnail: Vec<RgbaImage>) -> Self {
Self { master, thumbnail }
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Prompt {
Subset(RangeInclusive<u32>),
All,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum ShapeColor {
#[default]
Tint,
Original,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Shadow {
pub offset: Point,
pub color: Rgba<u8>,
}
impl Shadow {
#[must_use]
pub fn new(color: Rgba<u8>, offset: Point) -> Self {
Self { offset, color }
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum Distortion {
#[default]
None,
Background {
amplitude: u8,
},
Whole {
amplitude: u8,
},
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Noise {
pub circles: u16,
pub lines: u16,
pub colors: Vec<Rgba<u8>>,
pub opacity: u8,
pub distortion: Distortion,
}
impl Default for Noise {
fn default() -> Self {
Self {
circles: 24,
lines: 2,
colors: hint_colors(),
opacity: 62,
distortion: Distortion::Background { amplitude: 3 },
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Options {
pub image_size: Size,
pub thumbnail_size: Size,
pub symbol_count: RangeInclusive<u32>,
pub prompt: Prompt,
pub symbol_size: RangeInclusive<u32>,
pub thumbnail_symbol_size: RangeInclusive<u32>,
pub angles: Vec<RangeInclusive<i16>>,
pub colors: Vec<Rgba<u8>>,
pub thumbnail_colors: Vec<Rgba<u8>>,
pub shadow: Option<Shadow>,
pub image_opacity: u8,
pub shape_color: ShapeColor,
pub noise: Noise,
}
impl Default for Options {
fn default() -> Self {
Self {
image_size: Size::new(300, 220),
thumbnail_size: Size::new(150, 40),
symbol_count: 6..=7,
prompt: Prompt::Subset(2..=4),
symbol_size: 26..=32,
thumbnail_symbol_size: 22..=28,
angles: vec![20..=35, 35..=45, 45..=60, -70..=-55, -55..=-35, -35..=-30],
colors: vec![
Rgba([253, 233, 142, 255]),
Rgba([96, 193, 255, 255]),
Rgba([252, 176, 142, 255]),
Rgba([251, 136, 255, 255]),
Rgba([180, 254, 212, 255]),
Rgba([203, 250, 169, 255]),
Rgba([120, 214, 248, 255]),
],
thumbnail_colors: hint_colors(),
shadow: Some(Shadow::new(Rgba([16, 16, 16, 255]), Point::new(-1, -1))),
image_opacity: 255,
shape_color: ShapeColor::Tint,
noise: Noise::default(),
}
}
}
impl Options {
#[must_use]
pub fn for_shapes() -> Self {
Self {
symbol_size: 24..=30,
thumbnail_symbol_size: 14..=20,
noise: Noise {
distortion: Distortion::Background { amplitude: 1 },
..Noise::default()
},
..Self::default()
}
}
}
fn hint_colors() -> Vec<Rgba<u8>> {
vec![
Rgba([31, 85, 196, 255]),
Rgba([120, 5, 146, 255]),
Rgba([47, 107, 0, 255]),
Rgba([145, 0, 0, 255]),
Rgba([134, 68, 1, 255]),
Rgba([103, 89, 1, 255]),
Rgba([1, 110, 92, 255]),
]
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Target {
label: String,
bounds: Rect,
}
impl Target {
#[must_use]
pub fn label(&self) -> &str {
&self.label
}
#[must_use]
pub fn bounds(&self) -> Rect {
self.bounds
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Answer {
image_size: Size,
targets: Vec<Target>,
}
impl Answer {
#[must_use]
pub fn targets(&self) -> &[Target] {
&self.targets
}
#[must_use]
pub fn verify(&self, points: &[Point], padding: u32) -> bool {
!self.targets.is_empty()
&& points.len() == self.targets.len()
&& points.iter().zip(&self.targets).all(|(&point, target)| {
point.x >= 0
&& point.y >= 0
&& (point.x as u32) < self.image_size.width
&& (point.y as u32) < self.image_size.height
&& validate(point, target.bounds, padding)
})
}
}
#[must_use]
pub fn validate(point: Point, target: Rect, padding: u32) -> bool {
let x = i64::from(point.x) - i64::from(target.origin.x);
let y = i64::from(point.y) - i64::from(target.origin.y);
let extension = i64::from(padding) * 2;
(0..=i64::from(target.size.width) + extension).contains(&x)
&& (0..=i64::from(target.size.height) + extension).contains(&y)
}
#[derive(Debug)]
pub struct Captcha {
options: Options,
symbols: Symbols,
backgrounds: Backgrounds,
}
impl Captcha {
pub fn new(options: Options, symbols: Symbols) -> Result<Self, CaptchaError> {
validate_options(&options)?;
validate_symbols(&symbols, *options.symbol_count.end() as usize)?;
Ok(Self {
options,
symbols,
backgrounds: Backgrounds::default(),
})
}
pub fn with_backgrounds(mut self, backgrounds: Backgrounds) -> Result<Self, CaptchaError> {
for image in backgrounds.master.iter().chain(&backgrounds.thumbnail) {
render::check_image(image, "click backgrounds")?;
}
self.backgrounds = backgrounds;
Ok(self)
}
#[must_use]
pub fn options(&self) -> &Options {
&self.options
}
pub fn generate(&self) -> Result<Challenge<Answer>, CaptchaError> {
let mut rng = crate::rng()?;
let options = &self.options;
let count = rng.random_range(options.symbol_count.clone()) as usize;
let symbols = self.choose_symbols(count, &mut rng);
let draw = symbols
.iter()
.map(|symbol| self.draw_main_symbol(symbol, &mut rng))
.collect::<Result<Vec<_>, _>>()?;
let (mut master, targets) = self.draw_master(&symbols, draw, &mut rng);
render::opacity(&mut master, options.image_opacity);
let mut order: Vec<_> = (0..count).collect();
order.shuffle(&mut rng);
if let Prompt::Subset(range) = &options.prompt {
order.truncate(rng.random_range(range.clone()) as usize);
}
let hint = self.draw_hint(&symbols, &order, &mut rng)?;
let targets = order
.into_iter()
.map(|index| targets[index].clone())
.collect();
Ok(Challenge::new(
Image::new(master, Format::Jpeg),
Image::new(hint, Format::Png),
Answer {
image_size: options.image_size,
targets,
},
))
}
fn choose_symbols(&self, count: usize, rng: &mut impl Rng) -> Vec<Symbol<'_>> {
use rand::seq::IteratorRandom;
match &self.symbols {
Symbols::Text { labels, fonts } => labels
.choose_multiple(rng, count)
.map(|label| {
let font = fonts
.iter()
.filter(|font| covers(font, label))
.choose(rng)
.expect("each configured label has a compatible font");
Symbol::Text(label, font)
})
.collect(),
Symbols::Shapes(shapes) => shapes
.choose_multiple(rng, count)
.map(Symbol::Shape)
.collect(),
}
}
fn draw_main_symbol(
&self,
symbol: &Symbol<'_>,
rng: &mut impl Rng,
) -> Result<RgbaImage, CaptchaError> {
let options = &self.options;
let size = rng.random_range(options.symbol_size.clone());
let color = options.colors[rng.random_range(0..options.colors.len())];
let bitmap = symbol.render(size, color, options.shape_color)?;
Ok(render::rotate_fit(
bitmap,
render::angle(&options.angles, rng),
))
}
fn draw_master(
&self,
symbols: &[Symbol<'_>],
bitmaps: Vec<RgbaImage>,
rng: &mut impl Rng,
) -> (RgbaImage, Vec<Target>) {
let size = self.options.image_size;
let mut master = background(&self.backgrounds.master, size, Rgba([59, 68, 86, 255]), rng);
let (columns, rows) = grid(size, symbols.len() as u32);
let cell_width = size.width / columns;
let cell_height = size.height / rows;
let mut cells: Vec<_> = (0..columns * rows).collect();
cells.shuffle(rng);
let targets = symbols
.iter()
.zip(bitmaps)
.zip(cells)
.map(|((symbol, bitmap), cell)| {
let bitmap = render::scale_fit(
bitmap,
cell_width - 2 * CELL_MARGIN,
cell_height - 2 * CELL_MARGIN,
);
let x = (cell % columns) * cell_width
+ rng.random_range(CELL_MARGIN..=cell_width - bitmap.width() - CELL_MARGIN);
let y = (cell / columns) * cell_height
+ rng.random_range(CELL_MARGIN..=cell_height - bitmap.height() - CELL_MARGIN);
if let Some(shadow) = self.options.shadow {
let mut shadow_image = bitmap.clone();
render::tint(&mut shadow_image, shadow.color);
imageops::overlay(
&mut master,
&shadow_image,
i64::from(x) + i64::from(shadow.offset.x),
i64::from(y) + i64::from(shadow.offset.y),
);
}
imageops::overlay(&mut master, &bitmap, i64::from(x), i64::from(y));
Target {
label: symbol.label().to_owned(),
bounds: Rect::new(
Point::new(x as i32, y as i32),
Size::new(bitmap.width(), bitmap.height()),
),
}
})
.collect();
(master, targets)
}
fn draw_hint(
&self,
symbols: &[Symbol<'_>],
order: &[usize],
rng: &mut impl Rng,
) -> Result<RgbaImage, CaptchaError> {
let options = &self.options;
let size = options.thumbnail_size;
let mut hint = background(
&self.backgrounds.thumbnail,
size,
Rgba([249, 249, 249, 255]),
rng,
);
add_noise(&mut hint, &options.noise, rng);
let phase = rng.random_range(0.0..std::f64::consts::TAU);
if let Distortion::Background { amplitude } = options.noise.distortion {
hint = distort(&hint, amplitude, phase);
}
let cell_width = size.width / order.len() as u32;
for (slot, &index) in order.iter().enumerate() {
let scale = rng.random_range(options.thumbnail_symbol_size.clone());
let color =
options.thumbnail_colors[rng.random_range(0..options.thumbnail_colors.len())];
let bitmap = symbols[index].render(scale, color, options.shape_color)?;
let bitmap = render::scale_fit(
bitmap,
cell_width - 2 * CELL_MARGIN,
size.height - 2 * CELL_MARGIN,
);
let x = slot as u32 * cell_width + (cell_width - bitmap.width()) / 2;
let y = (size.height - bitmap.height()) / 2;
imageops::overlay(&mut hint, &bitmap, i64::from(x), i64::from(y));
}
if let Distortion::Whole { amplitude } = options.noise.distortion {
hint = distort(&hint, amplitude, phase);
}
Ok(hint)
}
}
fn grid(size: Size, count: u32) -> (u32, u32) {
(1..=count)
.map(|columns| (columns, count.div_ceil(columns)))
.max_by_key(|&(columns, rows)| (size.width / columns).min(size.height / rows))
.unwrap_or((1, 1))
}
fn validate_options(options: &Options) -> Result<(), CaptchaError> {
render::check_size(options.image_size, "image_size")?;
render::check_size(options.thumbnail_size, "thumbnail_size")?;
render::check_range(&options.symbol_count, 1..=MAX_SYMBOLS, "symbol_count")?;
render::check_range(&options.symbol_size, 1..=256, "symbol_size")?;
render::check_range(
&options.thumbnail_symbol_size,
1..=256,
"thumbnail_symbol_size",
)?;
render::check_angles(&options.angles, -360..=360)?;
let count = *options.symbol_count.end();
let max_prompt = match &options.prompt {
Prompt::All => count,
Prompt::Subset(range) => {
render::check_range(range, 1..=MAX_SYMBOLS, "prompt")?;
(*range.end()).min(count)
}
};
let (columns, rows) = grid(options.image_size, count);
let min_cell = 2 * CELL_MARGIN + 1;
if options.image_size.width / columns < min_cell || options.image_size.height / rows < min_cell
{
return Err(CaptchaError::invalid(
"image_size",
"too small for the maximum symbol count",
));
}
if options.thumbnail_size.width / max_prompt < min_cell
|| options.thumbnail_size.height < min_cell
{
return Err(CaptchaError::invalid(
"thumbnail_size",
"too small for the longest prompt",
));
}
if options.colors.is_empty() || options.thumbnail_colors.is_empty() {
return Err(CaptchaError::invalid(
"click colors",
"main and hint palettes must not be empty",
));
}
if options.noise.circles > 256 || options.noise.lines > 256 {
return Err(CaptchaError::invalid(
"noise",
"at most 256 circles and 256 lines are allowed",
));
}
Ok(())
}
fn covers(font: &Font, label: &str) -> bool {
let map = font.font_ref().charmap();
label
.chars()
.all(|character| character == ' ' || map.map(character) != 0)
}
fn validate_symbols(symbols: &Symbols, minimum: usize) -> Result<(), CaptchaError> {
let mut labels = HashSet::new();
match symbols {
Symbols::Text {
labels: text,
fonts,
} => {
for label in text {
if label.is_empty()
|| label.trim() != label
|| label.chars().count() > MAX_LABEL_CHARS
|| label.chars().any(char::is_control)
|| !fonts.iter().any(|font| covers(font, label))
{
return Err(CaptchaError::invalid(
"text labels",
"each label needs 1 to 32 printable characters covered by a font",
));
}
labels.insert(label);
}
if labels.len() != text.len() {
return Err(CaptchaError::invalid(
"text labels",
"labels must be unique",
));
}
}
Symbols::Shapes(shapes) => {
for shape in shapes {
render::check_size(
Size::new(shape.pixels.width(), shape.pixels.height()),
"shape",
)?;
if shape.name.trim().is_empty() || !shape.pixels.pixels().any(|pixel| pixel[3] != 0)
{
return Err(CaptchaError::invalid(
"shape",
"needs a name and visible pixels",
));
}
labels.insert(&shape.name);
}
if labels.len() != shapes.len() {
return Err(CaptchaError::invalid("shapes", "names must be unique"));
}
}
}
if labels.len() < minimum {
return Err(CaptchaError::invalid(
"symbols",
"need at least as many distinct labels as the maximum symbol count",
));
}
Ok(())
}
enum Symbol<'a> {
Text(&'a str, &'a Font),
Shape(&'a Shape),
}
impl Symbol<'_> {
fn label(&self) -> &str {
match self {
Self::Text(label, _) => label,
Self::Shape(shape) => &shape.name,
}
}
fn render(
&self,
size: u32,
color: Rgba<u8>,
style: ShapeColor,
) -> Result<RgbaImage, CaptchaError> {
match self {
Self::Text(label, font) => draw_text(label, font, size, color),
Self::Shape(shape) => {
let ratio =
f64::from(size) / f64::from(shape.pixels.width().max(shape.pixels.height()));
let width = (f64::from(shape.pixels.width()) * ratio).round().max(1.0) as u32;
let height = (f64::from(shape.pixels.height()) * ratio).round().max(1.0) as u32;
let mut bitmap = render::scale(shape.pixels.clone(), width, height);
if style == ShapeColor::Tint {
render::tint(&mut bitmap, color);
}
Ok(bitmap)
}
}
}
}
fn draw_text(
label: &str,
font: &Font,
size: u32,
color: Rgba<u8>,
) -> Result<RgbaImage, CaptchaError> {
let font = font.font_ref();
let mut context = ShapeContext::new();
let size = size as f32;
let script = label
.chars()
.map(Codepoint::script)
.find(|script| !matches!(script, Script::Common | Script::Inherited | Script::Unknown))
.unwrap_or(Script::Latin);
let direction = label
.chars()
.map(Codepoint::bidi_class)
.find_map(|class| match class {
BidiClass::L => Some(Direction::LeftToRight),
BidiClass::R | BidiClass::AL => Some(Direction::RightToLeft),
_ => None,
})
.unwrap_or(Direction::LeftToRight);
let mut shaper = context
.builder(font)
.script(script)
.direction(direction)
.size(size)
.build();
shaper.add_str(label);
let mut glyphs = Vec::with_capacity(label.chars().count());
let mut pen = 0.0;
shaper.shape_with(|cluster| {
for glyph in cluster.glyphs {
glyphs.push((glyph.id, pen + glyph.x, glyph.y));
pen += glyph.advance;
}
});
let mut context = ScaleContext::new();
let mut scaler = context.builder(font).size(size).build();
let mut layers = Vec::with_capacity(glyphs.len());
for (id, x, y) in glyphs {
let Some(outline) = scaler.scale_outline(id) else {
continue;
};
let bounds = outline.bounds();
if bounds.is_empty() {
continue;
}
let (_, placement) = Placement::compute(Origin::BottomLeft, Vector::ZERO, &bounds);
render::check_size(
Size::new(placement.width, placement.height),
"glyph outline",
)?;
let (mask, placement) = Mask::new(outline.path())
.origin(Origin::BottomLeft)
.render();
if placement.width != 0 && mask.iter().any(|&alpha| alpha != 0) {
let left = i64::from(x.round() as i32) + i64::from(placement.left);
let top = -i64::from(y.round() as i32) - i64::from(placement.top);
layers.push((left, top, placement, mask));
}
}
let Some(left) = layers.iter().map(|layer| layer.0).min() else {
return Err(CaptchaError::EmptyGlyphs {
label: label.to_owned(),
});
};
let top = layers.iter().map(|layer| layer.1).min().unwrap_or(0);
let right = layers
.iter()
.map(|(x, _, placement, _)| x + i64::from(placement.width))
.max()
.unwrap_or(left);
let bottom = layers
.iter()
.map(|(_, y, placement, _)| y + i64::from(placement.height))
.max()
.unwrap_or(top);
let width = u32::try_from(right - left).unwrap_or(u32::MAX);
let height = u32::try_from(bottom - top).unwrap_or(u32::MAX);
render::check_size(Size::new(width, height), "rasterized text size")?;
let [r, g, b, opacity] = color.0;
let mut image = RgbaImage::new(width, height);
for (x, y, placement, mask) in layers {
let offset_x = (x - left) as u32;
let offset_y = (y - top) as u32;
for (y, row) in mask.chunks_exact(placement.width as usize).enumerate() {
for (x, &alpha) in row.iter().enumerate() {
let pixel = image.get_pixel_mut(offset_x + x as u32, offset_y + y as u32);
pixel.blend(&Rgba([r, g, b, render::multiply_alpha(alpha, opacity)]));
}
}
}
Ok(image)
}
fn background(
images: &[RgbaImage],
size: Size,
fallback: Rgba<u8>,
rng: &mut impl Rng,
) -> RgbaImage {
match images.choose(rng) {
Some(source) => render::crop_background(source, size, rng),
None => RgbaImage::from_pixel(size.width, size.height, fallback),
}
}
fn noise_color(noise: &Noise, rng: &mut impl Rng) -> Rgba<u8> {
let mut pixel = noise.colors[rng.random_range(0..noise.colors.len())];
pixel[3] = render::multiply_alpha(pixel[3], noise.opacity);
pixel
}
fn add_noise(image: &mut RgbaImage, noise: &Noise, rng: &mut impl Rng) {
if noise.colors.is_empty() || noise.opacity == 0 {
return;
}
let width = image.width() as i32;
let height = image.height() as i32;
for _ in 0..noise.circles {
let x = rng.random_range(0..width);
let y = rng.random_range(0..height);
let radius: i32 = rng.random_range(1..=3);
let pixel = noise_color(noise, rng);
for dy in -radius..=radius {
for dx in -radius..=radius {
if dx * dx + dy * dy <= radius * radius
&& let Some(target) =
image.get_pixel_mut_checked((x + dx) as u32, (y + dy) as u32)
{
target.blend(&pixel);
}
}
}
}
for _ in 0..noise.lines {
let start = rng.random_range(0..height);
let end = rng.random_range(0..height);
let pixel = noise_color(noise, rng);
for x in 0..width {
let y = start + (end - start) * x / width;
image.get_pixel_mut(x as u32, y as u32).blend(&pixel);
}
}
}
fn distort(image: &RgbaImage, amplitude: u8, phase: f64) -> RgbaImage {
let width = f64::from(image.width() - 1);
let cycle = std::f64::consts::TAU / f64::from(image.height());
RgbaImage::from_fn(image.width(), image.height(), |x, y| {
let shift = (f64::from(y) * cycle + phase).sin() * f64::from(amplitude);
render::sample(
image,
(f64::from(x) - shift).clamp(0.0, width),
f64::from(y),
)
})
}