use std::collections::HashMap;
use std::fmt;
use crate::mesh::Mesh;
use crate::meta::Meta;
const BINARY_HEADER: usize = 84;
const BINARY_TRIANGLE: usize = 50;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ReadStlError {
NotStl,
Ascii { line: usize },
TooLarge,
}
impl fmt::Display for ReadStlError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotStl => f.write_str("not an STL file"),
Self::Ascii { line } => write!(f, "the ASCII STL is malformed on line {line}"),
Self::TooLarge => f.write_str("the STL has too many vertices"),
}
}
}
impl std::error::Error for ReadStlError {}
pub fn read_stl(bytes: &[u8]) -> Result<Mesh, ReadStlError> {
let (corners, meta) = match binary_triangle_count(bytes) {
Some(count) => (binary_corners(bytes, count), binary_meta(bytes)),
None => ascii(bytes)?,
};
let mut mesh = weld(&corners)?;
mesh.meta = meta;
Ok(mesh)
}
fn binary_triangle_count(bytes: &[u8]) -> Option<usize> {
let count = u32::from_le_bytes(bytes.get(80..BINARY_HEADER)?.try_into().ok()?);
let count = usize::try_from(count).ok()?;
let length = count
.checked_mul(BINARY_TRIANGLE)?
.checked_add(BINARY_HEADER)?;
(bytes.len() == length).then_some(count)
}
fn binary_corners(bytes: &[u8], count: usize) -> Vec<[u32; 3]> {
let mut corners = Vec::with_capacity(3 * count);
for facet in bytes[BINARY_HEADER..].as_chunks::<BINARY_TRIANGLE>().0 {
for corner in 0..3 {
let at = 12 + 12 * corner;
corners.push(std::array::from_fn(|i| {
let b = &facet[at + 4 * i..at + 4 * i + 4];
u32::from_le_bytes([b[0], b[1], b[2], b[3]])
}));
}
}
corners
}
fn binary_meta(bytes: &[u8]) -> Option<Meta> {
let header = &bytes[..80];
let end = header
.iter()
.rposition(|&b| b != 0 && b != b' ')
.map_or(0, |i| i + 1);
let text = std::str::from_utf8(&header[..end]).ok()?;
if text.is_empty() || text.chars().any(char::is_control) {
return None;
}
Some(Meta {
name: None,
comment: Some(text.to_owned()),
})
}
fn ascii(bytes: &[u8]) -> Result<(Vec<[u32; 3]>, Option<Meta>), ReadStlError> {
let text = std::str::from_utf8(bytes).map_err(|_| ReadStlError::NotStl)?;
let mut lines = text.lines().enumerate().map(|(i, line)| (i + 1, line));
let name = loop {
let Some((_, line)) = lines.next() else {
return Err(ReadStlError::NotStl);
};
let line = line.trim();
if line.is_empty() {
continue;
}
let rest = strip_keyword(line, "solid").ok_or(ReadStlError::NotStl)?;
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
return Err(ReadStlError::NotStl);
}
break rest.trim();
};
let mut corners = Vec::new();
let mut step = 0;
let mut ended = false;
for (number, line) in lines {
let bad = ReadStlError::Ascii { line: number };
let mut words = line.split_whitespace();
let Some(word) = words.next() else {
continue;
};
let word = word.to_ascii_lowercase();
step = match (step, word.as_str()) {
(0, "facet") => {
if !is(words.next(), "normal") {
return Err(bad);
}
for _ in 0..3 {
words.next().and_then(coordinate).ok_or(bad.clone())?;
}
1
}
(0, "endsolid") => {
ended = true;
break;
}
(1, "outer") if is(words.next(), "loop") => 2,
(2..=4, "vertex") => {
let mut corner = [0; 3];
for value in &mut corner {
*value = words.next().and_then(coordinate).ok_or(bad.clone())?;
}
corners.push(corner);
step + 1
}
(5, "endloop") => 6,
(6, "endfacet") => 0,
_ => return Err(bad),
};
if words.next().is_some() {
return Err(bad);
}
}
if !ended {
let last = text.lines().count().max(1);
return Err(ReadStlError::Ascii { line: last });
}
let meta = (!name.is_empty()).then(|| Meta {
name: Some(name.to_owned()),
comment: None,
});
Ok((corners, meta))
}
fn is(word: Option<&str>, keyword: &str) -> bool {
word.is_some_and(|word| word.eq_ignore_ascii_case(keyword))
}
fn strip_keyword<'a>(line: &'a str, keyword: &str) -> Option<&'a str> {
let head = line.get(..keyword.len())?;
head.eq_ignore_ascii_case(keyword)
.then(|| &line[keyword.len()..])
}
fn coordinate(word: &str) -> Option<u32> {
word.parse::<f32>().ok().map(f32::to_bits)
}
fn weld(corners: &[[u32; 3]]) -> Result<Mesh, ReadStlError> {
let mut index: HashMap<[u32; 3], u32> = HashMap::with_capacity(corners.len() / 2);
let mut vertices = Vec::new();
let mut ids = Vec::with_capacity(corners.len());
for corner in corners {
let id = match index.get(corner) {
Some(&id) => id,
None => {
let id = u32::try_from(vertices.len()).map_err(|_| ReadStlError::TooLarge)?;
vertices.push(corner.map(f32::from_bits));
index.insert(*corner, id);
id
}
};
ids.push(id);
}
let triangles = ids.as_chunks::<3>().0.to_vec();
Ok(Mesh {
meta: None,
vertices,
triangles,
})
}