1use std::collections::HashMap;
21use std::fmt;
22
23use crate::mesh::Mesh;
24use crate::meta::Meta;
25
26const BINARY_HEADER: usize = 84;
29const BINARY_TRIANGLE: usize = 50;
31
32#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum ReadStlError {
35 NotStl,
38 Ascii { line: usize },
40 TooLarge,
42}
43
44impl fmt::Display for ReadStlError {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 match self {
47 Self::NotStl => f.write_str("not an STL file"),
48 Self::Ascii { line } => write!(f, "the ASCII STL is malformed on line {line}"),
49 Self::TooLarge => f.write_str("the STL has too many vertices"),
50 }
51 }
52}
53
54impl std::error::Error for ReadStlError {}
55
56pub fn read_stl(bytes: &[u8]) -> Result<Mesh, ReadStlError> {
62 let (corners, meta) = match binary_triangle_count(bytes) {
63 Some(count) => (binary_corners(bytes, count), binary_meta(bytes)),
64 None => ascii(bytes)?,
65 };
66 let mut mesh = weld(&corners)?;
67 mesh.meta = meta;
68 Ok(mesh)
69}
70
71fn binary_triangle_count(bytes: &[u8]) -> Option<usize> {
74 let count = u32::from_le_bytes(bytes.get(80..BINARY_HEADER)?.try_into().ok()?);
75 let count = usize::try_from(count).ok()?;
76 let length = count
77 .checked_mul(BINARY_TRIANGLE)?
78 .checked_add(BINARY_HEADER)?;
79 (bytes.len() == length).then_some(count)
80}
81
82fn binary_corners(bytes: &[u8], count: usize) -> Vec<[u32; 3]> {
85 let mut corners = Vec::with_capacity(3 * count);
86 for facet in bytes[BINARY_HEADER..].as_chunks::<BINARY_TRIANGLE>().0 {
87 for corner in 0..3 {
88 let at = 12 + 12 * corner;
89 corners.push(std::array::from_fn(|i| {
90 let b = &facet[at + 4 * i..at + 4 * i + 4];
91 u32::from_le_bytes([b[0], b[1], b[2], b[3]])
92 }));
93 }
94 }
95 corners
96}
97
98fn binary_meta(bytes: &[u8]) -> Option<Meta> {
102 let header = &bytes[..80];
103 let end = header
104 .iter()
105 .rposition(|&b| b != 0 && b != b' ')
106 .map_or(0, |i| i + 1);
107 let text = std::str::from_utf8(&header[..end]).ok()?;
108 if text.is_empty() || text.chars().any(char::is_control) {
109 return None;
110 }
111 Some(Meta {
112 name: None,
113 comment: Some(text.to_owned()),
114 })
115}
116
117fn ascii(bytes: &[u8]) -> Result<(Vec<[u32; 3]>, Option<Meta>), ReadStlError> {
132 let text = std::str::from_utf8(bytes).map_err(|_| ReadStlError::NotStl)?;
133 let mut lines = text.lines().enumerate().map(|(i, line)| (i + 1, line));
134 let name = loop {
135 let Some((_, line)) = lines.next() else {
136 return Err(ReadStlError::NotStl);
137 };
138 let line = line.trim();
139 if line.is_empty() {
140 continue;
141 }
142 let rest = strip_keyword(line, "solid").ok_or(ReadStlError::NotStl)?;
143 if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
144 return Err(ReadStlError::NotStl);
145 }
146 break rest.trim();
147 };
148
149 let mut corners = Vec::new();
150 let mut step = 0;
153 let mut ended = false;
154 for (number, line) in lines {
155 let bad = ReadStlError::Ascii { line: number };
156 let mut words = line.split_whitespace();
157 let Some(word) = words.next() else {
158 continue;
159 };
160 let word = word.to_ascii_lowercase();
161 step = match (step, word.as_str()) {
162 (0, "facet") => {
163 if !is(words.next(), "normal") {
164 return Err(bad);
165 }
166 for _ in 0..3 {
167 words.next().and_then(coordinate).ok_or(bad.clone())?;
169 }
170 1
171 }
172 (0, "endsolid") => {
173 ended = true;
174 break;
175 }
176 (1, "outer") if is(words.next(), "loop") => 2,
177 (2..=4, "vertex") => {
178 let mut corner = [0; 3];
179 for value in &mut corner {
180 *value = words.next().and_then(coordinate).ok_or(bad.clone())?;
181 }
182 corners.push(corner);
183 step + 1
184 }
185 (5, "endloop") => 6,
186 (6, "endfacet") => 0,
187 _ => return Err(bad),
188 };
189 if words.next().is_some() {
190 return Err(bad);
191 }
192 }
193 if !ended {
194 let last = text.lines().count().max(1);
195 return Err(ReadStlError::Ascii { line: last });
196 }
197 let meta = (!name.is_empty()).then(|| Meta {
198 name: Some(name.to_owned()),
199 comment: None,
200 });
201 Ok((corners, meta))
202}
203
204fn is(word: Option<&str>, keyword: &str) -> bool {
206 word.is_some_and(|word| word.eq_ignore_ascii_case(keyword))
207}
208
209fn strip_keyword<'a>(line: &'a str, keyword: &str) -> Option<&'a str> {
211 let head = line.get(..keyword.len())?;
212 head.eq_ignore_ascii_case(keyword)
213 .then(|| &line[keyword.len()..])
214}
215
216fn coordinate(word: &str) -> Option<u32> {
218 word.parse::<f32>().ok().map(f32::to_bits)
219}
220
221fn weld(corners: &[[u32; 3]]) -> Result<Mesh, ReadStlError> {
224 let mut index: HashMap<[u32; 3], u32> = HashMap::with_capacity(corners.len() / 2);
225 let mut vertices = Vec::new();
226 let mut ids = Vec::with_capacity(corners.len());
227 for corner in corners {
228 let id = match index.get(corner) {
229 Some(&id) => id,
230 None => {
231 let id = u32::try_from(vertices.len()).map_err(|_| ReadStlError::TooLarge)?;
232 vertices.push(corner.map(f32::from_bits));
233 index.insert(*corner, id);
234 id
235 }
236 };
237 ids.push(id);
238 }
239 let triangles = ids.as_chunks::<3>().0.to_vec();
240 Ok(Mesh {
241 meta: None,
242 vertices,
243 triangles,
244 })
245}