#include "align.hpp" #include #include #include namespace align { namespace { using geom::cross; using geom::dot; using geom::norm; using geom::normalize; using geom::Vec3; constexpr double PI = 3.14159265358979323846; Vec3 axisVector(int axis) { if (axis == 0) return {1, 0, 0}; if (axis == 1) return {0, 1, 0}; return {0, 0, 1}; } int axisIndex(const std::string& target) { if (target == "X") return 0; if (target == "Y") return 1; if (target == "Z") return 2; return -1; } double component(const Vec3& p, int axis) { if (axis == 0) return p.x; if (axis == 1) return p.y; return p.z; } void setComponent(Vec3& p, int axis, double value) { if (axis == 0) p.x = value; else if (axis == 1) p.y = value; else p.z = value; } double determinant(const Mat3& R) { return R[0] * (R[4] * R[8] - R[5] * R[7]) - R[1] * (R[3] * R[8] - R[5] * R[6]) + R[2] * (R[3] * R[7] - R[4] * R[6]); } void setRow(Mat3& R, int row, const Vec3& v) { R[3 * row] = v.x; R[3 * row + 1] = v.y; R[3 * row + 2] = v.z; } Mat3 rotationFromOne(const Vec3& source, int targetAxis) { Vec3 sourceU, sourceV; geom::basisFromNormal(source, sourceU, sourceV); Vec3 target = axisVector(targetAxis), targetU, targetV; geom::basisFromNormal(target, targetU, targetV); // R = [targetU targetV target] [sourceU sourceV source]^T. Mat3 R{}; const Vec3 sourceBasis[3] = {sourceU, sourceV, source}; const Vec3 targetBasis[3] = {targetU, targetV, target}; for (int row = 0; row < 3; ++row) { Vec3 r; for (int k = 0; k < 3; ++k) r = r + sourceBasis[k] * component(targetBasis[k], row); setRow(R, row, r); } return R; } Mat3 rotationFromTwo(const Vec3& first, int firstTarget, const Vec3& secondPerp, int secondTarget) { Mat3 R{}; setRow(R, firstTarget, first); setRow(R, secondTarget, secondPerp); int thirdTarget = 3 - firstTarget - secondTarget; Vec3 third = cross(first, secondPerp); setRow(R, thirdTarget, third); if (determinant(R) < 0) setRow(R, thirdTarget, third * -1.0); return R; } const Feature* findFeature(const std::vector& features, int id) { auto it = std::find_if(features.begin(), features.end(), [id](const Feature& f) { return f.id == id; }); return it == features.end() ? nullptr : &*it; } std::string slotName(std::size_t index) { static const char* names[3] = {"primary", "secondary", "tertiary"}; return index < 3 ? names[index] : "slot"; } bool conflicting(double a, double b) { double scale = 1.0 + std::max(std::fabs(a), std::fabs(b)); return std::fabs(a - b) > 1e-9 * scale; } } // namespace Vec3 transformDirection(const Mat3& R, const Vec3& d) { return {R[0] * d.x + R[1] * d.y + R[2] * d.z, R[3] * d.x + R[4] * d.y + R[5] * d.z, R[6] * d.x + R[7] * d.y + R[8] * d.z}; } Vec3 transformPoint(const Mat3& R, const Vec3& t, const Vec3& p) { return transformDirection(R, p) + t; } namespace { void fillOriginAxes(Result& out) { // Current-model point that becomes the new origin: -R^T t. out.origin = { -out.R[0] * out.t.x - out.R[3] * out.t.y - out.R[6] * out.t.z, -out.R[1] * out.t.x - out.R[4] * out.t.y - out.R[7] * out.t.z, -out.R[2] * out.t.x - out.R[5] * out.t.y - out.R[8] * out.t.z}; // New frame's axes in current-model coordinates: rows of R (R^T e_i). out.axes = {Vec3{out.R[0], out.R[1], out.R[2]}, Vec3{out.R[3], out.R[4], out.R[5]}, Vec3{out.R[6], out.R[7], out.R[8]}}; } } // namespace Mat3 rot90(const std::string& axis) { if (axis == "X") return {1, 0, 0, 0, 0, -1, 0, 1, 0}; if (axis == "Y") return {0, 0, 1, 0, 1, 0, -1, 0, 0}; if (axis == "Z") return {0, -1, 0, 1, 0, 0, 0, 0, 1}; return {1, 0, 0, 0, 1, 0, 0, 0, 1}; } Result fromRigid(const Mat3& R, const Vec3& t) { Result out; out.R = R; out.t = t; out.rotLocked = {true, true, true}; out.transLocked = {true, true, true}; out.fullyDefined = true; fillOriginAxes(out); out.ok = true; return out; } Result buildFrame(const std::vector& features, const std::vector& slots, Vec3 translate) { Result out; if (slots.size() > 3) { out.error = "at most three alignment slots are allowed"; return out; } struct Resolved { const Feature* feature = nullptr; int target = -1; bool flip = false; std::size_t slotIndex = 0; }; std::vector resolved; resolved.reserve(slots.size()); for (std::size_t i = 0; i < slots.size(); ++i) { const Feature* feature = findFeature(features, slots[i].primId); if (!feature) { out.error = "unknown primitive id " + std::to_string(slots[i].primId); return out; } int target = -1; if (feature->kind != FeatureKind::PointLike) { target = axisIndex(slots[i].target); if (target < 0) { out.error = slotName(i) + " target must be X, Y, or Z"; return out; } if (norm(feature->direction) < 1e-12) { out.error = slotName(i) + " has no usable direction"; return out; } } resolved.push_back({feature, target, slots[i].flip, i}); } bool haveFirstDirection = false; bool haveSecondDirection = false; Vec3 firstDirection; int firstTarget = -1; for (const Resolved& item : resolved) { if (item.feature->kind == FeatureKind::PointLike) continue; Vec3 direction = normalize(item.feature->direction); if (item.flip) direction = direction * -1.0; if (!haveFirstDirection) { haveFirstDirection = true; firstDirection = direction; firstTarget = item.target; out.R = rotationFromOne(firstDirection, firstTarget); for (int axis = 0; axis < 3; ++axis) out.rotLocked[axis] = axis != firstTarget; continue; } if (haveSecondDirection) continue; if (item.target == firstTarget) { out.error = "secondary target conflicts with primary"; return out; } Vec3 perpendicular = direction - firstDirection * dot(direction, firstDirection); double sine = norm(perpendicular); if (sine < std::sin(2.0 * PI / 180.0)) { out.error = "secondary is parallel to primary"; return out; } perpendicular = perpendicular / sine; out.R = rotationFromTwo(firstDirection, firstTarget, perpendicular, item.target); out.rotLocked = {true, true, true}; haveSecondDirection = true; } std::array writtenValues{0, 0, 0}; std::array writerSlots{-1, -1, -1}; auto writeTranslation = [&](int axis, double value, std::size_t slotIndex) { if (!out.transLocked[axis]) { out.transLocked[axis] = true; writtenValues[axis] = value; writerSlots[axis] = static_cast(slotIndex); setComponent(out.t, axis, value); return; } if (!conflicting(writtenValues[axis], value)) return; static const char* axisNames[3] = {"X", "Y", "Z"}; std::ostringstream message; message << slotName(slotIndex) << " " << axisNames[axis] << " translation conflicts with " << slotName(static_cast(writerSlots[axis])) << " and was ignored"; out.overconstrained.push_back(message.str()); }; for (const Resolved& item : resolved) { Vec3 rotatedAnchor = transformDirection(out.R, item.feature->anchor); if (item.feature->kind == FeatureKind::Plane) { writeTranslation(item.target, -component(rotatedAnchor, item.target), item.slotIndex); } else if (item.feature->kind == FeatureKind::LineLike) { for (int axis = 0; axis < 3; ++axis) if (axis != item.target) writeTranslation(axis, -component(rotatedAnchor, axis), item.slotIndex); } else { for (int axis = 0; axis < 3; ++axis) writeTranslation(axis, -component(rotatedAnchor, axis), item.slotIndex); } } out.t = out.t + translate; out.fullyDefined = std::all_of(out.rotLocked.begin(), out.rotLocked.end(), [](bool locked) { return locked; }) && std::all_of(out.transLocked.begin(), out.transLocked.end(), [](bool locked) { return locked; }); fillOriginAxes(out); out.ok = true; return out; } Result buildFrameFromPoints(const PointsSpec& spec, Vec3 translate) { Result out; const std::vector& p = spec.points; const std::array& v = spec.values; if (p.size() != 3 && p.size() != 5 && p.size() != 6) { out.error = "3-2-1 alignment needs 3, 5, or 6 points"; return out; } // Rule "AAA-BB-C": the plane points set A, the line points set B, the // point sets C (A, B, C a permutation of X, Y, Z). const std::string& rule = spec.rule; int A = -1, B = -1, C = -1; if (rule.size() == 8 && rule[3] == '-' && rule[6] == '-' && rule[0] == rule[1] && rule[1] == rule[2] && rule[4] == rule[5]) { A = axisIndex(rule.substr(0, 1)); B = axisIndex(rule.substr(4, 1)); C = axisIndex(rule.substr(7, 1)); } if (A < 0 || B < 0 || C < 0 || A == B || B == C || A == C) { out.error = "rule must look like ZZZ-YY-X"; return out; } // Plane: unit n with n.(p_i - p_0) = v_i - v_0. Equal values give the // plain plane normal; unequal ones tilt it by an in-plane component w // (solved in span(e1, e2) from the 2x2 Gram system). Vec3 e1 = p[1] - p[0], e2 = p[2] - p[0]; Vec3 m = cross(e1, e2); double span = std::max({norm(e1), norm(e2), norm(p[2] - p[1])}); if (span < 1e-9 || norm(m) < 1e-3 * span * span) { out.error = "plane points are collinear - spread them out"; return out; } m = normalize(m); if (norm(spec.planeHint) > 1e-12 && dot(m, spec.planeHint) < 0) m = m * -1.0; if (spec.flipPlane) m = m * -1.0; double g11 = dot(e1, e1), g12 = dot(e1, e2), g22 = dot(e2, e2); double det = g11 * g22 - g12 * g12; double r1 = v[1] - v[0], r2 = v[2] - v[0]; Vec3 w = e1 * ((r1 * g22 - r2 * g12) / det) + e2 * ((g11 * r2 - g12 * r1) / det); double ww = dot(w, w); if (ww >= 1.0 - 1e-9) { out.error = "plane values differ by more than the points' spacing allows"; return out; } Vec3 n = m * std::sqrt(1.0 - ww) + w; Vec3 u, unused; geom::basisFromNormal(n, u, unused); out.R = rotationFromTwo(n, A, u, B); std::array t{0, 0, 0}; t[A] = v[0] - dot(n, p[0]); out.transLocked[A] = true; for (int axis = 0; axis < 3; ++axis) out.rotLocked[axis] = axis != A; if (p.size() >= 5) { // Line: unit b (the B axis) perpendicular to n with // b.(p4 - p3) = v4 - v3. The C axis then runs along the line; "line // positive" means C points from the first line point to the second. Vec3 f = p[4] - p[3]; Vec3 fp = f - n * dot(f, n); if (norm(fp) < std::sin(2.0 * PI / 180.0) * norm(f) || norm(fp) < 1e-9) { out.error = "line points are along the plane normal - " "pick two points across the secondary face"; return out; } Vec3 fh = normalize(fp), g = cross(n, fh); double s = (v[4] - v[3]) / norm(fp); if (std::fabs(s) >= 1.0 - 1e-9) { out.error = "line values differ by more than the points' spacing allows"; return out; } double tt = std::sqrt(1.0 - s * s); bool cyclic = (B - A + 3) % 3 == 1; // (A, B, C) = (X,Y,Z) up to rotation auto axisC = [&](const Vec3& b) { return cyclic ? cross(n, b) : cross(b, n); }; Vec3 b = fh * s + g * tt; bool positive = dot(axisC(b), fh) > 0; if (positive == spec.flipLine) b = fh * s - g * tt; Vec3 c = axisC(b); setRow(out.R, A, n); setRow(out.R, B, b); setRow(out.R, C, c); out.rotLocked = {true, true, true}; t[B] = v[3] - dot(b, p[3]); out.transLocked[B] = true; if (p.size() == 6) { t[C] = v[5] - dot(c, p[5]); out.transLocked[C] = true; } } out.t = Vec3{t[0], t[1], t[2]} + translate; out.fullyDefined = p.size() == 6; fillOriginAxes(out); out.ok = true; return out; } void applyTo(mesh::Mesh& mesh, const Mat3& R, const Vec3& t) { for (Vec3& p : mesh.verts) p = transformPoint(R, t, p); mesh.computeNormals(); mesh.computeBounds(); mesh.adj.clear(); mesh.curv.clear(); } } // namespace align