Skip to main content

three_rs/
error.rs

1//! The crate's error type.
2//!
3//! Nothing in three.js corresponds to this file: JavaScript throws, and the
4//! port's public entry points return `Result` instead (issue #9, and decision 4
5//! in `docs/api.md`). One enum covers the whole crate, so a caller writes one
6//! `match` — or none, since [`Error`] implements [`std::error::Error`].
7//!
8//! Panics are kept for invariants the caller cannot reach: a light list that
9//! only holds lights, a texture the renderer uploaded a moment earlier. Every
10//! such message starts `three-rs:` and names the invariant.
11
12use std::fmt;
13use std::path::PathBuf;
14
15use crate::animation::property_binding::ParseTrackNameError;
16
17/// Everything the public API of `three-rs` can fail with.
18///
19/// Non-exhaustive: new variants are added as more of the port's surface stops
20/// panicking, and matching code should carry a `_` arm.
21#[derive(Debug)]
22#[non_exhaustive]
23pub enum Error {
24    /// A file a loader was pointed at could not be read.
25    Io {
26        /// The file that could not be read.
27        path: PathBuf,
28        /// What the OS said.
29        source: std::io::Error,
30    },
31    /// A JSON document could not be parsed. `path` is `None` when the caller
32    /// handed the JSON over directly, as `BufferGeometryLoader::parse` does.
33    Json {
34        /// The file the JSON was read from, when there was one.
35        path: Option<PathBuf>,
36        /// What `serde_json` said.
37        source: serde_json::Error,
38    },
39    /// An image file the decoder rejected.
40    Image {
41        /// The image file.
42        path: PathBuf,
43        /// Why the decoder rejected it.
44        reason: String,
45    },
46    /// A Radiance RGBE (`.hdr`) file the decoder rejected. `reason` is
47    /// three.js' own `rgbe_error()` message, less its `THREE.HDRLoader: `
48    /// prefix.
49    Rgbe {
50        /// The decoder's message.
51        reason: String,
52    },
53    /// A KTX 2.0 file `KTX2Loader` rejected, or one it cannot transcode for
54    /// this device. `reason` is three.js' own message, less its
55    /// `THREE.KTX2Loader: ` prefix.
56    Ktx2 {
57        /// The decoder's message.
58        reason: String,
59    },
60    /// A colour lookup table `LUTCubeLoader`, `LUT3dlLoader` or
61    /// `LUTImageLoader` rejected. `loader` is the three.js class name and
62    /// `reason` its own message, less the `THREE.<loader>: ` prefix.
63    Lut {
64        /// The three.js loader class, e.g. `"LUTCubeLoader"`.
65        loader: &'static str,
66        /// The loader's message.
67        reason: String,
68    },
69    /// A file names a type, format or encoding this port does not implement.
70    /// `what` says which field it was read from.
71    UnsupportedFormat {
72        /// The field the value was read from.
73        what: &'static str,
74        /// The unsupported value.
75        value: String,
76    },
77    /// A texture type that is not a legal depth format (`gpu_format`) or not a
78    /// legal colour format (`color_gpu_format`).
79    UnsupportedTextureType {
80        /// Which check failed (`gpu_format` or `color_gpu_format`).
81        what: &'static str,
82        /// The texture type that failed it.
83        texture_type: crate::textures::TextureType,
84    },
85    /// A glTF asset the loader could not make sense of.
86    Gltf(GltfError),
87    /// `new KeyframeTrack()` with an empty `times` array.
88    NoKeyframes {
89        /// The track's name.
90        track: String,
91    },
92    /// A track type name that no `KeyframeTrack` subclass answers to.
93    UnsupportedTrackType {
94        /// The type name that was not recognized.
95        name: String,
96    },
97    /// An interpolation mode this track's value type does not support, where
98    /// the value type's own default does not support it either.
99    UnsupportedInterpolation {
100        /// The track's value type (`"vector"`, `"quaternion"`, …).
101        value_type: &'static str,
102        /// The track's name.
103        track: String,
104    },
105    /// A track name `PropertyBinding` cannot parse.
106    TrackName(ParseTrackNameError),
107    /// No adapter to render on — no Vulkan device natively, or
108    /// `navigator.gpu.requestAdapter()` resolving to null in a browser.
109    /// `wanted` is the `THREE_RS_ADAPTER_NAME` filter, when one was set and
110    /// matched nothing; it is always `None` on wasm32, where the browser picks
111    /// the adapter and there is nothing to filter.
112    NoAdapter {
113        /// The `THREE_RS_ADAPTER_NAME` filter that matched nothing, if one was set.
114        wanted: Option<String>,
115    },
116    /// `Renderer::new()` on wasm32 with nothing handed to
117    /// `renderer::adopt_device()` first. Device creation is asynchronous in a
118    /// browser and the examples' `init()` is not, so the host must create the
119    /// device and park it before the first `Renderer::new()`; see
120    /// `renderer::adopt_device`. wasm32 only.
121    #[cfg(target_arch = "wasm32")]
122    NoAdoptedDevice,
123    /// `adapter.request_device()` failed.
124    Device(wgpu::RequestDeviceError),
125    /// Reading pixels back off the GPU failed; `reason` is what wgpu said.
126    Readback {
127        /// What wgpu said.
128        reason: String,
129    },
130    /// A material field that is set but that no part of the port reads for
131    /// this kind of material — see
132    /// [`MeshBasicNodeMaterial::check_supported`](crate::materials::MeshBasicNodeMaterial::check_supported)
133    /// and the audit in `docs/api.md`. `field` is the three.js name.
134    Unsupported {
135        /// The three.js field name.
136        field: &'static str,
137        /// The material kind it was set on.
138        kind: crate::materials::MaterialKind,
139    },
140}
141
142/// What went wrong inside a glTF asset, as far as the loader reads it.
143#[derive(Debug)]
144#[non_exhaustive]
145pub enum GltfError {
146    /// A JSON chunk, or a `.gltf` file, that is not UTF-8.
147    NotUtf8,
148    /// `asset.version` is not 2.x.
149    UnsupportedVersion(String),
150    /// The 12-byte GLB header has the wrong magic.
151    BadHeader,
152    /// A GLB written against the draft container format.
153    LegacyBinary,
154    /// A GLB chunk that runs past the end of the file.
155    TruncatedChunk,
156    /// A GLB with no JSON chunk.
157    NoJsonChunk,
158    /// A buffer with no `uri` in a GLB that has no BIN chunk.
159    NoBinChunk,
160    /// A field a definition cannot be read without (`accessor.type`,
161    /// `sampler.input`, …). `what` names it.
162    MissingField {
163        /// The missing field's name.
164        what: &'static str,
165    },
166    /// An index into one of the asset's arrays that is not there. `kind` is the
167    /// array (`accessor`, `bufferView`, `buffer`, `mesh`).
168    MissingIndex {
169        /// The array the index was into.
170        kind: &'static str,
171        /// The index that was not there.
172        index: usize,
173    },
174    /// An accessor `componentType` the port does not read.
175    UnsupportedComponentType(i64),
176    /// An accessor `type` the port does not read.
177    UnsupportedAccessorType(String),
178    /// A `data:` URI that is not `data:<mime>;base64,<payload>`.
179    BadDataUri(String),
180    /// A character that is not in the base64 alphabet.
181    BadBase64(char),
182    /// An extension in `extensionsRequired` that the port does not read.
183    /// three.js only warns here (`'Unknown extension'`) and then decodes
184    /// nothing, which on this stack is a silent wrong picture, so the port
185    /// refuses the asset instead.
186    UnsupportedRequiredExtension(String),
187    /// A `KHR_draco_mesh_compression` primitive that does not decode. `mesh`
188    /// and `primitive` locate it; `reason` is the decoder's, or what
189    /// `DRACOLoader` would have thrown on.
190    Draco {
191        /// The mesh index.
192        mesh: usize,
193        /// The primitive index within `mesh`.
194        primitive: usize,
195        /// The decoder's message.
196        reason: String,
197    },
198    /// A bufferView whose byte range runs past the end of its buffer.
199    BufferViewOutOfRange {
200        /// The bufferView's index.
201        index: usize,
202    },
203    /// An `EXT_meshopt_compression` bufferView that does not decode.
204    /// `reason` is the decoder's, or the extension rule it breaks.
205    Meshopt {
206        /// The bufferView's index.
207        buffer_view: usize,
208        /// The decoder's message, or the extension rule that was broken.
209        reason: String,
210    },
211}
212
213impl fmt::Display for Error {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        match self {
216            Self::Io { path, source } => write!(f, "cannot read {}: {source}", path.display()),
217            Self::Json {
218                path: Some(path),
219                source,
220            } => write!(f, "cannot parse {}: {source}", path.display()),
221            Self::Json { path: None, source } => write!(f, "cannot parse JSON: {source}"),
222            Self::Image { path, reason } => {
223                write!(f, "cannot decode {}: {reason}", path.display())
224            }
225            Self::Rgbe { reason } => write!(f, "THREE.HDRLoader: {reason}"),
226            Self::Ktx2 { reason } => write!(f, "THREE.KTX2Loader: {reason}"),
227            Self::Lut { loader, reason } => write!(f, "THREE.{loader}: {reason}"),
228            Self::UnsupportedFormat { what, value } => {
229                write!(f, "unsupported {what}: {value}")
230            }
231            Self::UnsupportedTextureType { what, texture_type } => {
232                write!(f, "{texture_type:?} is not a {what} texture type")
233            }
234            Self::Gltf(error) => write!(f, "THREE.GLTFLoader: {error}"),
235            Self::NoKeyframes { track } => {
236                write!(f, "no keyframes in track named {track}")
237            }
238            Self::UnsupportedTrackType { name } => write!(f, "unsupported trackType: {name}"),
239            Self::UnsupportedInterpolation { value_type, track } => write!(
240                f,
241                "unsupported interpolation for {value_type} keyframe track named {track}"
242            ),
243            Self::TrackName(error) => write!(f, "{error}"),
244            Self::NoAdapter { wanted: Some(name) } => {
245                write!(f, "no Vulkan adapter matching THREE_RS_ADAPTER_NAME={name}")
246            }
247            Self::NoAdapter { wanted: None } => write!(f, "no Vulkan adapter found"),
248            #[cfg(target_arch = "wasm32")]
249            Self::NoAdoptedDevice => write!(
250                f,
251                "no device was adopted: call three_rs::renderer::adopt_device() \
252                 before Renderer::new()"
253            ),
254            Self::Device(source) => write!(f, "cannot create the device: {source}"),
255            Self::Readback { reason } => write!(f, "cannot read pixels back: {reason}"),
256            Self::Unsupported { field, kind } => {
257                write!(
258                    f,
259                    "material.{field} is not supported on a {kind:?} material"
260                )
261            }
262        }
263    }
264}
265
266impl fmt::Display for GltfError {
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        match self {
269            Self::NotUtf8 => write!(f, "not UTF-8 JSON"),
270            Self::UnsupportedVersion(version) => {
271                write!(f, "unsupported asset version {version}")
272            }
273            Self::BadHeader => write!(f, "unsupported glTF-Binary header"),
274            Self::LegacyBinary => write!(f, "legacy binary file detected"),
275            Self::TruncatedChunk => write!(f, "truncated glTF-Binary chunk"),
276            Self::NoJsonChunk => write!(f, "glTF-Binary without JSON content"),
277            Self::NoBinChunk => write!(f, "glTF-Binary without BIN chunk"),
278            Self::MissingField { what } => write!(f, "no {what}"),
279            Self::MissingIndex { kind, index } => write!(f, "no {kind} {index}"),
280            Self::UnsupportedComponentType(value) => {
281                write!(f, "unsupported componentType {value}")
282            }
283            Self::UnsupportedAccessorType(name) => write!(f, "unsupported accessor type {name}"),
284            Self::BadDataUri(uri) => write!(f, "bad data URI {uri}"),
285            Self::BadBase64(c) => write!(f, "bad base64 character {c:?}"),
286            Self::UnsupportedRequiredExtension(name) => {
287                write!(f, "unknown required extension \"{name}\"")
288            }
289            Self::Draco {
290                mesh,
291                primitive,
292                reason,
293            } => write!(
294                f,
295                "mesh {mesh} primitive {primitive}: THREE.DRACOLoader: {reason}"
296            ),
297            Self::BufferViewOutOfRange { index } => {
298                write!(f, "bufferView {index} runs past the end of its buffer")
299            }
300            Self::Meshopt {
301                buffer_view,
302                reason,
303            } => write!(f, "bufferView {buffer_view}: MeshoptDecoder: {reason}"),
304        }
305    }
306}
307
308impl std::error::Error for Error {
309    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
310        match self {
311            Self::Io { source, .. } => Some(source),
312            Self::Json { source, .. } => Some(source),
313            Self::Gltf(source) => Some(source),
314            Self::TrackName(source) => Some(source),
315            Self::Device(source) => Some(source),
316            _ => None,
317        }
318    }
319}
320
321impl std::error::Error for GltfError {}
322
323impl From<GltfError> for Error {
324    fn from(error: GltfError) -> Self {
325        Self::Gltf(error)
326    }
327}
328
329impl From<ParseTrackNameError> for Error {
330    fn from(error: ParseTrackNameError) -> Self {
331        Self::TrackName(error)
332    }
333}
334
335impl From<wgpu::RequestDeviceError> for Error {
336    fn from(error: wgpu::RequestDeviceError) -> Self {
337        Self::Device(error)
338    }
339}
340
341impl Error {
342    /// `std::fs::read`'s error, with the path that produced it.
343    pub(crate) fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
344        Self::Io {
345            path: path.into(),
346            source,
347        }
348    }
349
350    /// A decode failure, with the file that produced it.
351    pub(crate) fn image(path: impl Into<PathBuf>, reason: impl Into<String>) -> Self {
352        Self::Image {
353            path: path.into(),
354            reason: reason.into(),
355        }
356    }
357}