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
/*
Copyright 2017 Martin Buck
This file is part of rust-3d.
rust-3d is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
rust-3d is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with rust-3d.  If not, see <http://www.gnu.org/licenses/>.
*/

//! Module for IO operations of the ply file format

extern crate core;
extern crate byteorder;

use prelude::*;

use utils::to_words;

use self::core::str::FromStr;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
use std::fs::File;
use self::byteorder::{BigEndian, WriteBytesExt};

/// Saves an IsMesh3D in the ASCII .ply file format
pub fn save_ply_ascii<M, P>(mesh: &M, filepath: &str) -> Result<()> where
    M: IsMesh<P, Face3>,
    P: IsBuildable3D {

    let mut f = BufWriter::new(File::create(filepath).map_err(|e| e.to_error_kind())?);

    let header = "ply\n".to_string()
                   + "format ascii 1.0\n"
                   + "comment Created by rust-3d\n"
                   + "element vertex " + &mesh.num_vertices().to_string() + "\n"
                   + "property float x\n"
                   + "property float y\n"
                   + "property float z\n"
                   + "element face " + &mesh.num_faces().to_string() + "\n"
                   + "property list uchar uint vertex_indices\n"
                   + "end_header\n";
    f.write_all(header.as_bytes()).map_err(|e| e.to_error_kind())?;

    for i in 0..mesh.num_vertices() {
        let vertex = mesh.vertex(VId{val: i})?;
        f.write_all((vertex.to_str() + "\n").as_bytes()).map_err(|e| e.to_error_kind())?;
    }

    for i in 0..mesh.num_faces() {
        let face = mesh.face_vertex_ids(FId{val: i})?;
        f.write_all(("3 ".to_string() + &face.a.to_string() + " " + &face.b.to_string() + " " + &face.c.to_string() + "\n").as_bytes()).map_err(|e| e.to_error_kind())?;
    }
    Ok(())
}

/// Saves an IsMesh3D in the binary .ply file format
pub fn save_ply_binary<M, P>(mesh: &M, filepath: &str, precision: &Precision) -> Result<()> where
    M: IsMesh<P, Face3>,
    P: IsBuildable3D {

    let mut f = BufWriter::new(File::create(filepath).map_err(|e| e.to_error_kind())?);
    
    let header = match precision {
        Precision::P32 => {
            "ply\n".to_string() 
                + "format binary_big_endian 1.0\n"
                + "comment Created by rust-3d\n"
                + "element vertex " + &mesh.num_vertices().to_string() + "\n"
                + "property float32 x\n"
                + "property float32 y\n"
                + "property float32 z\n"
                + "element face " + &mesh.num_faces().to_string() + "\n"
                + "property list uint8 uint32 vertex_indices\n"
                + "end_header\n"
        },
        Precision::P64 => {
            "ply\n".to_string()
                + "format binary_big_endian 1.0\n"
                + "comment Created by rust-3d\n"
                + "element vertex " + &mesh.num_vertices().to_string() + "\n"
                + "property float64 x\n"
                + "property float64 y\n"
                + "property float64 z\n"
                + "element face " + &mesh.num_faces().to_string() + "\n"
                + "property list uint8 uint32 vertex_indices\n"
                + "end_header\n"
        }
    };
    
    f.write_all(header.as_bytes()).map_err(|e| e.to_error_kind())?;
    
    match precision {
        Precision::P32 => {
            for i in 0..mesh.num_vertices() {
                let vertex = mesh.vertex(VId{val: i})?;
                f.write_f32::<BigEndian>(vertex.get_position(0)? as f32).map_err(|e| e.to_error_kind())?;
                f.write_f32::<BigEndian>(vertex.get_position(1)? as f32).map_err(|e| e.to_error_kind())?;
                f.write_f32::<BigEndian>(vertex.get_position(2)? as f32).map_err(|e| e.to_error_kind())?;
            }
        },

        Precision::P64 => {
            for i in 0..mesh.num_vertices() {
                let vertex = mesh.vertex(VId{val: i})?;
                f.write_f64::<BigEndian>(vertex.get_position(0)?).map_err(|e| e.to_error_kind())?;
                f.write_f64::<BigEndian>(vertex.get_position(1)?).map_err(|e| e.to_error_kind())?;
                f.write_f64::<BigEndian>(vertex.get_position(2)?).map_err(|e| e.to_error_kind())?;
            }
        }
    }
    
    for i in 0..mesh.num_faces() {
        let face = mesh.face_vertex_ids(FId{val: i})?;
        f.write_u8(3).map_err(|e| e.to_error_kind())?;
        f.write_u32::<BigEndian>(face.a.val as u32).map_err(|e| e.to_error_kind())?;
        f.write_u32::<BigEndian>(face.b.val as u32).map_err(|e| e.to_error_kind())?;
        f.write_u32::<BigEndian>(face.c.val as u32).map_err(|e| e.to_error_kind())?;
    }

    Ok(())
}

// @todo allows incorrect headers and might fail on correct ones
/// Loads an IsMesh3D from the ASCII .ply file format
pub fn load_ply_ascii<EM, P>(mesh: &mut EM, filepath: &str) -> Result<()> where
    EM: IsEditableMesh<P, Face3>,
    P: IsBuildable3D + Clone {

        let mut f       = BufReader::new(File::open(filepath)?);
        let mut content = String::new();
        f.read_to_string(&mut content)?;
        let lines       = content.split("\n");

        let mut found_ply            = false;
        let mut format_found         = false;
        let mut vertex_indices_found = false;
        let mut header_ended         = false;

        let mut counted_properties   = 0;

        let mut vertex_count: Option<usize> = None;
        let mut face_count:   Option<usize> = None;

        let mut vertices = Vec::<P>::new();
        let mut indices  = Vec::<usize>::new();


        for line in lines {
            if !header_ended {
                if !found_ply {
                    if line == "ply" {
                        found_ply = true;
                        continue;
                    }
                    return Err(ErrorKind::PlyError(PlyError::LoadStartNotFound));
                }

                if !format_found {
                    if line == "format ascii 1.0" {
                        format_found = true;
                        continue;
                    }
                    return Err(ErrorKind::PlyError(PlyError::LoadFormatNotFound));
                }

                if line.starts_with("comment") {
                    continue;
                }

                match vertex_count {
                    None => {
                        if line.starts_with("element vertex") {
                            let words = to_words(line);
                            match words.len() {
                                3 => {
                                    vertex_count = Some(usize::from_str(words[2]).map_err(|e| e.to_error_kind())?);
                                    continue;
                                },
                                _ => return Err(ErrorKind::PlyError(PlyError::LoadError))
                            }
                        }
                        return Err(ErrorKind::PlyError(PlyError::LoadError));
                    }
                    Some(_) => {}
                }

                if line.starts_with("property float") {
                    counted_properties += 1;
                    continue;
                }

                if counted_properties < 3 {
                    return Err(ErrorKind::PlyError(PlyError::LoadWrongPropertyCount));
                }

                match face_count {
                    None => {
                        if line.starts_with("element face") {
                            let words = to_words(line);
                            match words.len() {
                                3 => {
                                    face_count = Some(usize::from_str(words[2]).map_err(|e| e.to_error_kind())?);
                                    continue;
                                },
                                _ => return Err(ErrorKind::PlyError(PlyError::LoadError))
                            }
                        }
                        return Err(ErrorKind::PlyError(PlyError::LoadError));
                    }
                    Some(_) => {}
                }

                if !vertex_indices_found {
                    if line.ends_with("vertex_indices") {
                        vertex_indices_found = true;
                        continue;
                    }
                    return Err(ErrorKind::PlyError(PlyError::LoadVertexIndexDefinitionNotFound));
                }

                if !header_ended {
                    if line == "end_header" {
                        header_ended = true;
                        continue;
                    }
                    return Err(ErrorKind::PlyError(PlyError::LoadHeaderEndNotFound));
                }
            }

            match vertex_count {
                None => { return Err(ErrorKind::PlyError(PlyError::LoadVertexCountNotFound)); }
                Some(x) => {
                    if x > vertices.len() {
                        let p = P::parse(line.to_string())?;
                        vertices.push(p);
                        continue;
                    }
                }
            }

            match face_count {
                None => { return Err(ErrorKind::PlyError(PlyError::LoadFaceCountNotFound)); }
                Some(x) => {
                    if x > indices.len() / 3 {
                        collect_index_line(line, &mut indices)?;
                        continue;
                    }
                }
            }
        }

        match vertex_count {
            None => { return Err(ErrorKind::PlyError(PlyError::LoadVertexCountNotFound)); }
            Some(x) => {
                if x != vertices.len() {
                    return Err(ErrorKind::PlyError(PlyError::LoadVertexCountIncorrect));
                }
            }
        }

        fill_mesh(vertices, indices, mesh)
    }

fn collect_index_line(line: &str, indices: &mut Vec<usize>) -> Result<()> {
    let words = to_words(line);
    match words.len() {
        4 => {
            //@todo ensure words[0] == 3 for tri faces
            let a = usize::from_str(words[1]).map_err(|e| e.to_error_kind())?;
            let b = usize::from_str(words[2]).map_err(|e| e.to_error_kind())?;
            let c = usize::from_str(words[3]).map_err(|e| e.to_error_kind())?;
            indices.push(a);
            indices.push(b);
            indices.push(c);
            Ok(())
        },
        _ => Err(ErrorKind::PlyError(PlyError::LoadError))
    }
}

fn fill_mesh<EM, P>(vertices: Vec<P>, indices: Vec<usize>, mesh: &mut EM) -> Result<()> where
    EM: IsEditableMesh<P, Face3>,
    P: IsBuildable3D + Clone {

    if indices.len() == 0 {
        return Err(ErrorKind::PlyError(PlyError::LoadVerticesIncorrect));
    }

    if indices.len() % 3 != 0 {
        return Err(ErrorKind::PlyError(PlyError::LoadVerticesIncorrect));
    }
    
    for vertex in vertices {
        mesh.add_vertex(vertex);
    }
    
    for chunk in indices.chunks(3) {
        if chunk.len() == 3 {
                mesh.try_add_connection(VId{val:chunk[0]}, VId{val:chunk[1]}, VId{val:chunk[2]})?;
        } else {
            return Err(ErrorKind::PlyError(PlyError::LoadVerticesIncorrect));
        }
    }

    Ok(())
}