#include "mesh.hpp" #include #include #include #include #include #include #include namespace mesh { using geom::Vec3; void Mesh::computeBounds() { if (verts.empty()) return; bbMin = bbMax = verts[0]; for (const auto& p : verts) { bbMin.x = std::min(bbMin.x, p.x); bbMin.y = std::min(bbMin.y, p.y); bbMin.z = std::min(bbMin.z, p.z); bbMax.x = std::max(bbMax.x, p.x); bbMax.y = std::max(bbMax.y, p.y); bbMax.z = std::max(bbMax.z, p.z); } } double Mesh::bboxDiag() const { geom::Vec3 d = bbMax - bbMin; return geom::norm(d); } void Mesh::buildAdjacency() { adj.assign(verts.size(), {}); auto addEdge = [&](int a, int b) { adj[a].push_back(b); }; for (const auto& t : tris) { addEdge(t[0], t[1]); addEdge(t[1], t[0]); addEdge(t[1], t[2]); addEdge(t[2], t[1]); addEdge(t[2], t[0]); addEdge(t[0], t[2]); } for (auto& a : adj) { std::sort(a.begin(), a.end()); a.erase(std::unique(a.begin(), a.end()), a.end()); } } void Mesh::computeCurvature() { if (adj.empty()) buildAdjacency(); curv.assign(verts.size(), 0.0f); for (size_t i = 0; i < verts.size(); ++i) { const auto& nb = adj[i]; if (nb.size() < 2) { curv[i] = 0; continue; } // covariance of {v} ∪ neighbours; surface variation = λ0 / (λ0+λ1+λ2) geom::Vec3 c = verts[i]; for (int j : nb) c = c + verts[j]; c = c / (double)(nb.size() + 1); double C[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; auto acc = [&](const geom::Vec3& p) { geom::Vec3 d = p - c; double dd[3] = {d.x, d.y, d.z}; for (int a = 0; a < 3; ++a) for (int b = 0; b < 3; ++b) C[a][b] += dd[a] * dd[b]; }; acc(verts[i]); for (int j : nb) acc(verts[j]); double ev[3], V[3][3]; geom::jacobiEigen3(C, ev, V); double sum = ev[0] + ev[1] + ev[2]; curv[i] = sum > 1e-20 ? (float)(ev[0] / sum) : 0.0f; } } void Mesh::computeNormals() { vnormals.assign(verts.size(), Vec3{0, 0, 0}); for (const auto& t : tris) { const Vec3& a = verts[t[0]]; const Vec3& b = verts[t[1]]; const Vec3& c = verts[t[2]]; Vec3 fn = geom::cross(b - a, c - a); // area-weighted (not normalized) for (int k = 0; k < 3; ++k) vnormals[t[k]] = vnormals[t[k]] + fn; } for (auto& n : vnormals) n = geom::normalize(n); } // ---- vertex welding key (quantized) so STL's duplicated corners merge ---- namespace { struct Welder { std::unordered_map map; std::vector& verts; double q; // quantization (grid) size explicit Welder(std::vector& v, double quant) : verts(v), q(quant) {} int add(const Vec3& p) { auto k = [&](double v) { return (int64_t)std::llround(v / q); }; // hash three quantized coords uint64_t h = 1469598103934665603ULL; int64_t kk[3] = {k(p.x), k(p.y), k(p.z)}; for (int i = 0; i < 3; ++i) { uint64_t v = (uint64_t)kk[i]; for (int b = 0; b < 8; ++b) { h ^= (v & 0xff); h *= 1099511628211ULL; v >>= 8; } } auto it = map.find(h); if (it != map.end()) return it->second; int idx = (int)verts.size(); verts.push_back(p); map.emplace(h, idx); return idx; } }; } // namespace // ---------------------------- STL ---------------------------- static bool loadSTL(const std::string& data, Mesh& out, std::string& err) { // Detect ASCII vs binary. Binary STL: 80-byte header + uint32 count; file // size == 84 + 50*count. ASCII starts with "solid" but so can binary headers, // so use the size check as the authority. bool binary = false; if (data.size() >= 84) { uint32_t n; std::memcpy(&n, data.data() + 80, 4); size_t expect = 84 + (size_t)n * 50; if (expect == data.size()) binary = true; } out = Mesh{}; // Quantize relative to a coarse epsilon; refined after we know the scale would // be ideal, but a fixed small grid works for typical mm-scale scans. Welder w(out.verts, 1e-5); if (binary) { const char* p = data.data() + 80; uint32_t n; std::memcpy(&n, p, 4); p += 4; out.tris.reserve(n); for (uint32_t i = 0; i < n; ++i) { const float* f = reinterpret_cast(p + 12); // skip normal Vec3 v0{f[0], f[1], f[2]}, v1{f[3], f[4], f[5]}, v2{f[6], f[7], f[8]}; out.tris.push_back({w.add(v0), w.add(v1), w.add(v2)}); p += 50; } } else { std::istringstream ss(data); std::string tok; std::vector face; while (ss >> tok) { if (tok == "vertex") { Vec3 v; ss >> v.x >> v.y >> v.z; face.push_back(v); if (face.size() == 3) { out.tris.push_back({w.add(face[0]), w.add(face[1]), w.add(face[2])}); face.clear(); } } } } if (out.tris.empty()) { err = "STL contained no triangles"; return false; } out.computeBounds(); out.computeNormals(); return true; } // ---------------------------- OBJ ---------------------------- static bool loadOBJ(const std::string& data, Mesh& out, std::string& err) { out = Mesh{}; std::istringstream ss(data); std::string line; while (std::getline(ss, line)) { if (line.size() < 2) continue; if (line[0] == 'v' && line[1] == ' ') { std::istringstream ls(line.substr(2)); Vec3 v; ls >> v.x >> v.y >> v.z; out.verts.push_back(v); } else if (line[0] == 'f' && line[1] == ' ') { std::istringstream ls(line.substr(2)); std::string vtok; std::vector idx; while (ls >> vtok) { // formats: v v/vt v//vn v/vt/vn (1-based, may be negative) int vi = 0; std::sscanf(vtok.c_str(), "%d", &vi); if (vi < 0) vi = (int)out.verts.size() + vi; // relative index else vi -= 1; if (vi >= 0 && vi < (int)out.verts.size()) idx.push_back(vi); } // fan-triangulate polygons for (size_t k = 1; k + 1 < idx.size(); ++k) out.tris.push_back({idx[0], idx[k], idx[k + 1]}); } } if (out.verts.empty() || out.tris.empty()) { err = "OBJ contained no faces/vertices"; return false; } out.computeBounds(); out.computeNormals(); return true; } // ---------------------------- PLY ---------------------------- // Revopoint / Revo Scan exports binary_little_endian PLY: vertices carry // x,y,z (+ optional nx,ny,nz, colour) and faces are `property list uchar uint // vertex_indices`. We parse the header generically (any property order/type), // then read either binary_little_endian or ascii bodies. Already-indexed, so // no welding needed — the connectivity is authoritative. namespace { struct PlyProp { std::string name; std::string type; // scalar type, or "list" element type if isList std::string countType; // for lists: the count's type std::string itemType; // for lists: the item's type bool isList = false; }; int plyTypeSize(const std::string& t) { if (t == "char" || t == "uchar" || t == "int8" || t == "uint8") return 1; if (t == "short" || t == "ushort" || t == "int16" || t == "uint16") return 2; if (t == "int" || t == "uint" || t == "int32" || t == "uint32" || t == "float" || t == "float32") return 4; if (t == "double" || t == "float64" || t == "int64" || t == "uint64") return 8; return 0; } // Read one scalar of the given type from p (little-endian), advance p, store in out. // Returns false on an unknown type or if fewer than the type's bytes remain before end // (so a truncated file fails cleanly instead of reading out of bounds). bool plyReadLE(const char*& p, const char* end, const std::string& t, double& out) { int sz = plyTypeSize(t); if (sz == 0 || end - p < sz) return false; auto rd = [&](auto tag) { decltype(tag) v; std::memcpy(&v, p, sizeof(v)); p += sizeof(v); return (double)v; }; if (t == "char" || t == "int8") out = rd((int8_t)0); else if (t == "uchar" || t == "uint8") out = rd((uint8_t)0); else if (t == "short" || t == "int16") out = rd((int16_t)0); else if (t == "ushort" || t == "uint16") out = rd((uint16_t)0); else if (t == "int" || t == "int32") out = rd((int32_t)0); else if (t == "uint" || t == "uint32") out = rd((uint32_t)0); else if (t == "float" || t == "float32") out = rd((float)0); else if (t == "double" || t == "float64") out = rd((double)0); else if (t == "int64") out = rd((int64_t)0); else if (t == "uint64") out = rd((uint64_t)0); else return false; return true; } } // namespace static bool loadPLY(const std::string& data, Mesh& out, std::string& err, bool requireFaces = true) { out = Mesh{}; // --- parse header (ASCII regardless of body format) --- size_t headerEnd = data.find("end_header"); if (data.compare(0, 3, "ply") != 0 || headerEnd == std::string::npos) { err = "not a PLY file"; return false; } // advance past the newline following end_header size_t bodyStart = data.find('\n', headerEnd); if (bodyStart == std::string::npos) { err = "PLY truncated header"; return false; } bodyStart += 1; std::string header = data.substr(0, headerEnd); std::istringstream hs(header); std::string line, format; int vertCount = 0, faceCount = 0; std::vector vertProps; PlyProp faceList; enum { NONE, VERTEX, FACE } cur = NONE; while (std::getline(hs, line)) { std::istringstream ls(line); std::string kw; ls >> kw; if (kw == "format") { ls >> format; } else if (kw == "element") { std::string ename; int n = 0; ls >> ename >> n; if (ename == "vertex") { cur = VERTEX; vertCount = n; } else if (ename == "face") { cur = FACE; faceCount = n; } else cur = NONE; } else if (kw == "property") { std::string t; ls >> t; if (t == "list") { PlyProp pp; pp.isList = true; ls >> pp.countType >> pp.itemType >> pp.name; if (cur == FACE) faceList = pp; } else { PlyProp pp; pp.type = t; ls >> pp.name; if (cur == VERTEX) vertProps.push_back(pp); } } } if (vertCount <= 0) { err = "PLY has no vertices"; return false; } bool ascii = format.find("ascii") != std::string::npos; bool bigEndian = format.find("big_endian") != std::string::npos; if (bigEndian) { err = "big-endian PLY not supported"; return false; } // locate x,y,z property indices int ix = -1, iy = -1, iz = -1; for (int i = 0; i < (int)vertProps.size(); ++i) { if (vertProps[i].name == "x") ix = i; else if (vertProps[i].name == "y") iy = i; else if (vertProps[i].name == "z") iz = i; } if (ix < 0 || iy < 0 || iz < 0) { err = "PLY vertex missing x/y/z"; return false; } out.verts.reserve(vertCount); if (ascii) { std::istringstream bs(data.substr(bodyStart)); for (int i = 0; i < vertCount; ++i) { std::vector vals(vertProps.size(), 0.0); for (auto& v : vals) if (!(bs >> v)) { err = "PLY truncated at vertex " + std::to_string(i); return false; } out.verts.push_back(Vec3{vals[ix], vals[iy], vals[iz]}); } for (int i = 0; i < faceCount; ++i) { int cnt = 0; if (!(bs >> cnt)) { err = "PLY truncated at face " + std::to_string(i); return false; } if (cnt < 0 || cnt > 100000) { err = "PLY bad face vertex count"; return false; } std::vector idx(cnt); for (int k = 0; k < cnt; ++k) { if (!(bs >> idx[k])) { err = "PLY truncated at face " + std::to_string(i); return false; } if (idx[k] < 0 || idx[k] >= vertCount) { err = "PLY face index out of range"; return false; } } for (int k = 1; k + 1 < cnt; ++k) out.tris.push_back({idx[0], idx[k], idx[k + 1]}); } } else { const char* p = data.data() + bodyStart; const char* end = data.data() + data.size(); // vertices for (int i = 0; i < vertCount; ++i) { double x = 0, y = 0, z = 0; for (int j = 0; j < (int)vertProps.size(); ++j) { double v; if (!plyReadLE(p, end, vertProps[j].type, v)) { err = "PLY truncated at vertex " + std::to_string(i); return false; } if (j == ix) x = v; else if (j == iy) y = v; else if (j == iz) z = v; } out.verts.push_back(Vec3{x, y, z}); } // faces if (faceCount > 0 && !faceList.isList) { err = "PLY face element has no vertex_indices list"; return false; } for (int i = 0; i < faceCount; ++i) { double dcnt; if (!plyReadLE(p, end, faceList.countType, dcnt)) { err = "PLY truncated at face " + std::to_string(i); return false; } int cnt = (int)dcnt; if (cnt < 0 || cnt > 100000) { err = "PLY bad face vertex count"; return false; } std::vector idx(cnt); for (int k = 0; k < cnt; ++k) { double di; if (!plyReadLE(p, end, faceList.itemType, di)) { err = "PLY truncated at face " + std::to_string(i); return false; } int id = (int)di; if (id < 0 || id >= vertCount) { err = "PLY face index out of range"; return false; } idx[k] = id; } for (int k = 1; k + 1 < cnt; ++k) out.tris.push_back({idx[0], idx[k], idx[k + 1]}); } } if (out.verts.empty() || (requireFaces && out.tris.empty())) { err = "PLY contained no faces/vertices"; return false; } out.computeBounds(); if (!out.tris.empty()) out.computeNormals(); return true; } bool loadFromMemory(const std::string& data, const std::string& ext, Mesh& out, std::string& err) { std::string e; for (char c : ext) e += (char)std::tolower(c); if (e == "obj") return loadOBJ(data, out, err); if (e == "stl") return loadSTL(data, out, err); if (e == "ply") return loadPLY(data, out, err); // sniff if (data.size() >= 3 && data.compare(0, 3, "ply") == 0) return loadPLY(data, out, err); if (data.size() > 5 && data.compare(0, 1, "v") == 0 && data.find("\nf ") != std::string::npos) return loadOBJ(data, out, err); return loadSTL(data, out, err); } bool loadPointsFromMemory(const std::string& data, const std::string& ext, std::vector& pts, std::string& err) { std::string e; for (char c : ext) e += (char)std::tolower(c); Mesh m; bool ok; if (e == "ply" || (data.size() >= 3 && data.compare(0, 3, "ply") == 0)) ok = loadPLY(data, m, err, /*requireFaces=*/false); else ok = loadFromMemory(data, e, m, err); // meshes are fine too; keep the verts if (!ok) return false; pts = std::move(m.verts); return true; } bool load(const std::string& path, Mesh& out, std::string& err) { std::ifstream f(path, std::ios::binary); if (!f) { err = "cannot open " + path; return false; } std::ostringstream buf; buf << f.rdbuf(); std::string data = buf.str(); std::string ext; auto dot = path.find_last_of('.'); if (dot != std::string::npos) ext = path.substr(dot + 1); return loadFromMemory(data, ext, out, err); } int windingOrientation(const Mesh& m) { if (m.empty()) return 0; // Divergence-theorem volume, centroid-relative so scan gaps cost little accuracy. geom::Vec3 c = (m.bbMin + m.bbMax) * 0.5; double v6 = 0; for (const auto& t : m.tris) v6 += geom::dot(m.verts[t[0]] - c, geom::cross(m.verts[t[1]] - c, m.verts[t[2]] - c)); double diag = m.bboxDiag(); if (std::abs(v6 / 6.0) < diag * diag * diag * 1e-5) return 0; return v6 >= 0 ? 1 : -1; } std::vector verticesInRadius(const Mesh& m, const Vec3& center, double radius) { std::vector out; double r2 = radius * radius; for (int i = 0; i < (int)m.verts.size(); ++i) { Vec3 d = m.verts[i] - center; if (geom::dot(d, d) <= r2) out.push_back(i); } return out; } int writeSTLRegion(const std::string& path, const Mesh& m, const Vec3& lo, const Vec3& hi) { auto inBox = [&](const Vec3& p) { return p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y && p.z >= lo.z && p.z <= hi.z; }; std::vector> keep; keep.reserve(m.tris.size() / 4 + 1); for (const auto& t : m.tris) { Vec3 c = (m.verts[t[0]] + m.verts[t[1]] + m.verts[t[2]]) / 3.0; if (inBox(c)) keep.push_back(t); } if (keep.empty()) return 0; std::ofstream f(path, std::ios::binary); if (!f) return 0; auto writeSTL = [&](const std::vector>& selected) { char header[80] = {0}; std::snprintf(header, sizeof header, "scan2cad binary mesh"); f.write(header, 80); uint32_t n = (uint32_t)selected.size(); f.write(reinterpret_cast(&n), 4); auto wf = [&](double v) { float x = (float)v; f.write(reinterpret_cast(&x), 4); }; for (const auto& t : selected) { const Vec3& a = m.verts[t[0]]; const Vec3& b = m.verts[t[1]]; const Vec3& c = m.verts[t[2]]; Vec3 nrm = geom::normalize(geom::cross(b - a, c - a)); wf(nrm.x); wf(nrm.y); wf(nrm.z); wf(a.x); wf(a.y); wf(a.z); wf(b.x); wf(b.y); wf(b.z); wf(c.x); wf(c.y); wf(c.z); uint16_t attr = 0; f.write(reinterpret_cast(&attr), 2); } }; writeSTL(keep); return f ? (int)keep.size() : 0; } namespace { void appendBytes(std::string& out, const void* data, std::size_t n) { out.append(static_cast(data), n); } std::string binarySTLImpl(const Mesh& m, const std::vector* triangleIds) { std::size_t count = triangleIds ? triangleIds->size() : m.tris.size(); std::string out; out.reserve(84 + count * 50); char header[80] = {0}; std::snprintf(header, sizeof header, "scan2cad binary mesh"); appendBytes(out, header, 80); uint32_t n = (uint32_t)count; appendBytes(out, &n, 4); auto appendTriangle = [&](const std::array& t) { const Vec3& a = m.verts[t[0]]; const Vec3& b = m.verts[t[1]]; const Vec3& c = m.verts[t[2]]; Vec3 nrm = geom::normalize(geom::cross(b - a, c - a)); float values[12] = { (float)nrm.x, (float)nrm.y, (float)nrm.z, (float)a.x, (float)a.y, (float)a.z, (float)b.x, (float)b.y, (float)b.z, (float)c.x, (float)c.y, (float)c.z}; appendBytes(out, values, sizeof values); uint16_t attr = 0; appendBytes(out, &attr, 2); }; if (triangleIds) { for (int ti : *triangleIds) if (ti >= 0 && ti < (int)m.tris.size()) appendTriangle(m.tris[ti]); } else { for (const auto& t : m.tris) appendTriangle(t); } return out; } } // namespace std::string binarySTL(const Mesh& m) { return binarySTLImpl(m, nullptr); } std::string binarySTL(const Mesh& m, const std::vector& triangleIds) { return binarySTLImpl(m, &triangleIds); } } // namespace mesh