three_rs/renderer/pass.rs
1//! Port of `three.js/src/nodes/display/PassNode.js`.
2//!
3//! `pass( scene, camera )` is a `TempNode` that owns a `RenderTarget`, renders
4//! the given scene into it once per frame from `updateBefore()`, and evaluates
5//! to the target's colour texture. Its `setup()` returns a `PassTextureNode`,
6//! which is itself a `TempNode`, so a pass **used as a value** contributes two
7//! vars to the generated shader — `nodeVarN = textureSample( … ); nodeVarN+1 =
8//! nodeVarN;` — and `.a` is taken on the outer one. `to_var( texture_uv( … ) )`
9//! reproduces that exactly ([`PassNode::node`]).
10//!
11//! `passNode.getTextureNode()` is the *inner* node on its own, so it emits one
12//! var and no copy ([`PassNode::texture_node`]). `webgpu_postprocessing_masking`
13//! takes the first form and `webgpu_postprocessing_difference` the second; both
14//! dumps show the difference.
15//!
16//! `PassTextureNode` also calls `setUpdateMatrix( false )`, so a pass samples
17//! the raw `uv()` varying with no texture matrix — unlike `texture( map )`,
18//! which carries a `mat3x3` in the object uniform block.
19
20use std::cell::{Cell, RefCell};
21use std::collections::HashMap;
22use std::rc::Rc;
23
24use crate::cameras::RenderCamera;
25use crate::core::{Layers, ObjectRef};
26use crate::nodes::node::SettableValue;
27use crate::nodes::tsl::{
28 pass_depth_texture, perspective_depth_to_view_z, texture_uv, to_var, uniform_settable, uv,
29 view_z_to_orthographic_depth,
30};
31use crate::nodes::{MrtNode, NodeRef, NodeUpdate, NodeUpdateType, Type};
32use crate::objects::Scene;
33use crate::textures::{DepthTexture, TextureFilter, TextureType};
34
35/// `PassNode`'s depth output name.
36pub const DEPTH_ATTACHMENT: &str = "depth";
37
38use super::render_target::{RenderTarget, RenderTargetOptions, OUTPUT_ATTACHMENT};
39use super::Renderer;
40
41/// `pass( scene, camera )`.
42///
43/// A handle: clones share one pass. The pass renders its scene from
44/// `updateBefore()` (`NodeUpdateType.FRAME`), which the renderer fires the
45/// first time in a frame that a draw samples one of the pass's textures, as
46/// three's does (`docs/nodes.md` §57). The nested render is its own submit,
47/// so the GPU runs it before the pass that samples it.
48///
49/// The scene and camera are shared handles, given by [`pass`] or
50/// [`PassNode::set_scene`]: the node holds them across frames, as three's
51/// `this.scene` / `this.camera` do. A pass without them never renders; the
52/// explicit `render()` that used to cover that case was removed in 0.2.0
53/// (`docs/api.md` decision 10).
54#[derive(Clone)]
55pub struct PassNode(Rc<PassState>);
56
57/// The handle reads through to what it shares, so the accessors below read
58/// the pass's fields as they did before it was a handle.
59impl std::ops::Deref for PassNode {
60 type Target = PassState;
61
62 fn deref(&self) -> &PassState {
63 &self.0
64 }
65}
66
67/// A shared scene, as a pass holds it.
68pub type SceneRef = Rc<RefCell<Scene>>;
69/// A shared camera, as a pass holds it.
70pub type CameraRef = Rc<RefCell<dyn RenderCamera>>;
71
72/// What a [`PassNode`] handle shares.
73pub struct PassState {
74 render_target: RenderTarget,
75 node: NodeRef,
76 /// `PassNode._previousTextureNodes` — the node for the *other* texture
77 /// behind an output name, memoised like `_textureNodes` so that two asks
78 /// compose one node.
79 previous_texture_nodes: RefCell<HashMap<String, NodeRef>>,
80 /// `PassNode._mrt` — the MRT the renderer is given for the duration of this
81 /// pass's own render.
82 mrt: RefCell<Option<MrtNode>>,
83 /// `PassNode._textureNodes` — one node per named attachment, memoised so
84 /// that two `getTextureNode( name )` calls compose the *same* node and the
85 /// builder sees one texture, not two.
86 texture_nodes: RefCell<HashMap<String, NodeRef>>,
87 /// `PassNode._viewZNodes` — memoised like the texture nodes, so two asks
88 /// compose one graph.
89 view_z_nodes: RefCell<HashMap<String, NodeRef>>,
90 /// `PassNode._linearDepthNodes`.
91 linear_depth_nodes: RefCell<HashMap<String, NodeRef>>,
92 /// `PassNode.scope === PassNode.DEPTH` — what [`depth_pass`] makes: the
93 /// pass used as a value is its linear depth, not its colour.
94 depth_scope: Cell<bool>,
95 /// `PassNode._cameraNear` / `_cameraFar`: `uniform( 0 )` a piece, written
96 /// from the pass's camera in `updateBefore()`. They are object-group
97 /// uniforms of whatever material samples the pass, which is why the fog
98 /// composite's shader reads `object.nodeUniform1` / `object.nodeUniform2`.
99 camera_near: (NodeRef, SettableValue),
100 camera_far: (NodeRef, SettableValue),
101 /// `PassNode.autoClearDepth`.
102 auto_clear_depth: bool,
103 /// Whether the depth attachment is this pass's own. A pass handed another
104 /// pass's depth texture must not resize it — the owner already did, and
105 /// `set_size` on a shared handle would drop the contents this pass exists
106 /// to read.
107 owns_depth_texture: bool,
108 /// `PassNode._layers`.
109 layers: RefCell<Option<Layers>>,
110 /// `PixelationPassNode.pixelSize` — the target is the drawing buffer's
111 /// size divided by this, floored. 1 for every other pass.
112 size_divisor: std::cell::Cell<u32>,
113 /// `PassNode._resolutionScale` — the target is `Math.floor( size *
114 /// resolutionScale )`. 1 by default; `RetroPassNode` sets 0.25.
115 resolution_scale: Cell<f64>,
116 /// The render-object function the pass installs on the renderer for the
117 /// length of its own render, as `RetroPassNode.updateBefore()` does
118 /// around `super.updateBefore()`. `None` leaves the renderer's as it is.
119 render_object_function: RefCell<Option<Rc<dyn super::RenderObjectFunction>>>,
120 /// `PassNode.opaque` / `.transparent` / `lighting.enabled`.
121 opaque: Cell<bool>,
122 transparent: Cell<bool>,
123 lighting_enabled: Cell<bool>,
124 /// `PassNode.contextNode`'s `getShadow`, from `builtinShadowContext(
125 /// shadowNode, light )`.
126 context_shadow: RefCell<Option<ShadowContext>>,
127 /// `PassNode.contextNode`'s `getAO`, from `builtinAOContext( ao )`.
128 context_ao: RefCell<Option<NodeRef>>,
129 /// `this.scene` / `this.camera`.
130 scene: RefCell<Option<(SceneRef, CameraRef)>>,
131}
132
133/// `builtinShadowContext( shadowNode, light )`'s `getShadow` hook, as a pass
134/// installs it on the renderer for the duration of its render: which light
135/// it applies to, and the node it multiplies that light's shadowed colour
136/// by. See [`PassNode::set_context_shadow`].
137#[derive(Clone)]
138pub(crate) struct ShadowContext {
139 /// `light` — compared by identity, as three's `light === shadowLight`.
140 pub light: ObjectRef,
141 /// `shadowNode`.
142 pub shadow: NodeRef,
143}
144
145/// `pass( scene, camera )`: a pass that renders `scene` through `camera`
146/// whenever a draw samples it.
147pub fn pass(scene: SceneRef, camera: CameraRef) -> PassNode {
148 let node = PassNode::new();
149 node.set_scene(scene, camera);
150 node
151}
152
153/// `depthPass( scene, camera )` — `new PassNode( PassNode.DEPTH, scene,
154/// camera )`: a pass whose [`node`](PassNode::node) is the scene's depth as
155/// `[0,1]` linear depth between the camera's clip planes
156/// ([`linear_depth_node`](PassNode::linear_depth_node)).
157pub fn depth_pass(scene: SceneRef, camera: CameraRef) -> PassNode {
158 let node = pass(scene, camera);
159 node.depth_scope.set(true);
160 node
161}
162
163/// `pass( scene, camera, options )`'s options object, as far as the ported
164/// pages use it.
165#[derive(Clone, Debug)]
166#[non_exhaustive]
167pub struct PassOptions {
168 /// `options.minFilter` — the pass's colour texture's minification filter.
169 pub min_filter: TextureFilter,
170 /// `options.magFilter` — the pass's colour texture's magnification filter.
171 pub mag_filter: TextureFilter,
172 /// `options.depthTexture` — `depthTexture = options.depthTexture || new
173 /// DepthTexture()`. A pass given another pass's depth attachment renders
174 /// *into* it, which is how `webgpu_deferred`'s transparent pass depth-tests
175 /// against the opaque G-buffer it never drew.
176 pub depth_texture: Option<DepthTexture>,
177 /// `options.autoClearDepth`, copied onto `renderer.autoClearDepth` for the
178 /// duration of the pass. `false` keeps the shared depth attachment's
179 /// contents (`loadOp: "load"`).
180 pub auto_clear_depth: bool,
181}
182
183impl Default for PassOptions {
184 /// `RenderTarget`'s own defaults: `LinearFilter` on both sides, a fresh
185 /// `DepthTexture`, and `autoClearDepth` on.
186 fn default() -> Self {
187 Self {
188 min_filter: TextureFilter::Linear,
189 mag_filter: TextureFilter::Linear,
190 depth_texture: None,
191 auto_clear_depth: true,
192 }
193 }
194}
195
196impl Default for PassNode {
197 fn default() -> Self {
198 Self::new()
199 }
200}
201
202impl PassNode {
203 /// `new PassNode( PassNode.COLOR, scene, camera )`: a 1×1 `RenderTarget`
204 /// with `{ type: HalfFloatType }` plus a `DepthTexture` named `depth`,
205 /// resized to the drawing buffer on the first frame.
206 pub fn new() -> Self {
207 Self::new_with_options(PassOptions::default())
208 }
209
210 /// `pass( scene, camera, options )` — the third argument, which three
211 /// spreads over `renderTarget.texture` and so over every attachment
212 /// `getTexture( name )` clones from it.
213 ///
214 /// The filter pair is not cosmetic: `webgpu_mrt` passes `NearestFilter` on
215 /// both sides, which makes all four attachments unfilterable, and the
216 /// composite shader that samples them is generated with `textureLoad` and
217 /// no samplers at all (`docs/nodes.md` §23).
218 pub fn new_with_options(options: PassOptions) -> Self {
219 let render_target = RenderTarget::new_with_options(
220 1,
221 1,
222 RenderTargetOptions {
223 // `PassNode.setup()` then overwrites this with
224 // `renderer.getOutputBufferType()`, which is `HalfFloatType`.
225 texture_type: TextureType::HalfFloat,
226 samples: 0,
227 depth_buffer: true,
228 min_filter: options.min_filter,
229 mag_filter: options.mag_filter,
230 },
231 )
232 .expect("three-rs: PassNode's render target is a HalfFloat colour type");
233 render_target.set_depth_texture(options.depth_texture.clone().unwrap_or_default());
234
235 // `getTextureNode()`'s node — the `PassTextureNode` — and the
236 // `PassNode` that wraps it. Both are `TempNode`s, which is why a pass
237 // *used as a value* contributes two vars and `getTextureNode()` one;
238 // sharing the inner node keeps them one texture to the builder.
239 let texture_node = texture_uv(&render_target.texture(), uv());
240 let node = to_var(None, texture_node.clone());
241
242 let texture_nodes = HashMap::from([(OUTPUT_ATTACHMENT.to_string(), texture_node)]);
243
244 let camera_near = uniform_settable(Type::F32, vec![0.0]);
245 let camera_far = uniform_settable(Type::F32, vec![0.0]);
246
247 let pass = Self(Rc::new(PassState {
248 render_target,
249 node,
250 previous_texture_nodes: RefCell::new(HashMap::new()),
251 mrt: RefCell::new(None),
252 texture_nodes: RefCell::new(texture_nodes),
253 view_z_nodes: RefCell::new(HashMap::new()),
254 linear_depth_nodes: RefCell::new(HashMap::new()),
255 depth_scope: Cell::new(false),
256 camera_near,
257 camera_far,
258 auto_clear_depth: options.auto_clear_depth,
259 owns_depth_texture: options.depth_texture.is_none(),
260 layers: RefCell::new(None),
261 size_divisor: std::cell::Cell::new(1),
262 resolution_scale: Cell::new(1.0),
263 render_object_function: RefCell::new(None),
264 opaque: Cell::new(true),
265 transparent: Cell::new(true),
266 lighting_enabled: Cell::new(true),
267 context_shadow: RefCell::new(None),
268 context_ao: RefCell::new(None),
269 scene: RefCell::new(None),
270 }));
271 // `PassTextureNode.passNode`: a draw that binds one of the pass's
272 // textures has the pass among its update-before nodes. The depth
273 // attachment only when it is this pass's own: a pass rendering into
274 // another's depth must not be taken for its producer.
275 pass.link(pass.0.render_target.texture().id());
276 if pass.0.owns_depth_texture {
277 pass.link(pass.depth_texture().id());
278 }
279 pass
280 }
281
282 /// Register `texture_id` as filled by this pass's `updateBefore()`.
283 fn link(&self, texture_id: usize) {
284 crate::nodes::frame::register_texture_update(texture_id, &self.0);
285 }
286
287 /// `passNode.scene = scene; passNode.camera = camera` — what the pass
288 /// renders from `updateBefore()`.
289 pub fn set_scene(&self, scene: SceneRef, camera: CameraRef) {
290 *self.0.scene.borrow_mut() = Some((scene, camera));
291 }
292
293 /// `PixelationPassNode.pixelSize = n` — the render target becomes
294 /// `floor( drawingBuffer / n )` on the next render. Crate-private: only
295 /// [`PixelationPassNode`](crate::nodes::display::PixelationPassNode)
296 /// overrides `setSize()` in three.js.
297 pub(crate) fn set_size_divisor(&self, divisor: u32) {
298 self.size_divisor.set(divisor);
299 }
300
301 /// `passNode.setResolutionScale( resolutionScale )` — the render target
302 /// becomes `Math.floor( drawingBuffer * resolutionScale )` on the next
303 /// render. `RetroPassNode` renders at a quarter of the canvas this way.
304 pub fn set_resolution_scale(&self, resolution_scale: f64) {
305 self.resolution_scale.set(resolution_scale);
306 }
307
308 /// `passNode.getResolutionScale()`.
309 pub fn resolution_scale(&self) -> f64 {
310 self.resolution_scale.get()
311 }
312
313 /// Install `function` on the renderer for the length of every render of
314 /// this pass — `renderer.setRenderObjectFunction( … )` around
315 /// `super.updateBefore( frame )`, with the previous function put back
316 /// after.
317 pub(crate) fn set_render_object_function(
318 &self,
319 function: Option<Rc<dyn super::RenderObjectFunction>>,
320 ) {
321 *self.render_object_function.borrow_mut() = function;
322 }
323
324 /// The pass's depth attachment, sampled at `coord` — the tap
325 /// `getTextureNode( 'depth' ).sample( coord )` makes.
326 pub(crate) fn depth_texture_node_at(&self, coord: NodeRef) -> NodeRef {
327 crate::nodes::tsl::pass_depth_texture_uv(&self.depth_texture(), coord)
328 }
329
330 /// `passNode.setLayers( layers )` — the camera layer mask this pass renders
331 /// with. `Layers::default()` (layer 0 only) is what `webgpu_deferred`'s
332 /// opaque and transparent passes set, to keep the resolve quad on layer 2
333 /// out of them.
334 pub fn set_layers(&self, layers: Layers) {
335 *self.layers.borrow_mut() = Some(layers);
336 }
337
338 /// `passNode.opaque` — `false` skips the opaque half of the render list,
339 /// and with it the skybox.
340 pub fn set_opaque(&mut self, opaque: bool) {
341 self.0.opaque.set(opaque);
342 }
343
344 /// `passNode.transparent`.
345 pub fn set_transparent(&mut self, transparent: bool) {
346 self.0.transparent.set(transparent);
347 }
348
349 /// `passNode.lighting = new Lighting(); passNode.lighting.enabled = false`
350 /// — the pass renders every material with an empty light list.
351 pub fn set_lighting_enabled(&mut self, enabled: bool) {
352 self.0.lighting_enabled.set(enabled);
353 }
354
355 /// `passNode.contextNode = builtinShadowContext( shadow, light )` — every
356 /// material this pass draws that receives `light`'s shadow multiplies
357 /// `shadow` (a `float` node, typically another pass's texture read at
358 /// `screenUV`) into that light's colour, after the shadow map's own
359 /// factor: three's `getShadow` returns `shadowColorNode.mul( shadow )`
360 /// for that light and every other light's `shadowColorNode` untouched.
361 ///
362 /// Like three's, the hook only runs where `AnalyticLightNode.setupShadow()`
363 /// does — `light.castShadow`, `object.receiveShadow` and
364 /// `renderer.shadowMap.enabled` — so an object that receives no shadow
365 /// map receives none of `shadow` either.
366 ///
367 /// `webgpu_postprocessing_sss`: `scenePass.contextNode =
368 /// builtinShadowContext( sssPass.getTextureNode().sample( screenUV ).r,
369 /// dirLight )`.
370 ///
371 /// The node is part of each receiving material's program key, so
372 /// replacing it builds new programs; keep one node for the pass's
373 /// lifetime.
374 pub fn set_context_shadow(&self, shadow: NodeRef, light: &ObjectRef) {
375 *self.0.context_shadow.borrow_mut() = Some(ShadowContext {
376 light: light.clone(),
377 shadow,
378 });
379 }
380
381 /// `passNode.contextNode = null` after a
382 /// [`set_context_shadow`](Self::set_context_shadow): the page's
383 /// "Shadow Maps only" output.
384 pub fn clear_context_shadow(&self) {
385 *self.0.context_shadow.borrow_mut() = None;
386 }
387
388 /// `passNode.contextNode = builtinAOContext( ao )` — every
389 /// non-transparent material this pass draws multiplies `ao` (a `float`
390 /// node, typically another pass's texture read at `screenUV`) into its
391 /// `AmbientOcclusion`, on top of its own `aoMap` when it has one. The
392 /// lighting models then occlude their indirect light by it, exactly as
393 /// they would by an `aoMap`.
394 ///
395 /// `webgpu_postprocessing_ao`:
396 /// `scenePass.contextNode = builtinAOContext( aoPass.getTextureNode()
397 /// .sample( screenUV ).r )`.
398 ///
399 /// The node is part of each material's program key, so replacing it
400 /// builds new programs; keep one node for the pass's lifetime.
401 pub fn set_context_ao(&self, ao: NodeRef) {
402 *self.0.context_ao.borrow_mut() = Some(ao);
403 }
404
405 /// `passNode.getTexture( 'depth' )` — the pass's own depth attachment.
406 ///
407 /// Three seeds `_textures[ 'depth' ]` in the constructor when the target
408 /// has a depth buffer and throws from `getTexture()` for any other pass;
409 /// here the target always has one, so this is infallible.
410 pub fn depth_texture(&self) -> DepthTexture {
411 self.render_target
412 .depth_texture()
413 .expect("three-rs: a PassNode's render target always carries a DepthTexture")
414 }
415
416 /// `passNode.getViewZNode( name )` — the depth attachment read back as a
417 /// view-space z.
418 ///
419 /// `perspectiveDepthToViewZ( getTextureNode( name ), cameraNear,
420 /// cameraFar )`. Only `'depth'` exists as a name here: a custom depth
421 /// output would be an extra colour attachment, which no ported page asks
422 /// for.
423 pub fn view_z_node(&self, name: &str) -> NodeRef {
424 if let Some(node) = self.view_z_nodes.borrow().get(name) {
425 return node.clone();
426 }
427 assert_eq!(
428 name, DEPTH_ATTACHMENT,
429 "three-rs: PassNode::view_z_node only knows the 'depth' output"
430 );
431 let node = perspective_depth_to_view_z(
432 pass_depth_texture(&self.depth_texture()),
433 self.camera_near.0.clone(),
434 self.camera_far.0.clone(),
435 );
436 self.view_z_nodes
437 .borrow_mut()
438 .insert(name.to_string(), node.clone());
439 node
440 }
441
442 /// `passNode.getLinearDepthNode( name )` — [`view_z_node`](Self::view_z_node)
443 /// as `viewZToOrthographicDepth( viewZ, cameraNear, cameraFar )`: `0` at
444 /// the near plane, `1` at the far one, linear in between.
445 pub fn linear_depth_node(&self, name: &str) -> NodeRef {
446 if let Some(node) = self.linear_depth_nodes.borrow().get(name) {
447 return node.clone();
448 }
449 let node = view_z_to_orthographic_depth(
450 self.view_z_node(name),
451 self.camera_near.0.clone(),
452 self.camera_far.0.clone(),
453 );
454 self.linear_depth_nodes
455 .borrow_mut()
456 .insert(name.to_string(), node.clone());
457 node
458 }
459
460 /// `passNode.setMRT( mrt )`.
461 ///
462 /// The names the MRT writes are *not* what creates the attachments —
463 /// `getTextureNode( name )` is, exactly as in three.js, where
464 /// `MRTNode.setup()` silently drops an output whose name is not among
465 /// `renderTarget.textures`. `webgpu_postprocessing_bloom_selective` asks
466 /// for `getTextureNode( 'bloomIntensity' )` and so gets the second
467 /// attachment; a page that set the MRT and never sampled the extra output
468 /// would render single-attachment, in three.js too.
469 pub fn set_mrt(&self, mrt: MrtNode) {
470 *self.mrt.borrow_mut() = Some(mrt);
471 }
472
473 /// `passNode.getMRT()`.
474 pub fn mrt(&self) -> Option<MrtNode> {
475 self.mrt.borrow().clone()
476 }
477
478 /// `passNode.getTextureNode( name )` — the node for one named colour
479 /// attachment, creating the attachment on first ask
480 /// (`PassNode.getTexture()`).
481 ///
482 /// Unlike [`PassNode::node`] this is **one** var, not two: a
483 /// `PassTextureNode` is what the graph holds, and the `PassNode` it builds
484 /// from its own `setup()` is then built only that once — `hasDependencies`
485 /// is false, so `TempNode` gives it no var of its own. `pass( scene, camera )`
486 /// used directly is the case with two, because there the graph holds the
487 /// `PassNode` as well and its usage count reaches two.
488 ///
489 /// `getTextureNode()` with no argument is that direct use,
490 /// [`PassNode::node`]; `getTextureNode( 'output' )` is this, on the same
491 /// `renderTarget.textures[ 0 ]`.
492 pub fn texture_node(&self, name: &str) -> NodeRef {
493 if let Some(node) = self.texture_nodes.borrow().get(name) {
494 return node.clone();
495 }
496 // `PassNode`'s constructor seeds `_textures.depth` with the depth
497 // attachment, so `getTextureNode( 'depth' )` is a tap on *that* and
498 // not a new colour attachment. `webgpu_deferred`'s resolve material
499 // reads it for both its `discard` and its `depthNode`.
500 if name == DEPTH_ATTACHMENT {
501 let node = pass_depth_texture(&self.depth_texture());
502 self.texture_nodes
503 .borrow_mut()
504 .insert(name.to_string(), node.clone());
505 return node;
506 }
507 let texture = if name == crate::renderer::OUTPUT_ATTACHMENT {
508 self.render_target.texture()
509 } else {
510 self.render_target.add_texture(name)
511 };
512 self.link(texture.id());
513 let node = texture_uv(&texture, uv());
514 self.texture_nodes
515 .borrow_mut()
516 .insert(name.to_string(), node.clone());
517 node
518 }
519
520 /// `passNode.getPreviousTextureNode( name )` — the node for the frame
521 /// *before* this one on that output.
522 ///
523 /// `PassNode.updateBefore()` calls `toggleTexture()` for every name that
524 /// has one **before** it renders, so on the very first frame the scene is
525 /// drawn into one of the pair and the node named "previous" points at the
526 /// other, which nothing has ever rendered into: a zero-initialised
527 /// texture. `webgpu_postprocessing_difference` grades exactly that frame,
528 /// so its `|previous − current|` is `|0 − current|` and the whole image is
529 /// a saturated version of the box. Rendering the previous buffer, or
530 /// swapping in the other order, is a different picture.
531 pub fn previous_texture_node(&self, name: &str) -> NodeRef {
532 if let Some(node) = self.previous_texture_nodes.borrow().get(name) {
533 return node.clone();
534 }
535 // `if ( this._textureNodes[ name ] === undefined ) this.getTextureNode(
536 // name );` — the attachment has to exist before its shadow does.
537 let _ = self.texture_node(name);
538 let texture = self.render_target.add_previous_texture(name);
539 self.link(texture.id());
540 let node = texture_uv(&texture, uv());
541 self.previous_texture_nodes
542 .borrow_mut()
543 .insert(name.to_string(), node.clone());
544 node
545 }
546
547 /// `passNode.getTexture( name )`.
548 pub fn texture_named(&self, name: &str) -> crate::textures::Texture {
549 self.render_target.add_texture(name)
550 }
551
552 /// The pass used as a value — `PassNode.setup()`: the colour texture
553 /// (`getTextureNode()`), or for a [`depth_pass`] the linear depth
554 /// (`getLinearDepthNode()`).
555 pub fn node(&self) -> NodeRef {
556 if self.depth_scope.get() {
557 self.linear_depth_node(DEPTH_ATTACHMENT)
558 } else {
559 self.node.clone()
560 }
561 }
562
563 /// `pass( … ).a` — the `a` of [`node`](Self::node), so a [`depth_pass`]
564 /// swizzles its linear depth as three's `PassNode` in depth scope does.
565 pub fn a(&self) -> NodeRef {
566 self.node().a()
567 }
568
569 /// `renderTarget.texture`.
570 pub fn texture(&self) -> crate::textures::Texture {
571 self.render_target.texture()
572 }
573
574 /// `passNode.renderTarget` — the accumulator an `SSAAPassNode` clones and
575 /// then draws into. `pub(crate)` because a `RenderTarget` is a handle and
576 /// handing one out would let an application render into a pass's target
577 /// behind its back.
578 pub(crate) fn render_target(&self) -> &RenderTarget {
579 &self.render_target
580 }
581
582 /// The render a pass's explicit `render()` used to do, before it was
583 /// removed in 0.2.0 (`docs/api.md` decision 10): for the passes that
584 /// wrap a `PassNode` and render it themselves (`SsaaPassNode`'s samples,
585 /// the toon outline).
586 pub(crate) fn render_scene(
587 &self,
588 renderer: &mut Renderer,
589 scene: &mut Scene,
590 camera: &mut dyn RenderCamera,
591 ) {
592 let (near, far) = (camera.near(), camera.far());
593 self.0.render_with(renderer, near, far, |renderer| {
594 renderer.render(scene, camera)
595 });
596 }
597
598 /// `PassNode.updateBefore()`'s bracket — the target sized to the
599 /// drawing buffer, its samples, the previous textures, `cameraNear` /
600 /// `cameraFar`, `setRenderTarget()` / `setMRT()` and their restore —
601 /// around a render of the caller's: `StereoPassNode`'s two eyes.
602 pub(crate) fn render_with(
603 &self,
604 renderer: &mut Renderer,
605 near: f64,
606 far: f64,
607 render: impl FnOnce(&mut Renderer),
608 ) {
609 self.0.render_with(renderer, near, far, render);
610 }
611}
612
613impl PassState {
614 /// `PassNode.updateBefore( frame )`: size the target to the drawing buffer,
615 /// then `renderer.setRenderTarget( this.renderTarget ); renderer.render(
616 /// this.scene, this.camera )` with the previous target restored after.
617 ///
618 /// `render` is the `renderer.render( this.scene, this.camera )` call, so
619 /// that a pass holding its scene in a `RefCell` can render it through a
620 /// shared borrow (see [`update_before`](NodeUpdate::update_before)).
621 /// `OITPassNode` renders twice inside it.
622 pub(crate) fn render_with(
623 &self,
624 renderer: &mut Renderer,
625 near: f64,
626 far: f64,
627 render: impl FnOnce(&mut Renderer),
628 ) {
629 let (width, height) = renderer.drawing_buffer_size();
630 // `PixelationPassNode.setSize()`: `Math.floor( size / pixelSize )`
631 // before `PassNode.setSize()` — a divisor of 1 is `PassNode`'s own.
632 let divisor = self.size_divisor.get().max(1);
633 let (width, height) = (width / divisor, height / divisor);
634 // `PassNode.setSize()`: `Math.floor( this._width *
635 // this._resolutionScale )`, where `updateBefore()` has set `_width`
636 // from `renderer.getDrawingBufferSize()`, which carries the pixel
637 // ratio. Kept at one texel or more: a zero-sized target is invalid
638 // in wgpu, where three's WebGPU backend would fail the frame.
639 let scale = self.resolution_scale.get();
640 let (width, height) = if scale == 1.0 {
641 (width, height)
642 } else {
643 (
644 ((f64::from(width) * scale).floor() as u32).max(1),
645 ((f64::from(height) * scale).floor() as u32).max(1),
646 )
647 };
648 self.render_target
649 .set_size_keeping_depth(width, height, !self.owns_depth_texture);
650 // `PassNode.setup()`: `renderTarget.samples = renderer.samples`.
651 self.render_target.set_samples(renderer.samples());
652
653 // `for ( const name in this._previousTextures ) this.toggleTexture(
654 // name );` — before the render, not after.
655 for name in self.previous_texture_nodes.borrow().keys() {
656 self.render_target.toggle_texture(name);
657 }
658
659 // `this._cameraNear.value = camera.near; this._cameraFar.value =
660 // camera.far;`
661 self.camera_near.1.set(vec![near]);
662 self.camera_far.1.set(vec![far]);
663
664 // `const currentRenderTarget = renderer.getRenderTarget()` and the
665 // rest of the save, restored when the scope drops.
666 let mut renderer = renderer.save_state();
667
668 renderer.set_render_target(Some(self.render_target.clone()));
669 renderer.set_mrt(self.mrt.borrow().clone());
670 renderer.auto_clear_depth = self.auto_clear_depth;
671 renderer.opaque = self.opaque.get();
672 renderer.transparent = self.transparent.get();
673 renderer.lighting_enabled = self.lighting_enabled.get();
674 // `renderer.contextNode = context( { ...renderer.contextNode
675 // .getFlowContextData(), ...this.contextNode.getFlowContextData() } )`
676 // — the pass's `getShadow` and `getAO` each win over an outer one,
677 // and an outer one survives a pass that sets none.
678 if let Some(shadow) = self.context_shadow.borrow().clone() {
679 renderer.context_shadow = Some(shadow);
680 }
681 if let Some(ao) = self.context_ao.borrow().clone() {
682 renderer.context_ao = Some(ao);
683 }
684 renderer.camera_layers = *self.layers.borrow();
685 if let Some(function) = self.render_object_function.borrow().clone() {
686 renderer.render_object_function = Some(function);
687 }
688
689 render(&mut renderer);
690 }
691}
692
693impl NodeUpdate for PassState {
694 /// `this.updateBeforeType = NodeUpdateType.FRAME`.
695 fn update_before_type(&self) -> NodeUpdateType {
696 NodeUpdateType::Frame
697 }
698
699 /// `PassNode.updateBefore( frame )`. A pass with no scene has nothing to
700 /// render, and does not count, so it is tried again at the next draw.
701 ///
702 /// The scene and camera are borrowed shared, not mutably: a pass's scene
703 /// can draw a material that samples another pass over the same scene
704 /// (the deferred page's resolve quad reads the opaque pass), and that
705 /// nested render borrows them again while the outer one holds them.
706 fn update_before(&self, renderer: &mut Renderer) -> bool {
707 let Some((scene, camera)) = self.scene.borrow().clone() else {
708 return false;
709 };
710 let (near, far) = {
711 let camera = camera.borrow();
712 (camera.near(), camera.far())
713 };
714 self.render_with(renderer, near, far, |renderer| {
715 renderer.render_shared(&scene.borrow(), &camera)
716 });
717 true
718 }
719
720 /// `PassNode.setup()`: `renderTarget.samples = renderer.samples`, ahead
721 /// of the pass's own render. A material that binds this pass's depth
722 /// texture (`getViewZNode()`) is built on the same call that discovers
723 /// the binding (`docs/nodes.md` §57.5), so the multisample flag the
724 /// builder reads has to be right before `updateBefore()` ever runs, not
725 /// after — this is what three's `setup()` does during graph analysis
726 /// and `render_with` alone cannot reproduce.
727 fn sync_before_build(&self, samples: u32) {
728 self.render_target.set_samples(samples);
729 }
730}
731
732#[cfg(test)]
733mod tests {
734 use super::*;
735
736 /// `dump-difference/dump.json` has two quad bind groups: 63, built with
737 /// the previous node on texture 4, and 64 — the one pass 0 actually binds
738 /// — with the current node on texture 4 (the rendered target) and the
739 /// previous node on texture 59, which no pass ever writes. So the two
740 /// nodes name two different textures, and only one of them is an
741 /// attachment.
742 ///
743 /// No GPU: this is the target's own bookkeeping, before any render.
744 #[test]
745 fn the_previous_texture_is_never_a_colour_attachment() {
746 let pass = PassNode::new();
747 let current = pass.texture_node(OUTPUT_ATTACHMENT);
748 let previous = pass.previous_texture_node(OUTPUT_ATTACHMENT);
749
750 assert_ne!(current.key(), previous.key());
751
752 let attachments: Vec<usize> = pass
753 .render_target()
754 .textures()
755 .iter()
756 .map(|texture| texture.id())
757 .collect();
758 assert_eq!(attachments.len(), 1);
759 assert_eq!(attachments[0], pass.render_target().texture().id());
760
761 let shadow = pass.render_target().add_previous_texture(OUTPUT_ATTACHMENT);
762 assert!(!attachments.contains(&shadow.id()));
763 }
764
765 /// Both accessors are memoised, so a page that asks twice composes one
766 /// node and the builder sees one texture — `_textureNodes` /
767 /// `_previousTextureNodes`.
768 #[test]
769 fn the_texture_nodes_are_memoised() {
770 let pass = PassNode::new();
771 assert_eq!(
772 pass.texture_node(OUTPUT_ATTACHMENT).key(),
773 pass.texture_node(OUTPUT_ATTACHMENT).key()
774 );
775 assert_eq!(
776 pass.previous_texture_node(OUTPUT_ATTACHMENT).key(),
777 pass.previous_texture_node(OUTPUT_ATTACHMENT).key()
778 );
779 }
780}