three_rs/nodes/reflector_node.rs
1//! Port of `three.js/src/nodes/utils/ReflectorNode.js`: `reflector()`, a
2//! planar mirror.
3//!
4//! Three splits it in two. `ReflectorNode` is a `TextureNode` whose uv is
5//! `screenUV.flipX()`; `ReflectorBaseNode` holds the virtual cameras and render
6//! targets and, as an `updateBefore` node of type `RENDER`, renders the scene
7//! from the mirrored camera into a target before the object that carries it is
8//! drawn, then points the texture node's `value` at that target.
9//!
10//! The port keeps the split. [`ReflectorNode`] is what the page holds: its
11//! [`uv_node`](ReflectorNode::uv_node) is public to be reassigned exactly as
12//! the page does (`groundReflector.uvNode = groundReflector.uvNode.add( … )`),
13//! and [`ReflectorNode::node`] is the `TextureNode` a material's graph takes.
14//! [`Reflector`] is `ReflectorBaseNode`; the renderer runs its
15//! `updateBefore()` (`Renderer::update_reflectors`, `src/renderer/reflector.rs`),
16//! because that is a nested `renderer.render()`.
17//!
18//! **Divergence** (`docs/nodes.md` §55): three samples one module-level
19//! `_defaultRT.texture` from every reflector and rewrites `textureNode.value`
20//! in place; a draw binds whatever `value` is when it is recorded. The port's
21//! bindings are resolved from the program, so each reflector has its own
22//! default texture, which the renderer finds in this module's registry and
23//! replaces, per draw, with the `value` the reflector had when that draw's
24//! object came up in the render list. The draw sees the texture three's
25//! would.
26
27use std::cell::RefCell;
28use std::collections::HashMap;
29use std::rc::Rc;
30
31use crate::cameras::PerspectiveCamera;
32use crate::core::{Object3D, ObjectRef, WeakObjectRef};
33use crate::nodes::tsl::{screen_uv, texture_uv};
34use crate::nodes::NodeRef;
35use crate::renderer::RenderTarget;
36use crate::textures::Texture;
37
38/// `reflector( parameters )`'s options. `generateMipmaps` and `depth` are not
39/// ported: no graded page sets them.
40#[derive(Clone, Debug)]
41#[non_exhaustive]
42pub struct ReflectorParameters {
43 /// `target` — `new Object3D()` when `None`.
44 pub target: Option<ObjectRef>,
45 /// `resolutionScale`.
46 pub resolution_scale: f64,
47 /// `bounces` — whether this reflector renders while another one is
48 /// rendering.
49 pub bounces: bool,
50 /// `samples` — the internal render target's MSAA sample count.
51 pub samples: u32,
52}
53
54impl Default for ReflectorParameters {
55 fn default() -> Self {
56 Self {
57 target: None,
58 resolution_scale: 1.0,
59 bounces: true,
60 samples: 0,
61 }
62 }
63}
64
65/// `ReflectorBaseNode`'s state.
66pub struct ReflectorBase {
67 /// `target` — the object whose world transform is the mirror plane: its
68 /// position is a point on the plane and its +Z the normal.
69 pub target: ObjectRef,
70 /// `resolutionScale`.
71 pub resolution_scale: f64,
72 /// `bounces`.
73 pub bounces: bool,
74 /// `samples`.
75 pub samples: u32,
76 /// `forceUpdate`.
77 pub force_update: bool,
78 /// `hasOutput`.
79 pub has_output: bool,
80 /// `virtualCameras`, keyed on the id of the camera being mirrored.
81 pub(crate) virtual_cameras: HashMap<u32, PerspectiveCamera>,
82 /// `renderTargets`, keyed on the id of the *virtual* camera.
83 pub(crate) render_targets: HashMap<u32, RenderTarget>,
84 /// `_defaultRT` — what the texture node samples before this reflector has
85 /// rendered anything. One per reflector here; see the module docs.
86 pub(crate) default_render_target: RenderTarget,
87 /// `textureNode.value`.
88 pub(crate) value: Texture,
89 /// The object [`ReflectorNode::add_target_on_setup`] defers
90 /// `object.add( target )` to, until the reflector is first set up.
91 pub(crate) add_target_to: Option<WeakObjectRef>,
92}
93
94impl std::fmt::Debug for ReflectorBase {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 f.debug_struct("ReflectorBase")
97 .field("resolution_scale", &self.resolution_scale)
98 .field("bounces", &self.bounces)
99 .field("samples", &self.samples)
100 .field("virtual_cameras", &self.virtual_cameras.len())
101 .finish_non_exhaustive()
102 }
103}
104
105/// `ReflectorBaseNode` — a shared handle, as a JS object is.
106#[derive(Clone, Debug)]
107pub struct Reflector(Rc<RefCell<ReflectorBase>>);
108
109impl Reflector {
110 /// Borrows the shared [`ReflectorBase`].
111 pub fn borrow(&self) -> std::cell::Ref<'_, ReflectorBase> {
112 self.0.borrow()
113 }
114
115 /// Mutably borrows the shared [`ReflectorBase`].
116 pub fn borrow_mut(&self) -> std::cell::RefMut<'_, ReflectorBase> {
117 self.0.borrow_mut()
118 }
119
120 /// Identity, for the renderer's once-per-render bookkeeping.
121 pub(crate) fn key(&self) -> usize {
122 Rc::as_ptr(&self.0) as *const u8 as usize
123 }
124
125 /// The id of the texture the texture node was built over — the binding
126 /// the renderer swaps for [`value`](Self::value).
127 pub(crate) fn default_texture_id(&self) -> usize {
128 self.0.borrow().default_render_target.texture().id()
129 }
130
131 /// `textureNode.value`.
132 pub fn value(&self) -> Texture {
133 self.0.borrow().value.clone()
134 }
135}
136
137thread_local! {
138 /// Default texture id → reflector, so the renderer can tell a reflector's
139 /// binding from any other texture's.
140 ///
141 /// The entries are strong. In three the material graph keeps the
142 /// `ReflectorBaseNode` alive through the `ReflectorNode` it holds; here
143 /// the graph holds only the texture node over the default texture, so the
144 /// registry keeps the reflector until nothing but the reflector itself
145 /// holds that texture any more ([`prune`]).
146 static REGISTRY: RefCell<HashMap<usize, Rc<RefCell<ReflectorBase>>>> =
147 RefCell::new(HashMap::new());
148 /// `const _defaultUV = screenUV.flipX()` — one node for every reflector.
149 static DEFAULT_UV: NodeRef = screen_uv().flip_x();
150}
151
152impl ReflectorBase {
153 /// Whether anything outside this reflector — a material graph, a built
154 /// program's bindings — still holds its default texture.
155 fn is_sampled(&self) -> bool {
156 let texture = self.default_render_target.texture();
157 // This clone, the render target's own handle, and `value` when it is
158 // still the default texture.
159 let own = 2 + usize::from(self.value.id() == texture.id());
160 texture.handle_count() > own
161 }
162}
163
164/// Drops every reflector nothing samples any more.
165fn prune(registry: &mut HashMap<usize, Rc<RefCell<ReflectorBase>>>) {
166 registry.retain(|_, base| base.try_borrow().map_or(true, |base| base.is_sampled()));
167}
168
169/// The reflector whose default texture is `texture_id`, if there is one.
170pub(crate) fn lookup(texture_id: usize) -> Option<Reflector> {
171 REGISTRY.with(|registry| registry.borrow().get(&texture_id).cloned().map(Reflector))
172}
173
174/// Whether any reflector is still sampled — the renderer skips the per-item
175/// lookup entirely on every page that has none.
176pub(crate) fn any() -> bool {
177 REGISTRY.with(|registry| {
178 let mut registry = registry.borrow_mut();
179 prune(&mut registry);
180 !registry.is_empty()
181 })
182}
183
184/// `ReflectorNode` — the `TextureNode` half.
185#[derive(Clone, Debug)]
186pub struct ReflectorNode {
187 /// `uvNode` — `screenUV.flipX()` until the page reassigns it.
188 pub uv_node: NodeRef,
189 reflector: Reflector,
190}
191
192impl ReflectorNode {
193 /// `reflectorNode.reflector`.
194 pub fn reflector(&self) -> &Reflector {
195 &self.reflector
196 }
197
198 /// `reflectorNode.target` — add it to the mirror's mesh
199 /// (`plane.add( groundReflector.target )`).
200 pub fn target(&self) -> ObjectRef {
201 self.reflector.0.borrow().target.clone()
202 }
203
204 /// `object.add( reflectorNode.target )` run when the reflector is first
205 /// set up rather than now — for a mirror created inside a `colorNode`
206 /// `Fn()`, whose body three runs when the material is first built
207 /// (`WaterMesh`). That build is part of the first frame's render, after
208 /// the scene's `updateMatrixWorld()`, so the frame's mirror is placed by
209 /// the target's matrixWorld as it stands then — identity, with +Z as the
210 /// normal — and only the next frame's sees the target where the object
211 /// puts it. The renderer does the add in `update_reflectors`, just before
212 /// the reflector's first `updateBefore()`.
213 pub fn add_target_on_setup(&self, object: &ObjectRef) {
214 self.reflector.0.borrow_mut().add_target_to = Some(object.downgrade());
215 }
216
217 /// The node itself, as a material graph uses it: a sample of the
218 /// reflection at [`uv_node`](Self::uv_node). `setUpdateMatrix( false )`,
219 /// so no uv transform.
220 pub fn node(&self) -> NodeRef {
221 let texture = self.reflector.0.borrow().default_render_target.texture();
222 texture_uv(&texture, self.uv_node.clone())
223 }
224}
225
226impl From<&ReflectorNode> for NodeRef {
227 fn from(node: &ReflectorNode) -> Self {
228 node.node()
229 }
230}
231
232/// `reflector( parameters )`.
233pub fn reflector(parameters: ReflectorParameters) -> ReflectorNode {
234 // `const _defaultRT = new RenderTarget()`; `setup()` resizes it to the
235 // drawing buffer before it can be sampled.
236 let default_render_target = RenderTarget::new(1, 1);
237 let value = default_render_target.texture();
238 let texture_id = value.id();
239
240 let base = Rc::new(RefCell::new(ReflectorBase {
241 target: parameters
242 .target
243 .unwrap_or_else(|| Object3D::default().into_node()),
244 resolution_scale: parameters.resolution_scale,
245 bounces: parameters.bounces,
246 samples: parameters.samples,
247 force_update: false,
248 has_output: false,
249 virtual_cameras: HashMap::new(),
250 render_targets: HashMap::new(),
251 default_render_target,
252 value,
253 add_target_to: None,
254 }));
255
256 REGISTRY.with(|registry| {
257 registry.borrow_mut().insert(texture_id, base.clone());
258 });
259
260 ReflectorNode {
261 uv_node: DEFAULT_UV.with(|uv| uv.clone()),
262 reflector: Reflector(base),
263 }
264}