use std::rc::Rc;
use crate::math::{Matrix3, Matrix4, Plane};
use crate::nodes::node::{BufferId, BufferNode, BufferSource, Node, NodeRef, Type};
use crate::nodes::tsl::{
boolean, diffuse_color, discard, float, fwidth, if_then, int, loop_n, position_view,
smoothstep, to_var,
};
use crate::objects::ClippingGroup;
#[derive(Clone, Debug, Default, PartialEq)]
#[doc(hidden)]
pub struct ClippingContext {
pub(crate) intersection: Vec<[f32; 4]>,
pub(crate) union: Vec<[f32; 4]>,
pub(crate) hardware: bool,
}
impl std::hash::Hash for ClippingContext {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.intersection.len().hash(state);
self.union.len().hash(state);
self.hardware.hash(state);
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct ClippingView {
pub view_matrix: Matrix4,
pub view_normal_matrix: Matrix3,
pub shadow_pass: bool,
pub hardware: bool,
}
impl ClippingView {
pub(crate) fn new(view_matrix: Matrix4, shadow_pass: bool, hardware: bool) -> Self {
let mut view_normal_matrix = Matrix3::default();
view_normal_matrix.get_normal_matrix(&view_matrix);
Self {
view_matrix,
view_normal_matrix,
shadow_pass,
hardware,
}
}
fn project(&self, plane: &Plane) -> [f32; 4] {
let mut plane = *plane;
plane.apply_matrix4(&self.view_matrix, Some(&self.view_normal_matrix));
[
-plane.normal.x as f32,
-plane.normal.y as f32,
-plane.normal.z as f32,
plane.constant as f32,
]
}
}
impl ClippingContext {
pub fn new(union: Vec<[f32; 4]>, intersection: Vec<[f32; 4]>, hardware: bool) -> Self {
Self {
intersection,
union,
hardware,
}
}
pub(crate) fn group_context(
parent: &Option<Rc<Self>>,
group: &ClippingGroup,
view: &ClippingView,
) -> Option<Rc<Self>> {
if view.shadow_pass && !group.clip_shadows {
return parent.clone();
}
let mut context = parent.as_deref().cloned().unwrap_or_default();
context.hardware = view.hardware;
let planes = group.clipping_planes.iter().map(|p| view.project(p));
if group.clip_intersection {
context.intersection.extend(planes);
} else {
context.union.extend(planes);
}
if context.intersection.is_empty() && context.union.is_empty() {
return None;
}
Some(Rc::new(context))
}
pub(crate) fn hardware_clipping(&self) -> bool {
self.hardware && (1..=8).contains(&self.union.len())
}
}
fn plane_buffer(source: BufferSource, count: usize) -> impl Fn(&NodeRef) -> NodeRef {
let buffer = Rc::new(BufferNode {
id: BufferId::next(),
source,
element_ty: Type::Vec4,
count,
});
move |index| {
NodeRef::new(Node::BufferElement {
buffer: buffer.clone(),
index: index.clone(),
})
}
}
pub(crate) fn clipping(context: &ClippingContext) -> Vec<NodeRef> {
let mut statements = Vec::new();
let union = context.union.len();
if !context.hardware_clipping() && union > 0 {
let planes = plane_buffer(BufferSource::ClippingUnion, union);
statements.push(loop_n("i", int(union as i64), |i| {
let plane = planes(i);
vec![if_then(
position_view().dot(plane.xyz()).greater_than(plane.w()),
vec![discard()],
)]
}));
}
let intersection = context.intersection.len();
if intersection > 0 {
let planes = plane_buffer(BufferSource::ClippingIntersection, intersection);
let clipped = to_var(Some("clipped"), boolean(true));
statements.push(clipped.clone());
statements.push(loop_n("i", int(intersection as i64), |i| {
let plane = planes(i);
vec![clipped.assign(
position_view()
.dot(plane.xyz())
.greater_than(plane.w())
.and(clipped.clone()),
)]
}));
statements.push(if_then(clipped, vec![discard()]));
}
statements
}
pub(crate) fn clipping_alpha(context: &ClippingContext) -> Vec<NodeRef> {
let distance = to_var(Some("distanceToPlane"), float(0.0));
let gradient = to_var(Some("distanceToGradient"), float(0.0));
let clip_opacity = to_var(Some("clipOpacity"), float(1.0));
let mut statements = vec![distance.clone(), gradient.clone(), clip_opacity.clone()];
let fade = |plane: &NodeRef| {
vec![
distance.assign(position_view().dot(plane.xyz()).negate().add(plane.w())),
gradient.assign(fwidth(distance.clone()).div(2.0)),
]
};
let step = || smoothstep(gradient.negate(), gradient.clone(), distance.clone());
let union = context.union.len();
if !context.hardware_clipping() && union > 0 {
let planes = plane_buffer(BufferSource::ClippingUnion, union);
statements.push(loop_n("i", int(union as i64), |i| {
let mut body = fade(&planes(i));
body.push(clip_opacity.mul_assign(step()));
body
}));
}
let intersection = context.intersection.len();
if intersection > 0 {
let planes = plane_buffer(BufferSource::ClippingIntersection, intersection);
let intersection_opacity = to_var(Some("intersectionClipOpacity"), float(1.0));
statements.push(intersection_opacity.clone());
statements.push(loop_n("i", int(intersection as i64), |i| {
let mut body = fade(&planes(i));
body.push(intersection_opacity.mul_assign(step().one_minus()));
body
}));
statements.push(clip_opacity.mul_assign(intersection_opacity.one_minus()));
}
statements.push(diffuse_color().w().mul_assign(clip_opacity));
statements.push(if_then(diffuse_color().w().equal(0.0), vec![discard()]));
statements
}
pub(crate) fn hardware_clipping(context: &ClippingContext) -> NodeRef {
let union = context.union.len();
let planes = plane_buffer(BufferSource::ClippingUnion, union);
loop_n("i", int(union as i64), |i| {
let plane = planes(i);
let target = NodeRef::new(Node::Expression {
snippet: "varyings.hw_clip_distances[ i ]".into(),
ty: Type::F32,
});
vec![target.assign(position_view().dot(plane.xyz()).sub(plane.w()).negate())]
})
}
#[derive(Default)]
pub(crate) struct MaterialClipping {
pub first: Vec<NodeRef>,
pub alpha: Vec<NodeRef>,
pub hardware: Option<(NodeRef, usize)>,
}
impl MaterialClipping {
pub(crate) fn new(context: Option<&ClippingContext>, alpha_to_coverage: bool) -> Self {
let Some(context) = context else {
return Self::default();
};
let hardware = context
.hardware_clipping()
.then(|| (hardware_clipping(context), context.union.len()));
let any = !context.union.is_empty() || !context.intersection.is_empty();
let (first, alpha) = match (any, alpha_to_coverage) {
(false, _) => (Vec::new(), Vec::new()),
(true, false) => (clipping(context), Vec::new()),
(true, true) => (Vec::new(), clipping_alpha(context)),
};
Self {
first,
alpha,
hardware,
}
}
}