use super::{Pattern, footprint};
use crate::cpu::kernels::effects::saturate;
use crate::cpu::kernels::{
CpuKernel, KernelContext, builtin_aa_pulse, builtin_premultiply, mix4, shade_row,
};
pub(super) fn kernel(id: &str) -> Option<&'static dyn CpuKernel> {
Some(match id {
"alpha2.generator.checkerboard" => &Checkerboard,
"alpha2.generator.grid" => &Grid,
_ => return None,
})
}
struct Checkerboard;
impl CpuKernel for Checkerboard {
fn row(&self, context: &KernelContext<'_>, y: u32, x0: u32, out: &mut [[f32; 4]]) {
let rotation = context.float("rotation");
let pattern = Pattern::new(context, context.vec2("offset"), rotation);
let size = context.float("size");
let footprint = footprint(&pattern, rotation) / size * 0.5;
let color_a = builtin_premultiply(context.vec4("color_a"));
let color_b = builtin_premultiply(context.vec4("color_b"));
shade_row(context, y, x0, out, |_, uv| {
let point = pattern.point(uv);
let p = [point[0] / size * 0.5, point[1] / size * 0.5];
let even = p.map(|phase| builtin_aa_pulse(phase, 0.5, footprint));
let alike = even[0] * even[1] + (1.0 - even[0]) * (1.0 - even[1]);
mix4(color_b, color_a, alike)
});
}
}
struct Grid;
impl CpuKernel for Grid {
fn row(&self, context: &KernelContext<'_>, y: u32, x0: u32, out: &mut [[f32; 4]]) {
let rotation = context.float("rotation");
let pattern = Pattern::new(context, context.vec2("offset"), rotation);
let size = context.float("size");
let footprint = footprint(&pattern, rotation) / size;
let duty = saturate(context.float("line_width") / size);
let color = builtin_premultiply(context.vec4("color"));
let background = builtin_premultiply(context.vec4("background"));
shade_row(context, y, x0, out, |_, uv| {
let point = pattern.point(uv);
let p = [point[0] / size, point[1] / size];
let across = builtin_aa_pulse(p[0] + duty * 0.5, duty, footprint);
let down = builtin_aa_pulse(p[1] + duty * 0.5, duty, footprint);
let coverage = across + down - across * down;
let lines = color.map(|channel| channel * coverage);
let beneath = 1.0 - lines[3];
[0, 1, 2, 3].map(|channel| lines[channel] + background[channel] * beneath)
});
}
}