use std::cell::{Cell, RefCell};
use std::hash::Hash;
use std::rc::Rc;
use crate::math::{Color, Matrix4, Vector2, Vector3};
use crate::textures::{
CubeDepthTexture, CubeTexture, Data3DTexture, DataArrayTexture, DataTexture, DepthTexture,
Texture,
};
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Type {
Void,
Bool,
F32,
I32,
U32,
Vec2,
Vec3,
Vec4,
UVec2,
IVec2,
UVec3,
UVec4,
IVec3,
IVec4,
BVec2,
BVec3,
BVec4,
Mat2,
Mat3,
Mat4,
}
impl Type {
pub fn components(self) -> usize {
match self {
Type::Void => 0,
Type::Bool | Type::F32 | Type::I32 | Type::U32 => 1,
Type::Vec2 | Type::UVec2 | Type::IVec2 | Type::BVec2 => 2,
Type::Vec3 | Type::UVec3 | Type::IVec3 | Type::BVec3 => 3,
Type::Vec4 | Type::UVec4 | Type::IVec4 | Type::BVec4 => 4,
Type::Mat2 => 4,
Type::Mat3 => 9,
Type::Mat4 => 16,
}
}
pub fn component_type(self) -> Type {
match self {
Type::UVec2 | Type::UVec3 | Type::UVec4 => Type::U32,
Type::IVec2 | Type::IVec3 | Type::IVec4 => Type::I32,
Type::BVec2 | Type::BVec3 | Type::BVec4 => Type::Bool,
Type::Vec2 | Type::Vec3 | Type::Vec4 | Type::Mat2 | Type::Mat3 | Type::Mat4 => {
Type::F32
}
other => other,
}
}
pub fn vector_of(component: Type, n: usize) -> Type {
match (component, n) {
(_, 1) => component,
(Type::U32, 2) => Type::UVec2,
(Type::I32, 2) => Type::IVec2,
(Type::U32, 3) => Type::UVec3,
(Type::I32, 3) => Type::IVec3,
(Type::I32, 4) => Type::IVec4,
(Type::Bool, 2) => Type::BVec2,
(Type::Bool, 3) => Type::BVec3,
(Type::Bool, 4) => Type::BVec4,
(Type::F32, 2) => Type::Vec2,
(Type::F32, 3) => Type::Vec3,
(Type::F32, 4) => Type::Vec4,
(Type::U32, 4) => Type::UVec4,
other => panic!("three-rs: the node builder only makes vectors of {other:?}"),
}
}
pub fn is_matrix(self) -> bool {
matches!(self, Type::Mat2 | Type::Mat3 | Type::Mat4)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum UniformGroup {
Render,
CameraIndex,
Object,
}
impl UniformGroup {
pub(crate) const ORDER: [UniformGroup; 3] = [
UniformGroup::Render,
UniformGroup::CameraIndex,
UniformGroup::Object,
];
pub(crate) fn struct_name(self) -> &'static str {
match self {
UniformGroup::Render => "render",
UniformGroup::CameraIndex => "cameraIndex",
UniformGroup::Object => "object",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum UpdateType {
Render,
Object,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum UniformSource {
CameraProjectionMatrix,
CameraViewMatrix,
CameraIndex,
CameraWorldMatrix,
CameraPosition,
ModelWorldMatrix,
ModelNormalMatrix,
CameraProjectionMatrixInverse,
ModelWorldMatrixInverse,
MaterialColor,
MaterialOpacity,
MaterialAlphaTest,
MaterialReflectivity,
MaterialEnvIntensity,
MaterialRotation,
MaterialShininess,
MaterialSpecular,
MaterialEmissive,
MaterialEmissiveIntensity,
MaterialAnisotropyVector,
MaterialClearcoat,
MaterialClearcoatRoughness,
MaterialClearcoatNormalScale,
MaterialTransmission,
MaterialThickness,
MaterialAttenuationDistance,
MaterialAttenuationColor,
EnvRotationMatrix,
BackgroundRotation,
BackgroundBlurriness,
BackgroundIntensity,
FogColor,
FogNear,
FogFar,
FogDensity,
Time,
DeltaTime,
FrameId,
ViewportSize,
Viewport,
ScreenDpr,
LightColorIntensity(usize),
LightCutoffDistance(usize),
LightDecay(usize),
LightViewPosition(usize),
MorphBase,
LightWorldPosition(usize),
LightTargetPosition(usize),
LightGroundColor(usize),
LightConeCos(usize),
LightPenumbraCos(usize),
ShadowMatrix(usize),
ShadowCameraNear(usize),
ShadowCameraFar(usize),
ShadowBias(usize),
ShadowNormalBias(usize),
ShadowRadius(usize),
ShadowBlurSamples(usize),
ShadowMapSize(usize),
ShadowIntensity(usize),
MaterialLineWidth,
MaterialMetalness,
MaterialRoughness,
MaterialBumpScale,
MaterialIor,
MaterialSpecularIntensity,
MaterialSpecularColor,
MaterialSheen,
MaterialSheenColor,
MaterialSheenRoughness,
MaterialDiffuseRoughness,
MaterialNormalScale,
MaterialAoMapIntensity,
ToneMappingExposure,
BindMatrix,
BindMatrixInverse,
ObjectCenter,
Value(Vec<f64>),
Settable(SettableValue),
ObjectUpdate(ObjectUpdate),
Live(LiveValue),
}
#[derive(Clone)]
pub struct LiveValue(Rc<dyn Fn() -> Vec<f64>>);
impl LiveValue {
pub(crate) fn new(read: impl Fn() -> Vec<f64> + 'static) -> Self {
Self(Rc::new(read))
}
pub(crate) fn get(&self) -> Vec<f64> {
(self.0)()
}
}
impl std::fmt::Debug for LiveValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("LiveValue")
.field(&Rc::as_ptr(&self.0).cast::<u8>())
.finish()
}
}
impl PartialEq for LiveValue {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl std::hash::Hash for LiveValue {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(Rc::as_ptr(&self.0).cast::<u8>() as usize).hash(state);
}
}
#[derive(Clone)]
pub struct ObjectUpdate(Rc<ObjectUpdateFn>);
pub(crate) type ObjectUpdateFn = dyn Fn(&NodeFrame) -> Vec<f64>;
#[derive(Clone, Copy)]
pub struct NodeFrame<'a> {
pub object: &'a crate::core::Object3D,
pub(crate) occluded: Option<&'a std::collections::HashSet<u32>>,
}
impl<'a> NodeFrame<'a> {
pub fn is_occluded(&self, object: &crate::core::Object3D) -> bool {
self.occluded.is_some_and(|set| set.contains(&object.id))
}
}
impl ObjectUpdate {
pub(crate) fn new(update: impl Fn(&crate::core::Object3D) -> Vec<f64> + 'static) -> Self {
Self(Rc::new(move |frame: &NodeFrame| update(frame.object)))
}
pub(crate) fn with_frame(update: impl Fn(&NodeFrame) -> Vec<f64> + 'static) -> Self {
Self(Rc::new(update))
}
pub(crate) fn value(&self, frame: &NodeFrame) -> Vec<f64> {
(self.0)(frame)
}
}
impl std::fmt::Debug for ObjectUpdate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ObjectUpdate")
.field(&Rc::as_ptr(&self.0).cast::<u8>())
.finish()
}
}
impl PartialEq for ObjectUpdate {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl std::hash::Hash for ObjectUpdate {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(Rc::as_ptr(&self.0).cast::<u8>() as usize).hash(state);
}
}
#[derive(Clone, Debug)]
pub struct SettableValue(Rc<RefCell<Vec<f64>>>);
impl SettableValue {
pub fn new(values: Vec<f64>) -> Self {
Self(Rc::new(RefCell::new(values)))
}
pub fn set(&self, values: Vec<f64>) {
*self.0.borrow_mut() = values;
}
pub fn get(&self) -> Vec<f64> {
self.0.borrow().clone()
}
}
impl PartialEq for SettableValue {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
impl std::hash::Hash for SettableValue {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(Rc::as_ptr(&self.0) as *const u8 as usize).hash(state);
}
}
impl UniformSource {
pub(crate) fn update_type(&self) -> UpdateType {
match self {
UniformSource::ModelWorldMatrix
| UniformSource::ModelNormalMatrix
| UniformSource::MaterialColor
| UniformSource::MaterialOpacity
| UniformSource::MaterialAlphaTest
| UniformSource::MaterialReflectivity
| UniformSource::MaterialEnvIntensity
| UniformSource::MaterialShininess
| UniformSource::MaterialSpecular
| UniformSource::MaterialEmissive
| UniformSource::MaterialEmissiveIntensity
| UniformSource::ModelWorldMatrixInverse
| UniformSource::MaterialLineWidth
| UniformSource::MaterialMetalness
| UniformSource::MaterialRoughness
| UniformSource::MaterialBumpScale
| UniformSource::MaterialIor
| UniformSource::MaterialSpecularIntensity
| UniformSource::MaterialSpecularColor
| UniformSource::MaterialSheen
| UniformSource::MaterialSheenColor
| UniformSource::MaterialSheenRoughness
| UniformSource::MaterialDiffuseRoughness
| UniformSource::MaterialNormalScale
| UniformSource::MaterialAoMapIntensity
| UniformSource::EnvRotationMatrix
| UniformSource::MorphBase
| UniformSource::BindMatrix
| UniformSource::BindMatrixInverse
| UniformSource::ObjectCenter
| UniformSource::Value(_)
| UniformSource::Settable(_)
| UniformSource::ObjectUpdate(_)
| UniformSource::Live(_) => UpdateType::Object,
_ => UpdateType::Render,
}
}
}
#[derive(Debug)]
pub struct UniformNode {
pub source: UniformSource,
pub ty: Type,
pub group: UniformGroup,
pub name: Option<&'static str>,
}
#[derive(Clone, PartialEq)]
#[non_exhaustive]
pub enum BufferSource {
InstanceMatrix,
InstanceColor,
Range {
min: [f64; 4],
max: [f64; 4],
},
MorphInfluences,
UniformArray(Rc<Vec<f32>>),
CameraViewMatrices,
CameraProjectionMatrices,
BoneMatrices,
Attribute(Rc<Vec<f32>>),
Storage,
AtomicStorage,
Struct {
layout: Rc<StructLayout>,
init: Rc<Vec<u32>>,
},
StorageData {
init: Rc<Vec<u32>>,
read_only: bool,
},
SkeletonBoneMatrices(SkeletonRef),
}
impl BufferSource {
pub(crate) fn is_storage(&self) -> bool {
matches!(
self,
BufferSource::Storage
| BufferSource::AtomicStorage
| BufferSource::Struct { .. }
| BufferSource::StorageData { .. }
)
}
pub(crate) fn group_and_name(&self) -> (UniformGroup, Option<&'static str>) {
match self {
BufferSource::CameraViewMatrices => (UniformGroup::Render, Some("cameraViewMatrices")),
BufferSource::CameraProjectionMatrices => {
(UniformGroup::Render, Some("cameraProjectionMatrices"))
}
_ => (UniformGroup::Object, None),
}
}
}
#[derive(Clone)]
pub struct SkeletonRef(pub(crate) Rc<RefCell<crate::objects::Skeleton>>);
impl PartialEq for SkeletonRef {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct StructMember {
pub name: &'static str,
pub ty: Type,
pub atomic: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct StructLayout {
pub name: &'static str,
pub members: Vec<StructMember>,
}
impl StructLayout {
pub(crate) fn wgsl(&self) -> String {
let members: Vec<String> = self
.members
.iter()
.map(|m| {
let ty = crate::nodes::wgsl::type_name(m.ty);
if m.atomic {
format!("\t{} : atomic< {ty} >", m.name)
} else {
format!("\t{} : {ty}", m.name)
}
})
.collect();
format!("struct {} {{\n{}\n}};", self.name, members.join(",\n"))
}
pub(crate) fn member(&self, name: &str) -> usize {
self.members
.iter()
.position(|m| m.name == name)
.unwrap_or_else(|| panic!("three-rs: struct {} has no member {name}", self.name))
}
}
#[derive(Debug)]
pub struct WorkgroupArrayDef {
pub element_ty: Type,
pub count: usize,
pub atomic: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BufferId(usize);
impl BufferId {
pub(crate) fn next() -> Self {
thread_local! {
static BUFFER_ID: Cell<usize> = const { Cell::new(0) };
}
BUFFER_ID.with(|id| {
let next = id.get();
id.set(next + 1);
BufferId(next)
})
}
pub fn get(&self) -> usize {
self.0
}
}
#[derive(Debug)]
pub struct InstanceBuffer {
pub id: BufferId,
pub source: BufferSource,
pub count: usize,
pub item_size: usize,
}
#[derive(Debug)]
pub struct BufferNode {
pub id: BufferId,
pub source: BufferSource,
pub element_ty: Type,
pub count: usize,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum TextureSource {
Texture2D(Texture),
Depth(DepthTexture),
ShadowMap(DepthTexture),
Cube(CubeTexture),
DataArray(DataArrayTexture),
Data(DataTexture),
CubeDepth(CubeDepthTexture),
Texture3D(Data3DTexture),
Storage(Texture, StorageAccess),
Storage3D(Data3DTexture, StorageAccess),
}
impl TextureSource {
pub(crate) fn id(&self) -> usize {
match self {
TextureSource::Texture2D(t) | TextureSource::Storage(t, _) => t.id(),
TextureSource::Depth(t) | TextureSource::ShadowMap(t) => t.id(),
TextureSource::Cube(t) => t.id(),
TextureSource::DataArray(t) => t.id(),
TextureSource::Data(t) => t.id(),
TextureSource::CubeDepth(t) => t.id(),
TextureSource::Texture3D(t) | TextureSource::Storage3D(t, _) => t.id(),
}
}
pub(crate) fn is_storage_binding(&self) -> bool {
matches!(
self,
TextureSource::Storage(..) | TextureSource::Storage3D(..)
)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum StorageAccess {
#[default]
WriteOnly,
ReadOnly,
ReadWrite,
}
impl StorageAccess {
pub(crate) fn wgsl(self) -> &'static str {
match self {
StorageAccess::WriteOnly => "write",
StorageAccess::ReadOnly => "read",
StorageAccess::ReadWrite => "read_write",
}
}
pub(crate) fn wgpu(self) -> wgpu::StorageTextureAccess {
match self {
StorageAccess::WriteOnly => wgpu::StorageTextureAccess::WriteOnly,
StorageAccess::ReadOnly => wgpu::StorageTextureAccess::ReadOnly,
StorageAccess::ReadWrite => wgpu::StorageTextureAccess::ReadWrite,
}
}
}
impl TextureSource {
pub(crate) fn owner(&self) -> crate::textures::TextureOwner {
match self {
TextureSource::Texture2D(texture) => texture.owner(),
TextureSource::Depth(depth) | TextureSource::ShadowMap(depth) => depth.owner(),
TextureSource::Cube(cube) => cube.owner(),
TextureSource::DataArray(data) => data.owner(),
TextureSource::Data(data) => data.owner(),
TextureSource::CubeDepth(cube) => cube.owner(),
TextureSource::Texture3D(data) | TextureSource::Storage3D(data, _) => data.owner(),
TextureSource::Storage(texture, _) => texture.owner(),
}
}
}
#[derive(Clone, Debug)]
pub enum SampleMode {
Sample,
Level(NodeRef),
Bias(NodeRef),
Grad(NodeRef, NodeRef),
Gather {
component: NodeRef,
offset: Option<NodeRef>,
},
GatherCompare {
compare: NodeRef,
offset: Option<NodeRef>,
},
Load,
LoadLayer(NodeRef),
SampleLayer(NodeRef),
Compare(NodeRef),
LoadTexel,
StorageLoad,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum Builtin {
VertexIndex,
InstanceIndex,
FragCoord,
FrontFacing,
InvocationLocalIndex,
WorkgroupId,
LocalId,
GlobalId,
NumWorkgroups,
}
impl Builtin {
pub(crate) fn name(self) -> &'static str {
match self {
Builtin::VertexIndex => "vertexIndex",
Builtin::InstanceIndex => "instanceIndex",
Builtin::FragCoord => "fragCoord",
Builtin::FrontFacing => "isFront",
Builtin::InvocationLocalIndex => "invocationLocalIndex",
Builtin::WorkgroupId => "workgroupId",
Builtin::LocalId => "localId",
Builtin::GlobalId => "globalId",
Builtin::NumWorkgroups => "numWorkgroups",
}
}
pub(crate) fn ty(self) -> Type {
match self {
Builtin::VertexIndex | Builtin::InstanceIndex | Builtin::InvocationLocalIndex => {
Type::U32
}
Builtin::WorkgroupId
| Builtin::LocalId
| Builtin::GlobalId
| Builtin::NumWorkgroups => Type::UVec3,
Builtin::FragCoord => Type::Vec4,
Builtin::FrontFacing => Type::Bool,
}
}
}
#[derive(Debug)]
pub struct VarDef {
pub name: Option<String>,
pub value: NodeRef,
pub ty: Type,
}
#[derive(Debug)]
pub struct VaryingDef {
pub name: Option<&'static str>,
pub value: NodeRef,
pub ty: Type,
pub flat: bool,
}
pub struct FnDef {
pub name: Option<&'static str>,
pub params: Vec<(&'static str, Type)>,
pub ret: Type,
pub layout: bool,
#[allow(clippy::type_complexity)]
pub body: Box<dyn Fn(&[NodeRef]) -> NodeRef>,
}
impl std::fmt::Debug for FnDef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FnDef").field("name", &self.name).finish()
}
}
pub trait CustomNode {
fn type_name(&self) -> &'static str;
fn node_type(&self) -> Type;
fn is_cacheable(&self) -> bool {
true
}
fn setup(&self, builder: &crate::nodes::NodeBuilder) -> NodeRef;
fn update_before_type(&self) -> crate::nodes::NodeUpdateType {
crate::nodes::NodeUpdateType::None
}
fn update_type(&self) -> crate::nodes::NodeUpdateType {
crate::nodes::NodeUpdateType::None
}
fn update_after_type(&self) -> crate::nodes::NodeUpdateType {
crate::nodes::NodeUpdateType::None
}
fn update_before(&self, _renderer: &mut crate::renderer::Renderer) -> bool {
true
}
fn update(&self, _renderer: &mut crate::renderer::Renderer) -> bool {
true
}
fn update_after(&self, _renderer: &mut crate::renderer::Renderer) -> bool {
true
}
}
pub(crate) struct CustomUpdate(pub(crate) Rc<dyn CustomNode>);
impl crate::nodes::NodeUpdate for CustomUpdate {
fn update_before_type(&self) -> crate::nodes::NodeUpdateType {
self.0.update_before_type()
}
fn update_type(&self) -> crate::nodes::NodeUpdateType {
self.0.update_type()
}
fn update_after_type(&self) -> crate::nodes::NodeUpdateType {
self.0.update_after_type()
}
fn update_before(&self, renderer: &mut crate::renderer::Renderer) -> bool {
self.0.update_before(renderer)
}
fn update(&self, renderer: &mut crate::renderer::Renderer) -> bool {
self.0.update(renderer)
}
fn update_after(&self, renderer: &mut crate::renderer::Renderer) -> bool {
self.0.update_after(renderer)
}
}
impl std::fmt::Debug for dyn CustomNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.type_name())
}
}
#[derive(Clone, Debug, Default)]
pub struct ContextValue {
pub(crate) entries: Vec<(&'static str, NodeRef)>,
}
impl ContextValue {
pub fn new() -> Self {
Self::default()
}
pub fn set(mut self, key: &'static str, value: impl Into<NodeRef>) -> Self {
self.entries.retain(|(k, _)| *k != key);
self.entries.push((key, value.into()));
self
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum Node {
Const {
ty: Type,
values: Vec<f64>,
},
ConstArray {
element_ty: Type,
values: Vec<f64>,
},
ArrayVar {
element_ty: Type,
values: Vec<f64>,
},
Uniform(Rc<UniformNode>),
BufferElement {
buffer: Rc<BufferNode>,
index: NodeRef,
},
Attribute {
name: &'static str,
ty: Type,
},
InstancedAttribute {
buffer: Rc<InstanceBuffer>,
offset: usize,
ty: Type,
},
Builtin(Builtin),
Compute {
flow: Rc<crate::nodes::ComputeFlow>,
output: NodeRef,
},
Var(Rc<VarDef>),
Let(Rc<VarDef>),
Varying(Rc<VaryingDef>),
Property {
name: &'static str,
ty: Type,
},
Param {
name: &'static str,
ty: Type,
},
Assign {
target: NodeRef,
value: NodeRef,
},
Op {
op: &'static str,
a: NodeRef,
b: NodeRef,
ty: Type,
},
Math {
name: &'static str,
args: Vec<NodeRef>,
ty: Type,
},
Swizzle {
node: NodeRef,
components: &'static str,
ty: Type,
},
Cast {
node: NodeRef,
ty: Type,
},
Neg {
node: NodeRef,
ty: Type,
},
Join {
args: Vec<NodeRef>,
ty: Type,
},
Element {
node: NodeRef,
index: NodeRef,
ty: Type,
},
Texture {
texture: Rc<TextureSource>,
uv: NodeRef,
mode: SampleMode,
ty: Type,
},
TextureSize {
texture: Rc<TextureSource>,
level: NodeRef,
},
VaryingProperty {
name: &'static str,
ty: Type,
flat: bool,
},
Call {
def: Rc<FnDef>,
args: Vec<NodeRef>,
},
Code(Rc<crate::nodes::code::CodeDef>),
CodeCall {
def: Rc<crate::nodes::code::CodeDef>,
args: Vec<NodeRef>,
},
Block {
statements: Vec<NodeRef>,
result: NodeRef,
},
Loop {
start: Option<NodeRef>,
count: NodeRef,
index: NodeRef,
condition: &'static str,
update: Option<NodeRef>,
body: Vec<NodeRef>,
},
Break,
TextureStore {
texture: Rc<TextureSource>,
coord: NodeRef,
value: NodeRef,
},
If {
cond: NodeRef,
body: Vec<NodeRef>,
else_body: Vec<NodeRef>,
},
IfVar {
pre: Vec<NodeRef>,
result: NodeRef,
cond: NodeRef,
body: Vec<NodeRef>,
},
Discard,
Return {
value: NodeRef,
},
Not {
node: NodeRef,
},
BitNot {
node: NodeRef,
ty: Type,
},
Select {
cond: NodeRef,
a: NodeRef,
b: NodeRef,
ty: Type,
},
StructMember {
buffer: Rc<BufferNode>,
member: usize,
},
Atomic {
method: &'static str,
pointer: NodeRef,
value: Option<NodeRef>,
},
Workgroup(Rc<WorkgroupArrayDef>),
Barrier {
scope: &'static str,
},
Custom(Rc<dyn CustomNode>),
Context {
node: NodeRef,
value: Rc<ContextValue>,
},
Isolate {
node: NodeRef,
},
}
#[derive(Clone, Debug)]
pub struct NodeRef(Rc<Node>);
impl NodeRef {
pub fn new(node: Node) -> Self {
NodeRef(Rc::new(node))
}
pub fn as_rc(&self) -> &Rc<Node> {
&self.0
}
pub fn node(&self) -> &Node {
&self.0
}
pub fn key(&self) -> usize {
Rc::as_ptr(&self.0) as *const u8 as usize
}
pub fn ty(&self) -> Type {
match &*self.0 {
Node::Const { ty, .. } => *ty,
Node::ConstArray { element_ty, .. } => *element_ty,
Node::ArrayVar { element_ty, .. } => *element_ty,
Node::Uniform(u) => u.ty,
Node::BufferElement { buffer, .. } => buffer.element_ty,
Node::Attribute { ty, .. } => *ty,
Node::InstancedAttribute { ty, .. } => *ty,
Node::Builtin(b) => b.ty(),
Node::Var(v) => v.ty,
Node::Let(v) => v.ty,
Node::Varying(v) => v.ty,
Node::TextureSize { .. } => Type::UVec2,
Node::VaryingProperty { ty, .. } => *ty,
Node::Property { ty, .. } => *ty,
Node::Param { ty, .. } => *ty,
Node::Assign { target, .. } => target.ty(),
Node::Op { ty, .. } => *ty,
Node::Math { ty, .. } => *ty,
Node::Swizzle { ty, .. } => *ty,
Node::Cast { ty, .. } => *ty,
Node::Neg { ty, .. } => *ty,
Node::Join { ty, .. } => *ty,
Node::Element { ty, .. } => *ty,
Node::Texture { ty, .. } => *ty,
Node::Call { def, .. } => def.ret,
Node::Code(_) => Type::Void,
Node::CodeCall { def, .. } => def.ret,
Node::IfVar { result, .. } => result.ty(),
Node::Select { ty, .. } => *ty,
Node::Block { result, .. } => result.ty(),
Node::Loop { .. }
| Node::If { .. }
| Node::Discard
| Node::Break
| Node::TextureStore { .. }
| Node::Return { .. } => Type::Void,
Node::Not { node } => Type::vector_of(Type::Bool, node.ty().components().max(1)),
Node::BitNot { ty, .. } => *ty,
Node::StructMember { buffer, member } => match &buffer.source {
BufferSource::Struct { layout, .. } => layout.members[*member].ty,
_ => unreachable!("three-rs: a struct member is only built on a struct buffer"),
},
Node::Atomic { pointer, .. } => pointer.ty(),
Node::Workgroup(def) => def.element_ty,
Node::Barrier { .. } => Type::Void,
Node::Compute { output, .. } => output.ty(),
Node::Custom(custom) => custom.node_type(),
Node::Context { node, .. } | Node::Isolate { node } => node.ty(),
}
}
}
impl From<&NodeRef> for NodeRef {
fn from(n: &NodeRef) -> Self {
n.clone()
}
}
macro_rules! const_from {
($t:ty, $ty:expr) => {
impl From<$t> for NodeRef {
fn from(v: $t) -> Self {
NodeRef::new(Node::Const {
ty: $ty,
values: vec![v as f64],
})
}
}
};
}
const_from!(f64, Type::F32);
const_from!(f32, Type::F32);
const_from!(i32, Type::I32);
const_from!(u32, Type::U32);
impl From<bool> for NodeRef {
fn from(v: bool) -> Self {
NodeRef::new(Node::Const {
ty: Type::Bool,
values: vec![if v { 1.0 } else { 0.0 }],
})
}
}
impl From<Color> for NodeRef {
fn from(c: Color) -> Self {
NodeRef::new(Node::Const {
ty: Type::Vec3,
values: vec![c.r, c.g, c.b],
})
}
}
impl From<Vector2> for NodeRef {
fn from(v: Vector2) -> Self {
NodeRef::new(Node::Const {
ty: Type::Vec2,
values: vec![v.x, v.y],
})
}
}
impl From<Vector3> for NodeRef {
fn from(v: Vector3) -> Self {
NodeRef::new(Node::Const {
ty: Type::Vec3,
values: vec![v.x, v.y, v.z],
})
}
}
impl From<Matrix4> for NodeRef {
fn from(m: Matrix4) -> Self {
NodeRef::new(Node::Const {
ty: Type::Mat4,
values: m.elements.to_vec(),
})
}
}
pub(crate) struct Lazy<T: 'static> {
cell: RefCell<Option<T>>,
}
impl<T: Clone + 'static> Default for Lazy<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Clone + 'static> Lazy<T> {
pub const fn new() -> Self {
Lazy {
cell: RefCell::new(None),
}
}
pub fn get(&self, init: impl FnOnce() -> T) -> T {
let mut slot = self.cell.borrow_mut();
if slot.is_none() {
*slot = Some(init());
}
slot.as_ref()
.expect("three-rs: the lazy slot was filled in just above")
.clone()
}
}
impl std::hash::Hash for UniformSource {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
match self {
UniformSource::LightColorIntensity(i)
| UniformSource::LightCutoffDistance(i)
| UniformSource::LightDecay(i)
| UniformSource::LightViewPosition(i)
| UniformSource::LightWorldPosition(i)
| UniformSource::LightTargetPosition(i)
| UniformSource::LightGroundColor(i)
| UniformSource::LightConeCos(i)
| UniformSource::LightPenumbraCos(i)
| UniformSource::ShadowMatrix(i)
| UniformSource::ShadowCameraNear(i)
| UniformSource::ShadowCameraFar(i)
| UniformSource::ShadowBias(i)
| UniformSource::ShadowNormalBias(i)
| UniformSource::ShadowRadius(i)
| UniformSource::ShadowBlurSamples(i)
| UniformSource::ShadowMapSize(i)
| UniformSource::ShadowIntensity(i) => i.hash(state),
UniformSource::Value(values) => {
values.len().hash(state);
for value in values {
value.to_bits().hash(state);
}
}
UniformSource::Settable(cell) => cell.hash(state),
UniformSource::Live(value) => value.hash(state),
_ => {}
}
}
}
impl std::hash::Hash for BufferSource {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
match self {
BufferSource::Range { min, max } => {
for value in min.iter().chain(max.iter()) {
value.to_bits().hash(state);
}
}
BufferSource::Attribute(data) | BufferSource::UniformArray(data) => {
(Rc::as_ptr(data) as *const u8 as usize).hash(state)
}
BufferSource::Struct { layout, .. } => {
layout.name.hash(state);
for member in &layout.members {
member.name.hash(state);
member.ty.hash(state);
member.atomic.hash(state);
}
}
BufferSource::StorageData { read_only, .. } => read_only.hash(state),
BufferSource::SkeletonBoneMatrices(skeleton) => {
(Rc::as_ptr(&skeleton.0) as *const u8 as usize).hash(state)
}
BufferSource::InstanceMatrix
| BufferSource::InstanceColor
| BufferSource::MorphInfluences
| BufferSource::BoneMatrices
| BufferSource::CameraViewMatrices
| BufferSource::CameraProjectionMatrices
| BufferSource::Storage
| BufferSource::AtomicStorage => {}
}
}
}
impl std::hash::Hash for TextureSource {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
match self {
TextureSource::Texture2D(texture) => texture.id().hash(state),
TextureSource::Depth(texture) | TextureSource::ShadowMap(texture) => {
texture.id().hash(state)
}
TextureSource::Cube(texture) => texture.id().hash(state),
TextureSource::DataArray(texture) => texture.id().hash(state),
TextureSource::Data(texture) => texture.id().hash(state),
TextureSource::CubeDepth(texture) => texture.id().hash(state),
TextureSource::Texture3D(texture) => texture.id().hash(state),
TextureSource::Storage(texture, access) => {
texture.id().hash(state);
access.hash(state);
}
TextureSource::Storage3D(texture, access) => {
texture.id().hash(state);
access.hash(state);
}
}
}
}
impl std::fmt::Debug for BufferSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BufferSource::InstanceMatrix => f.write_str("InstanceMatrix"),
BufferSource::InstanceColor => f.write_str("InstanceColor"),
BufferSource::Storage => f.write_str("Storage"),
BufferSource::AtomicStorage => f.write_str("AtomicStorage"),
BufferSource::Struct { layout, init } => f
.debug_struct("Struct")
.field("layout", &layout.name)
.field("init", &format_args!("{} words", init.len()))
.finish(),
BufferSource::Range { min, max } => f
.debug_struct("Range")
.field("min", min)
.field("max", max)
.finish(),
BufferSource::MorphInfluences => f.write_str("MorphInfluences"),
BufferSource::BoneMatrices => f.write_str("BoneMatrices"),
BufferSource::CameraViewMatrices => f.write_str("CameraViewMatrices"),
BufferSource::CameraProjectionMatrices => f.write_str("CameraProjectionMatrices"),
BufferSource::Attribute(data) => f
.debug_tuple("Attribute")
.field(&format_args!("{} floats", data.len()))
.finish(),
BufferSource::UniformArray(data) => f
.debug_tuple("UniformArray")
.field(&format_args!("{} floats", data.len()))
.finish(),
BufferSource::StorageData { init, read_only } => f
.debug_struct("StorageData")
.field("init", &format_args!("{} words", init.len()))
.field("read_only", read_only)
.finish(),
BufferSource::SkeletonBoneMatrices(skeleton) => f
.debug_tuple("SkeletonBoneMatrices")
.field(&format_args!("{} bones", skeleton.0.borrow().bones.len()))
.finish(),
}
}
}