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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use std::path::{Path, PathBuf};

use meshx::algo::Merge;
use rayon::prelude::*;

#[macro_use]
pub mod utils;
#[macro_use]
pub mod attrib;
pub mod config;
pub mod error;
pub mod export;
pub mod material;
pub mod mesh;
pub mod texture;

pub use attrib::*;
pub use error::*;
pub use material::*;
pub use texture::*;
pub use utils::*;

use mesh::{trimesh_f64_to_f32, Mesh};

/// Configuration for loading meshes.
#[derive(Clone, Copy, Debug)]
pub struct LoadConfig {
    pub reverse: bool,
    pub invert_tets: bool,
}

/// Configuration for locating attributes within loaded meshes.
#[derive(Clone, Copy, Debug)]
pub struct AttribConfig<'a> {
    pub attributes: &'a AttributeInfo,
    pub colors: &'a AttributeInfo,
    pub texcoords: &'a TextureAttributeInfo,
    pub material_attribute: &'a str,
}

/// Convenience routine for loading and meshes extracting the required
/// attributes and removing all extraneous attributes.
pub fn load_and_clean_meshes(
    mesh_meta: Vec<(String, u32, PathBuf)>,
    load_config: LoadConfig,
    attrib_config: AttribConfig,
) -> Vec<(String, u32, Mesh, AttribTransfer)> {
    let process_attrib_error = |e| log::warn!("{}, Skipping...", e);
    mesh_meta
        .into_par_iter()
        .filter_map(|(name, frame, path)| {
            load_and_clean_mesh(&path, load_config, attrib_config, process_attrib_error)
                .map(|(mesh, attrib_transfer)| (name, frame, mesh, attrib_transfer))
        })
        .collect()
}

/// Convenience routine just for extracting the required
/// attributes and removing all extraneous attributes from the given vector of named meshes.
///
/// The resulting vector can then be fed into `export_clean_meshes` for exporting.
/// The frame numbers are inferred from the order in which the meshes are given.
pub fn clean_named_meshes(
    meshes: Vec<(String, Mesh)>,
    attrib_config: AttribConfig,
) -> Vec<(String, u32, Mesh, AttribTransfer)> {
    let process_attrib_error = |e| log::warn!("{}, Skipping...", e);
    meshes
        .into_par_iter()
        .enumerate()
        .map(|(frame, (name, mut mesh))| {
            let attrib_transfer = clean_mesh(&mut mesh, attrib_config, process_attrib_error);
            (name, frame as u32, mesh, attrib_transfer)
        })
        .collect()
}

pub fn load_and_clean_mesh(
    path: &Path,
    load_config: LoadConfig,
    attrib_config: AttribConfig,
    process_attrib_error: impl FnMut(attrib::AttribError),
) -> Option<(Mesh, AttribTransfer)> {
    let mut mesh = load_mesh(path, load_config)?;
    let attrib_transfer = clean_mesh(&mut mesh, attrib_config, process_attrib_error);
    Some((mesh, attrib_transfer))
}

pub fn load_mesh(path: impl AsRef<Path>, config: LoadConfig) -> Option<Mesh> {
    load_mesh_impl(path.as_ref(), config)
}

fn load_mesh_impl(path: &Path, config: LoadConfig) -> Option<Mesh> {
    let polymesh_tris = if let Ok(polymesh) = meshx::io::load_polymesh::<f64, _>(path) {
        trimesh_f64_to_f32(meshx::TriMesh::from(polymesh))
    } else if let Ok(polymesh) = meshx::io::load_polymesh::<f32, _>(path) {
        meshx::TriMesh::<f32>::from(polymesh)
    } else {
        meshx::TriMesh::default()
    };

    let polymesh_tris = mesh::remove_orphaned_vertices(polymesh_tris);

    let mut tetmesh_tris = if let Ok(tetmesh) = meshx::io::load_tetmesh::<f64, _>(path) {
        trimesh_f64_to_f32(tetmesh.surface_trimesh())
    } else if let Ok(tetmesh) = meshx::io::load_tetmesh::<f32, _>(path) {
        tetmesh.surface_trimesh()
    } else {
        meshx::TriMesh::default()
    };

    // Reverse triangles that came from tets. This is faster than actually inverting tets but
    // achieves the same result.
    if config.invert_tets {
        tetmesh_tris.reverse();
    }

    tetmesh_tris.merge(polymesh_tris);
    let mut mesh = Mesh::from(tetmesh_tris);

    if mesh.is_empty() {
        mesh = if let Ok(ptcloud) = meshx::io::load_pointcloud::<f64, _>(path) {
            ptcloud.into()
        } else if let Ok(ptcloud) = meshx::io::load_pointcloud::<f32, _>(path) {
            ptcloud.into()
        } else {
            return None;
        };
    }

    if config.reverse {
        mesh.reverse();
    }
    Some(mesh)
}

#[cfg(test)]
mod tests {
    use super::*;
    use gltf::Gltf;

    #[test]
    fn box_rotate_obj() {
        let mesh_meta: Vec<_> = (1..=12)
            .map(|frame| {
                let path = format!("./assets/box_rotate_{}.obj", frame);
                (String::from("box_rotate"), frame, PathBuf::from(path))
            })
            .collect();

        let attributes = AttributeInfo::default();
        let colors = AttributeInfo::default();
        let texcoords: TextureAttributeInfo = "{\"uv\": f32}".parse().unwrap();
        let material_attribute = "mtl_id";

        let load_config = LoadConfig {
            reverse: false,
            invert_tets: false,
        };

        let attrib_config = AttribConfig {
            attributes: &attributes,
            colors: &colors,
            texcoords: &texcoords,
            material_attribute,
        };

        let meshes = load_and_clean_meshes(mesh_meta, load_config, attrib_config);

        assert!(!meshes.is_empty());
    }

    #[test]
    fn box_triangulated() {
        let mesh_meta: Vec<_> = (1..=1)
            .map(|frame| {
                let path = "./assets/box_triangulated.vtk";
                (String::from("box_triangulated"), frame, PathBuf::from(path))
            })
            .collect();

        let attributes = AttributeInfo::default();
        let colors = AttributeInfo::default();
        let texcoords = TextureAttributeInfo::default();
        let material_attribute = "mtl_id";

        let load_config = LoadConfig {
            reverse: false,
            invert_tets: false,
        };

        let attrib_config = AttribConfig {
            attributes: &attributes,
            colors: &colors,
            texcoords: &texcoords,
            material_attribute,
        };

        let meshes = load_and_clean_meshes(mesh_meta, load_config, attrib_config);

        assert!(!meshes.is_empty());
    }

    #[test]
    fn multi() {
        let mut mesh_meta = Vec::new();

        mesh_meta.extend((1..=12).map(|frame| {
            let path = format!("./assets/box_rotate_{}.vtk", frame);
            (String::from("box_rotate"), frame, PathBuf::from(path))
        }));
        mesh_meta.extend((1..=2).map(|frame| {
            let path = format!("./assets/tet_{}.vtk", frame);
            (String::from("tet"), frame, PathBuf::from(path))
        }));
        mesh_meta.extend((1..=1).map(|frame| {
            let path = "./assets/box_triangulated.vtk";
            (String::from("box_triangulated"), frame, PathBuf::from(path))
        }));

        let attributes = "{\"pressure\": f32}".parse().unwrap();
        let colors = AttributeInfo::default();
        let texcoords = TextureAttributeInfo::default();
        let material_attribute = "mtl_id";

        let load_config = LoadConfig {
            reverse: true,
            invert_tets: false,
        };

        let attrib_config = AttribConfig {
            attributes: &attributes,
            colors: &colors,
            texcoords: &texcoords,
            material_attribute,
        };

        let meshes = load_and_clean_meshes(mesh_meta, load_config, attrib_config);

        assert!(!meshes.is_empty());

        let dt = 1.0 / 24.0;

        let artifact = "./tests/artifacts/multi_test.glb";

        export::export_clean_meshes(
            meshes,
            export::ExportConfig {
                textures: Vec::new(),
                materials: Vec::new(),
                output: artifact.into(),
                time_step: dt,
                insert_vanishing_frames: false,
                animate_normals: false,
                animate_tangents: false,
                quiet: true,
            },
        );

        let actual = Gltf::open(artifact).unwrap().blob;

        dbg!(&actual);
    }

    // Alternative way to export loaded meshes.
    #[test]
    fn multi_alt() {
        let load_config = LoadConfig {
            reverse: true,
            invert_tets: false,
        };

        // Meshes can be loaded without any kind of attribute processing.
        let meshes = vec![(
            "box_triangulated".to_owned(),
            load_mesh("./assets/box_triangulated.vtk", load_config).unwrap(),
        )];

        assert!(!meshes.is_empty());

        let dt = 1.0 / 24.0;

        let artifact = "./tests/artifacts/multi_alt_test.glb";

        let attrib_config = AttribConfig {
            attributes: &"{\"pressure\": f32}".parse().unwrap(),
            colors: &AttributeInfo::default(),
            texcoords: &TextureAttributeInfo::default(),
            material_attribute: "mtl_id",
        };

        // The loaded meshes are then processed according to the given AttribConfig.
        export::export_named_meshes(
            meshes,
            attrib_config,
            export::ExportConfig {
                textures: Vec::new(),
                materials: Vec::new(),
                output: artifact.into(),
                time_step: dt,
                insert_vanishing_frames: false,
                animate_normals: false,
                animate_tangents: false,
                quiet: true,
            },
        );

        let actual = Gltf::open(artifact).unwrap().blob;

        dbg!(&actual);
    }
}