use std::rc::Rc;
use crate::nodes::tsl::{
block, depth_texture_sample, float, frag_coord, if_then, int, interleaved_gradient_noise,
loop_n, max, shadow_blur_samples, shadow_map_compare, shadow_map_size, shadow_radius, sqrt,
step, texture_sample, to_var, vec2, vec2_join, vogel_disk_sample,
};
use crate::nodes::{NodeRef, Type};
use crate::textures::{CubeDepthTexture, DepthTexture, Texture};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ShadowMapType {
Basic,
#[default]
Pcf,
PcfSoft,
Vsm,
}
impl ShadowMapType {
pub fn resolved(self) -> Self {
match self {
ShadowMapType::PcfSoft => ShadowMapType::Pcf,
other => other,
}
}
}
#[derive(Clone, Debug)]
pub enum ShadowFilterMap {
Depth(DepthTexture),
Moments(Texture),
Cube(CubeDepthTexture),
}
impl std::hash::Hash for ShadowFilterMap {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
match self {
ShadowFilterMap::Depth(texture) => texture.id().hash(state),
ShadowFilterMap::Moments(texture) => texture.id().hash(state),
ShadowFilterMap::Cube(texture) => texture.id().hash(state),
}
}
}
pub struct ShadowFilterInputs {
pub index: usize,
pub map: ShadowFilterMap,
pub shadow_coord: NodeRef,
pub dp: Option<NodeRef>,
}
#[derive(Clone)]
pub struct ShadowFilterFn(Rc<dyn Fn(&ShadowFilterInputs) -> NodeRef>);
impl ShadowFilterFn {
pub fn new(filter: impl Fn(&ShadowFilterInputs) -> NodeRef + 'static) -> Self {
Self(Rc::new(filter))
}
pub fn call(&self, inputs: &ShadowFilterInputs) -> NodeRef {
(self.0)(inputs)
}
}
impl std::fmt::Debug for ShadowFilterFn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ShadowFilterFn")
}
}
impl std::hash::Hash for ShadowFilterFn {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(Rc::as_ptr(&self.0) as *const () as usize).hash(state);
}
}
#[derive(Clone, Debug, Hash)]
#[doc(hidden)]
pub enum ShadowFilter {
Basic,
Pcf,
Vsm,
Custom(ShadowFilterFn),
}
impl ShadowFilter {
pub fn of(shadow_type: ShadowMapType, filter_node: Option<&ShadowFilterFn>) -> Self {
match (filter_node, shadow_type.resolved()) {
(Some(filter), _) => ShadowFilter::Custom(filter.clone()),
(None, ShadowMapType::Basic) => ShadowFilter::Basic,
(None, ShadowMapType::Vsm) => ShadowFilter::Vsm,
(None, _) => ShadowFilter::Pcf,
}
}
pub fn apply(&self, inputs: &ShadowFilterInputs) -> NodeRef {
match (self, &inputs.map) {
(ShadowFilter::Custom(filter), _) => filter.call(inputs),
(ShadowFilter::Basic, ShadowFilterMap::Cube(_)) => {
crate::lights::point_shadow::basic_point_shadow_filter(inputs)
}
(_, ShadowFilterMap::Cube(_)) => {
crate::lights::point_shadow::point_shadow_filter(inputs)
}
(ShadowFilter::Basic, _) => basic_shadow_filter(inputs),
(ShadowFilter::Pcf, _) => pcf_shadow_filter(inputs),
(ShadowFilter::Vsm, _) => vsm_shadow_filter(inputs),
}
}
}
fn depth_map(inputs: &ShadowFilterInputs, filter: &str) -> DepthTexture {
match &inputs.map {
ShadowFilterMap::Depth(map) => map.clone(),
other => panic!("three-rs: {filter} reads a depth texture, got {other:?}"),
}
}
pub fn basic_shadow_filter(inputs: &ShadowFilterInputs) -> NodeRef {
let map = depth_map(inputs, "BasicShadowFilter");
let coord = inputs.shadow_coord.clone();
shadow_map_compare(&map, coord.clone().xy(), coord.z())
}
pub fn pcf_shadow_filter(inputs: &ShadowFilterInputs) -> NodeRef {
let map = depth_map(inputs, "PCFShadowFilter");
let (index, coord) = (inputs.index, inputs.shadow_coord.clone());
let texel_size = vec2(1.0, 1.0).div(shadow_map_size(index));
let radius_scaled = shadow_radius(index).mul(texel_size.x());
#[allow(clippy::approx_constant)]
let phi = interleaved_gradient_noise(frag_coord().xy()).mul(float(6.28318530718));
let mut sum: Option<NodeRef> = None;
for i in 0..5 {
let offset = vogel_disk_sample(int(i), int(5), phi.clone()).mul(radius_scaled.clone());
let tap = shadow_map_compare(&map, coord.clone().xy().add(offset), coord.clone().z());
sum = Some(match sum {
Some(acc) => acc.add(tap),
None => tap,
});
}
sum.expect("three-rs: the five-tap loop always sets sum")
.mul(float(1.0 / 5.0))
}
pub fn vsm_shadow_filter(inputs: &ShadowFilterInputs) -> NodeRef {
let moments = match &inputs.map {
ShadowFilterMap::Moments(texture) => texture.clone(),
other => panic!("three-rs: VSMShadowFilter reads the VSM moments, got {other:?}"),
};
let coord = inputs.shadow_coord.clone();
let distribution = texture_sample(&moments, coord.clone().xy()).xy();
let mean = distribution.clone().x();
let variance = max(
float(0.0000001),
distribution.clone().y().mul(distribution.y()),
);
let hard_shadow = step(coord.clone().z(), mean.clone());
let output = to_var(None, float(1.0));
let d = coord.z().sub(mean);
let p_max = variance.clone().div(variance.add(d.clone().mul(d)));
let p_max = p_max.sub(0.3).div(0.65).clamp(0.0, 1.0);
block(
vec![
output.clone(),
if_then(
hard_shadow.clone().not_equal(float(1.0)),
vec![output.assign(max(hard_shadow, p_max))],
),
],
output,
)
}
#[doc(hidden)]
pub fn vsm_pass_vertical(index: usize, depth: &DepthTexture) -> NodeRef {
vsm_pass(index, "meanVertical", "squareMeanVertical", |offset| {
let uv = frag_coord()
.xy()
.add(vec2_join(vec![float(0.0), offset]).mul(shadow_radius(index)))
.div(shadow_map_size(index));
let depth = depth_texture_sample(depth, uv);
(depth.clone(), depth.clone().mul(depth))
})
}
#[doc(hidden)]
pub fn vsm_pass_horizontal(index: usize, vertical: &Texture) -> NodeRef {
vsm_pass(index, "meanHorizontal", "squareMeanHorizontal", |offset| {
let uv = frag_coord()
.xy()
.add(vec2_join(vec![offset, float(0.0)]).mul(shadow_radius(index)))
.div(shadow_map_size(index));
let distribution = texture_sample(vertical, uv).xy();
(
distribution.clone().x(),
distribution
.clone()
.y()
.mul(distribution.clone().y())
.add(distribution.clone().x().mul(distribution.x())),
)
})
}
fn vsm_pass(
index: usize,
mean_name: &'static str,
square_mean_name: &'static str,
tap: impl Fn(NodeRef) -> (NodeRef, NodeRef),
) -> NodeRef {
let samples = shadow_blur_samples(index);
let mean = to_var(Some(mean_name), float(0.0));
let squared_mean = to_var(Some(square_mean_name), float(0.0));
let uv_stride = samples
.clone()
.less_than_equal(float(1.0))
.select(float(0.0), float(2.0).div(samples.clone().sub(1.0)));
let uv_start = samples
.clone()
.less_than_equal(float(1.0))
.select(float(0.0), float(-1.0));
let body = {
let (mean, squared_mean) = (mean.clone(), squared_mean.clone());
move |i: &NodeRef| {
let uv_offset = uv_start.add(i.clone().to(Type::F32).mul(uv_stride));
let (value, square) = tap(uv_offset);
vec![mean.add_assign(value), squared_mean.add_assign(square)]
}
};
let std_dev = sqrt(max(
squared_mean.clone().sub(mean.clone().mul(mean.clone())),
float(0.0),
));
block(
vec![
mean.clone(),
squared_mean.clone(),
loop_n("i", samples.clone().to(Type::I32), body),
mean.div_assign(samples.clone()),
squared_mean.div_assign(samples),
],
vec2_join(vec![mean, std_dev]),
)
}