#include "prim.hpp" #include #include #include #include namespace prim { using geom::cross; using geom::dot; using geom::norm; using geom::normalize; using geom::Vec3; namespace { constexpr double PI = 3.14159265358979323846; double clamp1(double x) { return std::max(-1.0, std::min(1.0, x)); } Vec3 centroid(const std::vector& pts) { Vec3 c{0, 0, 0}; for (const auto& p : pts) c = c + p; return pts.empty() ? c : c / (double)pts.size(); } // Small pivoted dense solve. The largest system in this file is 6x6. bool solveLinear(int n, double a[6][6], double b[6], double x[6]) { double scale = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) scale = std::max(scale, std::fabs(a[i][j])); if (!(scale > 0) || !std::isfinite(scale)) return false; for (int k = 0; k < n; ++k) { int piv = k; for (int i = k + 1; i < n; ++i) if (std::fabs(a[i][k]) > std::fabs(a[piv][k])) piv = i; if (std::fabs(a[piv][k]) < scale * 1e-12) return false; if (piv != k) { for (int j = k; j < n; ++j) std::swap(a[k][j], a[piv][j]); std::swap(b[k], b[piv]); } for (int i = k + 1; i < n; ++i) { double f = a[i][k] / a[k][k]; a[i][k] = 0; for (int j = k + 1; j < n; ++j) a[i][j] -= f * a[k][j]; b[i] -= f * b[k]; } } for (int i = n - 1; i >= 0; --i) { double s = b[i]; for (int j = i + 1; j < n; ++j) s -= a[i][j] * x[j]; x[i] = s / a[i][i]; } return true; } double medianAbs(const std::vector& residuals) { if (residuals.empty()) return 0; std::vector a; a.reserve(residuals.size()); for (double e : residuals) a.push_back(std::fabs(e)); std::nth_element(a.begin(), a.begin() + a.size() / 2, a.end()); return a[a.size() / 2]; } std::vector huberWeights(const std::vector& residuals) { double sigma = std::max(1.4826 * medianAbs(residuals), 1e-7); double cutoff = 2.5 * sigma; std::vector w(residuals.size(), 1.0); for (size_t i = 0; i < residuals.size(); ++i) { double a = std::fabs(residuals[i]); if (a > cutoff) w[i] = cutoff / a; } return w; } bool sphereAlgebraic(const std::vector& pts, const std::vector& weights, Vec3& center, double& radius) { Vec3 base = centroid(pts); double A[6][6] = {}, b[6] = {}, x[6] = {}; for (size_t i = 0; i < pts.size(); ++i) { Vec3 q = pts[i] - base; double row[4] = {2 * q.x, 2 * q.y, 2 * q.z, 1}; double rhs = dot(q, q); double w = weights.empty() ? 1.0 : weights[i]; for (int r = 0; r < 4; ++r) { b[r] += w * row[r] * rhs; for (int c = 0; c < 4; ++c) A[r][c] += w * row[r] * row[c]; } } if (!solveLinear(4, A, b, x)) return false; Vec3 d{x[0], x[1], x[2]}; double r2 = x[3] + dot(d, d); if (!(r2 > 0) || !std::isfinite(r2)) return false; center = base + d; radius = std::sqrt(r2); return true; } std::vector sphereResiduals(const std::vector& pts, const Vec3& c, double r) { std::vector e; e.reserve(pts.size()); for (const auto& p : pts) e.push_back(norm(p - c) - r); return e; } struct P2 { double x = 0, y = 0; }; double cross2(const P2& o, const P2& a, const P2& b) { return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); } std::vector convexHull(std::vector p) { std::sort(p.begin(), p.end(), [](const P2& a, const P2& b) { return a.x < b.x || (a.x == b.x && a.y < b.y); }); p.erase(std::unique(p.begin(), p.end(), [](const P2& a, const P2& b) { return a.x == b.x && a.y == b.y; }), p.end()); if (p.size() < 3) return p; std::vector h(2 * p.size()); size_t k = 0; for (const auto& q : p) { while (k >= 2 && cross2(h[k - 2], h[k - 1], q) <= 0) --k; h[k++] = q; } size_t lower = k + 1; for (size_t i = p.size() - 1; i-- > 0;) { const auto& q = p[i]; while (k >= lower && cross2(h[k - 2], h[k - 1], q) <= 0) --k; h[k++] = q; } h.resize(k - 1); return h; } std::array minimumRectangle(const std::vector& pts, const Vec3& origin, const Vec3& u, const Vec3& v) { std::vector q; q.reserve(pts.size()); for (const auto& p : pts) { Vec3 d = p - origin; q.push_back({dot(d, u), dot(d, v)}); } auto h = convexHull(std::move(q)); if (h.empty()) return {}; double bestArea = std::numeric_limits::infinity(); double bestC = 1, bestS = 0, bestX0 = 0, bestX1 = 0, bestY0 = 0, bestY1 = 0; size_t tries = h.size() == 1 ? 1 : h.size(); for (size_t i = 0; i < tries; ++i) { double ex = 1, ey = 0; if (h.size() > 1) { P2 e{h[(i + 1) % h.size()].x - h[i].x, h[(i + 1) % h.size()].y - h[i].y}; double en = std::hypot(e.x, e.y); if (en < 1e-12) continue; ex = e.x / en; ey = e.y / en; } double x0 = 1e300, x1 = -1e300, y0 = 1e300, y1 = -1e300; for (const auto& p : h) { double x = p.x * ex + p.y * ey; double y = -p.x * ey + p.y * ex; x0 = std::min(x0, x); x1 = std::max(x1, x); y0 = std::min(y0, y); y1 = std::max(y1, y); } double area = (x1 - x0) * (y1 - y0); if (area < bestArea) { bestArea = area; bestC = ex; bestS = ey; bestX0 = x0; bestX1 = x1; bestY0 = y0; bestY1 = y1; } } auto world = [&](double x, double y) { double a = x * bestC - y * bestS; double b = x * bestS + y * bestC; return origin + u * a + v * b; }; return {world(bestX0, bestY0), world(bestX1, bestY0), world(bestX1, bestY1), world(bestX0, bestY1)}; } bool closestPointToLines(const std::vector& points, const std::vector& dirs, Vec3& out) { double A[6][6] = {}, b[6] = {}, x[6] = {}; for (size_t k = 0; k < points.size(); ++k) { Vec3 d = normalize(dirs[k]); double dv[3] = {d.x, d.y, d.z}; double pv[3] = {points[k].x, points[k].y, points[k].z}; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) { double m = (i == j ? 1.0 : 0.0) - dv[i] * dv[j]; A[i][j] += m; b[i] += m * pv[j]; } } if (!solveLinear(3, A, b, x)) return false; out = {x[0], x[1], x[2]}; return true; } std::vector coneResiduals(const std::vector& pts, const Vec3& apex, const Vec3& axis, double angle) { double c = std::cos(angle), s = std::sin(angle); std::vector e; e.reserve(pts.size()); for (const auto& p : pts) { Vec3 q = p - apex; double h = dot(q, axis); double rho = norm(q - axis * h); e.push_back(rho * c - h * s); } return e; } double rms(const std::vector& e) { double s2 = 0; for (double x : e) s2 += x * x; return e.empty() ? 0 : std::sqrt(s2 / e.size()); } bool coneStep(const std::vector& pts, const std::vector& weights, Vec3& apex, Vec3& axis, double& angle) { Vec3 u, v; geom::basisFromNormal(axis, u, v); double c = std::cos(angle), s = std::sin(angle); double H[6][6] = {}, b[6] = {}, dx[6] = {}; int used = 0; for (size_t i = 0; i < pts.size(); ++i) { Vec3 q = pts[i] - apex; double h = dot(q, axis); Vec3 radial = q - axis * h; double rho = norm(radial); if (rho < 1e-10) continue; Vec3 rh = radial / rho; double e = rho * c - h * s; Vec3 ja = rh * -c + axis * s; Vec3 axisGrad = rh * (-h * c) - q * s; double J[6] = {ja.x, ja.y, ja.z, dot(axisGrad, u), dot(axisGrad, v), -rho * s - h * c}; double w = weights.empty() ? 1.0 : weights[i]; for (int r = 0; r < 6; ++r) { b[r] -= w * J[r] * e; for (int col = 0; col < 6; ++col) H[r][col] += w * J[r] * J[col]; } ++used; } if (used < 6) return false; double trace = 0; for (int i = 0; i < 6; ++i) trace += H[i][i]; for (int i = 0; i < 6; ++i) H[i][i] += trace * 1e-12 + 1e-12; if (!solveLinear(6, H, b, dx)) return false; // Keep an unstable first iterate from crossing to the opposite cone sheet. double da = std::hypot(dx[3], dx[4]); if (da > 0.25) { double f = 0.25 / da; dx[3] *= f; dx[4] *= f; } dx[5] = std::max(-0.15, std::min(0.15, dx[5])); apex = apex + Vec3{dx[0], dx[1], dx[2]}; axis = normalize(axis + u * dx[3] + v * dx[4]); angle = std::max(0.5 * PI / 180.0, std::min(85.0 * PI / 180.0, angle + dx[5])); double step2 = 0; for (double d : dx) step2 += d * d; return step2 > 1e-20; } bool solve3Rows(const std::array& rows, const std::array& rhs, Vec3& p) { double A[6][6] = {}, b[6] = {rhs[0], rhs[1], rhs[2]}, x[6] = {}; for (int i = 0; i < 3; ++i) { A[i][0] = rows[i].x; A[i][1] = rows[i].y; A[i][2] = rows[i].z; } if (!solveLinear(3, A, b, x)) return false; p = {x[0], x[1], x[2]}; return true; } } // namespace void wandSelect(const mesh::Mesh& m, Vec3 seedPoint, double angleDeg, std::vector& out) { out.clear(); if (m.verts.empty() || m.vnormals.size() != m.verts.size()) return; if (m.adj.empty()) const_cast(m).buildAdjacency(); int seed = 0; double best = dot(m.verts[0] - seedPoint, m.verts[0] - seedPoint); for (int i = 1; i < (int)m.verts.size(); ++i) { double d2 = dot(m.verts[i] - seedPoint, m.verts[i] - seedPoint); if (d2 < best) { best = d2; seed = i; } } double cosTol = std::cos(std::max(0.0, std::min(180.0, angleDeg)) * PI / 180.0); Vec3 seedN = normalize(m.vnormals[seed]); std::vector seen(m.verts.size(), 0); std::queue q; seen[seed] = 1; q.push(seed); while (!q.empty() && out.size() < 2000000) { int i = q.front(); q.pop(); out.push_back(i); Vec3 currentN = normalize(m.vnormals[i]); for (int j : m.adj[i]) { if (seen[j]) continue; Vec3 n = normalize(m.vnormals[j]); if (dot(n, seedN) > cosTol && dot(n, currentN) > cosTol) { seen[j] = 1; q.push(j); } } } } void paintSelect(const mesh::Mesh& m, const std::vector& centers, double radius, std::vector& out) { out.clear(); if (centers.empty() || radius <= 0 || m.verts.empty()) return; std::vector selected(m.verts.size(), 0); for (const auto& center : centers) for (int i : mesh::verticesInRadius(m, center, radius)) if (!selected[i]) { selected[i] = 1; out.push_back(i); } } PlaneFit fitPlane(const std::vector& points, const std::vector& normals) { PlaneFit out; fit::PlaneFit f = fit::fitPlanePoints(points, normals, {0, 0, 0}); if (!f.ok) { out.err = "plane fit failed"; return out; } out.ok = true; out.origin = f.origin; out.normal = f.normal; out.u = f.u; out.v = f.v; out.rect = minimumRectangle(points, f.origin, f.u, f.v); out.rms = f.rms; out.npts = f.npts; return out; } CylinderFit fitCylinder(const std::vector& points, const std::vector& normals) { CylinderFit out; if (points.size() != normals.size()) { out.err = "cylinder fit needs surface normals"; return out; } fit::CylinderFit f = fit::fitCylinderPoints(points, normals, 0, {0, 0, 0}); if (!f.ok) { out.err = "cylinder fit failed"; return out; } out.ok = true; out.center = f.axisPoint; out.axis = f.axisDir; out.radius = f.radius; out.p1 = f.p1; out.p2 = f.p2; out.rms = f.rms; out.npts = f.npts; return out; } SphereFit fitSphere(const std::vector& points) { SphereFit out; out.npts = (int)points.size(); if (points.size() < 4) { out.err = "sphere fit needs at least 4 points"; return out; } Vec3 c; double r = 0; std::vector weights(points.size(), 1.0); for (int pass = 0; pass < 3; ++pass) { if (!sphereAlgebraic(points, weights, c, r)) { out.err = "sphere fit is singular"; return out; } weights = huberWeights(sphereResiduals(points, c, r)); } // Geometric Gauss--Newton refinement of ||p-c||-r. for (int it = 0; it < 15; ++it) { double H[6][6] = {}, b[6] = {}, dx[6] = {}; int used = 0; for (size_t i = 0; i < points.size(); ++i) { Vec3 d = points[i] - c; double len = norm(d); if (len < 1e-12) continue; Vec3 u = d / len; double e = len - r; double J[4] = {-u.x, -u.y, -u.z, -1}; double w = weights[i]; for (int row = 0; row < 4; ++row) { b[row] -= w * J[row] * e; for (int col = 0; col < 4; ++col) H[row][col] += w * J[row] * J[col]; } ++used; } if (used < 4 || !solveLinear(4, H, b, dx)) break; c = c + Vec3{dx[0], dx[1], dx[2]}; r += dx[3]; if (dx[0] * dx[0] + dx[1] * dx[1] + dx[2] * dx[2] + dx[3] * dx[3] < 1e-20) break; } if (!(r > 0) || !std::isfinite(r)) { out.err = "sphere fit produced an invalid radius"; return out; } out.ok = true; out.center = c; out.radius = r; out.rms = rms(sphereResiduals(points, c, r)); return out; } ConeFit fitCone(const std::vector& points, const std::vector& normals) { ConeFit out; out.npts = (int)points.size(); if (points.size() < 6 || normals.size() != points.size()) { out.err = "cone fit needs points with surface normals"; return out; } std::vector nn; nn.reserve(normals.size()); double N[3][3] = {}; for (const auto& raw : normals) { Vec3 n = normalize(raw); nn.push_back(n); double a[3] = {n.x, n.y, n.z}; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) N[i][j] += a[i] * a[j]; } double ev[3], V[3][3]; geom::jacobiEigen3(N, ev, V); // A cylinder is the limiting cone whose normals are all perpendicular to // one direction. Detect that constant near-zero projection explicitly: // the apex-line solve is singular at exactly zero angle. for (int k = 0; k < 3; ++k) { Vec3 candidate = normalize({V[0][k], V[1][k], V[2][k]}); double mean = 0; for (const auto& n : nn) mean += std::fabs(dot(n, candidate)); mean /= nn.size(); double variance = 0; for (const auto& n : nn) { double d = std::fabs(dot(n, candidate)) - mean; variance += d * d; } double deviation = std::sqrt(variance / nn.size()); if (mean < std::sin(1.5 * PI / 180.0) && deviation < std::sin(0.5 * PI / 180.0)) { out.err = "looks cylindrical - fit a cylinder"; return out; } } double span = 0; Vec3 pc = centroid(points); for (const auto& p : points) span = std::max(span, norm(p - pc)); span = std::max(span, 1.0); // Candidate axes from two spectra: the raw outer product (right for wide // azimuth coverage) and the CENTERED normal covariance — on a cone every // normal makes the same angle with the axis, so the axis is the direction // of least variance of n·w, which stays correct even for a partial-arc // selection where the raw matrix's eigenvectors tilt off-axis. std::vector candidates; for (int k = 0; k < 3; ++k) candidates.push_back(normalize({V[0][k], V[1][k], V[2][k]})); Vec3 nbar{0, 0, 0}; for (const auto& n : nn) nbar = nbar + n; nbar = nbar / (double)nn.size(); double C[3][3] = {}; for (const auto& n : nn) { Vec3 d = n - nbar; double a[3] = {d.x, d.y, d.z}; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) C[i][j] += a[i] * a[j]; } double evC[3], VC[3][3]; geom::jacobiEigen3(C, evC, VC); for (int k = 0; k < 3; ++k) candidates.push_back(normalize({VC[0][k], VC[1][k], VC[2][k]})); bool found = false; Vec3 bestApex, bestAxis; double bestAngle = 0, bestScore = 1e300; for (const Vec3& candidate : candidates) { Vec3 axis = candidate; double meanDot = 0; for (const auto& n : nn) meanDot += dot(n, axis); if (meanDot > 0) axis = axis * -1.0; double meanAbs = 0; for (const auto& n : nn) meanAbs += std::fabs(dot(n, axis)); meanAbs /= nn.size(); double angle = std::asin(clamp1(meanAbs)); if (angle < 0.5 * PI / 180.0 || angle > 85 * PI / 180.0) continue; std::vector generators; generators.reserve(points.size()); double s = std::sin(angle), c = std::cos(angle); for (const auto& n : nn) { Vec3 radial = n - axis * dot(n, axis); if (norm(radial) < 1e-8) radial = Vec3{1, 0, 0}; generators.push_back(normalize(axis * c + normalize(radial) * s)); } Vec3 apex; if (!closestPointToLines(points, generators, apex)) continue; auto residuals = coneResiduals(points, apex, axis, angle); double var = 0; for (const auto& n : nn) { double d = std::fabs(dot(n, axis)) - meanAbs; var += d * d; } var = std::sqrt(var / nn.size()); int positive = 0; for (const auto& p : points) if (dot(p - apex, axis) > 0) ++positive; double positiveFrac = (double)positive / points.size(); double score = rms(residuals) + 0.2 * span * var; if (positiveFrac < 0.8) score += span * (0.8 - positiveFrac); if (score < bestScore) { found = true; bestScore = score; bestApex = apex; bestAxis = axis; bestAngle = angle; } } if (!found) { out.err = "cone initialization failed"; return out; } Vec3 apex = bestApex, axis = bestAxis; double angle = bestAngle; std::vector weights(points.size(), 1.0); // Three robust rounds followed by an unchanging-weight geometric refinement. for (int pass = 0; pass < 3; ++pass) { for (int it = 0; it < 5; ++it) if (!coneStep(points, weights, apex, axis, angle)) break; weights = huberWeights(coneResiduals(points, apex, axis, angle)); } for (int it = 0; it < 10; ++it) if (!coneStep(points, weights, apex, axis, angle)) break; double angleDeg = angle * 180.0 / PI; if (angleDeg < 1.5) { out.err = "looks cylindrical - fit a cylinder"; return out; } double h1 = 1e300, h2 = -1e300; int positive = 0; for (const auto& p : points) { double h = dot(p - apex, axis); h1 = std::min(h1, h); h2 = std::max(h2, h); if (h > 0) ++positive; } if (positive < (int)(points.size() * 0.8) || h2 <= 0) { out.err = "cone apex or axis is ambiguous"; return out; } out.ok = true; out.apex = apex; out.axis = axis; out.halfAngleDeg = angleDeg; out.h1 = h1; out.h2 = h2; out.rms = rms(coneResiduals(points, apex, axis, angle)); return out; } Line lineFromPlanes(const Vec3& origin1, const Vec3& normal1, const Vec3& origin2, const Vec3& normal2) { Line out; Vec3 n1 = normalize(normal1), n2 = normalize(normal2); Vec3 d = cross(n1, n2); double d2 = dot(d, d); double sin1 = std::sin(PI / 180.0); if (d2 < sin1 * sin1) { out.err = "planes are near-parallel"; return out; } double b1 = dot(n1, origin1), b2 = dot(n2, origin2); out.ok = true; out.d = normalize(d); out.p = (cross(n2, d) * b1 + cross(d, n1) * b2) / d2; return out; } Line axisLine(const Vec3& p, const Vec3& d) { Line out; if (norm(d) < 1e-12) { out.err = "axis direction is zero"; return out; } out.ok = true; out.p = p; out.d = normalize(d); return out; } Line averageLines(const std::vector& lines) { Line out; if (lines.size() < 2) { out.err = "average needs at least two lines or cylinders"; return out; } Vec3 ref = normalize(lines[0].d); Vec3 avg{0, 0, 0}; double cos5 = std::cos(5.0 * PI / 180.0); std::vector dirs; dirs.reserve(lines.size()); std::vector points; points.reserve(lines.size()); for (const auto& line : lines) { if (!line.ok || norm(line.d) < 1e-12) { out.err = "invalid line in average"; return out; } Vec3 d = normalize(line.d); for (const auto& prior : dirs) if (std::fabs(dot(d, prior)) < cos5) { out.err = "axes are more than 5 degrees apart"; return out; } if (dot(d, ref) < 0) d = d * -1.0; avg = avg + d; dirs.push_back(d); points.push_back(line.p); } avg = normalize(avg); // Least-distance point, regularized only along the otherwise free average // direction so the returned anchor stays near the input anchors. double A[6][6] = {}, b[6] = {}, x[6] = {}; for (size_t k = 0; k < lines.size(); ++k) { double d[3] = {dirs[k].x, dirs[k].y, dirs[k].z}; double p[3] = {points[k].x, points[k].y, points[k].z}; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) { double m = (i == j ? 1.0 : 0.0) - d[i] * d[j]; A[i][j] += m; b[i] += m * p[j]; } } double av[3] = {avg.x, avg.y, avg.z}; double meanT = 0; for (const auto& p : points) meanT += dot(p, avg); meanT /= points.size(); for (int i = 0; i < 3; ++i) { b[i] += av[i] * meanT; for (int j = 0; j < 3; ++j) A[i][j] += av[i] * av[j]; } if (!solveLinear(3, A, b, x)) { out.err = "average axis is singular"; return out; } out.ok = true; out.p = {x[0], x[1], x[2]}; out.d = avg; return out; } Line projectLine(const Line& line, const Vec3& planeOrigin, const Vec3& planeNormal) { Line out; if (!line.ok) { out.err = "invalid line"; return out; } Vec3 n = normalize(planeNormal); Vec3 d = line.d - n * dot(line.d, n); if (norm(d) < std::sin(PI / 180.0)) { out.err = "line projects to a point"; return out; } out.ok = true; out.p = line.p - n * dot(line.p - planeOrigin, n); out.d = normalize(d); return out; } Point linePlanePoint(const Line& line, const Vec3& planeOrigin, const Vec3& planeNormal) { Point out; if (!line.ok) { out.err = "invalid line"; return out; } Vec3 n = normalize(planeNormal); double denom = dot(n, normalize(line.d)); if (std::fabs(denom) < std::sin(PI / 180.0)) { out.err = "line and plane are near-parallel"; return out; } out.ok = true; out.p = line.p + line.d * (dot(n, planeOrigin - line.p) / dot(n, line.d)); return out; } Point threePlanesPoint(const std::array& origins, const std::array& normals) { Point out; std::array rows = {normalize(normals[0]), normalize(normals[1]), normalize(normals[2])}; double det = dot(rows[0], cross(rows[1], rows[2])); if (std::fabs(det) < std::sin(PI / 180.0)) { out.err = "three planes are near-singular"; return out; } std::array rhs = {dot(rows[0], origins[0]), dot(rows[1], origins[1]), dot(rows[2], origins[2])}; if (!solve3Rows(rows, rhs, out.p)) { out.err = "three planes are near-singular"; return out; } out.ok = true; return out; } Point midpointPoints(const Vec3& a, const Vec3& b) { Point out; out.ok = true; out.p = (a + b) * 0.5; return out; } Point midpointLine(const Line& line) { Point out; if (!line.ok) { out.err = "invalid line"; return out; } out.ok = true; out.p = line.p; return out; } Point sphereCenter(const Vec3& center) { Point out; out.ok = true; out.p = center; return out; } Point centroidPoint(const std::vector& points) { Point out; if (points.empty()) { out.err = "selection is empty"; return out; } out.ok = true; out.p = centroid(points); return out; } } // namespace prim