mesh_loader/
loader.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
use std::{cmp, ffi::OsStr, fmt, fs, io, path::Path};

use crate::{utils::bytes::starts_with, Scene};

type Reader<B> = fn(&Path) -> io::Result<B>;

pub struct Loader<B = Vec<u8>> {
    reader: Reader<B>,
    merge_meshes: bool,
    // STL config
    #[cfg(feature = "stl")]
    stl_parse_color: bool,
}

fn default_reader(path: &Path) -> io::Result<Vec<u8>> {
    fs::read(path)
}

impl Default for Loader<Vec<u8>> {
    fn default() -> Self {
        Self {
            reader: default_reader,
            merge_meshes: false,
            #[cfg(feature = "stl")]
            stl_parse_color: false,
        }
    }
}

impl<B: AsRef<[u8]>> Loader<B> {
    /// Sets whether or not to merge meshes at load time.
    ///
    /// If set to `true`, it is guaranteed that there is exactly one mesh in the
    /// loaded `Scene` (i.e., `scene.meshes.len() == 1`).
    ///
    /// Default: `false`
    #[must_use]
    pub fn merge_meshes(mut self, enable: bool) -> Self {
        self.merge_meshes = enable;
        self
    }

    /// Use the given function as a file reader of this loader.
    ///
    /// Default: [`std::fs::read`]
    ///
    /// # Example
    ///
    /// This is useful if you want to load a mesh from a location that the
    /// default reader does not support.
    ///
    /// ```
    /// use std::fs;
    ///
    /// use mesh_loader::Loader;
    ///
    /// let loader = Loader::default().custom_reader(|path| {
    ///     match path.to_str() {
    ///         Some(url) if url.starts_with("https://") || url.starts_with("http://") => {
    ///             // Fetch online file
    ///             // ...
    /// #           unimplemented!()
    ///         }
    ///         _ => fs::read(path), // Otherwise, read from a file (same as the default reader)
    ///     }
    /// });
    /// ```
    #[must_use]
    pub fn custom_reader(mut self, reader: Reader<B>) -> Self {
        self.reader = reader;
        self
    }

    /// Creates a new loader with the given file reader.
    ///
    /// This is similar to [`Loader::default().custom_reader()`](Self::custom_reader),
    /// but the reader can return a non-`Vec<u8>` type.
    ///
    /// # Example
    ///
    /// This is useful when using mmap.
    ///
    /// ```
    /// use std::fs::File;
    ///
    /// use memmap2::Mmap;
    /// use mesh_loader::Loader;
    ///
    /// let loader = Loader::with_custom_reader(|path| unsafe { Mmap::map(&File::open(path)?) });
    /// ```
    #[must_use]
    pub fn with_custom_reader(reader: Reader<B>) -> Self {
        Self {
            reader,
            merge_meshes: false,
            #[cfg(feature = "stl")]
            stl_parse_color: false,
        }
    }

    pub fn load<P: AsRef<Path>>(&self, path: P) -> io::Result<Scene> {
        self.load_with_reader(path.as_ref(), self.reader)
    }
    pub fn load_with_reader<P: AsRef<Path>, F: FnMut(&Path) -> io::Result<B>>(
        &self,
        path: P,
        mut reader: F,
    ) -> io::Result<Scene> {
        let path = path.as_ref();
        self.load_from_slice_with_reader(reader(path)?.as_ref(), path, reader)
    }
    pub fn load_from_slice<P: AsRef<Path>>(&self, bytes: &[u8], path: P) -> io::Result<Scene> {
        self.load_from_slice_with_reader(bytes, path.as_ref(), self.reader)
    }
    pub fn load_from_slice_with_reader<P: AsRef<Path>, F: FnMut(&Path) -> io::Result<B>>(
        &self,
        bytes: &[u8],
        path: P,
        #[allow(unused_variables)] reader: F,
    ) -> io::Result<Scene> {
        let path = path.as_ref();
        match detect_file_type(path, bytes) {
            #[cfg(feature = "stl")]
            FileType::Stl => self.load_stl_from_slice(bytes, path),
            #[cfg(not(feature = "stl"))]
            FileType::Stl => Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "'stl' feature of mesh-loader must be enabled to parse STL file ({path:?})",
            )),
            #[cfg(feature = "collada")]
            FileType::Collada => self.load_collada_from_slice(bytes, path),
            #[cfg(not(feature = "collada"))]
            FileType::Collada => Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "'collada' feature of mesh-loader must be enabled to parse COLLADA file ({path:?})",
            )),
            #[cfg(feature = "obj")]
            FileType::Obj => self.load_obj_from_slice_with_reader(bytes, path, reader),
            #[cfg(not(feature = "obj"))]
            FileType::Obj => Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "'obj' feature of mesh-loader must be enabled to parse OBJ file ({path:?})",
            )),
            FileType::Unknown => Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "unsupported or unrecognized file type {path:?}",
            )),
        }
    }

    #[cfg(feature = "stl")]
    pub fn load_stl<P: AsRef<Path>>(&self, path: P) -> io::Result<Scene> {
        let path = path.as_ref();
        self.load_stl_from_slice((self.reader)(path)?.as_ref(), path)
    }
    #[cfg(feature = "stl")]
    pub fn load_stl_from_slice<P: AsRef<Path>>(&self, bytes: &[u8], path: P) -> io::Result<Scene> {
        let scene =
            crate::stl::from_slice_internal(bytes, Some(path.as_ref()), self.stl_parse_color)?;
        Ok(self.post_process(scene))
    }
    #[cfg(feature = "stl")]
    #[must_use]
    pub fn stl_parse_color(mut self, enable: bool) -> Self {
        self.stl_parse_color = enable;
        self
    }

    #[cfg(feature = "collada")]
    pub fn load_collada<P: AsRef<Path>>(&self, path: P) -> io::Result<Scene> {
        let path = path.as_ref();
        self.load_collada_from_slice((self.reader)(path)?.as_ref(), path)
    }
    #[cfg(feature = "collada")]
    pub fn load_collada_from_slice<P: AsRef<Path>>(
        &self,
        bytes: &[u8],
        path: P,
    ) -> io::Result<Scene> {
        let scene = crate::collada::from_slice_internal(bytes, Some(path.as_ref()))?;
        Ok(self.post_process(scene))
    }

    #[cfg(feature = "obj")]
    pub fn load_obj<P: AsRef<Path>>(&self, path: P) -> io::Result<Scene> {
        self.load_obj_with_reader(path.as_ref(), self.reader)
    }
    #[cfg(feature = "obj")]
    pub fn load_obj_from_slice<P: AsRef<Path>>(&self, bytes: &[u8], path: P) -> io::Result<Scene> {
        self.load_obj_from_slice_with_reader(bytes, path.as_ref(), self.reader)
    }
    #[cfg(feature = "obj")]
    pub fn load_obj_with_reader<P: AsRef<Path>, F: FnMut(&Path) -> io::Result<B>>(
        &self,
        path: P,
        mut reader: F,
    ) -> io::Result<Scene> {
        let path = path.as_ref();
        self.load_obj_from_slice_with_reader(reader(path)?.as_ref(), path, reader)
    }
    #[cfg(feature = "obj")]
    pub fn load_obj_from_slice_with_reader<P: AsRef<Path>, F: FnMut(&Path) -> io::Result<B>>(
        &self,
        bytes: &[u8],
        path: P,
        reader: F,
    ) -> io::Result<Scene> {
        let scene = crate::obj::from_slice(bytes, Some(path.as_ref()), reader)?;
        Ok(self.post_process(scene))
    }

    #[cfg(any(feature = "collada", feature = "obj", feature = "stl"))]
    fn post_process(&self, mut scene: Scene) -> Scene {
        if self.merge_meshes && scene.meshes.len() != 1 {
            scene.meshes = vec![crate::Mesh::merge(scene.meshes)];
            // TODO
            scene.materials = vec![crate::Material::default()];
        }
        scene
    }
}

impl fmt::Debug for Loader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut d = f.debug_struct("Loader");
        d.field("merge_meshes", &self.merge_meshes);
        #[cfg(feature = "stl")]
        d.field("stl_parse_color", &self.stl_parse_color);
        d.finish_non_exhaustive()
    }
}

enum FileType {
    Stl,
    Collada,
    Obj,
    Unknown,
}

fn detect_file_type(path: &Path, bytes: &[u8]) -> FileType {
    match path.extension().and_then(OsStr::to_str) {
        Some("stl" | "STL") => return FileType::Stl,
        Some("dae" | "DAE") => return FileType::Collada,
        Some("obj" | "OBJ") => return FileType::Obj,
        _ => {}
    }
    // Fallback: If failed to detect file type from extension,
    // read the first 1024 bytes to detect the file type.
    // TODO: rewrite based on what assimp does.
    let mut s = &bytes[..cmp::min(bytes.len(), 1024)];
    while let Some((&c, s_next)) = s.split_first() {
        match c {
            b's' => {
                if starts_with(s_next, &b"solid"[1..]) {
                    return FileType::Stl;
                }
            }
            b'<' => {
                // Compare whole s instead of s_next since needle.len() == 8
                if starts_with(s, b"<COLLADA") {
                    return FileType::Collada;
                }
            }
            _ => {}
        }
        s = s_next;
    }
    FileType::Unknown
}