use crate::materials::MeshBasicNodeMaterial;
use crate::nodes::node::{SettableValue, Type};
use crate::nodes::tsl::{
block, float, premultiply_alpha, texture_uv, texture_with_uv, to_var, uniform_settable,
unpremultiply_alpha, uv, vec2,
};
use crate::nodes::NodeRef;
use crate::objects::QuadMesh;
use crate::renderer::{RenderTarget, RenderTargetOptions, Renderer};
use crate::textures::{Texture, TextureFilter, TextureType};
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct GaussianBlurOptions {
pub premultiplied_alpha: bool,
pub resolution_scale: f64,
}
impl Default for GaussianBlurOptions {
fn default() -> Self {
Self {
premultiplied_alpha: false,
resolution_scale: 1.0,
}
}
}
pub struct GaussianBlurNode {
map: Texture,
horizontal: RenderTarget,
vertical: RenderTarget,
horizontal_quad: QuadMesh,
vertical_quad: QuadMesh,
inv_size: SettableValue,
node: NodeRef,
sigma: u32,
resolution_scale: f64,
}
struct Tap<'a> {
map: &'a Texture,
matrix: bool,
}
pub fn gaussian_blur(
map: &Texture,
direction: Option<NodeRef>,
sigma: u32,
options: GaussianBlurOptions,
) -> GaussianBlurNode {
GaussianBlurNode::new(map, direction, sigma, options)
}
fn coefficients(kernel_radius: u32) -> Vec<f64> {
let sigma = kernel_radius as f64 / 3.0;
let mut coefficients = vec![1.0];
let mut sum = 1.0;
for i in 1..kernel_radius {
let i = i as f64;
let w = (-0.5 * i * i / (sigma * sigma)).exp();
coefficients.push(w);
sum += 2.0 * w;
}
coefficients.into_iter().map(|c| c / sum).collect()
}
fn scaled_size(size: u32, resolution_scale: f64) -> u32 {
((size as f64 * resolution_scale).round() as u32).max(1)
}
fn texture_type_of(map: &Texture) -> TextureType {
match map.format() {
wgpu::TextureFormat::Rgba16Float
| wgpu::TextureFormat::Rg16Float
| wgpu::TextureFormat::R16Float => TextureType::HalfFloat,
_ => TextureType::UnsignedByte,
}
}
impl GaussianBlurNode {
pub fn new(
map: &Texture,
direction: Option<NodeRef>,
sigma: u32,
options: GaussianBlurOptions,
) -> Self {
Self::build(map, direction, sigma, options, false)
}
pub(crate) fn with_uv_matrix(
map: &Texture,
direction: Option<NodeRef>,
sigma: u32,
options: GaussianBlurOptions,
) -> Self {
Self::build(map, direction, sigma, options, true)
}
fn build(
map: &Texture,
direction: Option<NodeRef>,
sigma: u32,
options: GaussianBlurOptions,
uv_matrix: bool,
) -> Self {
let target = || {
RenderTarget::new_with_options(
1,
1,
RenderTargetOptions {
texture_type: texture_type_of(map),
samples: 0,
depth_buffer: false,
min_filter: TextureFilter::Linear,
mag_filter: TextureFilter::Linear,
},
)
.expect("three-rs: a gaussian blur target is a colour type")
};
let horizontal = target();
let vertical = target();
let (inv_size_node, inv_size) = uniform_settable(Type::Vec2, vec![0.0, 0.0]);
let direction = match direction {
Some(direction) => direction.to(Type::Vec2),
None => vec2(1.0, 1.0),
};
let blur = |map: &Texture, pass_direction: NodeRef, name: &'static str, matrix: bool| {
let mut material = MeshBasicNodeMaterial::new();
material.name = name;
material.fragment_node = Some(Self::blur(
Tap { map, matrix },
direction.clone(),
pass_direction,
inv_size_node.clone(),
sigma,
options.premultiplied_alpha,
));
QuadMesh::new(material)
};
let horizontal_quad = blur(map, vec2(1.0, 0.0), "Gaussian_blur_horizontal", uv_matrix);
let vertical_quad = blur(
&horizontal.texture(),
vec2(0.0, 1.0),
"Gaussian_blur_vertical",
false,
);
let node = to_var(None, texture_uv(&vertical.texture(), uv()));
Self {
map: map.clone(),
horizontal,
vertical,
horizontal_quad,
vertical_quad,
inv_size,
node,
sigma,
resolution_scale: options.resolution_scale,
}
}
fn blur(
tap: Tap,
direction: NodeRef,
pass_direction: NodeRef,
inv_size: NodeRef,
sigma: u32,
premultiplied_alpha: bool,
) -> NodeRef {
let uv_node = uv();
let sample = |coord: NodeRef| {
let texel = if tap.matrix {
texture_with_uv(tap.map, coord)
} else {
texture_uv(tap.map, coord)
};
if premultiplied_alpha {
premultiply_alpha(texel)
} else {
texel
}
};
let kernel_size = 3 + 2 * sigma;
let coefficients = coefficients(kernel_size);
let direction = direction.mul(pass_direction);
let diffuse_sum = to_var(
None,
sample(uv_node.clone())
.mul(float(coefficients[0]))
.to(Type::Vec4),
);
let mut statements = vec![diffuse_sum.clone()];
for (i, &w) in coefficients.iter().enumerate().skip(1) {
let x = float(i as f64);
let uv_offset = to_var(None, direction.clone().mul(inv_size.clone().mul(x)));
let sample1 = sample(uv_node.clone().add(uv_offset.clone()));
let sample2 = sample(uv_node.clone().sub(uv_offset));
statements.push(diffuse_sum.add_assign(sample1.add(sample2).mul(float(w))));
}
let result = if premultiplied_alpha {
unpremultiply_alpha(diffuse_sum)
} else {
diffuse_sum
};
block(statements, result)
}
pub fn node(&self) -> NodeRef {
self.node.clone()
}
pub fn texture(&self) -> Texture {
self.vertical.texture()
}
pub fn sigma(&self) -> u32 {
self.sigma
}
#[doc(hidden)]
pub fn quad_materials(&self) -> Vec<&MeshBasicNodeMaterial> {
vec![&self.horizontal_quad.material, &self.vertical_quad.material]
}
pub fn set_size(&self, width: u32, height: u32) {
let width = scaled_size(width, self.resolution_scale);
let height = scaled_size(height, self.resolution_scale);
self.inv_size
.set(vec![1.0 / width as f64, 1.0 / height as f64]);
self.horizontal.set_size(width, height);
self.vertical.set_size(width, height);
}
pub fn render(&self, renderer: &mut Renderer) {
renderer.update_texture_source(self.map.id());
let mut renderer = renderer.reset_state();
let (width, height) = self.map.size();
self.set_size(width, height);
renderer.set_render_target(Some(self.horizontal.clone()));
renderer.render_quad(&self.horizontal_quad);
renderer.set_render_target(Some(self.vertical.clone()));
renderer.render_quad(&self.vertical_quad);
drop(renderer);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sigma_20_matches_the_dumped_coefficients() {
let c = coefficients(3 + 2 * 20);
assert_eq!(c.len(), 43);
assert_eq!(c[0], 0.027917486897724192);
assert_eq!(c[1], 0.027849625383014897);
assert_eq!(c[2], 0.027647028978021935);
assert_eq!(c[42], 0.0003814108419989991);
}
#[test]
fn set_size_rounds_and_clamps_to_one() {
assert_eq!(scaled_size(512, 1.0), 512);
assert_eq!(scaled_size(5, 0.5), 3);
assert_eq!(scaled_size(1, 0.25), 1);
}
}