use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use super::builder::{current_context, push_context};
use super::node::{
BufferNode, BufferSource, Builtin, ContextValue, CustomNode, FnDef, InstanceBuffer, Lazy,
LiveValue, Node, NodeRef, Object3DScope, SampleMode, SettableValue, Type, UniformGroup,
UniformNode, UniformSource, VarDef, VaryingDef,
};
use crate::materials::{MeshBasicNodeMaterial, Side};
use crate::math::{Color, Matrix3};
use crate::textures::{
CubeDepthTexture, CubeTexture, DataArrayTexture, DataTexture, DepthTexture, Texture,
};
pub use super::node::TextureSource;
mod depth_aware_blur;
mod gpgpu;
mod lighting;
mod rnoise;
mod specular_helpers;
mod utils;
mod wrappers;
pub use depth_aware_blur::depth_aware_blur;
pub use gpgpu::*;
pub use lighting::*;
pub use rnoise::*;
pub use specular_helpers::*;
pub use utils::*;
pub use wrappers::*;
type NormalViewKey = (
Option<&'static str>,
Option<usize>,
bool,
Side,
bool,
Option<usize>,
);
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct OverrideNodes {
pub position_view: Option<NodeRef>,
pub position_view_direction: Option<NodeRef>,
pub normal_view: Option<NodeRef>,
}
impl std::hash::Hash for OverrideNodes {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
for node in [
&self.position_view,
&self.position_view_direction,
&self.normal_view,
] {
node.as_ref().map(|n| n.key()).hash(state);
}
}
}
pub(crate) fn with_override_nodes<R>(
overrides: Option<&OverrideNodes>,
f: impl FnOnce() -> R,
) -> R {
let _overrides = push_context(|cx| cx.override_nodes = overrides.cloned());
f()
}
fn override_node(pick: fn(&OverrideNodes) -> &Option<NodeRef>) -> Option<NodeRef> {
current_context(|cx| cx.override_nodes.as_ref().and_then(|o| pick(o).clone()))
}
thread_local! {
static NORMAL_VIEW_GEOMETRY: RefCell<HashMap<bool, NodeRef>> = RefCell::new(HashMap::new());
static NORMAL_VIEW: RefCell<HashMap<NormalViewKey, NodeRef>> =
RefCell::new(HashMap::new());
static TANGENT_VIEW: RefCell<HashMap<NormalViewKey, (NodeRef, NodeRef)>> =
RefCell::new(HashMap::new());
static NORMAL_WORLD: RefCell<HashMap<NormalViewKey, NodeRef>> =
RefCell::new(HashMap::new());
static POSITION_VIEW: RefCell<HashMap<Option<usize>, (NodeRef, NodeRef)>> =
RefCell::new(HashMap::new());
}
fn sub_build_name(name: &str) -> String {
match current_context(|cx| cx.sub_build) {
Some(layer) => format!("{layer}_{name}"),
None => name.to_string(),
}
}
pub fn context(node: impl Into<NodeRef>, value: ContextValue) -> NodeRef {
NodeRef::new(Node::Context {
node: node.into(),
value: Rc::new(value),
})
}
pub fn replace_default_uv(uv: impl Into<NodeRef>, node: impl Into<NodeRef>) -> NodeRef {
context(node, ContextValue::new().set("getUV", uv))
}
pub fn isolate(node: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Isolate { node: node.into() })
}
pub fn custom(node: impl CustomNode + 'static) -> NodeRef {
NodeRef::new(Node::Custom(Rc::new(node)))
}
fn in_sub_build<R>(layer: &'static str, f: impl FnOnce() -> R) -> R {
let _layer = push_context(|cx| cx.sub_build = Some(layer));
f()
}
pub(crate) fn with_material_normal<R>(
normal: Option<NodeRef>,
flat_shading: bool,
side: Side,
f: impl FnOnce() -> R,
) -> R {
let _material = push_context(|cx| {
cx.setup_normal = normal;
cx.flat_shading = flat_shading;
cx.material_side = side;
});
f()
}
pub(crate) fn with_tangent_attribute<R>(has_tangent: bool, f: impl FnOnce() -> R) -> R {
let _tangent = push_context(|cx| cx.has_tangent = has_tangent);
f()
}
pub(crate) fn with_orthographic_camera<R>(orthographic: bool, f: impl FnOnce() -> R) -> R {
let _camera = push_context(|cx| cx.orthographic_camera = orthographic);
f()
}
pub(crate) fn with_material_side<R>(side: Side, f: impl FnOnce() -> R) -> R {
let _side = push_context(|cx| cx.material_side = side);
f()
}
fn negate_on_back_side(vector: NodeRef) -> NodeRef {
match current_context(|cx| cx.material_side) {
Side::Front => vector,
Side::Back => vector.mul(float(-1.0)),
Side::Double => vector.mul(face_direction()),
}
}
pub fn direction_to_face_direction(vector: NodeRef, side: Side) -> NodeRef {
match side {
Side::Front => vector,
Side::Back => vector.mul(float(-1.0)),
Side::Double => vector.mul(face_direction()),
}
}
pub(crate) fn with_material_position_view<R>(value: Option<NodeRef>, f: impl FnOnce() -> R) -> R {
let _position_view = push_context(|cx| cx.setup_position_view = value);
f()
}
fn position_view_pair() -> (NodeRef, NodeRef) {
let value = current_context(|cx| cx.setup_position_view.clone());
let key = value.as_ref().map(|v| v.key());
if let Some(pair) = POSITION_VIEW.with(|m| m.borrow().get(&key).cloned()) {
return pair;
}
let view = value.unwrap_or_else(|| {
model_view_matrix()
.mul(vec4_join(vec![position_local(), float(1.0)]))
.xyz()
});
let view = to_varying(Some("v_positionView"), view);
let mvp = to_varying(
Some("v_modelViewProjection"),
camera_projection_matrix().mul(view.clone()),
);
let pair = (view, mvp);
POSITION_VIEW.with(|m| m.borrow_mut().insert(key, pair.clone()));
pair
}
fn constant(ty: Type, values: Vec<f64>) -> NodeRef {
NodeRef::new(Node::Const { ty, values })
}
pub fn float(v: impl Into<f64>) -> NodeRef {
constant(Type::F32, vec![v.into()])
}
pub fn int(v: i64) -> NodeRef {
constant(Type::I32, vec![v as f64])
}
pub fn boolean(v: bool) -> NodeRef {
constant(Type::Bool, vec![f64::from(u8::from(v))])
}
pub fn vec2(x: impl Into<f64>, y: impl Into<f64>) -> NodeRef {
constant(Type::Vec2, vec![x.into(), y.into()])
}
pub fn vec3(x: impl Into<f64>, y: impl Into<f64>, z: impl Into<f64>) -> NodeRef {
constant(Type::Vec3, vec![x.into(), y.into(), z.into()])
}
pub fn vec3s(x: impl Into<f64>) -> NodeRef {
let x = x.into();
constant(Type::Vec3, vec![x, x, x])
}
pub fn vec4(x: impl Into<f64>, y: impl Into<f64>, z: impl Into<f64>, w: impl Into<f64>) -> NodeRef {
constant(Type::Vec4, vec![x.into(), y.into(), z.into(), w.into()])
}
pub fn join(ty: Type, args: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::Join { args, ty })
}
pub fn vec2_join(args: Vec<NodeRef>) -> NodeRef {
join(Type::Vec2, args)
}
pub fn vec3_join(args: Vec<NodeRef>) -> NodeRef {
join(Type::Vec3, args)
}
pub fn vec4_join(args: Vec<NodeRef>) -> NodeRef {
join(Type::Vec4, args)
}
pub fn const_array(values: Vec<f64>) -> NodeRef {
NodeRef::new(Node::ConstArray {
element_ty: Type::F32,
values,
})
}
pub fn const_array_of(element_ty: Type, values: Vec<f64>) -> NodeRef {
assert_eq!(
values.len() % element_ty.components().max(1),
0,
"three-rs: const_array_of takes whole elements"
);
NodeRef::new(Node::ConstArray { element_ty, values })
}
pub fn array_var(values: Vec<f64>) -> NodeRef {
NodeRef::new(Node::ArrayVar {
element_ty: Type::F32,
values,
})
}
pub fn attribute(name: &'static str, ty: Type) -> NodeRef {
NodeRef::new(Node::Attribute { name, ty })
}
pub fn uniform_value(ty: Type, values: Vec<f64>) -> NodeRef {
uniform(UniformSource::Value(values), ty, UniformGroup::Object, None)
}
pub fn uniform_settable(ty: Type, values: Vec<f64>) -> (NodeRef, SettableValue) {
let cell = SettableValue::new(values);
let node = uniform(
UniformSource::Settable(cell.clone()),
ty,
UniformGroup::Object,
None,
);
(node, cell)
}
pub fn uniform_object(
ty: Type,
update: impl Fn(&crate::core::Object3D) -> Vec<f64> + 'static,
) -> NodeRef {
uniform(
UniformSource::ObjectUpdate(crate::nodes::node::ObjectUpdate::new(update)),
ty,
UniformGroup::Object,
None,
)
}
pub fn uniform_frame(
ty: Type,
update: impl Fn(&crate::nodes::NodeFrame) -> Vec<f64> + 'static,
) -> NodeRef {
uniform(
UniformSource::ObjectUpdate(crate::nodes::node::ObjectUpdate::with_frame(update)),
ty,
UniformGroup::Object,
None,
)
}
pub fn user_data(name: &str, ty: Type) -> NodeRef {
let name = name.to_owned();
let length = ty.components();
uniform_object(ty, move |object| {
let mut values = match object.user_data.get(&name) {
Some(serde_json::Value::Number(n)) => vec![n.as_f64().unwrap_or(0.0)],
Some(serde_json::Value::Array(items)) => {
items.iter().map(|v| v.as_f64().unwrap_or(0.0)).collect()
}
_ => Vec::new(),
};
values.resize(length, 0.0);
values
})
}
pub fn uniform(
source: UniformSource,
ty: Type,
group: UniformGroup,
name: Option<&'static str>,
) -> NodeRef {
NodeRef::new(Node::Uniform(Rc::new(UniformNode {
source,
ty,
group,
name: std::cell::Cell::new(name),
})))
}
pub fn to_var(name: Option<&'static str>, value: NodeRef) -> NodeRef {
let ty = value.ty();
NodeRef::new(Node::Var(Rc::new(VarDef {
name: name.map(sub_build_name),
value,
ty,
})))
}
pub fn to_const(name: Option<&'static str>, value: NodeRef) -> NodeRef {
let ty = value.ty();
NodeRef::new(Node::Let(Rc::new(VarDef {
name: name.map(sub_build_name),
value,
ty,
})))
}
pub fn to_var_intent(value: NodeRef) -> NodeRef {
let ty = value.ty();
NodeRef::new(Node::VarIntent(Rc::new(VarDef {
name: None,
value,
ty,
})))
}
fn to_var_untagged(name: &'static str, value: NodeRef) -> NodeRef {
let ty = value.ty();
NodeRef::new(Node::Var(Rc::new(VarDef {
name: Some(name.to_string()),
value,
ty,
})))
}
pub fn to_varying(name: Option<&'static str>, value: NodeRef) -> NodeRef {
let ty = value.ty();
NodeRef::new(Node::Varying(Rc::new(VaryingDef {
name,
value,
ty,
flat: matches!(ty, Type::U32 | Type::I32),
})))
}
pub fn output_struct(members: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::OutputStruct { members })
}
pub fn property(name: &'static str, ty: Type) -> NodeRef {
NodeRef::new(Node::Property { name, ty })
}
const COMPARISONS: [&str; 6] = ["==", "!=", "<", "<=", ">", ">="];
const LOGICAL: [&str; 2] = ["&&", "||"];
fn binary(op: &'static str, a: NodeRef, b: NodeRef) -> NodeRef {
let (ta, tb) = (a.ty(), b.ty());
if LOGICAL.contains(&op) {
return NodeRef::new(Node::Op {
op,
a,
b,
ty: Type::Bool,
});
}
if COMPARISONS.contains(&op) {
let n = ta.components().max(tb.components());
let ty = if n == 1 {
Type::Bool
} else {
Type::vector_of(Type::Bool, n)
};
return NodeRef::new(Node::Op { op, a, b, ty });
}
if ta.is_matrix() && !tb.is_matrix() && tb.components() > 1 {
let want = match ta {
Type::Mat4 => 4,
Type::Mat2 => 2,
_ => 3,
};
let ty = Type::vector_of(Type::F32, want);
let b = pad(b, want);
return NodeRef::new(Node::Op { op, a, b, ty });
}
if tb.is_matrix() && !ta.is_matrix() && ta.components() > 1 {
let want = match tb {
Type::Mat4 => 4,
Type::Mat2 => 2,
_ => 3,
};
let ty = Type::vector_of(Type::F32, want);
let a = pad(a, want);
return NodeRef::new(Node::Op { op, a, b, ty });
}
let ty = if ta.is_matrix() {
ta
} else if tb.is_matrix() || tb.components() > ta.components() {
tb
} else {
ta
};
NodeRef::new(Node::Op { op, a, b, ty })
}
fn pad(node: NodeRef, want: usize) -> NodeRef {
let have = node.ty().components();
if have >= want {
return node;
}
let mut args = vec![node];
for _ in have..want - 1 {
args.push(float(0.0));
}
args.push(float(1.0));
join(Type::vector_of(Type::F32, want), args)
}
fn math(name: &'static str, args: Vec<NodeRef>, ty: Type) -> NodeRef {
NodeRef::new(Node::Math { name, args, ty })
}
pub fn all(x: impl Into<NodeRef>) -> NodeRef {
math("all", vec![x.into()], Type::Bool)
}
pub fn mix(a: impl Into<NodeRef>, b: impl Into<NodeRef>, t: impl Into<NodeRef>) -> NodeRef {
let (a, b, t) = (a.into(), b.into(), t.into());
let ty = if b.ty().components() > a.ty().components() {
b.ty()
} else {
a.ty()
};
math("mix", vec![a, b, t], ty)
}
pub fn dot(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
math("dot", vec![a.into(), b.into()], Type::F32)
}
pub fn cross(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
let a = a.into();
let ty = a.ty();
math("cross", vec![a, b.into()], ty)
}
pub fn refract(i: impl Into<NodeRef>, n: impl Into<NodeRef>, eta: impl Into<NodeRef>) -> NodeRef {
let i = i.into();
let ty = i.ty();
math("refract", vec![i, n.into(), eta.into()], ty)
}
pub fn ceil(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("ceil", vec![x], ty)
}
pub fn reflect(i: impl Into<NodeRef>, n: impl Into<NodeRef>) -> NodeRef {
let i = i.into();
let ty = i.ty();
math("reflect", vec![i, n.into()], ty)
}
pub fn floor(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("floor", vec![x], ty)
}
pub fn fract(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("fract", vec![x], ty)
}
pub fn sign(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("sign", vec![x], ty)
}
pub fn exp2(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("exp2", vec![x], ty)
}
pub fn log2(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("log2", vec![x], ty)
}
pub fn log(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("log", vec![x], ty)
}
pub fn exp(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("exp", vec![x], ty)
}
pub fn min_of(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
let a = a.into();
let ty = a.ty();
math("min", vec![a, b.into()], ty)
}
pub fn length(v: impl Into<NodeRef>) -> NodeRef {
math("length", vec![v.into()], Type::F32)
}
pub fn distance(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
math("distance", vec![a.into(), b.into()], Type::F32)
}
pub fn two_pi() -> NodeRef {
float(std::f64::consts::TAU)
}
pub fn rotate(position: impl Into<NodeRef>, rotation: impl Into<NodeRef>) -> NodeRef {
let (position, rotation) = (position.into(), rotation.into());
match position.ty() {
Type::Vec2 => {
let cos_angle = rotation.cos();
let sin_angle = rotation.sin();
join(
Type::Mat2,
vec![
cos_angle.clone(),
sin_angle.clone(),
sin_angle.negate(),
cos_angle,
],
)
.mul(position)
}
Type::Vec3 => {
let r = &rotation;
let row = |args: Vec<NodeRef>| join(Type::Vec4, args);
let mat4 = |rows: Vec<NodeRef>| join(Type::Mat4, rows);
let zero = || float(0.0);
let rotation_x = mat4(vec![
vec4(1.0, 0.0, 0.0, 0.0),
row(vec![zero(), r.x().cos(), r.x().sin(), zero()]),
row(vec![zero(), r.x().sin().negate(), r.x().cos(), zero()]),
vec4(0.0, 0.0, 0.0, 1.0),
]);
let rotation_y = mat4(vec![
row(vec![r.y().cos(), zero(), r.y().sin().negate(), zero()]),
vec4(0.0, 1.0, 0.0, 0.0),
row(vec![r.y().sin(), zero(), r.y().cos(), zero()]),
vec4(0.0, 0.0, 0.0, 1.0),
]);
let rotation_z = mat4(vec![
row(vec![r.z().cos(), r.z().sin(), zero(), zero()]),
row(vec![r.z().sin().negate(), r.z().cos(), zero(), zero()]),
vec4(0.0, 0.0, 1.0, 0.0),
vec4(0.0, 0.0, 0.0, 1.0),
]);
rotation_x
.mul(rotation_y)
.mul(rotation_z)
.mul(vec4_join(vec![position, float(1.0)]))
.xyz()
}
ty => panic!("three-rs: rotate() of a {ty:?}"),
}
}
pub fn abs(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("abs", vec![x], ty)
}
pub fn fwidth(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("fwidth", vec![x], ty)
}
pub fn mod_float(x: impl Into<NodeRef>, y: impl Into<NodeRef>) -> NodeRef {
math("tsl_mod_float", vec![x.into(), y.into()], Type::F32)
}
pub fn smoothstep(
low: impl Into<NodeRef>,
high: impl Into<NodeRef>,
x: impl Into<NodeRef>,
) -> NodeRef {
let (low, high, x) = (low.into(), high.into(), x.into());
let ty = wrappers::math_input_type(&[&low, &high, &x]);
math("smoothstep", vec![low, high, x], ty)
}
pub fn dpdx(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("dpdx", vec![x], ty)
}
pub fn dpdy(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("- dpdy", vec![x], ty)
}
pub fn checker(coord: impl Into<NodeRef>) -> NodeRef {
let uv = coord.into().mul(2.0);
let cx = floor(uv.x());
let cy = floor(uv.y());
sign(mod_float(cx.add(cy), 2.0))
}
pub fn perspective_depth_to_view_z(
depth: impl Into<NodeRef>,
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
) -> NodeRef {
let (depth, near, far) = (depth.into(), near.into(), far.into());
near.clone()
.mul(far.clone())
.div(far.clone().sub(near).mul(depth).sub(far))
}
pub fn view_z_to_perspective_depth(
view_z: impl Into<NodeRef>,
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
) -> NodeRef {
let (view_z, near, far) = (view_z.into(), near.into(), far.into());
near.clone()
.add(view_z.clone())
.mul(far.clone())
.div(far.sub(near).mul(view_z))
}
pub fn get_view_position(
screen_position: NodeRef,
depth: NodeRef,
projection_matrix_inverse: NodeRef,
) -> NodeRef {
let screen_position = vec2_join(vec![screen_position.x(), screen_position.y().one_minus()])
.mul(2.0)
.sub(1.0);
let clip_space_position = vec4_join(vec![vec3_join(vec![screen_position, depth]), float(1.0)]);
let view_space_position = projection_matrix_inverse.mul(clip_space_position);
view_space_position.xyz().div(view_space_position.w())
}
pub fn get_screen_position_from_clip(clip_position: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("getScreenPositionFromClip"),
vec![("clipPosition", Type::Vec4)],
Type::Vec2,
|args| {
let clip = &args[0];
let screen = to_var(None, clip.xy().div(clip.w()).mul(0.5).add(0.5));
block(
vec![screen.clone()],
vec2_join(vec![screen.x(), screen.y().one_minus()]),
)
},
)
})
});
call(&def, vec![clip_position])
}
pub fn get_screen_position(view_position: NodeRef, projection_matrix: NodeRef) -> NodeRef {
let sample_clip_pos = projection_matrix.mul(vec4_join(vec![view_position, float(1.0)]));
let sample_uv = to_var(
None,
sample_clip_pos
.xy()
.div(sample_clip_pos.w())
.mul(0.5)
.add(0.5),
);
vec2_join(vec![sample_uv.x(), sample_uv.y().one_minus()])
}
pub fn get_normal_from_depth(
uv: NodeRef,
depth_texture: &DepthTexture,
projection_matrix_inverse: NodeRef,
) -> NodeRef {
let size = texture_size(TextureSource::Depth(depth_texture.clone()), int(0));
let p = to_var(None, uv.clone().mul(size.clone()).to(Type::IVec2));
let load = |coord: NodeRef| to_var(None, depth_texture_load(depth_texture, coord));
let c0 = load(p.clone());
let l2 = load(p.clone().sub(ivec2(2, 0)));
let l1 = load(p.clone().sub(ivec2(1, 0)));
let r1 = load(p.clone().add(ivec2(1, 0)));
let r2 = load(p.clone().add(ivec2(2, 0)));
let b2 = load(p.clone().add(ivec2(0, 2)));
let b1 = load(p.clone().add(ivec2(0, 1)));
let t1 = load(p.clone().sub(ivec2(0, 1)));
let t2 = load(p.sub(ivec2(0, 2)));
let delta = |near: &NodeRef, far: NodeRef| {
to_var(
None,
abs(float(2.0).mul(near.clone()).sub(far).sub(c0.clone())),
)
};
let dl = delta(&l1, l2.clone());
let dr = delta(&r1, r2.clone());
let db = delta(&b1, b2.clone());
let dt = delta(&t1, t2.clone());
let ce = to_var(
None,
get_view_position(uv.clone(), c0.clone(), projection_matrix_inverse.clone()),
);
let at = |coord: NodeRef, depth: NodeRef| {
get_view_position(coord, depth, projection_matrix_inverse.clone())
};
let texel_x = || vec2_join(vec![float(1.0).div(size.x()), float(0.0)]);
let texel_y = || vec2_join(vec![float(0.0), float(1.0).div(size.y())]);
let dpdx = dl.clone().less_than(dr.clone()).select(
ce.clone().sub(at(uv.clone().sub(texel_x()), l1.clone())),
ce.clone()
.negate()
.add(at(uv.clone().add(texel_x()), r1.clone())),
);
let dpdy = db.clone().less_than(dt.clone()).select(
ce.clone().sub(at(uv.clone().add(texel_y()), b1.clone())),
ce.clone().negate().add(at(uv.sub(texel_y()), t1.clone())),
);
block(
vec![p, c0, l2, l1, r1, r2, b2, b1, t1, t2, dl, dr, db, dt, ce],
cross(dpdx, dpdy).normalize(),
)
}
pub fn get_parallax_correct_normal(
normal: NodeRef,
cube_size: NodeRef,
cube_pos: NodeRef,
) -> NodeRef {
let n_dir = to_var(None, normal.normalize());
let toward = |half: f64| {
to_var(
None,
cube_size
.clone()
.mul(half)
.add(cube_pos.clone())
.sub(position_world())
.div(n_dir.clone()),
)
};
let rbmax = toward(0.5);
let rbmin = toward(-0.5);
let rbminmax = to_var(None, vec3(0.0, 0.0, 0.0));
let axis = |c: &'static str| {
rbminmax.swizzle(c).assign(
n_dir
.swizzle(c)
.greater_than(float(0.0))
.select(rbmax.swizzle(c), rbmin.swizzle(c)),
)
};
let correction = to_var(None, rbminmax.x().min(rbminmax.y()).min(rbminmax.z()));
let box_intersection = to_var(
None,
position_world().add(n_dir.clone().mul(correction.clone())),
);
let axes = vec![axis("x"), axis("y"), axis("z")];
let mut statements = vec![
n_dir.clone(),
rbmax.clone(),
rbmin.clone(),
rbminmax.clone(),
];
statements.extend(axes);
statements.extend([correction, box_intersection.clone()]);
block(statements, box_intersection.sub(cube_pos))
}
pub fn view_z_to_orthographic_depth(
view_z: impl Into<NodeRef>,
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
) -> NodeRef {
let (near, far) = (near.into(), far.into());
view_z.into().add(near.clone()).div(near.sub(far))
}
pub fn view_z_to_reversed_orthographic_depth(
view_z: impl Into<NodeRef>,
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
) -> NodeRef {
let (near, far) = (near.into(), far.into());
view_z.into().add(far.clone()).div(far.sub(near))
}
pub fn orthographic_depth_to_view_z(
depth: impl Into<NodeRef>,
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
) -> NodeRef {
let near = near.into();
near.clone().sub(far.into()).mul(depth.into()).sub(near)
}
pub fn view_z_to_reversed_perspective_depth(
view_z: impl Into<NodeRef>,
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
) -> NodeRef {
let (view_z, near, far) = (view_z.into(), near.into(), far.into());
near.clone()
.mul(view_z.clone().add(far.clone()))
.div(view_z.mul(near.sub(far)))
}
pub fn view_z_to_logarithmic_depth(
view_z: impl Into<NodeRef>,
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
) -> NodeRef {
let near = to_var(None, near.into().max(1e-6));
let numerator = log2(view_z.into().negate().div(near.clone()));
let denominator = log2(far.into().div(near));
numerator.div(denominator)
}
pub fn logarithmic_depth_to_view_z(
depth: impl Into<NodeRef>,
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
) -> NodeRef {
let near = near.into();
let exponent = depth.into().mul(log(far.into().div(near.clone())));
float(std::f64::consts::E).pow(exponent).mul(near).negate()
}
pub fn linear_depth() -> NodeRef {
view_z_to_orthographic_depth(position_view().z(), camera_near(), camera_far())
}
pub fn linear_depth_of(value: impl Into<NodeRef>) -> NodeRef {
let view_z = perspective_depth_to_view_z(value, camera_near(), camera_far());
view_z_to_orthographic_depth(view_z, camera_near(), camera_far())
}
fn fog_view_z() -> NodeRef {
current_context(|cx| cx.extra.get("getViewZ").cloned()).unwrap_or_else(|| position_view().z())
}
pub fn range_fog_factor(near: impl Into<NodeRef>, far: impl Into<NodeRef>) -> NodeRef {
let (near, far) = (near.into(), far.into());
fog_factor_fn(move || range_fog_factor_with_view_z(near.clone(), far.clone(), fog_view_z()))
}
fn fog_factor_fn(body: impl Fn() -> NodeRef + 'static) -> NodeRef {
call(&inline_fn(0, Type::F32, move |_| body()), Vec::new())
}
pub(crate) fn resolve_fog_factor(factor: &NodeRef) -> NodeRef {
resolve_fn_call(factor)
}
pub(crate) fn resolve_fn_call(node: &NodeRef) -> NodeRef {
match node.node() {
Node::Call { def, args } if !def.layout && args.is_empty() => (def.body)(&[]),
_ => node.clone(),
}
}
pub fn range_fog_factor_with_view_z(
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
view_z: impl Into<NodeRef>,
) -> NodeRef {
smoothstep(near, far, view_z.into().negate())
}
pub fn density_fog_factor(density: impl Into<NodeRef>) -> NodeRef {
let density = density.into();
fog_factor_fn(move || density_fog_factor_with_view_z(density.clone(), fog_view_z()))
}
pub fn density_fog_factor_with_view_z(
density: impl Into<NodeRef>,
view_z: impl Into<NodeRef>,
) -> NodeRef {
let density = density.into();
let view_z = to_const(None, view_z.into().negate());
exp(density
.clone()
.mul(density)
.mul(view_z.clone())
.mul(view_z)
.negate())
.one_minus()
}
pub fn exponential_height_fog_factor(
density: impl Into<NodeRef>,
height: impl Into<NodeRef>,
) -> NodeRef {
let (density, height) = (density.into(), height.into());
fog_factor_fn(move || {
exponential_height_fog_factor_with_view_z(density.clone(), height.clone(), fog_view_z())
})
}
pub fn exponential_height_fog_factor_with_view_z(
density: impl Into<NodeRef>,
height: impl Into<NodeRef>,
view_z: impl Into<NodeRef>,
) -> NodeRef {
let density = density.into();
let view_z = view_z.into().negate();
let distance = to_const(None, height.into().sub(position_world().y()).max(0.0));
let m = to_const(None, distance.mul(view_z));
exp(density.clone().mul(density).mul(m.clone()).mul(m).negate()).one_minus()
}
pub fn fog(color: impl Into<NodeRef>, factor: impl Into<NodeRef>) -> FogNode {
FogNode {
color: color.into(),
factor: factor.into(),
}
}
#[derive(Clone)]
pub struct FogNode {
pub color: NodeRef,
pub factor: NodeRef,
}
impl std::hash::Hash for FogNode {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.color.key().hash(state);
self.factor.key().hash(state);
}
}
pub(crate) fn light_color_intensity(index: usize) -> NodeRef {
uniform(
UniformSource::LightColorIntensity(index),
Type::Vec3,
UniformGroup::Render,
None,
)
}
pub(crate) fn light_cutoff_distance(index: usize) -> NodeRef {
uniform(
UniformSource::LightCutoffDistance(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn light_decay(index: usize) -> NodeRef {
uniform(
UniformSource::LightDecay(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub fn light_view_position(index: usize) -> NodeRef {
uniform(
UniformSource::LightViewPosition(index),
Type::Vec3,
UniformGroup::Render,
None,
)
}
pub(crate) fn light_ground_color(index: usize) -> NodeRef {
uniform(
UniformSource::LightGroundColor(index),
Type::Vec3,
UniformGroup::Render,
None,
)
}
pub fn light_world_position(index: usize) -> NodeRef {
uniform(
UniformSource::LightWorldPosition(index),
Type::Vec3,
UniformGroup::Render,
None,
)
}
pub fn light_target_position(index: usize) -> NodeRef {
uniform(
UniformSource::LightTargetPosition(index),
Type::Vec3,
UniformGroup::Render,
None,
)
}
pub(crate) fn light_cone_cos(index: usize) -> NodeRef {
uniform(
UniformSource::LightConeCos(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn light_penumbra_cos(index: usize) -> NodeRef {
uniform(
UniformSource::LightPenumbraCos(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub fn shadow_matrix(index: usize) -> NodeRef {
thread_local! {
static CACHE: RefCell<HashMap<usize, NodeRef>> = RefCell::new(HashMap::new());
}
CACHE.with(|c| {
c.borrow_mut()
.entry(index)
.or_insert_with(|| {
outside_sub_build(|| {
uniform(
UniformSource::ShadowMatrix(index),
Type::Mat4,
UniformGroup::Render,
None,
)
})
})
.clone()
})
}
pub fn light_projection_uv(light: usize, position: NodeRef) -> NodeRef {
let position = if position.ty() == Type::Vec3 {
vec4_join(vec![position, float(1.0)])
} else {
position
};
let spot_light_coord = shadow_matrix(light).mul(position);
spot_light_coord.xyz().div(spot_light_coord.w())
}
pub fn direct_point_light(
color: NodeRef,
light_vector: NodeRef,
cutoff_distance: NodeRef,
decay_exponent: NodeRef,
) -> (NodeRef, NodeRef) {
use crate::materials::phong::{
distance_attenuation_no_cutoff, distance_attenuation_with_cutoff,
};
let attenuation = cutoff_distance.greater_than(0.0).select(
distance_attenuation_with_cutoff(
length(light_vector.clone()),
cutoff_distance,
decay_exponent.clone(),
),
distance_attenuation_no_cutoff(length(light_vector.clone()), decay_exponent),
);
(light_vector.normalize(), color.mul(attenuation))
}
pub(crate) fn shadow_camera_near(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowCameraNear(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_camera_far(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowCameraFar(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_bias(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowBias(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_normal_bias(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowNormalBias(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_radius(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowRadius(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_blur_samples(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowBlurSamples(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_map_size(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowMapSize(index),
Type::Vec2,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_intensity(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowIntensity(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub fn material_metalness() -> NodeRef {
uniform(
UniformSource::MaterialMetalness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_ior() -> NodeRef {
uniform(
UniformSource::MaterialIor,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_specular_intensity() -> NodeRef {
uniform(
UniformSource::MaterialSpecularIntensity,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_specular_color() -> NodeRef {
uniform(
UniformSource::MaterialSpecularColor,
Type::Vec3,
UniformGroup::Object,
None,
)
}
pub fn material_sheen() -> NodeRef {
uniform(
UniformSource::MaterialSheen,
Type::F32,
UniformGroup::Object,
None,
)
}
pub(crate) fn material_sheen_color() -> NodeRef {
uniform(
UniformSource::MaterialSheenColor,
Type::Vec3,
UniformGroup::Object,
None,
)
}
pub fn material_sheen_roughness() -> NodeRef {
uniform(
UniformSource::MaterialSheenRoughness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_iridescence() -> NodeRef {
uniform(
UniformSource::MaterialIridescence,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_iridescence_ior() -> NodeRef {
uniform(
UniformSource::MaterialIridescenceIor,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_iridescence_thickness_max() -> NodeRef {
uniform(
UniformSource::MaterialIridescenceThicknessMax,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_iridescence_thickness_min() -> NodeRef {
uniform(
UniformSource::MaterialIridescenceThicknessMin,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_diffuse_roughness() -> NodeRef {
uniform(
UniformSource::MaterialDiffuseRoughness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_anisotropy_vector() -> NodeRef {
uniform(
UniformSource::MaterialAnisotropyVector,
Type::Vec2,
UniformGroup::Object,
None,
)
}
pub fn material_clearcoat() -> NodeRef {
uniform(
UniformSource::MaterialClearcoat,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_clearcoat_roughness() -> NodeRef {
uniform(
UniformSource::MaterialClearcoatRoughness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_transmission() -> NodeRef {
uniform(
UniformSource::MaterialTransmission,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_thickness() -> NodeRef {
uniform(
UniformSource::MaterialThickness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_attenuation_distance() -> NodeRef {
uniform(
UniformSource::MaterialAttenuationDistance,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_attenuation_color() -> NodeRef {
uniform(
UniformSource::MaterialAttenuationColor,
Type::Vec3,
UniformGroup::Object,
None,
)
}
pub(crate) fn material_clearcoat_normal_scale() -> NodeRef {
uniform(
UniformSource::MaterialClearcoatNormalScale,
Type::Vec2,
UniformGroup::Object,
None,
)
}
pub(crate) fn material_normal_scale() -> NodeRef {
uniform(
UniformSource::MaterialNormalScale,
Type::Vec2,
UniformGroup::Object,
None,
)
}
pub fn material_roughness() -> NodeRef {
uniform(
UniformSource::MaterialRoughness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_metalness_value() -> NodeRef {
current_context(|cx| cx.material_metalness.clone()).unwrap_or_else(material_metalness)
}
pub fn material_roughness_value() -> NodeRef {
current_context(|cx| cx.material_roughness.clone()).unwrap_or_else(material_roughness)
}
pub(crate) fn with_material_values<R>(
metalness: NodeRef,
roughness: NodeRef,
f: impl FnOnce() -> R,
) -> R {
let _values = push_context(|cx| {
cx.material_metalness = Some(metalness);
cx.material_roughness = Some(roughness);
});
f()
}
pub(crate) fn material_bump_scale() -> NodeRef {
uniform(
UniformSource::MaterialBumpScale,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn tone_mapping_exposure() -> NodeRef {
uniform(
UniformSource::ToneMappingExposure,
Type::F32,
UniformGroup::Render,
None,
)
}
pub fn inverse_sqrt(x: impl Into<NodeRef>) -> NodeRef {
math("inverseSqrt", vec![x.into()], Type::F32)
}
pub fn tbn_view_matrix() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
let key = normal_key();
if let Some(node) = CELL.with(|m| m.borrow().get(&key).cloned()) {
return node;
}
let node = to_var(
Some("TBNViewMatrix"),
join(
Type::Mat3,
vec![tangent_view(), bitangent_view(), normal_view()],
),
);
CELL.with(|m| m.borrow_mut().insert(key, node.clone()));
node
}
pub fn normal_map(node: impl Into<NodeRef>) -> NodeRef {
let texel = node.into();
in_sub_build("NORMAL", || {
tbn_view_matrix()
.mul(texel.mul(2.0).sub(1.0).xyz())
.normalize()
})
}
pub fn normal_map_scaled(node: impl Into<NodeRef>, scale: NodeRef) -> NodeRef {
let texel = node.into();
in_sub_build("NORMAL", || normal_map_scaled_unlayered(texel, scale))
}
fn normal_map_scaled_unlayered(texel: NodeRef, scale: NodeRef) -> NodeRef {
let unpacked = to_var(None, texel.mul(2.0).sub(1.0));
tbn_view_matrix()
.mul(vec3_join(vec![unpacked.xy().mul(scale), unpacked.z()]))
.normalize()
}
pub fn sqrt(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("sqrt", vec![x], ty)
}
pub fn max(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
let a = a.into();
let ty = a.ty();
math("max", vec![a, b.into()], ty)
}
fn whole(ty: Type) -> &'static str {
match ty.components() {
1 => "x",
2 => "xy",
3 => "xyz",
_ => "xyzw",
}
}
fn swizzle(node: NodeRef, components: &'static str) -> NodeRef {
if components == whole(node.ty()) {
return node;
}
if node.ty().components() == 1 {
let ty = Type::vector_of(node.ty().component_type(), components.len());
return node.to(ty);
}
let ty = Type::vector_of(node.ty().component_type(), components.len());
NodeRef::new(Node::Swizzle {
node,
components,
ty,
})
}
fn cached_rgb(node: NodeRef) -> NodeRef {
if node.ty().components() != 3 {
return swizzle(node, "xyz");
}
let ty = Type::vector_of(node.ty().component_type(), 3);
NodeRef::new(Node::Swizzle {
node,
components: "xyz",
ty,
})
}
impl NodeRef {
pub fn add(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("+", self.clone(), other.into())
}
pub fn sub(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("-", self.clone(), other.into())
}
pub fn mul(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("*", self.clone(), other.into())
}
pub fn div(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("/", self.clone(), other.into())
}
pub fn modulo(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("%", self.clone(), other.into())
}
pub fn equal(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("==", self.clone(), other.into())
}
pub fn not_equal(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("!=", self.clone(), other.into())
}
pub fn less_than_equal(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("<=", self.clone(), other.into())
}
pub fn greater_than(&self, other: impl Into<NodeRef>) -> NodeRef {
binary(">", self.clone(), other.into())
}
pub fn greater_than_equal(&self, other: impl Into<NodeRef>) -> NodeRef {
binary(">=", self.clone(), other.into())
}
pub fn less_than(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("<", self.clone(), other.into())
}
pub fn and(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("&&", self.clone(), other.into())
}
pub fn or(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("||", self.clone(), other.into())
}
pub fn not(&self) -> NodeRef {
NodeRef::new(Node::Not { node: self.clone() })
}
pub fn shift_left(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("<<", self.clone(), other.into())
}
pub fn shift_right(&self, other: impl Into<NodeRef>) -> NodeRef {
binary(">>", self.clone(), other.into())
}
pub fn bit_and(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("&", self.clone(), other.into())
}
pub fn bit_or(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("|", self.clone(), other.into())
}
pub fn bit_xor(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("^", self.clone(), other.into())
}
pub fn one_minus(&self) -> NodeRef {
binary("-", float(1.0), self.clone())
}
pub fn negate(&self) -> NodeRef {
NodeRef::new(Node::Neg {
node: self.clone(),
ty: self.ty(),
})
}
pub fn normalize(&self) -> NodeRef {
math("normalize", vec![self.clone()], self.ty())
}
pub fn cos(&self) -> NodeRef {
math("cos", vec![self.clone()], self.ty())
}
pub fn sin(&self) -> NodeRef {
math("sin", vec![self.clone()], self.ty())
}
pub fn asin(&self) -> NodeRef {
math("asin", vec![self.clone()], self.ty())
}
pub fn atan2(&self, x: impl Into<NodeRef>) -> NodeRef {
math("atan2", vec![self.clone(), x.into()], self.ty())
}
pub fn floor(&self) -> NodeRef {
math("floor", vec![self.clone()], self.ty())
}
pub fn fract(&self) -> NodeRef {
math("fract", vec![self.clone()], self.ty())
}
pub fn sqrt(&self) -> NodeRef {
math("sqrt", vec![self.clone()], self.ty())
}
pub fn abs(&self) -> NodeRef {
math("abs", vec![self.clone()], self.ty())
}
pub fn saturate(&self) -> NodeRef {
let ty = self.ty();
let lo = if ty.components() > 1 {
constant(ty, vec![0.0; ty.components()])
} else {
float(0.0)
};
let hi = if ty.components() > 1 {
constant(ty, vec![1.0; ty.components()])
} else {
float(1.0)
};
math("clamp", vec![self.clone(), lo, hi], ty)
}
pub fn pow(&self, other: impl Into<NodeRef>) -> NodeRef {
math("pow", vec![self.clone(), other.into()], self.ty())
}
pub fn pow3(&self) -> NodeRef {
self.mul(self.clone()).mul(self.clone())
}
pub fn reciprocal(&self) -> NodeRef {
float(1.0).div(self.clone())
}
pub fn exp2(&self) -> NodeRef {
exp2(self.clone())
}
pub fn max(&self, other: impl Into<NodeRef>) -> NodeRef {
math("max", vec![self.clone(), other.into()], self.ty())
}
pub fn min(&self, other: impl Into<NodeRef>) -> NodeRef {
math("min", vec![self.clone(), other.into()], self.ty())
}
pub fn clamp(&self, lo: impl Into<NodeRef>, hi: impl Into<NodeRef>) -> NodeRef {
math("clamp", vec![self.clone(), lo.into(), hi.into()], self.ty())
}
pub fn dot(&self, other: impl Into<NodeRef>) -> NodeRef {
dot(self.clone(), other)
}
pub fn cross(&self, other: impl Into<NodeRef>) -> NodeRef {
cross(self.clone(), other)
}
pub fn mix(&self, a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
mix(a, b, self.clone())
}
pub fn swizzle(&self, components: &'static str) -> NodeRef {
swizzle(self.clone(), components)
}
pub fn x(&self) -> NodeRef {
swizzle(self.clone(), "x")
}
pub fn y(&self) -> NodeRef {
swizzle(self.clone(), "y")
}
pub fn z(&self) -> NodeRef {
swizzle(self.clone(), "z")
}
pub fn w(&self) -> NodeRef {
swizzle(self.clone(), "w")
}
pub fn xy(&self) -> NodeRef {
swizzle(self.clone(), "xy")
}
pub fn yz(&self) -> NodeRef {
swizzle(self.clone(), "yz")
}
pub fn zw(&self) -> NodeRef {
swizzle(self.clone(), "zw")
}
pub fn zx(&self) -> NodeRef {
swizzle(self.clone(), "zx")
}
pub fn xyz(&self) -> NodeRef {
swizzle(self.clone(), "xyz")
}
pub fn xz(&self) -> NodeRef {
swizzle(self.clone(), "xz")
}
pub fn zzz(&self) -> NodeRef {
swizzle(self.clone(), "zzz")
}
pub fn rgb(&self) -> NodeRef {
swizzle(self.clone(), "xyz")
}
pub fn a(&self) -> NodeRef {
swizzle(self.clone(), "w")
}
pub fn set_z(&self, z: impl Into<NodeRef>) -> NodeRef {
join(Type::Vec4, vec![self.x(), self.y(), z.into(), self.w()])
}
pub fn to(&self, ty: Type) -> NodeRef {
if self.ty() == ty {
return self.clone();
}
NodeRef::new(Node::Cast {
node: self.clone(),
ty,
})
}
pub fn element(&self, index: usize) -> NodeRef {
let ty = match self.ty() {
Type::Mat4 => Type::Vec4,
Type::Mat3 => Type::Vec3,
Type::Mat2 => Type::Vec2,
other => other.component_type(),
};
NodeRef::new(Node::Element {
node: self.clone(),
index: constant(Type::U32, vec![index as f64]),
ty,
})
}
pub fn element_node(&self, index: NodeRef) -> NodeRef {
let ty = match self.ty() {
Type::Mat4 => Type::Vec4,
Type::Mat3 => Type::Vec3,
Type::Mat2 => Type::Vec2,
other if matches!(self.node(), Node::ConstArray { .. } | Node::ArrayVar { .. }) => {
other
}
other => other.component_type(),
};
NodeRef::new(Node::Element {
node: self.clone(),
index,
ty,
})
}
pub fn select(&self, a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
let a = a.into();
let ty = a.ty();
NodeRef::new(Node::Select {
cond: self.clone(),
a,
b: b.into(),
ty,
})
}
pub fn flip_y(&self) -> NodeRef {
let source = to_var(None, self.clone());
match self.ty() {
Type::Vec2 => vec2_join(vec![source.x(), float(1.0).sub(source.y())]),
Type::Vec3 => vec3_join(vec![source.x(), float(1.0).sub(source.y()), source.z()]),
Type::Vec4 => vec4_join(vec![
source.x(),
float(1.0).sub(source.y()),
source.z(),
source.w(),
]),
ty => panic!("flipY() on a {ty:?}"),
}
}
pub fn flip_x(&self) -> NodeRef {
let source = to_var(None, self.clone());
match self.ty() {
Type::Vec2 => vec2_join(vec![float(1.0).sub(source.x()), source.y()]),
Type::Vec3 => vec3_join(vec![float(1.0).sub(source.x()), source.y(), source.z()]),
Type::Vec4 => vec4_join(vec![
float(1.0).sub(source.x()),
source.y(),
source.z(),
source.w(),
]),
ty => panic!("flipX() on a {ty:?}"),
}
}
pub fn to_var(&self, name: &'static str) -> NodeRef {
to_var(Some(name), self.clone())
}
pub fn context(&self, value: ContextValue) -> NodeRef {
context(self.clone(), value)
}
pub fn isolate(&self) -> NodeRef {
isolate(self.clone())
}
pub fn to_varying(&self, name: &'static str) -> NodeRef {
to_varying(Some(name), self.clone())
}
pub fn add_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
self.assign(self.add(value))
}
pub fn sub_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
self.assign(self.sub(value))
}
pub fn mul_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
self.assign(self.mul(value))
}
pub fn div_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
self.assign(self.div(value))
}
pub fn assign(&self, value: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Assign {
target: self.clone(),
value: value.into(),
})
}
}
macro_rules! accessor {
($(#[$m:meta])* pub(crate) $name:ident, $body:expr) => {
$(#[$m])*
pub(crate) fn $name() -> NodeRef {
thread_local! {
static CELL: Lazy<NodeRef> = const { Lazy::new() };
}
CELL.with(|c| c.get(|| outside_sub_build(|| $body)))
}
};
($(#[$m:meta])* $name:ident, $body:expr) => {
$(#[$m])*
pub fn $name() -> NodeRef {
thread_local! {
static CELL: Lazy<NodeRef> = const { Lazy::new() };
}
CELL.with(|c| c.get(|| outside_sub_build(|| $body)))
}
};
}
fn outside_sub_build<R>(f: impl FnOnce() -> R) -> R {
let _top = push_context(|cx| cx.sub_build = None);
f()
}
accessor!(
position_geometry,
attribute("position", Type::Vec3)
);
accessor!(
normal_geometry,
attribute("normal", Type::Vec3)
);
accessor!(
uv,
to_varying(None, attribute("uv", Type::Vec2))
);
accessor!(
uv1,
to_varying(None, attribute("uv1", Type::Vec2))
);
accessor!(
pub(crate) vertex_color_rgb,
to_varying(
None,
vec4_join(vec![attribute("color", Type::Vec3), float(1.0)])
)
);
accessor!(
pub(crate) vertex_color_rgba,
to_varying(None, attribute("color", Type::Vec4))
);
pub fn vertex_color(item_size: usize) -> NodeRef {
match item_size {
4 => vertex_color_rgba(),
_ => vertex_color_rgb(),
}
}
accessor!(
vertex_index,
NodeRef::new(Node::Builtin(Builtin::VertexIndex))
);
accessor!(
instance_index,
NodeRef::new(Node::Builtin(Builtin::InstanceIndex))
);
accessor!(
invocation_local_index,
NodeRef::new(Node::Builtin(Builtin::InvocationLocalIndex))
);
accessor!(
workgroup_id,
NodeRef::new(Node::Builtin(Builtin::WorkgroupId))
);
accessor!(
local_id,
NodeRef::new(Node::Builtin(Builtin::LocalId))
);
accessor!(
global_id,
NodeRef::new(Node::Builtin(Builtin::GlobalId))
);
accessor!(
num_workgroups,
NodeRef::new(Node::Builtin(Builtin::NumWorkgroups))
);
accessor!(
subgroup_size,
NodeRef::new(Node::Builtin(Builtin::SubgroupSize))
);
accessor!(
subgroup_index,
NodeRef::new(Node::Builtin(Builtin::SubgroupIndex))
);
accessor!(
invocation_subgroup_index,
NodeRef::new(Node::Builtin(Builtin::InvocationSubgroupIndex))
);
accessor!(
front_facing,
NodeRef::new(Node::Builtin(Builtin::FrontFacing))
);
accessor!(
face_direction,
front_facing().to(Type::F32).mul(2.0).sub(1.0)
);
accessor!(
frag_coord,
NodeRef::new(Node::Builtin(Builtin::FragCoord))
);
accessor!(
camera_projection_matrix,
uniform(
UniformSource::CameraProjectionMatrix,
Type::Mat4,
UniformGroup::Render,
Some("cameraProjectionMatrix")
)
);
accessor!(
camera_view_matrix,
uniform(
UniformSource::CameraViewMatrix,
Type::Mat4,
UniformGroup::Render,
Some("cameraViewMatrix")
)
);
accessor!(
camera_world_matrix,
uniform(
UniformSource::CameraWorldMatrix,
Type::Mat4,
UniformGroup::Render,
Some("cameraWorldMatrix")
)
);
accessor!(
camera_position,
uniform(
UniformSource::CameraPosition,
Type::Vec3,
UniformGroup::Render,
Some("cameraPosition")
)
);
accessor!(
model_world_matrix,
uniform(
UniformSource::ModelWorldMatrix,
Type::Mat4,
UniformGroup::Object,
None
)
);
accessor!(
model_normal_matrix,
uniform(
UniformSource::ModelNormalMatrix,
Type::Mat3,
UniformGroup::Object,
None
)
);
accessor!(
material_color,
uniform(
UniformSource::MaterialColor,
Type::Vec3,
UniformGroup::Object,
None
)
);
accessor!(
material_opacity,
uniform(
UniformSource::MaterialOpacity,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_alpha_test,
uniform(
UniformSource::MaterialAlphaTest,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_rotation,
uniform(
UniformSource::MaterialRotation,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_shininess,
uniform(
UniformSource::MaterialShininess,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_specular,
uniform(
UniformSource::MaterialSpecular,
Type::Vec3,
UniformGroup::Object,
None
)
);
accessor!(
material_emissive,
uniform(
UniformSource::MaterialEmissive,
Type::Vec3,
UniformGroup::Object,
None
)
);
accessor!(
pub(crate) material_emissive_intensity,
uniform(
UniformSource::MaterialEmissiveIntensity,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
pub(crate) material_ao_map_intensity,
uniform(
UniformSource::MaterialAoMapIntensity,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
pub(crate) material_light_map_intensity,
uniform(
UniformSource::MaterialLightMapIntensity,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_point_size,
uniform(
UniformSource::MaterialPointSize,
Type::F32,
UniformGroup::Object,
None
)
);
fn with_material_normal_scope<R>(material: &MeshBasicNodeMaterial, f: impl FnOnce() -> R) -> R {
let _material = push_context(|cx| {
cx.material_side = material.side;
cx.flat_shading = material.flat_shading;
});
f()
}
pub fn material_normal(material: &MeshBasicNodeMaterial) -> NodeRef {
with_material_normal_scope(material, || {
match (&material.normal_map, &material.bump_map) {
(Some(map), _) => normal_map_scaled_unlayered(texture(map), material_normal_scale()),
(None, Some(bump)) => {
bump_map_unlayered(|texture| texture(bump).x(), material_bump_scale())
}
(None, None) => normal_view(),
}
})
}
pub fn material_clearcoat_normal(material: &MeshBasicNodeMaterial) -> NodeRef {
with_material_normal_scope(material, || match &material.clearcoat_normal_map {
Some(map) => normal_map_scaled_unlayered(texture(map), material_clearcoat_normal_scale()),
None => normal_view(),
})
}
pub fn material_specular_strength(material: &MeshBasicNodeMaterial) -> NodeRef {
match &material.specular_map {
Some(map) => texture(map).x(),
None => float(1.0),
}
}
pub fn material_light_map(material: &MeshBasicNodeMaterial) -> NodeRef {
match &material.light_map {
Some(map) => texture(map).rgb().mul(material_light_map_intensity()),
None => vec3(0.0, 0.0, 0.0),
}
}
pub fn material_ao(material: &MeshBasicNodeMaterial) -> NodeRef {
match &material.ao_map {
Some(map) => texture(map)
.x()
.sub(float(1.0))
.mul(material_ao_map_intensity())
.add(float(1.0)),
None => float(1.0),
}
}
accessor!(
material_env_intensity,
uniform(
UniformSource::MaterialEnvIntensity,
Type::F32,
UniformGroup::Object,
None,
)
);
accessor!(
material_reflectivity,
uniform(
UniformSource::MaterialReflectivity,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_refraction_ratio,
uniform(
UniformSource::MaterialRefractionRatio,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_env_rotation,
uniform(
UniformSource::EnvRotationMatrix,
Type::Mat4,
UniformGroup::Object,
None
)
);
accessor!(
background_rotation,
uniform(
UniformSource::BackgroundRotation,
Type::Mat4,
UniformGroup::Render,
None
)
);
accessor!(
background_blurriness,
uniform(
UniformSource::BackgroundBlurriness,
Type::F32,
UniformGroup::Render,
None
)
);
accessor!(
background_intensity,
uniform(
UniformSource::BackgroundIntensity,
Type::F32,
UniformGroup::Render,
None
)
);
accessor!(
time,
uniform(UniformSource::Time, Type::F32, UniformGroup::Render, None)
);
accessor!(
viewport_size,
uniform(
UniformSource::ViewportSize,
Type::Vec2,
UniformGroup::Render,
None
)
);
accessor!(
viewport,
uniform(UniformSource::Viewport, Type::Vec4, UniformGroup::Render, None)
);
accessor!(
screen_dpr,
uniform(UniformSource::ScreenDpr, Type::F32, UniformGroup::Render, None)
);
accessor!(
screen_size,
viewport_size()
);
accessor!(
screen_coordinate,
frag_coord().xy()
);
accessor!(
viewport_coordinate,
screen_coordinate().sub(viewport().xy())
);
accessor!(
viewport_uv,
viewport_coordinate().div(viewport().zw())
);
accessor!(
camera_near,
uniform(
UniformSource::CameraNear,
Type::F32,
UniformGroup::Render,
Some("cameraNear")
)
);
accessor!(
camera_far,
uniform(
UniformSource::CameraFar,
Type::F32,
UniformGroup::Render,
Some("cameraFar")
)
);
accessor!(
camera_normal_matrix,
uniform(
UniformSource::CameraNormalMatrix,
Type::Mat3,
UniformGroup::Render,
Some("cameraNormalMatrix")
)
);
accessor!(
camera_projection_matrix_inverse,
uniform(
UniformSource::CameraProjectionMatrixInverse,
Type::Mat4,
UniformGroup::Render,
Some("cameraProjectionMatrixInverse")
)
);
accessor!(
model_world_matrix_inverse,
uniform(
UniformSource::ModelWorldMatrixInverse,
Type::Mat4,
UniformGroup::Object,
None
)
);
accessor!(
material_line_width,
uniform(
UniformSource::MaterialLineWidth,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
screen_uv,
frag_coord().xy().div(viewport_size())
);
accessor!(
position_local,
to_varying(Some("positionLocal"), position_geometry())
);
accessor!(
position_previous,
to_varying(Some("positionPrevious"), position_geometry())
);
accessor!(
normal_local,
to_var(Some("normalLocal"), normal_geometry())
);
accessor!(
model_view_matrix,
to_var(Some("modelViewMatrix"), mediump_model_view_matrix())
);
pub fn mediump_model_view_matrix() -> NodeRef {
camera_view_matrix().mul(model_world_matrix())
}
accessor!(
highp_model_view_matrix,
to_var(
Some("highpModelViewMatrix"),
uniform(
UniformSource::HighpModelViewMatrix,
Type::Mat4,
UniformGroup::Object,
None
)
)
);
accessor!(
highp_model_normal_view_matrix,
to_var(
Some("highpModelNormalViewMatrix"),
uniform(
UniformSource::HighpModelNormalViewMatrix,
Type::Mat3,
UniformGroup::Object,
None
)
)
);
fn object_3d_uniform(scope: Object3DScope, object: Option<LiveValue>) -> NodeRef {
let ty = match scope {
Object3DScope::Radius => Type::F32,
_ => Type::Vec3,
};
uniform(
UniformSource::Object3D { scope, object },
ty,
UniformGroup::Object,
None,
)
}
accessor!(
model_direction,
object_3d_uniform(Object3DScope::Direction, None)
);
accessor!(
model_position,
object_3d_uniform(Object3DScope::Position, None)
);
accessor!(
model_scale,
object_3d_uniform(Object3DScope::Scale, None)
);
accessor!(
model_view_position,
object_3d_uniform(Object3DScope::ViewPosition, None)
);
accessor!(
model_radius,
object_3d_uniform(Object3DScope::Radius, None)
);
pub fn clip_space() -> NodeRef {
struct ClipSpace;
impl CustomNode for ClipSpace {
fn type_name(&self) -> &'static str {
"ClipSpace"
}
fn node_type(&self) -> Type {
Type::Vec4
}
fn setup(&self, builder: &crate::nodes::NodeBuilder) -> NodeRef {
builder
.context("clipSpace")
.unwrap_or_else(|| vec4(0.0, 0.0, 0.0, 0.0))
}
}
struct ClipSpaceFn(NodeRef);
impl CustomNode for ClipSpaceFn {
fn type_name(&self) -> &'static str {
"ClipSpaceFn"
}
fn node_type(&self) -> Type {
Type::Vec4
}
fn is_cacheable(&self) -> bool {
false
}
fn setup(&self, builder: &crate::nodes::NodeBuilder) -> NodeRef {
if builder.is_fragment_stage() {
return self.0.clone();
}
thread_local! { static WARNED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
if !WARNED.with(|w| w.replace(true)) {
eprintln!("three-rs: TSL: `clipSpace` is only available in fragment stage.");
}
vec4(0.0, 0.0, 0.0, 0.0)
}
}
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| {
c.get(|| {
custom(ClipSpaceFn(to_varying(
Some("v_clipSpace"),
custom(ClipSpace),
)))
})
})
}
pub fn position_view() -> NodeRef {
if let Some(node) = override_node(|o| &o.position_view) {
return node;
}
position_view_pair().0
}
accessor!(
position_world,
to_varying(
Some("v_positionWorld"),
model_world_matrix()
.mul(vec4_join(vec![position_local(), float(1.0)]))
.xyz()
)
);
accessor!(
position_world_direction,
to_var(
Some("positionWorldDirection"),
to_varying(
Some("v_positionWorldDirection"),
model_world_matrix()
.mul(vec4_join(vec![position_local(), float(0.0)]))
.xyz()
.normalize()
)
.normalize()
)
);
pub fn position_view_direction() -> NodeRef {
if let Some(node) = override_node(|o| &o.position_view_direction) {
return node;
}
thread_local! {
static PERSPECTIVE: Lazy<NodeRef> = const { Lazy::new() };
static ORTHOGRAPHIC: Lazy<NodeRef> = const { Lazy::new() };
}
if current_context(|cx| cx.orthographic_camera) {
ORTHOGRAPHIC.with(|c| {
c.get(|| {
outside_sub_build(|| to_var(Some("positionViewDirection"), vec3(0.0, 0.0, 1.0)))
})
})
} else {
PERSPECTIVE.with(|c| {
c.get(|| {
outside_sub_build(|| {
to_var(
Some("positionViewDirection"),
to_varying(Some("v_positionViewDirection"), position_view().negate())
.normalize(),
)
})
})
})
}
}
accessor!(
normal_flat,
to_var(
Some("normalFlat"),
cross(dpdx(position_view()), dpdy(position_view())).normalize()
)
);
pub fn normal_view_geometry() -> NodeRef {
let flat = current_context(|cx| cx.flat_shading);
if let Some(node) = NORMAL_VIEW_GEOMETRY.with(|m| m.borrow().get(&flat).cloned()) {
return node;
}
let value = if flat {
normal_flat()
} else {
to_varying(
Some("v_normalViewGeometry"),
camera_view_matrix()
.mul(vec4_join(vec![
model_normal_matrix().mul(normal_local()),
float(0.0),
]))
.xyz()
.normalize(),
)
.normalize()
};
let node = to_var(Some("normalViewGeometry"), value);
NORMAL_VIEW_GEOMETRY.with(|m| m.borrow_mut().insert(flat, node.clone()));
node
}
fn normal_key() -> NormalViewKey {
let layer = current_context(|cx| cx.sub_build);
let value = if layer.is_some() {
None
} else {
current_context(|cx| cx.setup_normal.clone())
};
(
layer,
value.as_ref().map(|v| v.key()),
current_context(|cx| cx.flat_shading),
current_context(|cx| cx.material_side),
current_context(|cx| cx.has_tangent),
override_node(|o| &o.normal_view).map(|n| n.key()),
)
}
fn normal_value() -> Option<NodeRef> {
let layer = current_context(|cx| cx.sub_build);
if layer.is_some() {
None
} else {
current_context(|cx| cx.setup_normal.clone())
}
}
pub fn normal_view() -> NodeRef {
if let Some(node) = override_node(|o| &o.normal_view) {
return node;
}
let key = normal_key();
let flat = current_context(|cx| cx.flat_shading);
if let Some(node) = NORMAL_VIEW.with(|m| m.borrow().get(&key).cloned()) {
return node;
}
let node = to_var(
Some("normalView"),
match normal_value() {
Some(value) => value,
None if flat => normal_view_geometry(),
None => negate_on_back_side(normal_view_geometry()),
},
);
NORMAL_VIEW.with(|m| m.borrow_mut().insert(key, node.clone()));
node
}
fn tangent_frame() -> (NodeRef, NodeRef) {
let key = normal_key();
if let Some(pair) = TANGENT_VIEW.with(|m| m.borrow().get(&key).cloned()) {
return pair;
}
if current_context(|cx| cx.has_tangent || cx.sub_build == Some("VERTEX")) {
let pair = tangent_attribute_frame();
TANGENT_VIEW.with(|m| m.borrow_mut().insert(key, pair.clone()));
return pair;
}
let n = normal_view();
let q1perp = cross(dpdy(position_view()), n.clone());
let q0perp = cross(n, dpdx(position_view()));
let st0 = dpdx(uv());
let st1 = dpdy(uv());
let t = q1perp
.clone()
.mul(st0.clone().x())
.add(q0perp.clone().mul(st1.clone().x()));
let b = q1perp.mul(st0.y()).add(q0perp.mul(st1.y()));
let det = max(t.clone().dot(t.clone()), b.clone().dot(b.clone()));
let scale = det
.clone()
.equal(float(0.0))
.select(float(0.0), inverse_sqrt(det));
let flat = current_context(|cx| cx.flat_shading);
let frame = |name, value| {
if flat {
value
} else {
let _ = name;
negate_on_back_side(value)
}
};
let pair = (
to_var(
Some("tangentView"),
frame(
"tangentView",
to_var_untagged("tangentViewFrame", t.mul(scale.clone())),
),
),
to_var(
Some("bitangentView"),
frame(
"bitangentView",
to_var_untagged("bitangentViewFrame", b.mul(scale)),
),
),
);
TANGENT_VIEW.with(|m| m.borrow_mut().insert(key, pair.clone()));
pair
}
fn tangent_attribute_frame() -> (NodeRef, NodeRef) {
let tangent_geometry = tangent_geometry();
let tangent_local = tangent_local();
let flat = current_context(|cx| cx.flat_shading);
let front_side = |value: NodeRef| {
if flat {
value
} else {
negate_on_back_side(value)
}
};
thread_local! { static TANGENT_VARYING: Lazy<NodeRef> = const { Lazy::new() }; }
let tangent = TANGENT_VARYING
.with(|c| {
c.get(|| {
outside_sub_build(|| {
to_varying(
Some("v_tangentView"),
model_view_matrix()
.mul(vec4_join(vec![tangent_local, float(0.0)]))
.xyz(),
)
})
})
})
.normalize();
let tangent_view = to_var(Some("tangentView"), front_side(tangent));
let cross_normal_tangent = cross(normal_view(), tangent_view.clone()).mul(tangent_geometry.w());
let in_normal_layer = current_context(|cx| cx.sub_build) == Some("NORMAL");
let bitangent = if in_normal_layer && !flat {
to_varying(Some("NORMAL_v_bitangentView"), cross_normal_tangent)
} else {
cross_normal_tangent
}
.normalize();
let bitangent_view = to_var(Some("bitangentView"), front_side(bitangent));
(tangent_view, bitangent_view)
}
pub fn tangent_view() -> NodeRef {
tangent_frame().0
}
pub fn bitangent_view() -> NodeRef {
tangent_frame().1
}
accessor!(
tangent_geometry,
attribute("tangent", Type::Vec4)
);
accessor!(
tangent_local,
to_var(Some("tangentLocal"), tangent_geometry().xyz())
);
fn keyed_by_normal(
cell: &'static std::thread::LocalKey<RefCell<HashMap<NormalViewKey, NodeRef>>>,
build: impl FnOnce() -> NodeRef,
) -> NodeRef {
let key = normal_key();
if let Some(node) = cell.with(|m| m.borrow().get(&key).cloned()) {
return node;
}
let node = build();
cell.with(|m| m.borrow_mut().insert(key, node.clone()));
node
}
pub fn tangent_world() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
keyed_by_normal(&CELL, || {
let world = in_sub_build("VERTEX", || {
transform_direction(camera_world_matrix(), tangent_view())
});
to_var(
Some("tangentWorld"),
to_varying(Some("v_tangentWorld"), world).normalize(),
)
})
}
fn get_bitangent(cross_normal_tangent: NodeRef, varying_in_normal_layer: &'static str) -> NodeRef {
let bitangent = cross_normal_tangent.mul(tangent_geometry().w());
let in_normal_layer = current_context(|cx| cx.sub_build) == Some("NORMAL");
if in_normal_layer && !current_context(|cx| cx.flat_shading) {
to_varying(Some(varying_in_normal_layer), bitangent)
} else {
bitangent
}
}
pub fn bitangent_geometry() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
keyed_by_normal(&CELL, || {
to_var(
Some("bitangentGeometry"),
get_bitangent(
cross(normal_geometry(), tangent_geometry().xyz()),
"NORMAL_v_bitangentGeometry",
)
.normalize(),
)
})
}
pub fn bitangent_local() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
keyed_by_normal(&CELL, || {
to_var(
Some("bitangentLocal"),
get_bitangent(
cross(normal_local(), tangent_local()),
"NORMAL_v_bitangentLocal",
)
.normalize(),
)
})
}
pub fn bitangent_world() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
keyed_by_normal(&CELL, || {
to_var(
Some("bitangentWorld"),
get_bitangent(
cross(normal_world(), tangent_world()),
"NORMAL_v_bitangentWorld",
)
.normalize(),
)
})
}
pub fn parallax_direction() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
keyed_by_normal(&CELL, || position_view_direction().mul(tbn_view_matrix()))
}
pub fn parallax_uv(uv: impl Into<NodeRef>, scale: impl Into<NodeRef>) -> NodeRef {
uv.into().sub(parallax_direction().mul(scale.into()))
}
pub fn normal_world() -> NodeRef {
let key = normal_key();
if let Some(node) = NORMAL_WORLD.with(|m| m.borrow().get(&key).cloned()) {
return node;
}
let node = to_var(
Some("normalWorld"),
vec4_join(vec![normal_view(), float(0.0)])
.mul(camera_view_matrix())
.xyz()
.normalize(),
);
NORMAL_WORLD.with(|m| m.borrow_mut().insert(key, node.clone()));
node
}
accessor!(
normal_world_geometry,
to_var(
Some("normalWorldGeometry"),
to_varying(
Some("v_normalWorldGeometry"),
vec4_join(vec![normal_view_geometry(), float(0.0)])
.mul(camera_view_matrix())
.xyz()
.normalize()
)
.normalize()
)
);
pub fn model_view_projection() -> NodeRef {
position_view_pair().1
}
pub fn reflect_view() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
keyed_by_normal(&CELL, || {
reflect(position_view_direction().negate(), normal_view())
})
}
pub fn refract_view() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
keyed_by_normal(&CELL, || {
refract(
position_view_direction().negate(),
normal_view(),
material_refraction_ratio(),
)
})
}
pub fn reflect_vector() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
keyed_by_normal(&CELL, || {
to_var(
Some("reflectVector"),
transform_direction(camera_world_matrix(), reflect_view()),
)
})
}
pub fn refract_vector() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
keyed_by_normal(&CELL, || {
to_var(
Some("refractVector"),
transform_direction(camera_world_matrix(), refract_view()),
)
})
}
pub fn diffuse_color() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| property("DiffuseColor", Type::Vec4)))
}
macro_rules! prop {
($(#[$meta:meta])* pub(crate) $name:ident, $wgsl:literal, $ty:expr) => {
$(#[$meta])*
pub(crate) fn $name() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| property($wgsl, $ty)))
}
};
($(#[$meta:meta])* $name:ident, $wgsl:literal, $ty:expr) => {
$(#[$meta])*
pub fn $name() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| property($wgsl, $ty)))
}
};
}
prop!(
output_property, "Output", Type::Vec4);
prop!(pub(crate) total_diffuse, "totalDiffuse", Type::Vec3);
prop!(pub(crate) total_specular, "totalSpecular", Type::Vec3);
prop!(pub(crate) outgoing_light, "outgoingLight", Type::Vec3);
prop!(
shininess, "Shininess", Type::F32);
prop!(
specular_color, "SpecularColor", Type::Vec3);
prop!(
emissive_color, "EmissiveColor", Type::Vec3);
prop!(
point_width, "pointWidth", Type::F32);
pub(crate) fn ambient_occlusion_property() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| property("AmbientOcclusion", Type::F32)))
}
macro_rules! lighting_var {
($(#[$meta:meta])* pub(crate) $name:ident, $wgsl:literal, $init:expr) => {
$(#[$meta])*
pub(crate) fn $name() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| to_var_untagged($wgsl, $init)))
}
};
($(#[$meta:meta])* $name:ident, $wgsl:literal, $init:expr) => {
$(#[$meta])*
pub fn $name() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| to_var_untagged($wgsl, $init)))
}
};
}
lighting_var!(pub(crate) direct_diffuse, "directDiffuse", vec3(0.0, 0.0, 0.0));
lighting_var!(pub(crate) direct_specular, "directSpecular", vec3(0.0, 0.0, 0.0));
lighting_var!(pub(crate) indirect_diffuse, "indirectDiffuse", vec3(0.0, 0.0, 0.0));
lighting_var!(pub(crate) indirect_specular, "indirectSpecular", vec3(0.0, 0.0, 0.0));
lighting_var!(
irradiance, "irradiance", vec3(0.0, 0.0, 0.0));
lighting_var!(
ambient_occlusion, "ambientOcclusion", float(1.0));
lighting_var!(
radiance, "radiance", vec3(0.0, 0.0, 0.0));
lighting_var!(
ibl_irradiance, "iblIrradiance", vec3(0.0, 0.0, 0.0));
prop!(
metalness, "Metalness", Type::F32);
prop!(pub(crate) single_scattering, "singleScattering", Type::Vec3);
prop!(pub(crate) multi_scattering, "multiScattering", Type::Vec3);
prop!(
roughness, "Roughness", Type::F32);
prop!(
specular_color_blended, "SpecularColorBlended", Type::Vec3);
prop!(
specular_f90, "SpecularF90", Type::F32);
prop!(
ior, "IOR", Type::F32);
prop!(
diffuse_contribution, "DiffuseContribution", Type::Vec3);
prop!(
sheen, "Sheen", Type::Vec3);
prop!(
sheen_roughness, "SheenRoughness", Type::F32);
prop!(pub(crate) sheen_specular_direct, "sheenSpecularDirect", Type::Vec3);
prop!(pub(crate) sheen_specular_indirect, "sheenSpecularIndirect", Type::Vec3);
prop!(
diffuse_roughness, "DiffuseRoughness", Type::F32);
prop!(
iridescence, "Iridescence", Type::F32);
prop!(
iridescence_ior, "IridescenceIOR", Type::F32);
prop!(
iridescence_thickness, "IridescenceThickness", Type::F32);
prop!(
pub(crate) single_scattering_dielectric,
"singleScatteringDielectric",
Type::Vec3
);
prop!(
pub(crate) multi_scattering_dielectric,
"multiScatteringDielectric",
Type::Vec3
);
prop!(
pub(crate) single_scattering_metallic,
"singleScatteringMetallic",
Type::Vec3
);
prop!(
pub(crate) multi_scattering_metallic,
"multiScatteringMetallic",
Type::Vec3
);
prop!(
anisotropy, "Anisotropy", Type::F32);
prop!(
alpha_t, "AlphaT", Type::F32);
prop!(
anisotropy_t, "AnisotropyT", Type::Vec3);
prop!(
anisotropy_b, "AnisotropyB", Type::Vec3);
prop!(
clearcoat, "Clearcoat", Type::F32);
prop!(
clearcoat_roughness, "ClearcoatRoughness", Type::F32);
prop!(
transmission, "Transmission", Type::F32);
prop!(
thickness, "Thickness", Type::F32);
prop!(
attenuation_distance, "AttenuationDistance", Type::F32);
prop!(
attenuation_color, "AttenuationColor", Type::Vec3);
lighting_var!(pub(crate) clearcoat_radiance, "clearcoatRadiance", vec3(0.0, 0.0, 0.0));
lighting_var!(
pub(crate) clearcoat_specular_direct,
"clearcoatSpecularDirect",
vec3(0.0, 0.0, 0.0)
);
lighting_var!(
pub(crate) clearcoat_specular_indirect,
"clearcoatSpecularIndirect",
vec3(0.0, 0.0, 0.0)
);
thread_local! {
static CLEARCOAT_NORMAL_VIEW: RefCell<HashMap<Option<usize>, NodeRef>> =
RefCell::new(HashMap::new());
}
pub(crate) fn with_clearcoat_normal<R>(normal: Option<NodeRef>, f: impl FnOnce() -> R) -> R {
let _clearcoat = push_context(|cx| cx.setup_clearcoat_normal = normal);
f()
}
pub fn clearcoat_normal_view() -> NodeRef {
let value = current_context(|cx| cx.setup_clearcoat_normal.clone());
let key = value.as_ref().map(|v| v.key());
if let Some(node) = CLEARCOAT_NORMAL_VIEW.with(|m| m.borrow().get(&key).cloned()) {
return node;
}
let node = to_var(
Some("clearcoatNormalView"),
value.unwrap_or_else(|| in_sub_build("NORMAL", normal_view)),
);
CLEARCOAT_NORMAL_VIEW.with(|m| m.borrow_mut().insert(key, node.clone()));
node
}
pub fn bent_normal_view() -> NodeRef {
let bent = cross(
cross(anisotropy_b(), position_view_direction()),
anisotropy_b(),
)
.normalize();
let base = to_var(None, anisotropy().mul(roughness().one_minus()).one_minus());
let squared = to_var(None, base.clone().mul(base));
mix(bent, normal_view(), squared.clone().mul(squared)).normalize()
}
pub(crate) fn texture_node(
source: TextureSource,
uv: NodeRef,
mode: SampleMode,
ty: Type,
) -> NodeRef {
NodeRef::new(Node::Texture {
texture: Rc::new(source),
uv,
mode,
ty,
})
}
fn transformed_uv(uv: NodeRef, key: (u8, usize), matrix: Matrix3) -> NodeRef {
thread_local! {
static CACHE: RefCell<HashMap<(u8, usize), NodeRef>> = RefCell::new(HashMap::new());
}
let matrix_uniform = CACHE.with(|c| {
c.borrow_mut()
.entry(key)
.or_insert_with(|| {
uniform(
UniformSource::Value(
matrix
.to_padded_f32_array()
.iter()
.map(|&v| v as f64)
.collect(),
),
Type::Mat3,
UniformGroup::Object,
None,
)
})
.clone()
});
matrix_uniform.mul(vec3_join(vec![uv, float(1.0)])).xy()
}
fn default_uv(map: &Texture) -> NodeRef {
match map.channel() {
0 => uv(),
_ => uv1(),
}
}
pub fn texture(map: &Texture) -> NodeRef {
let (get_uv, level) = current_context(|cx| {
(
cx.extra.get("getUV").cloned(),
cx.extra.get("getTextureLevel").cloned(),
)
});
let uv = get_uv.unwrap_or_else(|| default_uv(map));
let mode = match (sample_mode_for(map), level) {
(SampleMode::Sample, Some(level)) => SampleMode::Level(level),
(mode, _) => mode,
};
texture_node(
TextureSource::Texture2D(map.clone()),
transformed_uv(uv, (0, map.id()), map.matrix()),
mode,
texture_type_for(map),
)
}
pub fn texture_with_uv(map: &Texture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
transformed_uv(coord, (0, map.id()), map.matrix()),
sample_mode_for(map),
texture_type_for(map),
)
}
#[derive(Clone, Debug)]
pub struct Texture3DNode {
source: Rc<TextureSource>,
level: Option<NodeRef>,
}
pub fn texture_3d(texture: &crate::textures::Data3DTexture, level: NodeRef) -> Texture3DNode {
Texture3DNode {
source: Rc::new(TextureSource::Texture3D(texture.clone())),
level: Some(level),
}
}
pub fn texture_3d_sampled(texture: &crate::textures::Data3DTexture) -> Texture3DNode {
Texture3DNode {
source: Rc::new(TextureSource::Texture3D(texture.clone())),
level: None,
}
}
impl Texture3DNode {
fn mode(&self) -> SampleMode {
match &self.level {
Some(level) => SampleMode::Level(level.clone()),
None => SampleMode::Sample,
}
}
pub fn sample(&self, uv: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Texture {
texture: self.source.clone(),
uv: uv.into(),
mode: self.mode(),
ty: Type::Vec4,
})
}
pub fn sample_r(&self, uv: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Texture {
texture: self.source.clone(),
uv: uv.into(),
mode: self.mode(),
ty: Type::F32,
})
}
pub fn normal(&self, uv: NodeRef) -> NodeRef {
let epsilon = 0.0001;
let ret = to_var(None, vec3(0.0, 0.0, 0.0));
let step = 0.01;
let x = self
.sample_r(uv.add(vec3(-step, 0.0, 0.0)))
.sub(self.sample_r(uv.add(vec3(step, 0.0, 0.0))));
let y = self
.sample_r(uv.add(vec3(0.0, -step, 0.0)))
.sub(self.sample_r(uv.add(vec3(0.0, step, 0.0))));
let z = self
.sample_r(uv.add(vec3(0.0, 0.0, -step)))
.sub(self.sample_r(uv.add(vec3(0.0, 0.0, step))));
let arms = [
(uv.x().less_than(epsilon), vec3(1.0, 0.0, 0.0)),
(uv.y().less_than(epsilon), vec3(0.0, 1.0, 0.0)),
(uv.z().less_than(epsilon), vec3(0.0, 0.0, 1.0)),
(uv.x().greater_than(1.0 - epsilon), vec3(-1.0, 0.0, 0.0)),
(uv.y().greater_than(1.0 - epsilon), vec3(0.0, -1.0, 0.0)),
(uv.z().greater_than(1.0 - epsilon), vec3(0.0, 0.0, -1.0)),
];
let mut chain = vec![ret.assign(vec3_join(vec![x, y, z]))];
for (cond, axis) in arms.into_iter().rev() {
chain = vec![if_else(cond, vec![ret.assign(axis)], chain)];
}
let mut statements = vec![ret.clone()];
statements.extend(chain);
block(statements, ret.normalize())
}
}
#[derive(Clone, Debug)]
pub struct StorageTextureNode {
source: Rc<TextureSource>,
}
pub fn storage_texture(texture: &Texture) -> StorageTextureNode {
assert!(
texture.is_storage(),
"three-rs: storageTexture() needs a Texture::storage()"
);
StorageTextureNode {
source: Rc::new(TextureSource::Storage(
texture.clone(),
crate::nodes::node::StorageAccess::WriteOnly,
)),
}
}
pub fn storage_texture_3d(texture: &crate::textures::Data3DTexture) -> StorageTextureNode {
assert!(
texture.is_storage(),
"three-rs: storageTexture() needs a Data3DTexture::storage()"
);
StorageTextureNode {
source: Rc::new(TextureSource::Storage3D(
texture.clone(),
crate::nodes::node::StorageAccess::WriteOnly,
)),
}
}
impl StorageTextureNode {
pub fn set_access(self, access: crate::nodes::node::StorageAccess) -> Self {
let source = match &*self.source {
TextureSource::Storage(t, _) => TextureSource::Storage(t.clone(), access),
TextureSource::Storage3D(t, _) => TextureSource::Storage3D(t.clone(), access),
_ => unreachable!("three-rs: a StorageTextureNode holds a storage source"),
};
Self {
source: Rc::new(source),
}
}
pub fn load(&self, coord: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Texture {
texture: self.source.clone(),
uv: coord.into(),
mode: SampleMode::StorageLoad,
ty: Type::Vec4,
})
}
}
pub fn texture_store(
texture: &StorageTextureNode,
coord: impl Into<NodeRef>,
value: impl Into<NodeRef>,
) -> NodeRef {
NodeRef::new(Node::TextureStore {
texture: texture.source.clone(),
coord: coord.into(),
value: value.into(),
})
}
fn texture_type_for(map: &Texture) -> Type {
texture_type_for_format(map.format())
}
fn texture_type_for_format(format: wgpu::TextureFormat) -> Type {
use wgpu::TextureSampleType as S;
if format.has_depth_aspect() {
return Type::F32;
}
if format.is_compressed() {
return Type::Vec4;
}
let component = match format.sample_type(None, None) {
Some(S::Uint) => Type::U32,
Some(S::Sint) => Type::I32,
_ => Type::F32,
};
let length = match format.components() {
1 => 1,
2 => 2,
_ => 4,
};
Type::vector_of(component, length)
}
fn sample_mode_for(map: &Texture) -> SampleMode {
if map.is_unfilterable() {
SampleMode::Load
} else {
SampleMode::Sample
}
}
pub fn triplanar_texture(
map_x: &Texture,
map_y: Option<&Texture>,
map_z: Option<&Texture>,
scale: NodeRef,
) -> NodeRef {
triplanar_textures(map_x, map_y, map_z, scale, position_local(), normal_local())
}
pub fn bump_map(map: &Texture, scale: NodeRef) -> NodeRef {
bump_map_with(|texture| texture(map).x(), scale)
}
pub fn bump_map_with(
height: impl Fn(&dyn Fn(&Texture) -> NodeRef) -> NodeRef,
scale: NodeRef,
) -> NodeRef {
in_sub_build("NORMAL", || bump_map_unlayered(height, scale))
}
fn bump_map_unlayered(
height: impl Fn(&dyn Fn(&Texture) -> NodeRef) -> NodeRef,
scale: NodeRef,
) -> NodeRef {
let tap = |coord: NodeRef| {
height(&|map: &Texture| {
texture_uv(
map,
transformed_uv(coord.clone(), (0, map.id()), map.matrix()),
)
})
};
let hll = tap(uv());
let dhdxy = join(
Type::Vec2,
vec![
tap(uv().add(dpdx(uv()))).sub(hll.clone()),
tap(uv().add(dpdy(uv()))).sub(hll),
],
)
.mul(scale);
let surf_norm = normal_view();
let v_sigma_x = dpdx(position_view()).normalize();
let v_sigma_y = dpdy(position_view()).normalize();
let r1 = cross(v_sigma_y, surf_norm.clone());
let r2 = cross(surf_norm.clone(), v_sigma_x.clone());
let f_det = v_sigma_x.dot(r1.clone()).mul(face_direction());
let v_grad = sign(f_det.clone()).mul(dhdxy.clone().x().mul(r1).add(dhdxy.y().mul(r2)));
abs(f_det).mul(surf_norm).sub(v_grad).normalize()
}
pub fn texture_grad(map: &Texture, coord: NodeRef, grad_x: NodeRef, grad_y: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
SampleMode::Grad(grad_x, grad_y),
Type::Vec4,
)
}
pub fn texture_gather(
map: &Texture,
coord: NodeRef,
component: NodeRef,
offset: Option<NodeRef>,
) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
SampleMode::Gather { component, offset },
Type::Vec4,
)
}
pub fn depth_texture_gather_compare(
map: &DepthTexture,
coord: NodeRef,
compare: NodeRef,
offset: Option<NodeRef>,
) -> NodeRef {
texture_node(
TextureSource::ShadowMap(map.clone()),
coord,
SampleMode::GatherCompare { compare, offset },
Type::Vec4,
)
}
pub fn depth_texture_gather(map: &DepthTexture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Depth(map.clone()),
coord,
SampleMode::Gather {
component: int(0),
offset: None,
},
Type::Vec4,
)
}
pub fn texture_level(map: &Texture, coord: NodeRef, level: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
SampleMode::Level(level),
Type::Vec4,
)
}
pub fn texture_bias(map: &Texture, coord: NodeRef, bias: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
SampleMode::Bias(bias),
Type::Vec4,
)
}
pub fn texture_array(map: &Texture, coord: NodeRef, layer: NodeRef) -> NodeRef {
assert!(
map.is_array(),
"three-rs: texture_array needs a texture with array layers"
);
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
SampleMode::SampleLayer(layer),
Type::Vec4,
)
}
pub fn equirect_uv(direction: NodeRef) -> NodeRef {
let u = direction
.z()
.atan2(direction.x())
.mul(float(1.0 / (std::f64::consts::PI * 2.0)))
.add(float(0.5));
let v = direction
.y()
.clamp(float(-1.0), float(1.0))
.asin()
.mul(float(1.0 / std::f64::consts::PI))
.add(float(0.5));
vec2_join(vec![u, v])
}
pub fn equirect_direction(uv: impl Into<NodeRef>) -> NodeRef {
let uv = uv.into();
let theta = uv.x().sub(0.5).mul(std::f64::consts::PI * 2.0);
let phi = uv.y().sub(0.5).mul(std::f64::consts::PI);
let cos_phi = phi.cos();
let x = cos_phi.mul(theta.cos());
let y = phi.sin();
let z = cos_phi.mul(theta.sin());
vec3_join(vec![x, y, z])
}
pub fn matcap_uv() -> NodeRef {
let view = position_view_direction();
let x = vec3_join(vec![view.z(), float(0.0), view.x().negate()]).normalize();
let y = view.cross(x.clone());
to_var(
Some("matcapUV"),
vec2_join(vec![x.dot(normal_view()), y.dot(normal_view())])
.mul(0.495)
.add(0.5),
)
}
pub fn max_mip_level(map: &Texture) -> NodeRef {
let map = map.clone();
uniform(
UniformSource::Live(crate::nodes::node::LiveValue::new(move || {
let (width, height) = map.size();
vec![f64::from(width.max(height)).log2()]
})),
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn spritesheet_uv(
count: impl Into<NodeRef>,
uv: impl Into<NodeRef>,
frame: impl Into<NodeRef>,
) -> NodeRef {
let count = count.into();
let width = count.x();
let height = count.y();
let frame_num = mod_float(frame, width.clone().mul(height.clone())).floor();
let column = mod_float(frame_num.clone(), width.clone());
let row = height.sub(ceil(frame_num.add(1.0).div(width)));
let scale = count.reciprocal();
uv.into().add(vec2_join(vec![column, row])).mul(scale)
}
pub fn triplanar_textures(
map_x: &Texture,
map_y: Option<&Texture>,
map_z: Option<&Texture>,
scale: NodeRef,
position: NodeRef,
normal: NodeRef,
) -> NodeRef {
let map_y = map_y.unwrap_or(map_x);
let map_z = map_z.unwrap_or(map_x);
let bf = normal.abs().normalize();
let bf = bf.clone().div(bf.dot(vec3(1.0, 1.0, 1.0)));
let tx = position.yz().mul(scale.clone());
let ty = position.zx().mul(scale.clone());
let tz = position.xy().mul(scale);
let cx = texture_uv(map_x, tx).mul(bf.x());
let cy = texture_uv(map_y, ty).mul(bf.y());
let cz = texture_uv(map_z, tz).mul(bf.z());
cx.add(cy).add(cz)
}
pub fn texture_bicubic(map: &Texture, uv: NodeRef, strength: impl Into<NodeRef>) -> NodeRef {
let lod = strength.into().mul(max_mip_level(map));
texture_bicubic_level(map, uv, lod)
}
pub fn texture_bicubic_level(map: &Texture, uv: NodeRef, lod: impl Into<NodeRef>) -> NodeRef {
let lod = lod.into();
let size = |level: NodeRef| {
texture_size(TextureSource::Texture2D(map.clone()), level.to_int()).to_vec2()
};
let lod_size = vec4_join(vec![size(lod.clone()), size(lod.add(1.0))]);
let lod_size_inv = float(1.0).div(lod_size.clone());
let uv_scaled = uv.swizzle("xyxy").mul(lod_size).add(0.5);
let iuv = uv_scaled.floor();
let fuv = uv_scaled.fract();
let (g0, g1, h0, h1) = bicubic_weights(&fuv);
let p0 = iuv.clone().add(h0).sub(0.5).mul(lod_size_inv.clone());
let p3 = iuv.add(h1).sub(0.5).mul(lod_size_inv);
let f_sample = bicubic(map, &p0.xy(), &p3.xy(), &g0.xy(), &g1.xy(), lod.floor());
let c_sample = bicubic(
map,
&p0.zw(),
&p3.zw(),
&g0.zw(),
&g1.zw(),
ceil(lod.clone()),
);
lod.fract().mix(f_sample, c_sample)
}
fn bicubic_weights(a: &NodeRef) -> (NodeRef, NodeRef, NodeRef, NodeRef) {
let bc = 1.0 / 6.0;
let w0 = float(bc).mul(a.mul(a.mul(a.negate().add(3.0)).sub(3.0)).add(1.0));
let w1 = float(bc).mul(a.mul(a.mul(float(3.0).mul(a.clone()).sub(6.0))).add(4.0));
let w2 = float(bc).mul(
a.mul(a.mul(float(-3.0).mul(a.clone()).add(3.0)).add(3.0))
.add(1.0),
);
let w3 = float(bc).mul(a.pow(float(3.0)));
let g0 = w0.add(w1.clone());
let g1 = w2.add(w3.clone());
let h0 = float(-1.0).add(w1.div(g0.clone()));
let h1 = float(1.0).add(w3.div(g1.clone()));
(g0, g1, h0, h1)
}
fn bicubic(
map: &Texture,
p0: &NodeRef,
p3: &NodeRef,
g0: &NodeRef,
g1: &NodeRef,
lod: NodeRef,
) -> NodeRef {
let p1 = vec2_join(vec![p3.x(), p0.y()]);
let p2 = vec2_join(vec![p0.x(), p3.y()]);
let tap = |p: NodeRef| texture_level(map, p, lod.clone());
let a = g0
.y()
.mul(g0.x().mul(tap(p0.clone())).add(g1.x().mul(tap(p1))));
let b = g1
.y()
.mul(g0.x().mul(tap(p2)).add(g1.x().mul(tap(p3.clone()))));
a.add(b)
}
fn texture_3d_type(volume: &crate::textures::Data3DTexture) -> Type {
match volume.format().components() {
1 => Type::F32,
2 => Type::Vec2,
_ => Type::Vec4,
}
}
pub fn texture_3d_load(volume: &crate::textures::Data3DTexture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture3D(volume.clone()),
coord.to_ivec3(),
SampleMode::LoadTexel,
texture_3d_type(volume),
)
}
pub fn texture_3d_level(
volume: &crate::textures::Data3DTexture,
uv: NodeRef,
level: impl Into<NodeRef>,
) -> NodeRef {
texture_node(
TextureSource::Texture3D(volume.clone()),
uv,
SampleMode::Level(level.into()),
texture_3d_type(volume),
)
}
pub fn texture_sample(map: &Texture, coord: NodeRef) -> NodeRef {
let matrix = uniform(
UniformSource::Value(
map.matrix()
.to_padded_f32_array()
.iter()
.map(|&v| v as f64)
.collect(),
),
Type::Mat3,
UniformGroup::Object,
None,
);
texture_uv(map, matrix.mul(vec3_join(vec![coord, float(1.0)])).xy())
}
pub fn texture_uv(map: &Texture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
sample_mode_for(map),
texture_type_for(map),
)
}
pub fn depth_texture(map: &DepthTexture) -> NodeRef {
texture_node(
TextureSource::Depth(map.clone()),
transformed_uv(uv(), (1, map.id()), Matrix3::identity()),
SampleMode::Load,
Type::F32,
)
}
pub fn depth_texture_sample(map: &DepthTexture, coord: NodeRef) -> NodeRef {
let matrix = uniform(
UniformSource::Value(
Matrix3::identity()
.to_padded_f32_array()
.iter()
.map(|&v| v as f64)
.collect(),
),
Type::Mat3,
UniformGroup::Object,
None,
);
texture_node(
TextureSource::Depth(map.clone()),
matrix.mul(vec3_join(vec![coord, float(1.0)])).xy(),
SampleMode::Load,
Type::F32,
)
}
pub fn pass_depth_texture(map: &DepthTexture) -> NodeRef {
pass_depth_texture_uv(map, uv())
}
pub fn pass_depth_texture_uv(map: &DepthTexture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Depth(map.clone()),
coord,
SampleMode::Load,
Type::F32,
)
}
pub fn cube_texture(map: &CubeTexture, dir: NodeRef) -> NodeRef {
let dir = vec3_join(vec![dir.x().negate(), dir.yz()]);
texture_node(
TextureSource::Cube(map.clone()),
dir,
SampleMode::Sample,
Type::Vec4,
)
}
pub fn cube_depth_texture_compare(map: &CubeDepthTexture, dir: NodeRef, dp: NodeRef) -> NodeRef {
let dir = vec3_join(vec![dir.x(), dir.y().negate(), dir.z()]);
texture_node(
TextureSource::CubeDepth(map.clone()),
dir,
SampleMode::Compare(dp),
Type::F32,
)
}
pub fn cube_texture_level(map: &CubeTexture, dir: NodeRef, level: NodeRef) -> NodeRef {
let dir = vec3_join(vec![dir.x().negate(), dir.yz()]);
texture_node(
TextureSource::Cube(map.clone()),
dir,
SampleMode::Level(level),
Type::Vec4,
)
}
#[derive(Clone)]
pub struct StorageArray {
buffer: Rc<BufferNode>,
per_vertex: bool,
}
pub fn instanced_array(count: usize, element_ty: Type) -> StorageArray {
StorageArray {
buffer: Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::Storage,
element_ty,
count,
}),
per_vertex: false,
}
}
pub fn attribute_array(count: usize, element_ty: Type) -> StorageArray {
StorageArray {
per_vertex: true,
..instanced_array(count, element_ty)
}
}
pub fn storage_element(storage: &StorageArray, index: impl Into<NodeRef>) -> NodeRef {
storage.element(index)
}
impl StorageArray {
pub fn element(&self, index: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: self.buffer.clone(),
index: index.into(),
})
}
pub fn id(&self) -> crate::nodes::node::BufferId {
self.buffer.id
}
pub fn count(&self) -> usize {
self.buffer.count
}
pub fn element_ty(&self) -> Type {
self.buffer.element_ty
}
}
impl StorageArray {
pub fn to_atomic(&self) -> StorageArray {
assert!(
matches!(self.buffer.element_ty, Type::U32 | Type::I32),
"three-rs: an atomic storage array holds u32 or i32 (WGSL atomic<T>)"
);
StorageArray {
buffer: Rc::new(BufferNode {
id: self.buffer.id,
source: BufferSource::AtomicStorage,
element_ty: self.buffer.element_ty,
count: self.buffer.count,
}),
per_vertex: self.per_vertex,
}
}
}
fn storage_item_size(element_ty: Type) -> usize {
match element_ty.components() {
3 => 4,
n => n,
}
}
pub fn storage_data(words: &[u32], element_ty: Type) -> StorageArray {
let item_size = element_ty.components();
let stride = storage_item_size(element_ty);
let count = words.len() / item_size;
let mut init = vec![0u32; count * stride];
for (i, element) in words.chunks_exact(item_size).enumerate() {
init[i * stride..i * stride + item_size].copy_from_slice(element);
}
StorageArray {
buffer: Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::StorageData {
init: Rc::new(init),
read_only: false,
},
element_ty,
count,
}),
per_vertex: false,
}
}
pub fn storage_f32(array: &[f32], element_ty: Type) -> StorageArray {
let words: Vec<u32> = array.iter().map(|v| v.to_bits()).collect();
storage_data(&words, element_ty)
}
pub fn storage(
attribute: &crate::core::StorageBufferAttribute,
element_ty: Type,
count: usize,
) -> StorageArray {
assert_eq!(
element_ty.components(),
attribute.item_size,
"three-rs: storage() over a StorageBufferAttribute of itemSize {} wants a type of that many components, got {element_ty:?}",
attribute.item_size
);
StorageArray {
buffer: Rc::new(BufferNode {
id: attribute.id(),
source: BufferSource::StorageData {
init: Rc::new(attribute.init_words(false)),
read_only: false,
},
element_ty,
count,
}),
per_vertex: !attribute.is_instanced(),
}
}
impl StorageArray {
pub fn to_read_only(&self) -> StorageArray {
let source = match &self.buffer.source {
BufferSource::StorageData { init, .. } => BufferSource::StorageData {
init: init.clone(),
read_only: true,
},
_ => panic!("three-rs: to_read_only() is ported for storage over a CPU array"),
};
StorageArray {
buffer: Rc::new(BufferNode {
id: self.buffer.id,
source,
element_ty: self.buffer.element_ty,
count: self.buffer.count,
}),
per_vertex: self.per_vertex,
}
}
pub fn to_attribute(&self) -> NodeRef {
let buffer = Rc::new(InstanceBuffer {
id: self.buffer.id,
source: self.buffer.source.clone(),
count: self.buffer.count,
item_size: storage_item_size(self.buffer.element_ty),
per_vertex: self.per_vertex,
});
instanced_attribute(&buffer, 0, self.buffer.element_ty)
}
}
pub fn compute_node(flow: crate::nodes::ComputeFlow, output: NodeRef) -> NodeRef {
NodeRef::new(Node::Compute {
flow: Rc::new(flow),
output,
})
}
fn object_matrix_world(object: &crate::core::ObjectRef, name: &'static str) -> LiveValue {
let object = object.downgrade();
LiveValue::new(move || {
let object = object
.upgrade()
.unwrap_or_else(|| panic!("three-rs: {name}( object ) outlived its object"));
let world = object.borrow().matrix_world;
world.elements.to_vec()
})
}
pub fn object_direction(object: &crate::core::ObjectRef) -> NodeRef {
let object = object.downgrade();
let direction = LiveValue::new(move || {
let object = object
.upgrade()
.unwrap_or_else(|| panic!("three-rs: objectDirection( object ) outlived its object"));
let mut direction = object.get_world_direction();
if object.borrow().is_camera {
direction.negate();
}
vec![direction.x, direction.y, direction.z]
});
object_3d_uniform(Object3DScope::Direction, Some(direction))
}
pub fn object_position(object: &crate::core::ObjectRef) -> NodeRef {
object_3d_uniform(
Object3DScope::Position,
Some(object_matrix_world(object, "objectPosition")),
)
}
pub fn object_scale(object: &crate::core::ObjectRef) -> NodeRef {
object_3d_uniform(
Object3DScope::Scale,
Some(object_matrix_world(object, "objectScale")),
)
}
pub fn object_view_position(object: &crate::core::ObjectRef) -> NodeRef {
object_3d_uniform(
Object3DScope::ViewPosition,
Some(object_matrix_world(object, "objectViewPosition")),
)
}
pub fn object_radius(object: &crate::core::ObjectRef) -> NodeRef {
object_3d_uniform(
Object3DScope::Radius,
Some(object_matrix_world(object, "objectRadius")),
)
}
pub fn object_world_matrix(object: &crate::core::ObjectRef) -> NodeRef {
uniform(
UniformSource::Live(object_matrix_world(object, "objectWorldMatrix")),
Type::Mat4,
UniformGroup::Object,
None,
)
}
pub fn shape_circle() -> NodeRef {
thread_local! {
static DEF: Rc<FnDef> = inline_fn(1, Type::F32, |args| {
let coord = args[0].clone();
let len2 = length_sq(coord.mul(2.0).sub(1.0));
let smooth = crate::nodes::builder::current_context(|cx| cx.alpha_to_coverage_samples);
if smooth {
let dlen = to_var(None, fwidth(len2.clone()));
smoothstep(dlen.one_minus(), dlen.add(1.0), len2).one_minus()
} else {
len2.greater_than(1.0).select(float(0.0), float(1.0))
}
});
}
DEF.with(|def| call(def, vec![uv()]))
}
pub use super::node::StructLayout;
pub use super::node::StructMember;
pub fn struct_type(name: &'static str, members: Vec<StructMember>) -> Rc<StructLayout> {
Rc::new(StructLayout { name, members })
}
pub fn struct_new(layout: &Rc<StructLayout>, values: Vec<NodeRef>) -> NodeRef {
assert_eq!(
values.len(),
layout.members.len(),
"three-rs: a struct value takes one value per member"
);
NodeRef::new(Node::StructNew {
layout: layout.clone(),
values,
})
}
pub fn struct_get(value: &NodeRef, layout: &Rc<StructLayout>, name: &str) -> NodeRef {
let member = layout
.members
.iter()
.position(|m| m.name == name)
.unwrap_or_else(|| panic!("three-rs: struct {} has no member {name}", layout.name));
NodeRef::new(Node::StructGet {
value: value.clone(),
layout: layout.clone(),
member,
})
}
impl StructMember {
pub fn new(name: &'static str, ty: Type) -> Self {
Self {
name,
ty,
atomic: false,
}
}
pub fn atomic(name: &'static str, ty: Type) -> Self {
Self {
name,
ty,
atomic: true,
}
}
}
#[derive(Clone)]
pub struct StorageStruct(Rc<BufferNode>);
pub fn storage_struct(
attribute: &crate::core::IndirectStorageBufferAttribute,
layout: Rc<StructLayout>,
) -> StorageStruct {
assert!(
layout
.members
.iter()
.all(|m| matches!(m.ty, Type::U32 | Type::I32 | Type::F32)),
"three-rs: storage_struct() lays out 4-byte scalar members only"
);
assert_eq!(
layout.members.len(),
attribute.array().len(),
"three-rs: struct {} does not cover the indirect attribute's words",
layout.name
);
StorageStruct(Rc::new(BufferNode {
id: attribute.id(),
source: BufferSource::Struct {
layout,
init: attribute.array(),
},
element_ty: Type::U32,
count: attribute.count(),
}))
}
impl StorageStruct {
pub fn get(&self, member: &str) -> NodeRef {
let BufferSource::Struct { layout, .. } = &self.0.source else {
unreachable!("three-rs: a StorageStruct is always a struct buffer")
};
NodeRef::new(Node::StructMember {
buffer: self.0.clone(),
member: layout.member(member),
})
}
}
pub fn atomic_func(
method: &'static str,
pointer: impl Into<NodeRef>,
value: Option<NodeRef>,
) -> NodeRef {
NodeRef::new(Node::Atomic {
method,
pointer: pointer.into(),
value,
})
}
macro_rules! atomic_fns {
($($(#[$m:meta])* $name:ident => $method:literal;)*) => {
$(
$(#[$m])*
pub fn $name(pointer: impl Into<NodeRef>, value: impl Into<NodeRef>) -> NodeRef {
atomic_func($method, pointer, Some(value.into()))
}
)*
};
}
atomic_fns! {
atomic_store => "atomicStore";
atomic_add => "atomicAdd";
atomic_sub => "atomicSub";
atomic_max => "atomicMax";
atomic_min => "atomicMin";
atomic_and => "atomicAnd";
atomic_or => "atomicOr";
atomic_xor => "atomicXor";
}
pub fn atomic_load(pointer: impl Into<NodeRef>) -> NodeRef {
atomic_func("atomicLoad", pointer, None)
}
#[derive(Clone)]
pub struct WorkgroupArray(Rc<super::node::WorkgroupArrayDef>);
pub fn workgroup_array(element_ty: Type, count: usize) -> WorkgroupArray {
WorkgroupArray(Rc::new(super::node::WorkgroupArrayDef {
element_ty,
count,
atomic: false,
}))
}
impl WorkgroupArray {
pub fn element(&self, index: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Element {
node: NodeRef::new(Node::Workgroup(self.0.clone())),
index: index.into(),
ty: self.0.element_ty,
})
}
pub fn to_atomic(&self) -> WorkgroupArray {
WorkgroupArray(Rc::new(super::node::WorkgroupArrayDef {
atomic: true,
..*self.0
}))
}
}
pub fn workgroup_barrier() -> NodeRef {
NodeRef::new(Node::Barrier { scope: "workgroup" })
}
pub fn storage_barrier() -> NodeRef {
NodeRef::new(Node::Barrier { scope: "storage" })
}
pub fn texture_barrier() -> NodeRef {
NodeRef::new(Node::Barrier { scope: "texture" })
}
#[derive(Clone)]
pub struct UniformArray(Rc<BufferNode>);
pub fn uniform_array_vec3(values: &[[f64; 3]]) -> UniformArray {
let mut padded = Vec::with_capacity(values.len() * 4);
for v in values {
padded.extend([v[0] as f32, v[1] as f32, v[2] as f32, 0.0]);
}
UniformArray(Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::UniformArray(Rc::new(padded)),
element_ty: Type::Vec4,
count: values.len(),
}))
}
pub fn uniform_array_vec2(values: &[[f64; 2]]) -> UniformArray {
let mut padded = Vec::with_capacity(values.len() * 4);
for v in values {
padded.extend([v[0] as f32, v[1] as f32, 0.0, 0.0]);
}
UniformArray(Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::UniformArray(Rc::new(padded)),
element_ty: Type::Vec4,
count: values.len(),
}))
}
pub fn uniform_array_f32(values: &[f64]) -> UniformArray {
let mut padded = Vec::with_capacity(values.len() * 4);
for &v in values {
padded.extend([v as f32, 0.0, 0.0, 0.0]);
}
UniformArray(Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::UniformArray(Rc::new(padded)),
element_ty: Type::Vec4,
count: values.len(),
}))
}
impl UniformArray {
pub fn element(&self, index: usize) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: self.0.clone(),
index: constant(Type::U32, vec![index as f64]),
})
.xyz()
}
pub fn element_xy(&self, index: NodeRef) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: self.0.clone(),
index,
})
.xy()
}
pub fn element_xyz(&self, index: NodeRef) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: self.0.clone(),
index,
})
.xyz()
}
pub fn element_x(&self, index: NodeRef) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: self.0.clone(),
index,
})
.x()
}
}
pub(crate) fn uniform_array_live(
count: usize,
read: impl Fn() -> Vec<f64> + 'static,
) -> UniformArray {
UniformArray(Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::Live(crate::nodes::node::LiveValue::new(read)),
element_ty: Type::Vec4,
count,
}))
}
pub(crate) fn light_probe_sh(index: usize) -> UniformArray {
UniformArray(Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::LightProbe(index),
element_ty: Type::Vec4,
count: 9,
}))
}
pub fn get_sh_irradiance_at(normal: NodeRef, sh: &UniformArray) -> NodeRef {
let (x, y, z) = (normal.x(), normal.y(), normal.z());
let mut result = sh.element(0).mul(0.886227);
result = result.add(sh.element(1).mul(2.0 * 0.511664).mul(y.clone()));
result = result.add(sh.element(2).mul(2.0 * 0.511664).mul(z.clone()));
result = result.add(sh.element(3).mul(2.0 * 0.511664).mul(x.clone()));
result = result.add(
sh.element(4)
.mul(2.0 * 0.429043)
.mul(x.clone())
.mul(y.clone()),
);
result = result.add(
sh.element(5)
.mul(2.0 * 0.429043)
.mul(y.clone())
.mul(z.clone()),
);
result = result.add(
sh.element(6)
.mul(z.mul(z.clone()).mul(0.743125).sub(0.247708)),
);
result = result.add(sh.element(7).mul(2.0 * 0.429043).mul(x.clone()).mul(z));
result.add(
sh.element(8)
.mul(0.429043)
.mul(x.mul(x.clone()).sub(y.mul(y.clone()))),
)
}
fn buffer_element(source: BufferSource, element_ty: Type, count: usize, index: NodeRef) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source,
element_ty,
count,
}),
index,
})
}
fn instanced_attribute(buffer: &Rc<InstanceBuffer>, offset: usize, ty: Type) -> NodeRef {
NodeRef::new(Node::InstancedAttribute {
buffer: buffer.clone(),
offset,
ty,
})
}
pub(crate) fn instance_matrix(count: usize) -> NodeRef {
let matrix_count = count.max(1);
let uniform_buffer_size = matrix_count * 16 * 4;
if uniform_buffer_size <= crate::nodes::builder::uniform_buffer_limit() {
return buffer_element(
BufferSource::InstanceMatrix,
Type::Mat4,
count,
instance_index(),
);
}
let interleaved = Rc::new(InstanceBuffer {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::InstanceMatrix,
count: matrix_count,
item_size: 16,
per_vertex: false,
});
join(
Type::Mat4,
(0..4)
.map(|i| instanced_attribute(&interleaved, i * 4, Type::Vec4))
.collect(),
)
}
pub fn instance_color(count: usize) -> NodeRef {
let buffer = Rc::new(InstanceBuffer {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::InstanceColor,
count: count.max(1),
item_size: 3,
per_vertex: false,
});
to_varying(
Some("vInstanceColor"),
instanced_attribute(&buffer, 0, Type::Vec3),
)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RangeValue {
Scalar(f64),
Color(Color),
Vec3([f64; 3]),
}
impl From<f64> for RangeValue {
fn from(v: f64) -> Self {
RangeValue::Scalar(v)
}
}
impl From<Color> for RangeValue {
fn from(v: Color) -> Self {
RangeValue::Color(v)
}
}
impl From<crate::math::Vector3> for RangeValue {
fn from(v: crate::math::Vector3) -> Self {
RangeValue::Vec3([v.x, v.y, v.z])
}
}
impl RangeValue {
fn vector4(self) -> [f64; 4] {
match self {
RangeValue::Scalar(v) => [v, v, v, v],
RangeValue::Color(c) => [c.r, c.g, c.b, 1.0],
RangeValue::Vec3([x, y, z]) => [x, y, z, 0.0],
}
}
fn ty(self) -> Type {
match self {
RangeValue::Scalar(_) => Type::F32,
RangeValue::Color(_) | RangeValue::Vec3(_) => Type::Vec3,
}
}
}
pub fn range(min: [f64; 4], max: [f64; 4], count: usize, index: NodeRef) -> NodeRef {
buffer_element(BufferSource::Range { min, max }, Type::Vec4, count, index)
}
pub(crate) fn instanced_range(
min: impl Into<RangeValue>,
max: impl Into<RangeValue>,
count: usize,
) -> NodeRef {
let (min, max) = (min.into(), max.into());
let ty = min.ty();
let uniform_buffer_size = count * 4 * 4;
let vec4 = if uniform_buffer_size <= crate::nodes::builder::uniform_buffer_limit() {
range(
min.vector4(),
max.vector4(),
count,
to_varying(None, instance_index()),
)
} else {
let buffer = Rc::new(InstanceBuffer {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::Range {
min: min.vector4(),
max: max.vector4(),
},
count,
item_size: 4,
per_vertex: false,
});
instanced_attribute(&buffer, 0, Type::Vec4)
};
match ty {
Type::F32 => vec4.x(),
Type::Vec2 => vec4.xy(),
Type::Vec3 => vec4.xyz(),
_ => vec4,
}
}
pub fn loop_index() -> NodeRef {
NodeRef::new(Node::Param {
name: "i",
ty: Type::I32,
})
}
pub fn loop_statement(count: usize, index: NodeRef, body: Vec<NodeRef>) -> NodeRef {
let count = int(count as i64);
NodeRef::new(Node::Loop {
start: None,
index,
count,
condition: "<",
update: None,
body,
})
}
pub(crate) fn if_statement(cond: NodeRef, body: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::If {
cond,
body,
else_body: Vec::new(),
})
}
pub fn ivec2(x: impl Into<NodeRef>, y: impl Into<NodeRef>) -> NodeRef {
join(Type::IVec2, vec![x.into(), y.into()])
}
pub fn texture_size(source: TextureSource, level: NodeRef) -> NodeRef {
NodeRef::new(Node::TextureSize {
texture: Rc::new(source),
level,
})
}
pub fn texture_load_texel(map: &DataTexture, coord: NodeRef, ty: Type) -> NodeRef {
texture_node(
TextureSource::Data(map.clone()),
coord,
SampleMode::LoadTexel,
ty,
)
}
pub fn texture_load(map: &Texture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord.to(Type::IVec2),
SampleMode::LoadTexel,
texture_type_for(map),
)
}
pub fn texture_load_offset(map: &Texture, coord: NodeRef, offset: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord.to(Type::IVec2).add(offset),
SampleMode::LoadTexel,
texture_type_for(map),
)
}
pub fn depth_texture_load(map: &DepthTexture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Depth(map.clone()),
coord.to(Type::IVec2),
SampleMode::LoadTexel,
Type::F32,
)
}
pub fn texture_load_transformed(map: &Texture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
transformed_uv(coord.to(Type::Vec2), (0, map.id()), map.matrix()).to(Type::IVec2),
SampleMode::LoadTexel,
texture_type_for(map),
)
}
pub fn depth_texture_load_transformed(map: &DepthTexture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Depth(map.clone()),
transformed_uv(coord.to(Type::Vec2), (1, map.id()), Matrix3::identity()).to(Type::IVec2),
SampleMode::LoadTexel,
Type::F32,
)
}
pub fn varying_property(name: &'static str, ty: Type, flat: bool) -> NodeRef {
NodeRef::new(Node::VaryingProperty { name, ty, flat })
}
pub fn texture_load_array(map: &DataArrayTexture, coord: NodeRef, layer: NodeRef) -> NodeRef {
texture_node(
TextureSource::DataArray(map.clone()),
coord,
SampleMode::LoadLayer(layer),
Type::Vec4,
)
}
pub(crate) fn morph_influences(count: usize, index: NodeRef) -> NodeRef {
buffer_element(BufferSource::MorphInfluences, Type::Vec4, count, index)
}
pub(crate) fn morph_base() -> NodeRef {
uniform(
UniformSource::MorphBase,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn instanced_data_attribute(
data: &Rc<Vec<f32>>,
item_size: usize,
offset: usize,
ty: Type,
) -> NodeRef {
instanced_buffer_attribute(&instanced_data_buffer(data, item_size), offset, ty)
}
pub fn instanced_data_buffer(data: &Rc<Vec<f32>>, item_size: usize) -> Rc<InstanceBuffer> {
let count = data.len().checked_div(item_size).unwrap_or(0);
Rc::new(InstanceBuffer {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::Attribute(data.clone()),
count,
item_size,
per_vertex: false,
})
}
pub fn instanced_buffer_attribute(buffer: &Rc<InstanceBuffer>, offset: usize, ty: Type) -> NodeRef {
assert!(
offset + ty.components() <= buffer.item_size,
"three-rs: instanced attribute reads past the instance stride"
);
instanced_attribute(buffer, offset, ty)
}
pub fn inline_fn(
params: usize,
ret: Type,
body: impl Fn(&[NodeRef]) -> NodeRef + 'static,
) -> Rc<FnDef> {
Rc::new(FnDef {
name: None,
params: vec![("", Type::Void); params],
ret,
layout: false,
body: Box::new(body),
})
}
pub use crate::nodes::code::wgsl_fn;
pub fn code(def: &Rc<crate::nodes::code::CodeDef>) -> NodeRef {
NodeRef::new(Node::Code(def.clone()))
}
pub fn call_wgsl(def: &Rc<crate::nodes::code::CodeDef>, args: Vec<(&str, NodeRef)>) -> NodeRef {
let ordered = def
.params
.iter()
.map(|(name, _)| {
args.iter()
.find(|(given, _)| given == name)
.map(|(_, node)| node.clone())
.unwrap_or_else(|| {
panic!(
"three-rs: wgslFn `{}` has no argument for `{name}`",
def.name
)
})
})
.collect();
for (given, _) in &args {
assert!(
def.params.iter().any(|(name, _)| name == given),
"three-rs: wgslFn `{}` has no parameter `{given}`",
def.name
);
}
NodeRef::new(Node::CodeCall {
def: def.clone(),
args: ordered,
})
}
pub fn shader_fn(
name: Option<&'static str>,
params: Vec<(&'static str, Type)>,
ret: Type,
body: impl Fn(&[NodeRef]) -> NodeRef + 'static,
) -> Rc<FnDef> {
Rc::new(FnDef {
name,
params,
ret,
layout: true,
body: Box::new(body),
})
}
pub(crate) fn if_node(
pre: Vec<NodeRef>,
result: NodeRef,
cond: NodeRef,
body: Vec<NodeRef>,
) -> NodeRef {
NodeRef::new(Node::IfVar {
pre,
result,
cond,
body,
})
}
pub fn call(def: &Rc<FnDef>, args: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::Call {
def: def.clone(),
args,
})
}
pub fn luminance(color: NodeRef) -> NodeRef {
dot(color, vec3(0.2126, 0.7152, 0.0722))
}
pub fn saturation(color: NodeRef, adjustment: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
inline_fn(2, Type::Vec3, |args| {
let (color, adjustment) = (args[0].clone(), args[1].clone());
let rgb = cached_rgb(color);
adjustment.mix(luminance(rgb.clone()), rgb).max(float(0.0))
})
})
});
call(&def, vec![color, adjustment])
}
pub fn hue(color: NodeRef, adjustment: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
inline_fn(2, Type::Vec3, |args| {
let (color, adjustment) = (args[0].clone(), args[1].clone());
let k = vec3(0.57735, 0.57735, 0.57735);
let cos_angle = adjustment.cos();
color
.rgb()
.mul(cos_angle.clone())
.add(
k.cross(color.rgb())
.mul(adjustment.sin())
.add(k.mul(dot(k.clone(), color.rgb()).mul(cos_angle.one_minus()))),
)
.max(float(0.0))
})
})
});
call(&def, vec![color, adjustment])
}
pub fn grayscale(color: NodeRef) -> NodeRef {
luminance(color.rgb())
}
pub fn posterize(source: NodeRef, steps: impl Into<NodeRef>) -> NodeRef {
let steps = steps.into();
source.mul(steps.clone()).floor().div(steps)
}
pub fn blend_overlay(base: NodeRef, blend: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("blendOverlay"),
vec![("base", Type::Vec3), ("blend", Type::Vec3)],
Type::Vec3,
|args| {
let (base, blend) = (args[0].clone(), args[1].clone());
mix(
base.mul(float(2.0)).mul(blend.clone()),
base.one_minus()
.mul(float(2.0))
.mul(blend.one_minus())
.one_minus(),
step(float(0.5), base),
)
},
)
})
});
call(&def, vec![base, blend])
}
pub fn blend_burn(base: NodeRef, blend: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("blendBurn"),
vec![("base", Type::Vec3), ("blend", Type::Vec3)],
Type::Vec3,
|args| {
let (base, blend) = (args[0].clone(), args[1].clone());
math(
"min",
vec![float(1.0), base.one_minus().div(blend)],
Type::Vec3,
)
.one_minus()
},
)
})
});
call(&def, vec![base, blend])
}
pub fn blend_dodge(base: NodeRef, blend: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("blendDodge"),
vec![("base", Type::Vec3), ("blend", Type::Vec3)],
Type::Vec3,
|args| {
let (base, blend) = (args[0].clone(), args[1].clone());
base.div(blend.one_minus()).min(float(1.0))
},
)
})
});
call(&def, vec![base, blend])
}
pub fn blend_screen(base: NodeRef, blend: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("blendScreen"),
vec![("base", Type::Vec3), ("blend", Type::Vec3)],
Type::Vec3,
|args| {
let (base, blend) = (args[0].clone(), args[1].clone());
base.one_minus().mul(blend.one_minus()).one_minus()
},
)
})
});
call(&def, vec![base, blend])
}
pub fn blend_color(base: NodeRef, blend: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("blendColor"),
vec![("base", Type::Vec4), ("blend", Type::Vec4)],
Type::Vec4,
|args| {
let (base, blend) = (args[0].clone(), args[1].clone());
let out_alpha = blend.a().add(base.a().mul(blend.a().one_minus()));
vec4_join(vec![
blend
.rgb()
.mul(blend.a())
.add(base.rgb().mul(base.a()).mul(blend.a().one_minus()))
.div(out_alpha.clone()),
out_alpha,
])
},
)
})
});
call(&def, vec![base, blend])
}
pub fn vibrance(color: NodeRef, adjustment: impl Into<NodeRef>) -> NodeRef {
let average = color.x().add(color.y()).add(color.z()).div(float(3.0));
let mx = color.x().max(color.y().max(color.z()));
let amt = mx
.clone()
.sub(average)
.mul(adjustment.into())
.mul(float(-3.0));
mix(color.rgb(), mx, amt).max(float(0.0))
}
pub fn cdl(
color: NodeRef,
slope: NodeRef,
offset: NodeRef,
power: NodeRef,
saturation: impl Into<NodeRef>,
luminance_coefficients: NodeRef,
) -> NodeRef {
let luma = color.rgb().dot(luminance_coefficients);
let v = to_var_intent(color.rgb().mul(slope).add(offset).max(float(0.0)));
let channel = |c: &'static str| {
if_then(
v.swizzle(c).greater_than(0.0),
vec![v.swizzle(c).assign(v.clone().pow(power.clone()).swizzle(c))],
)
};
let statements = vec![
channel("x"),
channel("y"),
channel("z"),
v.assign(
luma.clone()
.add(v.clone().sub(luma).mul(saturation.into()))
.max(float(0.0)),
),
];
block(statements, vec4_join(vec![v.rgb(), color.a()]))
}
pub fn osc_sine(t: NodeRef) -> NodeRef {
t.add(float(0.75))
.mul(float(std::f64::consts::TAU))
.sin()
.mul(float(0.5))
.add(float(0.5))
}
pub fn srgb_transfer_oetf(color: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("sRGBTransferOETF"),
vec![("color", Type::Vec3)],
Type::Vec3,
|args| {
let color = args[0].clone();
mix(
color
.pow(float(0.41666))
.mul(float(1.055))
.sub(float(0.055)),
color.mul(float(12.92)),
color.less_than_equal(float(0.0031308)).to(Type::Vec3),
)
},
)
})
});
call(&def, vec![color])
}
pub fn linear_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("linearToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
args[0]
.clone()
.mul(args[1].clone())
.clamp(float(0.0), float(1.0))
},
)
})
});
call(&def, vec![color, exposure])
}
pub fn cineon_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("cineonToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
let color = args[0]
.clone()
.mul(args[1].clone())
.sub(float(0.004))
.max(float(0.0));
let a = color
.clone()
.mul(color.clone().mul(float(6.2)).add(float(0.5)));
let b = color
.clone()
.mul(color.mul(float(6.2)).add(float(1.7)))
.add(float(0.06));
a.div(b).pow(float(2.2))
},
)
})
});
call(&def, vec![color, exposure])
}
pub fn srgb_transfer_eotf(color: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("sRGBTransferEOTF"),
vec![("color", Type::Vec3)],
Type::Vec3,
|args| {
let color = args[0].clone();
mix(
color
.mul(float(0.9478672986))
.add(float(0.0521327014))
.pow(float(2.4)),
color.mul(float(0.0773993808)),
color.less_than_equal(float(0.04045)).to(Type::Vec3),
)
},
)
})
});
call(&def, vec![color])
}
pub fn srgb_to_working(color: NodeRef) -> NodeRef {
vec4_join(vec![srgb_transfer_eotf(color.rgb()), color.a()])
}
pub fn pack_normal_to_rgb(node: NodeRef) -> NodeRef {
node.mul(float(0.5)).add(float(0.5))
}
pub fn reinhard_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("reinhardToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
let color = args[0].clone().mul(args[1].clone());
color
.clone()
.div(color.add(float(1.0)))
.clamp(float(0.0), float(1.0))
},
)
})
});
call(&def, vec![color, exposure])
}
pub fn premultiply_alpha(color: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(None, vec![("color", Type::Vec4)], Type::Vec4, |args| {
let color = args[0].clone();
vec4_join(vec![color.rgb().mul(color.a()), color.a()])
})
})
});
call(&def, vec![color])
}
pub fn unpremultiply_alpha(color: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(None, vec![("color", Type::Vec4)], Type::Vec4, |args| {
let color = args[0].clone();
color.a().equal(float(0.0)).select(
vec4(0.0, 0.0, 0.0, 0.0),
vec4_join(vec![color.rgb().div(color.a().to(Type::Vec3)), color.a()]),
)
})
})
});
call(&def, vec![color])
}
pub fn block(statements: Vec<NodeRef>, result: NodeRef) -> NodeRef {
NodeRef::new(Node::Block { statements, result })
}
pub fn loop_n(
name: &'static str,
count: NodeRef,
body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
) -> NodeRef {
let index = NodeRef::new(Node::Param {
name,
ty: Type::I32,
});
let body = body(&index);
NodeRef::new(Node::Loop {
start: None,
count,
index,
condition: "<",
update: None,
body,
})
}
pub fn loop_range(
name: &'static str,
start: NodeRef,
end: NodeRef,
body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
) -> NodeRef {
let index = NodeRef::new(Node::Param {
name,
ty: Type::I32,
});
let body = body(&index);
NodeRef::new(Node::Loop {
start: Some(start),
count: end,
condition: "<",
update: None,
index,
body,
})
}
pub fn loop_options(
name: &'static str,
ty: Type,
start: NodeRef,
end: NodeRef,
condition: &'static str,
body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
) -> NodeRef {
let index = NodeRef::new(Node::Param { name, ty });
let body = body(&index);
NodeRef::new(Node::Loop {
start: Some(start),
count: end,
index,
condition,
update: None,
body,
})
}
pub fn loop_float(
name: &'static str,
start: NodeRef,
end: NodeRef,
update: NodeRef,
body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
) -> NodeRef {
let index = NodeRef::new(Node::Param {
name,
ty: Type::F32,
});
let body = body(&index);
NodeRef::new(Node::Loop {
start: Some(start),
count: end,
index,
condition: "<",
update: Some(update),
body,
})
}
pub fn break_loop() -> NodeRef {
NodeRef::new(Node::Break)
}
pub fn continue_loop() -> NodeRef {
NodeRef::new(Node::Continue)
}
pub fn if_then(cond: NodeRef, body: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::If {
cond,
body,
else_body: Vec::new(),
})
}
pub fn if_else(cond: NodeRef, body: Vec<NodeRef>, else_body: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::If {
cond,
body,
else_body,
})
}
pub fn if_else_if(
cond: NodeRef,
body: Vec<NodeRef>,
other: NodeRef,
other_body: Vec<NodeRef>,
) -> NodeRef {
if_else(cond, body, vec![if_then(other, other_body)])
}
pub fn return_statement(value: NodeRef) -> NodeRef {
NodeRef::new(Node::Return { value })
}
pub fn discard() -> NodeRef {
NodeRef::new(Node::Discard)
}
pub fn discard_if(cond: NodeRef) -> NodeRef {
if_then(cond.not(), vec![discard()])
}
pub fn wgsl_select(f: NodeRef, t: NodeRef, cond: NodeRef) -> NodeRef {
let ty = t.ty();
math("select", vec![f, t, cond], ty)
}
pub fn step(edge: impl Into<NodeRef>, x: impl Into<NodeRef>) -> NodeRef {
let (edge, x) = (edge.into(), x.into());
let ty = if edge.ty().components() > x.ty().components() {
edge.ty()
} else {
x.ty()
};
math("step", vec![edge, x], ty)
}
pub fn uint(v: u32) -> NodeRef {
constant(Type::U32, vec![v as f64])
}
prop!(
shadow_position_world,
"shadowPositionWorld",
Type::Vec3
);
pub fn transform_direction(matrix: NodeRef, dir: NodeRef) -> NodeRef {
matrix
.mul(vec4_join(vec![dir, float(0.0)]))
.xyz()
.normalize()
}
pub fn light_target_direction(index: usize) -> NodeRef {
transform_direction(
camera_view_matrix(),
light_world_position(index).sub(light_target_position(index)),
)
}
pub fn shadow_map_compare(map: &DepthTexture, coord: NodeRef, z: NodeRef) -> NodeRef {
texture_node(
TextureSource::ShadowMap(map.clone()),
coord,
SampleMode::Compare(z),
Type::F32,
)
}
pub fn interleaved_gradient_noise(position: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("interleavedGradientNoise"),
vec![("position", Type::Vec2)],
Type::F32,
|args| {
float(52.9829189)
.mul(dot(args[0].clone(), vec2(0.06711056, 0.00583715)).fract())
.fract()
},
)
})
});
call(&def, vec![position])
}
pub fn vogel_disk_sample(sample_index: NodeRef, samples_count: NodeRef, phi: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("vogelDiskSample"),
vec![
("sampleIndex", Type::I32),
("samplesCount", Type::I32),
("phi", Type::F32),
],
Type::Vec2,
|args| {
let (index, count, phi) = (args[0].clone(), args[1].clone(), args[2].clone());
let theta = index
.clone()
.to(Type::F32)
.mul(float(2.399963229728653))
.add(phi);
let r = index
.to(Type::F32)
.add(float(0.5))
.div(count.to(Type::F32))
.sqrt();
vec2_join(vec![theta.cos(), theta.sin()]).mul(r)
},
)
})
});
call(&def, vec![sample_index, samples_count, phi])
}
pub fn aces_filmic_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("acesFilmicToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
let (color, exposure) = (args[0].clone(), args[1].clone());
let input = constant(
Type::Mat3,
vec![
0.59719, 0.076, 0.0284, 0.35458, 0.90834, 0.13383, 0.04823, 0.01566, 0.83777,
],
);
let output = constant(
Type::Mat3,
vec![
1.60475, -0.10208, -0.00327, -0.53108, 1.10813, -0.07276, -0.07367, -0.00605, 1.07602,
],
);
let c = input.mul(color.mul(exposure).div(float(0.6)));
let a = c
.clone()
.mul(c.clone().add(float(0.0245786)))
.sub(float(0.000090537));
let b = c
.clone()
.mul(c.add(float(0.432951)).mul(float(0.983729)))
.add(float(0.238081));
output.mul(a.div(b)).saturate()
},
)
})
});
call(&def, vec![color, exposure])
}
pub fn agx_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("agxToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
let (color, exposure) = (args[0].clone(), args[1].clone());
let srgb_to_rec2020 = constant(
Type::Mat3,
vec![
0.6274, 0.0691, 0.0164, 0.3293, 0.9195, 0.088, 0.0433, 0.0113, 0.8956,
],
);
let inset = constant(
Type::Mat3,
vec![
0.856627153315983,
0.137318972929847,
0.11189821299995,
0.0951212405381588,
0.761241990602591,
0.0767994186031903,
0.0482516061458583,
0.101439036467562,
0.811302368396859,
],
);
let outset = constant(
Type::Mat3,
vec![
1.1271005818144368,
-0.1413297634984383,
-0.14132976349843826,
-0.11060664309660323,
1.157823702216272,
-0.11060664309660294,
-0.016493938717834573,
-0.016493938717834257,
1.2519364065950405,
],
);
let rec2020_to_srgb = constant(
Type::Mat3,
vec![
1.6605, -0.1246, -0.0182, -0.5876, 1.1329, -0.1006, -0.0728, -0.0083, 1.1187,
],
);
let min_ev = || float(-12.47393);
let max_ev = float(4.026069);
let colortone = to_var(None, color);
let x = to_var(None, colortone.clone());
let x2 = to_var(None, x.clone().mul(x.clone()));
let x4 = to_var(None, x2.clone().mul(x2.clone()));
let contrast = float(15.5)
.mul(x4.clone().mul(x2.clone()))
.sub(float(40.14).mul(x4.clone().mul(x.clone())))
.add(
float(31.96)
.mul(x4)
.sub(float(6.868).mul(x2.clone().mul(x.clone())))
.add(
float(0.4298)
.mul(x2)
.add(float(0.1191).mul(x).sub(float(0.00232))),
),
);
block(
vec![
colortone.assign(colortone.mul(exposure)),
colortone.assign(srgb_to_rec2020.mul(colortone.clone())),
colortone.assign(inset.mul(colortone.clone())),
colortone.assign(max(colortone.clone(), float(1e-10))),
colortone.assign(log2(colortone.clone())),
colortone.assign(colortone.sub(min_ev()).div(max_ev.sub(min_ev()))),
colortone.assign(colortone.clamp(0.0, 1.0)),
colortone.assign(contrast),
colortone.assign(outset.mul(colortone.clone())),
colortone.assign(
max(vec3(0.0, 0.0, 0.0), colortone.clone())
.pow(vec3(2.2, 2.2, 2.2)),
),
colortone.assign(rec2020_to_srgb.mul(colortone.clone())),
colortone.assign(colortone.clamp(0.0, 1.0)),
],
colortone,
)
},
)
})
});
call(&def, vec![color, exposure])
}
pub fn neutral_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("neutralToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
let start_compression = || float(0.76);
let desaturation = float(0.15);
let color = to_var(None, args[0].clone().mul(args[1].clone()));
let x = color.x().min(color.y().min(color.z()));
let offset = x
.less_than(float(0.08))
.select(x.sub(float(6.25).mul(x.mul(x.clone()))), float(0.04));
let peak = color.x().max(color.y().max(color.z()));
let d = float(1.0).sub(start_compression());
let new_peak =
float(1.0).sub(d.mul(d.clone()).div(peak.add(d.sub(start_compression()))));
let g = float(1.0).sub(
float(1.0)
.div(desaturation.mul(peak.sub(new_peak.clone())).add(float(1.0))),
);
block(
vec![
color.assign(color.sub(offset)),
if_statement(
peak.less_than(start_compression()),
vec![return_statement(color.clone())],
),
color.assign(color.mul(new_peak.div(peak))),
],
mix(color, new_peak.to(Type::Vec3), g),
)
},
)
})
});
call(&def, vec![color, exposure])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn texture_type_follows_threes_format_mapping() {
use wgpu::TextureFormat as F;
let cases = [
(F::R8Unorm, Type::F32),
(F::R16Float, Type::F32),
(F::R32Float, Type::F32),
(F::R32Uint, Type::U32),
(F::R32Sint, Type::I32),
(F::Rg16Float, Type::Vec2),
(F::Rg32Uint, Type::UVec2),
(F::Rgba8Unorm, Type::Vec4),
(F::Rgba16Uint, Type::UVec4),
(F::Depth32Float, Type::F32),
(F::Depth24PlusStencil8, Type::F32),
(F::Bc4RUnorm, Type::Vec4),
(F::Bc4RSnorm, Type::Vec4),
(F::Bc5RgUnorm, Type::Vec4),
(F::EacR11Unorm, Type::Vec4),
(F::EacR11Snorm, Type::Vec4),
(F::EacRg11Unorm, Type::Vec4),
];
for (format, ty) in cases {
assert_eq!(texture_type_for_format(format), ty, "{format:?}");
}
}
#[test]
fn a_swizzle_of_a_scalar_splats_it() {
let s = float(0.5);
assert!(matches!(s.x().node(), Node::Const { .. }));
assert_eq!(s.y().ty(), Type::F32);
assert!(matches!(s.y().node(), Node::Const { .. }));
let v = s.xyz();
assert_eq!(v.ty(), Type::Vec3);
assert!(matches!(v.node(), Node::Cast { ty: Type::Vec3, .. }));
}
}