#include "discover.hpp" #include #include #include #include #include "fit.hpp" namespace discover { using geom::dot; using geom::norm; using geom::normalize; using geom::Vec3; // Local topological neighbourhood: BFS from seed collecting up to K vertices. static std::vector kRing(const mesh::Mesh& m, int seed, int K, std::vector& kstamp, int gen) { std::vector out{seed}, stack{seed}; kstamp[seed] = gen; while (!stack.empty() && (int)out.size() < K) { int cur = stack.back(); stack.pop_back(); for (int w : m.adj[cur]) { if ((int)out.size() >= K) break; if (kstamp[w] != gen) { kstamp[w] = gen; out.push_back(w); stack.push_back(w); } } } return out; } // Grow a planar region from a fixed seed plane (origin o, unit normal n). static std::vector growPlane(const mesh::Mesh& m, int seed, const Vec3& o, const Vec3& n, const std::vector& claimed, std::vector& stamp, int gen, double cosTol, double distTol) { std::vector region{seed}, stack{seed}; stamp[seed] = gen; while (!stack.empty()) { int cur = stack.back(); stack.pop_back(); for (int w : m.adj[cur]) { if (claimed[w] || stamp[w] == gen) continue; if (std::fabs(dot(m.vnormals[w], n)) < cosTol) continue; if (std::fabs(dot(m.verts[w] - o, n)) > distTol) continue; stamp[w] = gen; region.push_back(w); stack.push_back(w); } } return region; } // Grow a cylinder-wall region: a neighbour joins if it sits at radius ≈ r from the // axis and its normal points radially (perpendicular to the axis). static std::vector growCyl(const mesh::Mesh& m, int seed, const Vec3& axisPt, const Vec3& axis, double r, const std::vector& claimed, std::vector& stamp, int gen, double distTol, double normCosMin) { std::vector region{seed}, stack{seed}; stamp[seed] = gen; while (!stack.empty()) { int cur = stack.back(); stack.pop_back(); for (int w : m.adj[cur]) { if (claimed[w] || stamp[w] == gen) continue; Vec3 d = m.verts[w] - axisPt; Vec3 radial = d - axis * dot(d, axis); double rd = norm(radial); if (std::fabs(rd - r) > distTol) continue; if (rd > 1e-9 && std::fabs(dot(m.vnormals[w], radial / rd)) < normCosMin) continue; stamp[w] = gen; region.push_back(w); stack.push_back(w); } } return region; } static void gather(const mesh::Mesh& m, const std::vector& ids, std::vector& pts, std::vector& nrm) { pts.clear(); nrm.clear(); pts.reserve(ids.size()); nrm.reserve(ids.size()); for (int v : ids) { pts.push_back(m.verts[v]); nrm.push_back(m.vnormals[v]); } } // Angular coverage of a point set around an axis (fraction of the circle spanned). static double coverageOf(const std::vector& pts, const Vec3& axisPt, const Vec3& axis) { Vec3 uu, vv; geom::basisFromNormal(axis, uu, vv); const int SECT = 36; int occ[SECT] = {0}; for (const auto& q : pts) { Vec3 d = q - axisPt; Vec3 rad = d - axis * dot(d, axis); double ang = std::atan2(dot(rad, vv), dot(rad, uu)); int s = (int)((ang + M_PI) / (2 * M_PI) * SECT) % SECT; if (s >= 0 && s < SECT) occ[s] = 1; } int filled = 0; for (int s = 0; s < SECT; ++s) filled += occ[s]; return (double)filled / SECT; } Result discover(mesh::Mesh& m, const Params& p) { auto t0 = std::chrono::steady_clock::now(); Result R; R.nverts = (int)m.verts.size(); R.ntris = (int)m.tris.size(); if (m.verts.size() < 10) { R.note = "mesh too small"; return R; } m.computeNormals(); if (m.adj.empty()) m.buildAdjacency(); if (p.smoothPasses > 0) { // optional normal denoising for noisy scans std::vector sn = m.vnormals, tmp(m.vnormals.size()); for (int it = 0; it < p.smoothPasses; ++it) { for (size_t i = 0; i < sn.size(); ++i) { Vec3 acc = sn[i]; for (int w : m.adj[i]) acc = acc + sn[w]; tmp[i] = normalize(acc); } sn.swap(tmp); } m.vnormals.swap(sn); } m.computeCurvature(); const double diag = m.bboxDiag(); const double distTol = std::max(p.distTolRel * diag, 1e-4); const double cosTol = std::cos(p.angTolDeg * M_PI / 180.0); const double maxRadius = p.maxRadiusRel * diag; // explicit diameter bounds (UI) override the defaults when set (>0) const double minRadius = p.minDiameterMM > 0 ? 0.5 * p.minDiameterMM : p.minRadiusMM; const double maxRadiusEff = p.maxDiameterMM > 0 ? 0.5 * p.maxDiameterMM : maxRadius; const int K = 60; const double normCosMin = 0.6; const int minPlane = std::max(p.minPlanePts, (int)(m.verts.size() / 2000)); std::vector order(m.verts.size()); std::iota(order.begin(), order.end(), 0); std::sort(order.begin(), order.end(), [&](int a, int b) { return m.curv[a] < m.curv[b]; }); std::vector claimed(m.verts.size(), 0), dead(m.verts.size(), 0); // Cylinder-pass-only reject mask: a region that grows but fails validation is // marked here so it isn't re-grown from every one of its vertices (budget saver), // yet stays UNclaimed so the plane pass can still use those vertices for the datum. std::vector cylDead(m.verts.size(), 0); // Region restriction: exclude vertices outside the drag-box frustum by pre-claiming // them, so they can neither seed nor be grown into. Inside ⇔ on the ≤0 side of every plane. if (!p.region.empty()) { int kept = 0; for (size_t i = 0; i < m.verts.size(); ++i) { const Vec3& v = m.verts[i]; bool inside = true; for (const auto& pl : p.region) { if (pl[0] * v.x + pl[1] * v.y + pl[2] * v.z + pl[3] > 1e-6) { inside = false; break; } } if (inside) ++kept; else { claimed[i] = 1; dead[i] = 1; } } R.note = "region: " + std::to_string(kept) + " of " + std::to_string(m.verts.size()) + " verts"; } std::vector stamp(m.verts.size(), -1), kstamp(m.verts.size(), -1); int gen = 0, kgen = 0; std::vector pts, nrm; // ---- pass 1: cylinders. Grow them FIRST so hole walls are claimed before any // plane can bleed onto them — otherwise a flat face growing past a rim eats part // of a wall and that hole is lost. ---- int fits = 0; for (int seed : order) { if (claimed[seed] || cylDead[seed]) continue; if (m.curv[seed] > p.curvCap) break; if (++fits > p.maxSeedFits) { R.note = "seed-fit budget reached"; break; } auto nb = kRing(m, seed, K, kstamp, ++kgen); gather(m, nb, pts, nrm); auto pf = fit::fitPlanePoints(pts, nrm, {0, 0, 0}); auto cf = fit::fitCylinderPoints(pts, nrm, 0.0, {0, 0, 0}); bool cylBetter = cf.ok && cf.radius >= minRadius && cf.radius <= maxRadiusEff && pf.ok && cf.rms < 0.6 * std::max(pf.rms, 1e-6) && cf.rms < p.cylRmsRatio * cf.radius; if (!cylBetter) continue; // leave for the plane pass auto region = growCyl(m, seed, cf.axisPoint, cf.axisDir, cf.radius, claimed, stamp, ++gen, std::max(distTol, 3 * cf.rms), normCosMin); R.dbgMaxRegion = std::max(R.dbgMaxRegion, (int)region.size()); // Mark the grown region as cylinder-tested up front so it can't reseed, but do // NOT claim it yet — claiming happens only once the refit fully validates below, // so a rejected region is left intact for the plane pass. auto rejectRegion = [&]() { for (int v : region) cylDead[v] = 1; }; if ((int)region.size() < p.minCylPts) { ++R.dbgCylRejSmall; rejectRegion(); continue; } gather(m, region, pts, nrm); auto rc = fit::fitCylinderPoints(pts, nrm, 0.0, {0, 0, 0}); if (!rc.ok) { ++R.dbgCylRejFit; rejectRegion(); continue; } if (rc.radius < minRadius || rc.radius > maxRadiusEff) { ++R.dbgCylRejRadius; rejectRegion(); continue; } if (rc.rms > p.cylRmsRatio * rc.radius) { ++R.dbgCylRejRms; rejectRegion(); continue; } double coverage = coverageOf(pts, rc.axisPoint, rc.axisDir); if (coverage < p.minCoverage) { ++R.dbgCylRejCoverage; rejectRegion(); continue; } for (int v : region) claimed[v] = 1; DCyl dc; dc.coverage = coverage; dc.center = rc.axisPoint; dc.axis = rc.axisDir; dc.diameter = rc.diameter; dc.depth = rc.tMax - rc.tMin; dc.p1 = rc.p1; dc.p2 = rc.p2; dc.npts = (int)region.size(); dc.rms = rc.rms; double inward = 0; int c = 0; for (size_t k = 0; k < pts.size(); ++k) { Vec3 dd = pts[k] - rc.axisPoint; Vec3 rad = dd - rc.axisDir * dot(dd, rc.axisDir); double rl = norm(rad); if (rl > 1e-9) { inward += dot(nrm[k], rad / rl); ++c; } } dc.isHole = (c > 0 && inward / c < 0); if (p.holesOnly && !dc.isHole) continue; R.cyls.push_back(dc); } // ---- pass 2: planar faces over the remaining vertices ---- for (int seed : order) { if (claimed[seed] || dead[seed]) continue; if (m.curv[seed] > p.curvCap) break; if (++fits > 2 * p.maxSeedFits) { R.note = "seed-fit budget reached"; break; } auto nb = kRing(m, seed, K, kstamp, ++kgen); gather(m, nb, pts, nrm); auto pf = fit::fitPlanePoints(pts, nrm, {0, 0, 0}); if (!pf.ok) { dead[seed] = 1; continue; } auto region = growPlane(m, seed, pf.origin, pf.normal, claimed, stamp, ++gen, cosTol, distTol); R.dbgMaxRegion = std::max(R.dbgMaxRegion, (int)region.size()); if ((int)region.size() < minPlane) { dead[seed] = 1; ++R.dbgPlanesRejected; continue; } for (int v : region) claimed[v] = 1; gather(m, region, pts, nrm); auto rp = fit::fitPlanePoints(pts, nrm, {0, 0, 0}); DPlane dp; dp.origin = rp.origin; dp.normal = rp.normal; dp.u = rp.u; dp.v = rp.v; dp.npts = (int)region.size(); dp.rms = rp.rms; dp.umin = dp.vmin = 1e300; dp.umax = dp.vmax = -1e300; for (const auto& q : pts) { Vec3 d = q - rp.origin; double cu = dot(d, rp.u), cv = dot(d, rp.v); dp.umin = std::min(dp.umin, cu); dp.umax = std::max(dp.umax, cu); dp.vmin = std::min(dp.vmin, cv); dp.vmax = std::max(dp.vmax, cv); } R.planes.push_back(dp); } for (size_t i = 0; i < m.verts.size(); ++i) R.dbgLeftover += claimed[i] ? 0 : 1; // ---- dedup coaxial cylinders of the same physical hole ---- std::sort(R.cyls.begin(), R.cyls.end(), [](const DCyl& a, const DCyl& b) { return a.npts > b.npts; }); { std::vector keep; for (const auto& c : R.cyls) { bool dup = false; for (const auto& k : keep) { if (std::fabs(dot(c.axis, k.axis)) < 0.94) continue; Vec3 dc = c.center - k.center; double perp = norm(dc - k.axis * dot(dc, k.axis)); if (perp < 0.5 * std::max(k.diameter, 2.0) && std::fabs(c.diameter - k.diameter) < 0.2 * k.diameter) { dup = true; break; } } if (!dup) keep.push_back(c); } R.cyls.swap(keep); } std::sort(R.planes.begin(), R.planes.end(), [](const DPlane& a, const DPlane& b) { return a.npts > b.npts; }); if ((int)R.planes.size() > p.maxPlanes) R.planes.resize(p.maxPlanes); if ((int)R.cyls.size() > p.maxCyls) R.cyls.resize(p.maxCyls); if (!R.planes.empty()) R.datumIndex = 0; auto t1 = std::chrono::steady_clock::now(); R.ms = std::chrono::duration(t1 - t0).count(); return R; } } // namespace discover