Skip to main content

three_rs/renderer/
cube_render_target.rs

1//! Port of `three.js/src/renderers/common/CubeRenderTarget.js`: the target
2//! itself, which [`CubeCamera`](crate::cameras::CubeCamera) renders into, and
3//! `fromEquirectangularTexture()`.
4//!
5//! `CubeMapNode.updateBefore()` takes it whenever a material's or a scene's
6//! environment is a `Texture` with `EquirectangularReflectionMapping`: the
7//! equirectangular map becomes a `CubeTexture` of `image.height` a side, cached
8//! per source texture, and everything downstream samples the cube. That is why
9//! three's dump of `webgpu_postprocessing_bloom_emissive` — whose page assigns
10//! the raw 1024×512 HDR straight to `scene.background` — contains a 512² cube
11//! conversion pass nobody wrote.
12//!
13//! **What this port does differently.** Three renders the six faces straight
14//! into the cube texture's array layers, one `setRenderTarget( target, face )`
15//! each. [`Renderer`] has no layered colour attachment, so each face is drawn
16//! into a plain 2-D render target of the same size and format and then copied
17//! into its layer. The copy is exact — same format, same extent, no sampling —
18//! so the cube's texels are the ones three's are, and the divergence is a
19//! command-buffer one, recorded in `docs/nodes.md`.
20
21use crate::cameras::PerspectiveCamera;
22use crate::error::Error;
23use crate::geometries::box_geometry;
24use crate::materials::{Blending, MeshBasicNodeMaterial, Side};
25use crate::math::Vector3;
26use crate::nodes::tsl::{equirect_uv, float, position_world_direction, texture_level};
27use crate::objects::{Mesh, Scene};
28use crate::textures::{CubeTexture, Texture, TextureFilter, TextureType};
29
30use super::render_target::{RenderTarget, RenderTargetOptions};
31use super::Renderer;
32
33use std::rc::Rc;
34
35/// `CubeCamera.updateCoordinateSystem()`'s `WebGPUCoordinateSystem` branch: the
36/// `up` vector and the point each face camera looks at, in the order px, nx,
37/// py, ny, pz, nz — the order [`CubeTexture`]'s images are in.
38///
39/// Note px looking at **-x** and nx at **+x**: the same left-handed cube-map
40/// convention the `x` negation in `CubeTextureNode.setupUV()` undoes at the
41/// sampling end.
42pub(crate) const FACES: [([f64; 3], [f64; 3]); 6] = [
43    ([0.0, -1.0, 0.0], [-1.0, 0.0, 0.0]),
44    ([0.0, -1.0, 0.0], [1.0, 0.0, 0.0]),
45    ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
46    ([0.0, 0.0, -1.0], [0.0, -1.0, 0.0]),
47    ([0.0, -1.0, 0.0], [0.0, 0.0, 1.0]),
48    ([0.0, -1.0, 0.0], [0.0, 0.0, -1.0]),
49];
50
51/// `const fov = - 90; // negative fov is not an error` — the vertical flip a
52/// cube face needs under WebGPU's top-left texture origin, expressed as a
53/// frustum with `top < bottom`.
54pub(crate) const FOV: f64 = -90.0;
55
56/// `new CubeRenderTarget( size, { type } )` — the cube a
57/// [`CubeCamera`](crate::cameras::CubeCamera) draws its six faces into.
58///
59/// `texture` is three's `cubeRenderTarget.texture`: a [`CubeTexture`] with
60/// no mipmaps and `LinearFilter` both ways, the defaults three's descriptor
61/// dump of `webgpu_sky` shows (`mipLevelCount: 1`). It is what a material's
62/// `envMap` takes.
63///
64/// Three renders each face straight into a layer of the cube; the port has no
65/// layered colour attachment, so the target also owns one 2-D render target
66/// of the same size and type, with a depth buffer (`depthBuffer` defaults to
67/// `true`), which each face is drawn into and then copied out of — see the
68/// module comment.
69#[derive(Clone, Debug)]
70pub struct CubeRenderTarget {
71    /// `cubeRenderTarget.texture`.
72    pub texture: CubeTexture,
73    pub(crate) face: RenderTarget,
74}
75
76impl CubeRenderTarget {
77    /// `cubeRenderTarget.dispose()` — drops the target and, with it, its
78    /// handles on the cube texture and the face target; the GPU side goes
79    /// with the last handle, as for [`RenderTarget::dispose`]. Dropping the
80    /// target does the same; this exists so three.js code ports line for
81    /// line.
82    pub fn dispose(self) {}
83
84    /// `new CubeRenderTarget( size, { type: textureType } )`.
85    ///
86    /// # Errors
87    ///
88    /// [`Error::UnsupportedTextureType`] if `texture_type` is not a colour
89    /// type.
90    pub fn new(size: u32, texture_type: TextureType) -> Result<Self, Error> {
91        let texture = CubeTexture::render_target(size, texture_type);
92        let face = RenderTarget::new_with_options(
93            size,
94            size,
95            RenderTargetOptions {
96                texture_type,
97                samples: 0,
98                depth_buffer: true,
99                min_filter: TextureFilter::Linear,
100                mag_filter: TextureFilter::Linear,
101            },
102        )?;
103        Ok(Self { texture, face })
104    }
105
106    /// `cubeRenderTarget.width` — the side of every face.
107    pub fn size(&self) -> u32 {
108        self.texture.size().0
109    }
110}
111
112/// `new CubeRenderTarget( texture.image.height ).fromEquirectangularTexture(
113/// renderer, texture )`.
114///
115/// The returned cube carries the source's type and colour space, no mipmaps and
116/// `LinearFilter` both ways, which is what three's descriptor dump shows.
117pub fn from_equirectangular_texture(
118    renderer: &mut Renderer,
119    source: &Texture,
120) -> Result<CubeTexture, Error> {
121    let size = source.size().1;
122
123    let texture_type = match source.format() {
124        wgpu::TextureFormat::Rgba16Float => TextureType::HalfFloat,
125        _ => TextureType::UnsignedByte,
126    };
127    let cube = CubeTexture::render_target(size, texture_type);
128    cube.set_color_space(source.color_space());
129
130    // `new Mesh( new BoxGeometry( 5, 5, 5 ), material )`, seen from inside:
131    // `side = BackSide`, `blending = NoBlending`, and a colour node that is the
132    // equirectangular map read at level 0 along the world-space view direction.
133    let mut material = MeshBasicNodeMaterial::new();
134    material.color_node = Some(texture_level(
135        source,
136        equirect_uv(position_world_direction()),
137        float(0.0),
138    ));
139    material.side = Side::Back;
140    material.blending = Blending::No;
141
142    let mesh = Mesh::new(Rc::new(box_geometry(5.0, 5.0, 5.0, 1, 1, 1)), material);
143    let mut scene = Scene::new();
144    scene.add(&mesh);
145
146    let face_target = RenderTarget::new_with_options(
147        size,
148        size,
149        RenderTargetOptions {
150            texture_type,
151            samples: 0,
152            depth_buffer: true,
153            min_filter: TextureFilter::Linear,
154            mag_filter: TextureFilter::Linear,
155        },
156    )?;
157
158    // `const currentMRT = renderer.getMRT(); renderer.setMRT( null )` — the
159    // conversion writes one attachment however many the frame that asked for it
160    // has.
161    let mut renderer = renderer.save_state();
162    renderer.set_mrt(None);
163    renderer.set_render_target(Some(face_target.clone()));
164
165    let mut camera = PerspectiveCamera::new(FOV, 1.0, 1.0, 10.0);
166    for (layer, (up, look_at)) in FACES.iter().enumerate() {
167        {
168            let mut object = camera.node.borrow_mut();
169            object.up = Vector3::new(up[0], up[1], up[2]);
170        }
171        camera.look_at(&Vector3::new(look_at[0], look_at[1], look_at[2]));
172        renderer.render(&mut scene, &mut camera);
173        renderer.copy_to_cube_layer(&face_target, &cube, layer as u32, 0);
174    }
175    drop(renderer);
176
177    Ok(cube)
178}