Skip to main content

three_rs/nodes/display/
retro_pass.rs

1//! Port of `three.js/examples/jsm/tsl/display/RetroPassNode.js` — a scene
2//! pass drawn the way a PlayStation 1 drew it: at a quarter of the canvas,
3//! with nearest filtering, with every vertex snapped to that low-resolution
4//! grid, with no texture mipmaps and, optionally, with affine (not
5//! perspective-correct) texture mapping.
6
7use std::cell::{Cell, OnceCell};
8use std::rc::Rc;
9
10use crate::materials::{MaterialKind, MeshBasicNodeMaterial};
11use crate::math::Color;
12use crate::nodes::tsl::{
13    block, camera_projection_matrix, camera_view_matrix, custom, float, mix, position_world,
14    screen_size, texture_uv, to_varying, uv, vec2, vec4_join,
15};
16use crate::nodes::{ContextValue, CustomNode, NodeBuilder, NodeRef, Type};
17use crate::renderer::{CameraRef, PassNode, PassOptions, RenderObjectFunction, SceneRef};
18use crate::textures::TextureFilter;
19
20/// `retroPass( scene, camera, options )`'s options object.
21#[derive(Clone, Debug, Default)]
22#[non_exhaustive]
23pub struct RetroPassOptions {
24    /// `options.affineDistortion` — when set, every 2D texture tap of a
25    /// classic material reads `mix( uv(), affineUv / w, affineDistortion )`:
26    /// 0 is perspective-correct, 1 the PS1's affine mapping. `null` by
27    /// default, which leaves the uv alone.
28    pub affine_distortion: Option<NodeRef>,
29    /// `options.filterTextures` — `false` by default, which samples every
30    /// texture of a classic material at level 0 (`getTextureLevel: () =>
31    /// uint( 0 )`), so no mipmaps.
32    pub filter_textures: bool,
33}
34
35impl RetroPassOptions {
36    /// The options with `affine_distortion` set.
37    pub fn affine_distortion(mut self, node: impl Into<NodeRef>) -> Self {
38        self.affine_distortion = Some(node.into());
39        self
40    }
41
42    /// The options with `filter_textures` set.
43    pub fn filter_textures(mut self, filter_textures: bool) -> Self {
44        self.filter_textures = filter_textures;
45        self
46    }
47}
48
49/// `RetroPassNode`, a port of
50/// `three.js/examples/jsm/tsl/display/RetroPassNode.js`: a scene pass drawn
51/// the way a PlayStation 1 drew it. It renders at a quarter of the canvas,
52/// with nearest filtering, with every vertex snapped to that low-resolution
53/// grid, with no texture mipmaps and, optionally, with affine (not
54/// perspective-correct) texture mapping.
55///
56/// Three subclasses `PassNode` and swaps the renderer's render-object
57/// function around `super.updateBefore()`. The port wraps a [`PassNode`] and
58/// gives it a render-object function (the crate-private
59/// `RenderObjectFunction`). The pass installs it on the renderer for the
60/// length of its own render, and the render loop asks it once per draw,
61/// exactly where three calls the function.
62/// [`ToonOutlinePassNode`](super::ToonOutlinePassNode) swaps the same
63/// function in three; its port predates this hook and has a dedicated
64/// `toon_outline` field on the renderer instead.
65///
66/// # Which material a draw is made with
67///
68/// Three derives a retro material per source material (cached on its
69/// `version`): a `MeshBasicNodeMaterial` for a basic source, a
70/// `MeshPhongNodeMaterial` for anything else, whose `vertexNode` is the
71/// snapping `_clipSpaceRetro`, whose `colorNode` is `materialColor` and whose
72/// `contextNode` carries the `getUV` / `getTextureLevel` overrides. It then
73/// copies **every property of the source that the retro material also has**
74/// over it (`for ( const property in material )`). A classic material
75/// (`MeshStandardMaterial`, `MeshBasicMaterial`, what `GLTFLoader` makes) has
76/// none of the node slots, so its maps, colours and flags come across and the
77/// retro nodes stay. A node material has all of them, null ones included, so
78/// its own `vertexNode`, `colorNode`, `contextNode` and the rest overwrite the
79/// retro ones and it is drawn as itself, as a basic or a Phong material: the
80/// smoke in `webgpu_postprocessing_retro` is neither snapped nor level-0
81/// sampled in three's dump (`m05`/`m06`), and the mug is (`m03`/`m04`).
82///
83/// The port has one material struct for both, so "classic" is decided by the
84/// node slots: a source with none of them set is a classic one. See
85/// `is_node_material`.
86///
87/// # Not ported
88///
89/// - the `MeshStandardMaterial` + `envMap` / `scene.environment` branch,
90///   which mixes a `CubeMapNode` reflection into `colorNode` by metalness:
91///   the page takes it only for the Damaged Helmet, which is not its default
92///   model. A standard source is drawn as a Phong one without it.
93/// - the background draw keeps its own material. Three's background is a
94///   plain `NodeMaterial`, so its retro material is a Phong one with
95///   `lights = false` and every node copied over; that draws diffuse plus a
96///   black emissive, which is the background's colour unchanged (`m01`).
97/// - sprite, points, fat-line and normal materials are drawn as themselves;
98///   three would hand them to a Phong material, which the port's flows for
99///   those kinds cannot be.
100/// - the per-material cache and `dispose()`: the port derives the material
101///   per draw (a clone) and keys its programs on the source's, so a changed
102///   source or a changed [`set_filter_textures`](RetroPassNode::set_filter_textures)
103///   is picked up on the next frame without one.
104pub struct RetroPassNode {
105    pass: PassNode,
106    node: NodeRef,
107    function: Rc<RetroFunction>,
108}
109
110/// `retroPass( scene, camera, options )`.
111pub fn retro_pass(scene: SceneRef, camera: CameraRef, options: RetroPassOptions) -> RetroPassNode {
112    RetroPassNode::new(scene, camera, options)
113}
114
115impl RetroPassNode {
116    /// `new RetroPassNode( scene, camera, options )`: a colour pass at a
117    /// resolution scale of 0.25 with `NearestFilter` on both sides.
118    ///
119    /// Three also sets the target's type to `UnsignedByteType`, and
120    /// `PassNode.setup()` then overwrites it with the renderer's output
121    /// buffer type, `HalfFloatType` — its dump binds an `rgba16float` target —
122    /// so the port's pass keeps `HalfFloat`.
123    pub fn new(scene: SceneRef, camera: CameraRef, options: RetroPassOptions) -> Self {
124        let pass = PassNode::new_with_options(PassOptions {
125            min_filter: TextureFilter::Nearest,
126            mag_filter: TextureFilter::Nearest,
127            ..PassOptions::default()
128        });
129        pass.set_scene(scene, camera);
130        pass.set_resolution_scale(0.25);
131
132        let function = Rc::new(RetroFunction {
133            affine_distortion: options.affine_distortion,
134            filter_textures: Cell::new(options.filter_textures),
135            id: next_id(),
136        });
137        pass.set_render_object_function(Some(function.clone()));
138
139        let node = custom(RetroTextureNode { pass: pass.clone() });
140
141        Self {
142            pass,
143            node,
144            function,
145        }
146    }
147
148    /// `getTextureNode()` — the pass's colour, to compose with. Its uv is the
149    /// `getUV` of the [`context`](crate::nodes::tsl::context) it is built in,
150    /// as a `PassTextureNode`'s is, so
151    /// [`replace_default_uv`](crate::nodes::tsl::replace_default_uv) around
152    /// it reads the pass where the given uv says (`webgpu_postprocessing_retro`
153    /// reads it through [`barrel_uv`](super::barrel_uv)). Without one it is
154    /// `uv()`.
155    pub fn node(&self) -> NodeRef {
156        self.node.clone()
157    }
158
159    /// The wrapped pass.
160    pub fn pass(&self) -> &PassNode {
161        &self.pass
162    }
163
164    /// `retroPass.filterTextures = value` (followed, on the page, by
165    /// `retro.dispose()`): whether classic materials' textures keep their
166    /// mipmaps. Takes effect on the next frame.
167    pub fn set_filter_textures(&self, filter_textures: bool) {
168        self.function.filter_textures.set(filter_textures);
169    }
170
171    /// `retroPass.filterTextures`.
172    pub fn filter_textures(&self) -> bool {
173        self.function.filter_textures.get()
174    }
175
176    /// `retroPass.affineDistortionNode`.
177    pub fn affine_distortion(&self) -> Option<NodeRef> {
178        self.function.affine_distortion.clone()
179    }
180}
181
182impl From<&RetroPassNode> for NodeRef {
183    fn from(retro: &RetroPassNode) -> NodeRef {
184        retro.node()
185    }
186}
187
188fn next_id() -> usize {
189    thread_local! { static NEXT: Cell<usize> = const { Cell::new(0) }; }
190    NEXT.with(|n| {
191        let id = n.get();
192        n.set(id + 1);
193        id
194    })
195}
196
197/// The pass's `PassTextureNode`: a tap on its colour texture whose uv is
198/// `builder.context.getUV` when there is one — `TextureNode.setup()`'s
199/// `if ( uvNode === null && builder.context.getUV ) uvNode =
200/// builder.context.getUV( this, builder )` — and `uv()` otherwise. The texture
201/// is unfilterable (`NearestFilter` on both sides), so the tap is a
202/// `textureLoad`, as three's dump has it.
203///
204/// It holds the pass, as three's `PassTextureNode.passNode` does, so the pass
205/// is rendered for as long as a graph reads it.
206struct RetroTextureNode {
207    pass: PassNode,
208}
209
210impl CustomNode for RetroTextureNode {
211    fn type_name(&self) -> &'static str {
212        "PassTextureNode"
213    }
214
215    fn node_type(&self) -> Type {
216        Type::Vec4
217    }
218
219    fn setup(&self, builder: &NodeBuilder) -> NodeRef {
220        let coord = builder.context("getUV").unwrap_or_else(uv);
221        texture_uv(&self.pass.texture(), coord)
222    }
223}
224
225/// `_affineUv`, `_w` and `_clipSpaceRetro`: module-level in three, so one
226/// node per thread here.
227struct ClipSpaceRetro {
228    affine_uv: NodeRef,
229    w: NodeRef,
230    position: NodeRef,
231}
232
233fn clip_space_retro() -> Rc<ClipSpaceRetro> {
234    thread_local! { static CELL: OnceCell<Rc<ClipSpaceRetro>> = const { OnceCell::new() }; }
235    CELL.with(|c| {
236        c.get_or_init(|| {
237            // `varying( vec2() )` / `varying( float() )`.
238            let affine_uv = to_varying(None, vec2(0.0, 0.0));
239            let w = to_varying(None, float(0.0));
240
241            let default_position = camera_projection_matrix()
242                .mul(camera_view_matrix())
243                .mul(position_world());
244
245            let half_w = default_position.w().mul(2.0);
246            let rounded_position = default_position
247                .xy()
248                .div(half_w.clone())
249                .mul(screen_size().xy())
250                .round()
251                .div(screen_size().xy())
252                .mul(half_w);
253
254            let assign_affine_uv = affine_uv.assign(uv().mul(default_position.w()));
255            let assign_w = w.assign(default_position.w());
256
257            let position = block(
258                vec![assign_affine_uv, assign_w],
259                vec4_join(vec![rounded_position.xy(), default_position.zw()]),
260            );
261
262            Rc::new(ClipSpaceRetro {
263                affine_uv,
264                w,
265                position,
266            })
267        })
268        .clone()
269    })
270}
271
272/// Whether `material` is what three calls a node material: one with any node
273/// slot set. A classic three material has none of `NodeMaterial`'s
274/// properties, so `RetroPassNode`'s property copy leaves the retro nodes in
275/// place; a node material overwrites them. `GLTFLoader` sets none of these.
276pub(crate) fn is_node_material(material: &MeshBasicNodeMaterial) -> bool {
277    let m = material;
278    [
279        &m.color_node,
280        &m.opacity_node,
281        &m.alpha_test_node,
282        &m.emissive_node,
283        &m.mask_node,
284        &m.cast_shadow_node,
285        &m.received_shadow_position_node,
286        &m.specular_node,
287        &m.normal_node,
288        &m.position_node,
289        &m.scale_node,
290        &m.rotation_node,
291        &m.size_node,
292        &m.vertex_node,
293        &m.fragment_node,
294        &m.output_node,
295        &m.backdrop_node,
296        &m.backdrop_alpha_node,
297        &m.metalness_node,
298        &m.roughness_node,
299        &m.depth_node,
300    ]
301    .iter()
302    .any(|slot| slot.is_some())
303        || m.mrt_node.is_some()
304        || m.context_overrides.is_some()
305        || m.context_node.is_some()
306        || m.lighting_model.is_some()
307        || m.lights_node.is_some()
308}
309
310/// The render-object function `RetroPassNode.updateBefore()` installs.
311struct RetroFunction {
312    affine_distortion: Option<NodeRef>,
313    filter_textures: Cell<bool>,
314    id: usize,
315}
316
317impl RenderObjectFunction for RetroFunction {
318    fn material(&self, source: &MeshBasicNodeMaterial, background: bool) -> MeshBasicNodeMaterial {
319        let mut material = source.clone();
320        let basic = match source.kind {
321            MaterialKind::Basic => true,
322            MaterialKind::Phong
323            | MaterialKind::Lambert
324            | MaterialKind::Standard
325            | MaterialKind::Physical
326            | MaterialKind::Toon => false,
327            // Not ported; see the module documentation.
328            _ => return material,
329        };
330        if background {
331            return material;
332        }
333
334        // `new MeshBasicNodeMaterial()` / `new MeshPhongNodeMaterial()`, with
335        // the source's properties copied over. A Phong material's own
336        // `specular` and `shininess` are the only ones a non-Phong source has
337        // nothing to copy into.
338        if !basic {
339            if source.kind != MaterialKind::Phong {
340                let phong = MeshBasicNodeMaterial::phong(Color::new(1.0, 1.0, 1.0));
341                material.specular = phong.specular;
342                material.shininess = phong.shininess;
343            }
344            material.kind = MaterialKind::Phong;
345            material.lights = source.lights || !is_node_material(source);
346        }
347
348        if is_node_material(source) {
349            // Every node slot, null ones included, was copied over the retro
350            // material's: the source is drawn as itself.
351            return material;
352        }
353
354        // `retroMaterial.vertexNode = material.vertexNode || _clipSpaceRetro`;
355        // `colorNode = material.colorNode || materialColor`, which is the
356        // port's `color_node: None`.
357        let clip = clip_space_retro();
358        material.vertex_node = Some(clip.position.clone());
359        material.color_node = None;
360
361        let mut context = ContextValue::new();
362        if let Some(affine) = &self.affine_distortion {
363            // `getUV: ( texture ) => texture.isCubeTextureNode ? reflectVector
364            // : affine.mix( uv(), _affineUv.div( _w ) )`. Only 2D taps read
365            // `getUV` in the port, and a cube tap's default is
366            // `reflectVector` already.
367            context = context.set(
368                "getUV",
369                mix(uv(), clip.affine_uv.div(clip.w.clone()), affine.clone()),
370            );
371        }
372        if !self.filter_textures.get() {
373            // `getTextureLevel: () => uint( 0 )`, which the builder formats
374            // as the `f32` level `textureSampleLevel` takes: `0.0` in the dump.
375            context = context.set("getTextureLevel", float(0.0));
376        }
377        material.context_node = Some(context);
378
379        material
380    }
381
382    fn variant(&self) -> u64 {
383        (self.id as u64) << 1 | u64::from(self.filter_textures.get())
384    }
385}