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
313
314
315
316
317
318
319
320
321
322
323
extern crate byteorder;

#[cfg(test)]
mod tests {
    use parser;

    const bin_stl_file: &str = "/home/vishpat/Downloads/HalfDonut.stl";
    const txt_stl_file: &str = "/home/vishpat/Downloads/HalfDonut.txt.stl";

    #[test]
    fn binary_format_check() {
        let fmt = parser::get_format(&bin_stl_file.to_string());
        match fmt {
            Ok(Binary) => println!("Pass: Binary format"),
            _ => panic!("Test failed to detect the binary format for the STL file"),
        }
    }

    #[test]
    fn text_format_check() {
        let fmt = parser::get_format(&txt_stl_file.to_string());
        match fmt {
            Ok(Text) => println!("Pass: Text format"),
            _ => panic!("Test failed for detect the text format for the STL file"),
        }
    }

    #[test]
    fn binary_stl_load() {
        match parser::load_file(&bin_stl_file.to_string()) {
            Ok(model) => {
                let mut idx = 0;
                for triangle in (*model).iter() {
                    println!("Triangle {}\n{}", idx, triangle);
                    idx += 1;
                }
            }
            _ => panic!("Failed to parse the binary STL file"),
        }
    }

    #[test]
    fn text_stl_load() {
        match parser::load_file(&txt_stl_file.to_string()) {
            Ok(model) => {
                let mut idx = 0;
                for triangle in (*model).iter() {
                    println!("Triangle {}\n{}", idx, triangle);
                    idx += 1;
                }
            }
            _ => panic!("Failed to parse the text STL file"),
        }
    }
}

/// A RUST module to parse STL files. The format of the STL 
/// file can be found at https://en.wikipedia.org/wiki/STL_(file_format)
pub mod parser {

    use std::fs::File;
    use std::io::Read;
    use std;

    const HEADER_SIZE: usize = 80;
    const VERTEX_CNT: usize = 3;
    const F32_SIZE: usize = 4;

    /// Types of STL file
    #[derive(Debug)]
    pub enum FileFormat {
        Text,
        Binary,
    }

    /// Possible Errors while parsing the STL file
    pub enum Error {
        InvalidPath(std::io::Error),
        InvalidRead(std::io::Error),
        InvalidFormat(std::string::FromUtf8Error),
    }

    /// Determines if an STL file is in text or a binary format
    pub fn get_format(stl_file_path: &str) -> Result<FileFormat, Error> {
        let mut stl_file = File::open(stl_file_path).map_err(self::Error::InvalidPath)?;
        let mut buf = [0; HEADER_SIZE];

        stl_file
            .read_exact(&mut buf)
            .map_err(self::Error::InvalidRead)?;
        let header = String::from_utf8(buf.to_vec()).map_err(self::Error::InvalidFormat)?;

        if header.trim().to_lowercase().starts_with("solid") {
            Ok(FileFormat::Text)
        } else {
            Ok(FileFormat::Binary)
        }
    }

    /// Represents a 3D vertex of a triangle
    #[derive(Debug, Copy, Clone)]
    pub struct Vertex {
        x: f32,
        y: f32,
        z: f32,
    }

    /// Represents a triangle that makes up the 3D object
    #[derive(Debug, Copy, Clone)]
    pub struct Triangle {
        normal: Vertex,
        vertex: [Vertex; VERTEX_CNT],
    }

    impl Triangle {
        fn new() -> Triangle {
            Triangle {
                normal: Vertex {
                    x: 0.0,
                    y: 0.0,
                    z: 0.0,
                },
                vertex: Triangle::new_vertices(),
            }
        }

        fn new_vertices() -> [Vertex; VERTEX_CNT] {
            [
                Vertex {
                    x: 0.0,
                    y: 0.0,
                    z: 0.0,
                },
                Vertex {
                    x: 0.0,
                    y: 0.0,
                    z: 0.0,
                },
                Vertex {
                    x: 0.0,
                    y: 0.0,
                    z: 0.0,
                },
            ]
        }
    }

    impl std::fmt::Display for Triangle {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(
                f,
                "{:.2} {:.2} {:.2}\n{:.2} {:.2} {:.2}\n{:.2} {:.2} {:.2}\n{:.2} {:.2} {:.2}",
                self.normal.x,
                self.normal.y,
                self.normal.z,
                self.vertex[0].x,
                self.vertex[0].y,
                self.vertex[0].z,
                self.vertex[1].x,
                self.vertex[1].y,
                self.vertex[1].z,
                self.vertex[2].x,
                self.vertex[2].y,
                self.vertex[2].z
            )
        }
    }

    /// Representation of the 3D object in terms of triangles 
    #[derive(Debug)]
    pub struct Model {
        triangles: Vec<Triangle>,
    }

    impl Model {
        /// Iterator to iterate over all the triangles that
        /// make up the 3D object
        pub fn iter(&self) -> TriangleIterator {
            TriangleIterator {
                index: 0,
                model: self,
            }
        }
    }

    /// The iterator for all the triangles making up the 3D 
    /// object
    pub struct TriangleIterator<'a> {
        index: usize,
        model: &'a Model,
    }

    impl<'a> Iterator for TriangleIterator<'a> {
        type Item = &'a Triangle;

        fn next(&mut self) -> Option<&'a Triangle> {
            if self.index < self.model.triangles.len() {
                match self.model.triangles.get(self.index) {
                    Some(triangle) => {
                        self.index += 1;
                        Some(triangle)
                    }
                    None => None,
                }
            } else {
                None
            }
        }
    }

    /// Load a STL file and return the Model struct
    pub fn load_file(stl_file_path: &str) -> Result<Box<Model>, Error> {
        let stl_fmt = get_format(stl_file_path)?;
        println!("format {:?}", stl_fmt);
        match stl_fmt {
            FileFormat::Binary => load_bin_file(stl_file_path),
            FileFormat::Text => load_txt_file(stl_file_path),
        }
    }

    use std::io::BufReader;
    use std::io::BufRead;

    fn load_txt_file(stl_file_path: &str) -> Result<Box<Model>, Error> {
        let stl_file = File::open(stl_file_path).map_err(self::Error::InvalidPath)?;
        let mut file = BufReader::new(&stl_file);

        let mut model = Box::new(Model {
            triangles: Vec::new(),
        });
        let mut triangle = Triangle {
            normal: Vertex {
                x: 0.0,
                y: 0.0,
                z: 0.0,
            },
            vertex: Triangle::new_vertices(),
        };
        let mut vertex: usize = 0;

        loop {
            let mut line = String::new();
            file.read_line(&mut line).map_err(self::Error::InvalidRead)?;

            if line.is_empty() {
                break;
            }

            let tokens: Vec<&str> = line.trim().split(' ').collect();

            if tokens[0] == "facet" {
                vertex = 0;
                if tokens.len() == 5 {
                    triangle.normal.x = tokens[2].parse::<f32>().unwrap();
                    triangle.normal.y = tokens[3].parse::<f32>().unwrap();
                    triangle.normal.z = tokens[4].parse::<f32>().unwrap();
                }
            }

            if tokens[0] == "vertex" && tokens.len() == 4 {
                triangle.vertex[vertex].x = tokens[1].parse::<f32>().unwrap();
                triangle.vertex[vertex].y = tokens[2].parse::<f32>().unwrap();
                triangle.vertex[vertex].z = tokens[3].parse::<f32>().unwrap();
                vertex += 1;
            }

            if tokens[0] == "endfacet" {
                model.triangles.push(triangle);
            }
        }

        Ok(model)
    }

    use byteorder::LittleEndian;
    use byteorder::ByteOrder;

    fn load_vertex(buf: &[u8], vertex: &mut Vertex, offset: &mut usize) {
        vertex.x = LittleEndian::read_f32(&buf[*offset..*offset + F32_SIZE]);
        *offset += F32_SIZE;

        vertex.y = LittleEndian::read_f32(&buf[*offset..*offset + F32_SIZE]);
        *offset += F32_SIZE;

        vertex.z = LittleEndian::read_f32(&buf[*offset..*offset + F32_SIZE]);
        *offset += F32_SIZE;
    }

    fn load_bin_file(stl_file_path: &str) -> Result<Box<Model>, Error> {
        let mut stl_file = File::open(stl_file_path).map_err(self::Error::InvalidPath)?;

        let mut triangle_byte_vec = Vec::new();
        stl_file
            .read_to_end(&mut triangle_byte_vec)
            .map_err(self::Error::InvalidRead)?;
        let buf = triangle_byte_vec.as_slice();

        let mut offset = HEADER_SIZE;
        let triangle_cnt = LittleEndian::read_u32(&buf[offset..offset + F32_SIZE]);
        offset += F32_SIZE;

        let mut model = Box::new(Model {
            triangles: Vec::new(),
        });
        for _ in 0..triangle_cnt {
            let mut triangle = Triangle::new();

            /* Normal Vector */
            load_vertex(buf, &mut triangle.normal, &mut offset);

            /* Triangle Side vertices */
            for v in 0..VERTEX_CNT {
                load_vertex(buf, &mut triangle.vertex[v], &mut offset);
            }

            offset += 2;

            model.triangles.push(triangle);
        }

        Ok(model)
    }
}