three_rs/loaders/cube_texture_loader.rs
1//! Port of `three.js/src/loaders/CubeTextureLoader.js` (+ the image decode
2//! that `ImageLoader` gets from the browser).
3//!
4//! The page's load is asynchronous, but the harness fires its single RAF only
5//! once the network is idle, so the faces are always present for the graded
6//! frame; here they are decoded synchronously.
7
8use std::path::{Path, PathBuf};
9
10use crate::error::Error;
11use crate::math::ColorSpace;
12use crate::textures::{CubeTexture, Image};
13
14/// three.js' `CubeTextureLoader`.
15#[derive(Debug, Clone, Default)]
16pub struct CubeTextureLoader {
17 /// `Loader.path`, prefixed to every url.
18 path: PathBuf,
19}
20
21impl CubeTextureLoader {
22 /// A loader with an empty [`path`](Self::set_path).
23 pub fn new() -> Self {
24 Self::default()
25 }
26
27 /// `loader.setPath( path )`.
28 pub fn set_path<P: AsRef<Path>>(mut self, path: P) -> Self {
29 self.path = path.as_ref().to_path_buf();
30 self
31 }
32
33 /// `new CubeTextureLoader().load( urls )` — the loader sets
34 /// `texture.colorSpace = SRGBColorSpace`.
35 pub fn load<P: AsRef<Path>>(&self, urls: [P; 6]) -> Result<CubeTexture, Error> {
36 let images = self.load_faces(&urls)?;
37 let texture = CubeTexture::new(images);
38 texture.set_color_space(ColorSpace::Srgb);
39 Ok(texture)
40 }
41
42 /// The six decoded faces on their own — what a hand-authored mip level of
43 /// a [`CubeTexture`] is made of. On the page each level is a whole
44 /// `CubeTexture` and only its `images` is ever read, so the port skips the
45 /// texture and keeps the faces.
46 pub fn load_images<P: AsRef<Path>>(&self, urls: [P; 6]) -> Result<Vec<Image>, Error> {
47 self.load_faces(&urls)
48 }
49
50 fn load_faces<P: AsRef<Path>>(&self, urls: &[P; 6]) -> Result<Vec<Image>, Error> {
51 urls.iter()
52 .map(|url| decode(&self.path.join(url.as_ref())))
53 .collect()
54 }
55}
56
57/// What the browser hands `copyExternalImageToTexture`: 8-bit RGBA, top-down,
58/// opaque where the source has no alpha channel.
59///
60/// The decoder is picked by the file's magic and not by its extension, as it
61/// is in the browser: `webgpu_materials_basic`'s six faces are PNG,
62/// `webgpu_pmrem_scene`'s are JPEG, and both reach
63/// [`super::texture_loader::decode_image`].
64fn decode(path: &Path) -> Result<Image, Error> {
65 let bytes = crate::io::read(path)?;
66 super::texture_loader::decode_image(path, &bytes)
67}